--- /dev/null
+Arlo Breault <arlolra@gmail.com>
+Alex K. Wolfe <alexkwolfe@gmail.com>
+Andrew Lunny <alunny@gmail.com>
+Benjamin Coe <bencoe@gmail.com>
+Brian White <mscdex@mscdex.net> <mscdex@gmail.com>
+Charlie Robbins <charlie.robbins@gmail.com>
+Dalmais Maxence <root@ip-10-195-202-5.ec2.internal>
+David Beitey <david@davidjb.com>
+Domenic Denicola <domenic@domenicdenicola.com>
+Einar Otto Stangvik <einaros@gmail.com>
+Evan Lucas <evan@btc.com> <evanlucas@me.com> <evan.lucas@hattiesburgclinic.com>
+Faiq Raza <faiqrazarizvi@gmail.com>
+Forbes Lindesay <forbes@lindesay.co.uk>
+Forrest L. Norvell <forrest@npmjs.com> <ogd@aoaioxxysz.net>
+Gabriel Barros <descartavel1@gmail.com>
+Geoff Flarity <geoff.flarity@gmail.com> <gflarity@raptvm-x02.(none)>
+Isaac Z. Schlueter <i@izs.me> <i@foohack.com>
+Jake Verbaten <raynos2@gmail.com>
+James Sanders <jimmyjazz14@gmail.com>
+Jason Smith <jhs@iriscouch.com>
+Kris Windham <kriswindham@gmail.com>
+Lin Clark <lin.w.clark@gmail.com>
+Maciej Małecki <me@mmalecki.com> <maciej.malecki@notimplemented.org>
+Maximilian Antoni <mail@maxantoni.de> <maximilian.antoni@juliusbaer.com>
+Maxim Bogushevich <boga1@mail.ru>
+Max Goodman <c@chromakode.com>
+Nicolas Morel <marsup@gmail.com>
+Olivier Melcher <olivier.melcher@gmail.com>
+Visnu Pitiyanuvath <visnupx@gmail.com>
+Will Elwood <w.elwood08@gmail.com>
+Zeke Sikelianos <zeke@sikelianos.com>
\ No newline at end of file
# Authors sorted by whether or not they're me
-Isaac Z. Schlueter <i@izs.me>
-Steve Steiner <ssteinerX@gmail.com>
-Mikeal Rogers <mikeal.rogers@gmail.com>
-Aaron Blohowiak <aaron.blohowiak@gmail.com>
-Martyn Smith <martyn@dollyfish.net.nz>
-Mathias Pettersson <mape@mape.me>
-Brian Hammond <brian@fictorial.com>
-Charlie Robbins <charlie.robbins@gmail.com>
-Francisco Treacy <francisco.treacy@gmail.com>
-Cliffano Subagio <cliffano@gmail.com>
-Christian Eager <christian.eager@nokia.com>
-Dav Glass <davglass@gmail.com>
-Alex K. Wolfe <alexkwolfe@gmail.com>
-James Sanders <jimmyjazz14@gmail.com>
-Reid Burke <me@reidburke.com>
-Arlo Breault <arlolra@gmail.com>
-Timo Derstappen <teemow@gmail.com>
-Bradley Meck <bradley.meck@gmail.com>
-Bart Teeuwisse <bart.teeuwisse@thecodemill.biz>
-Ben Noordhuis <info@bnoordhuis.nl>
-Tor Valamo <tor.valamo@gmail.com>
-Whyme.Lyu <5longluna@gmail.com>
-Olivier Melcher <olivier.melcher@gmail.com>
-Tomaž Muraus <kami@k5-storitve.net>
Evan Meagher <evan.meagher@gmail.com>
Orlando Vazquez <ovazquez@gmail.com>
+Kai Chen <kaichenxyz@gmail.com>
George Miroshnykov <gmiroshnykov@lohika.com>
Geoff Flarity <geoff.flarity@gmail.com>
+Max Goodman <c@chromakode.com>
Pete Kruckenberg <pete@kruckenberg.com>
Laurie Harper <laurie@holoweb.net>
+Neil Gentleman <ngentleman@gmail.com>
+Kris Kowal <kris.kowal@cixar.com>
+Alex Gorbatchev <alex.gorbatchev@gmail.com>
+Shawn Wildermuth <shawn@wildermuth.com>
+Wesley de Souza <wesleywex@gmail.com>
+Patrick Pfeiffer <patrick@buzzle.at>
+yoyoyogi <yogesh.k@gmail.com>
+Paul Miller <paul@paulmillr.com>
+Jérémy Lal <kapouer@melix.org>
+J. Tangelder <j.tangelder@gmail.com>
+seebees <seebees@gmail.com>
+Anders Janmyr <anders@janmyr.com>
+Jean Lauliac <jean@lauliac.com>
+Carl Lange <carl@flax.ie>
+Chris Meyers <chris.meyers.fsu@gmail.com>
+Andrey Kislyuk <kislyuk@gmail.com>
+Jan Lehnardt <jan@apache.org>
+Ludwig Magnusson <ludwig@mediatool.com>
+Thorsten Lorenz <thlorenz@gmx.de>
+Stuart P. Bentley <stuart@testtrack4.com>
+wmertens <Wout.Mertens@gmail.com>
+Johan Sköld <johan@skold.cc>
+Nick Santos <nick@medium.com>
+Stuart Knightley <stuart@stuartk.com>
+Terin Stock <terinjokes@gmail.com>
+Niggler <nirk.niggler@gmail.com>
+Faiq Raza <faiqrazarizvi@gmail.com>
+Paolo Fragomeni <paolo@async.ly>
+Thomas Torp <thomas@erupt.no>
+Jaakko Manninen <jaakko@rocketpack.fi>
+Sam Mikes <smikes@cubane.com>
+Luke Arduini <luke.arduini@gmail.com>
+Larz Conwell <larz@larz-laptop.(none)>
+Marcel Klehr <mklehr@gmx.net>
+Robert Kowalski <rok@kowalski.gd>
Chris Wong <chris@chriswongstudio.com>
-Max Goodman <c@chromacode.com>
+Forbes Lindesay <forbes@lindesay.co.uk>
Scott Bronson <brons_github@rinspin.com>
+Vaz Allen <vaz@tryptid.com>
Federico Romero <federomero@gmail.com>
+Jake Verbaten <raynos2@gmail.com>
Visnu Pitiyanuvath <visnupx@gmail.com>
+Schabse Laks <Dev@SLaks.net>
Irakli Gozalishvili <rfobic@gmail.com>
+Florian Margaine <florian@margaine.com>
Mark Cahill <mark@tiemonster.info>
Zearin <zearin@gonk.net>
Iain Sproat <iainsproat@gmail.com>
Trent Mick <trentm@gmail.com>
Felix Geisendörfer <felix@debuggable.com>
-Conny Brunnkvist <cbrunnkvist@gmail.com>
+Julian Gruber <julian@juliangruber.com>
+Benjamin Coe <bencoe@gmail.com>
+Alex Ford <Alex.Ford@CodeTunnel.com>
+Matt Hickford <matt.hickford@gmail.com>
+Sean McGivern <sean.mcgivern@rightscale.com>
+C J Silverio <ceejceej@gmail.com>
+Mat Tyndall <mat.tyndall@gmail.com>
+Robin Tweedie <robin@songkick.com>
+Tauren Mills <tauren@sportzing.com>
+Miroslav Bajtoš <miroslav@strongloop.com>
+Isaac Z. Schlueter <i@izs.me>
+Ron Martinez <ramartin.net@gmail.com>
+David Glasser <glasser@davidglasser.net>
+Steve Steiner <ssteinerX@gmail.com>
+Kazuhito Hokamura <k.hokamura@gmail.com>
+Gianluca Casati <casati_gianluca@yahoo.it>
+Mikeal Rogers <mikeal.rogers@gmail.com>
+Tristan Davies <github@tristan.io>
+Aaron Blohowiak <aaron.blohowiak@gmail.com>
+David Volm <david@volminator.com>
+Martyn Smith <martyn@dollyfish.net.nz>
+Lin Clark <lin.w.clark@gmail.com>
+Charlie Robbins <charlie.robbins@gmail.com>
+Ben Page <bpage@dewalch.com>
+Francisco Treacy <francisco.treacy@gmail.com>
+Jeff Jo <jeffjo@squareup.com>
+Johan Nordberg <its@johan-nordberg.com>
+Cliffano Subagio <cliffano@gmail.com>
+martinvd <martinvdpub@gmail.com>
+Ian Babrou <ibobrik@gmail.com>
+Christian Eager <christian.eager@nokia.com>
+Di Wu <dwu@palantir.com>
+Mathias Bynens <mathias@qiwi.be>
+Matt McClure <matt.mcclure@mapmyfitness.com>
+Jameson Little <t.jameson.little@gmail.com>
+Matt Lunn <matt@mattlunn.me.uk>
+Conny Brunnkvist <conny@fuchsia.se>
+Alexey Kreschuk <akrsch@gmail.com>
Will Elwood <w.elwood08@gmail.com>
+elisee <elisee@sparklin.org>
+Dean Landolt <dean@deanlandolt.com>
+Robert Gieseke <robert.gieseke@gmail.com>
Oleg Efimov <efimovov@gmail.com>
+François Frisch <francoisfrisch@gmail.com>
Martin Cooper <mfncooper@gmail.com>
-Jameson Little <t.jameson.little@gmail.com>
+Jann Horn <jannhorn@googlemail.com>
cspotcode <cspotcode@gmail.com>
-Maciej Małecki <maciej.malecki@notimplemented.org>
+Maciej Małecki <me@mmalecki.com>
Stephen Sugden <glurgle@gmail.com>
+Forrest L Norvell <forrest@npmjs.com>
+Karsten Tinnefeld <k.tinnefeld@googlemail.com>
+Bryan Burgers <bryan@burgers.io>
+David Beitey <david@davidjb.com>
+Evan You <yyou@google.com>
+Zach Pomerantz <zmp@umich.edu>
+Mark J. Titorenko <nospam-github.com@titorenko.net>
+Chris Williams <cwilliams88@gmail.com>
+Oddur Sigurdsson <oddurs@gmail.com>
+sudodoki <smd.deluzion@gmail.com>
+Eric Mill <eric@konklone.com>
+Mick Thompson <dthompson@gmail.com>
+Gabriel Barros <descartavel1@gmail.com>
+Felix Rabe <felix@rabe.io>
+KevinSheedy <kevinsheedy@gmail.com>
+Aleksey Smolenchuk <aleksey@uber.com>
+Ed Morley <emorley@mozilla.com>
+Blaine Bublitz <blaine@iceddev.com>
+Andrey Fedorov <anfedorov@gmail.com>
+Trevor Burnham <tburnham@hubspot.com>
+Daijiro Wachi <daijiro.wachi@gmail.com>
+Alan Shaw <alan@freestyle-developments.co.uk>
+TJ Holowaychuk <tj@vision-media.ca>
+Luke Arduini <luke.arduini@me.com>
+Nicholas Kinsey <pyro@feisty.io>
+Michael Budde <mbudde@gmail.com>
+Paulo Cesar <pauloc062@gmail.com>
+Jason Smith <jhs@iriscouch.com>
+Elan Shanker <elan.shanker@gmail.com>
Gautham Pai <buzypi@gmail.com>
+Jon Spencer <jon@jonspencer.ca>
David Trejo <david.daniel.trejo@gmail.com>
+Jason Diamond <jason@diamond.name>
Paul Vorbach <paul@vorb.de>
+Maximilian Antoni <mail@maxantoni.de>
George Ornbo <george@shapeshed.com>
Tim Oxley <secoif@gmail.com>
Tyler Green <tyler.green2@gmail.com>
+Dave Pacheco <dap@joyent.com>
atomizer <danila.gerasimov@gmail.com>
+Michael Hayes <michael@hayes.io>
+Chris Dickinson <christopher.s.dickinson@gmail.com>
+Bradley Meck <bradley.meck@gmail.com>
+GeJ <geraud@gcu.info>
+Andrew Terris <atterris@gmail.com>
+Michael Nisi <michael.nisi@gmail.com>
+Luc Thevenard <lucthevenard@gmail.com>
+fengmk2 <fengmk2@gmail.com>
+Aria Stewart <aredridel@nbtsc.org>
+Adam Meadows <adam.meadows@gmail.com>
+Charlie Rudolph <charles.w.rudolph@gmail.com>
+Chulki Lee <chulki.lee@gmail.com>
+不四 <busi.hyy@taobao.com>
+Thom Blake <tblake@brightroll.com>
+Jess Martin <jessmartin@gmail.com>
+Spain Train <michael.spainhower@opower.com>
+Alex Rodionov <p0deje@gmail.com>
+Matt Colyer <matt@colyer.name>
Rod Vagg <rod@vagg.org>
+Evan You <yyx990803@gmail.com>
Christian Howe <coderarity@gmail.com>
+bitspill <bitspill+github@bitspill.net>
Andrew Lunny <alunny@gmail.com>
+Gabriel Falkenberg <gabriel.falkenberg@gmail.com>
Henrik Hodne <dvyjones@binaryhex.com>
+Alexej Yaroshevich <alex@qfox.ru>
Adam Blackburn <regality@gmail.com>
+Quim Calpe <quim@kalpe.com>
Kris Windham <kriswindham@gmail.com>
Jens Grunert <jens.grunert@gmail.com>
Joost-Wim Boekesteijn <joost-wim@boekesteijn.nl>
-Dalmais Maxence <github@maxired.fr>
+Dalmais Maxence <root@ip-10-195-202-5.ec2.internal>
Marcus Ekwall <marcus.ekwall@gmail.com>
+Steve Mason <stevem@brandwatch.com>
+Wil Moore III <wil.moore@wilmoore.com>
+Sergey Belov <peimei@ya.ru>
+Tom Huang <hzlhu.dargon@gmail.com>
+CamilleM <camille.moulin@alterway.fr>
Aaron Stacy <aaron.r.stacy@gmail.com>
+Sébastien Santoro <dereckson@espace-win.org>
Phillip Howell <phowell@cothm.org>
+Evan Lucas <evan@btc.com>
Domenic Denicola <domenic@domenicdenicola.com>
+Quinn Slack <qslack@qslack.com>
James Halliday <mail@substack.net>
+Alex Kocharin <alex@kocharin.ru>
Jeremy Cantrell <jmcantrell@gmail.com>
+Evan Lucas <evan.lucas@hattiesburgclinic.com>
+Trent Mick <trent.mick@joyent.com>
Ribettes <patlogan29@gmail.com>
-Einar Otto Stangvik <einaros@gmail.com>
Don Park <donpark@docuverse.com>
+Einar Otto Stangvik <einaros@gmail.com>
Kei Son <heyacct@gmail.com>
+Dav Glass <davglass@gmail.com>
+Alex K. Wolfe <alexkwolfe@gmail.com>
+James Sanders <jimmyjazz14@gmail.com>
+Reid Burke <me@reidburke.com>
+Arlo Breault <arlolra@gmail.com>
+Timo Derstappen <teemow@gmail.com>
+Bart Teeuwisse <bart.teeuwisse@thecodemill.biz>
+Ben Noordhuis <info@bnoordhuis.nl>
+Tor Valamo <tor.valamo@gmail.com>
+Whyme.Lyu <5longluna@gmail.com>
+Daniel Santiago <daniel.santiago@highlevelwebs.com>
+Denis Gladkikh <outcoldman@gmail.com>
+Andrew Horton <andrew.j.horton@gmail.com>
+Zeke Sikelianos <zeke@sikelianos.com>
+Dylan Greene <dylang@gmail.com>
Nicolas Morel <marsup@gmail.com>
+Franck Cuny <franck.cuny@gmail.com>
Mark Dube <markisdee@gmail.com>
+dead_horse <dead_horse@qq.com>
+Yeonghoon Park <sola92@gmail.com>
Nathan Rajlich <nathan@tootallnate.net>
+Kenan Yildirim <kenan@kenany.me>
+Rafael de Oleza <rafa@spotify.com>
Maxim Bogushevich <boga1@mail.ru>
-Justin Beckwith <justbe@microsoft.com>
+Laurie Voss <git@seldo.com>
+Mikola Lysenko <mikolalysenko@gmail.com>
Meaglin <Meaglin.wasabi@gmail.com>
+Rebecca Turner <turner@mikomi.org>
+Yazhong Liu <yorkiefixer@gmail.com>
Ben Evans <ben@bensbit.co.uk>
+Hunter Loftis <hunter@hunterloftis.com>
Nathan Zadoks <nathan@nathan7.eu>
-Brian White <mscdex@gmail.com>
+Peter Richardson <github@zoomy.net>
+Brian White <mscdex@mscdex.net>
+Jussi Kalliokoski <jussi.kalliokoski@gmail.com>
Jed Schmidt <tr@nslator.jp>
+Filip Weiss <me@fiws.net>
Ian Livingstone <ianl@cs.dal.ca>
-Patrick Pfeiffer <patrick@buzzle.at>
-Paul Miller <paul@paulmillr.com>
-seebees <seebees@gmail.com>
-Carl Lange <carl@flax.ie>
-Jan Lehnardt <jan@apache.org>
-Alexey Kreschuk <akrsch@gmail.com>
-Di Wu <dwu@palantir.com>
-Florian Margaine <florian@margaine.com>
-Forbes Lindesay <forbes@lindesay.co.uk>
-Ian Babrou <ibobrik@gmail.com>
-Jaakko Manninen <jaakko@rocketpack.fi>
-Johan Nordberg <its@johan-nordberg.com>
-Johan Sköld <johan@skold.cc>
-Larz Conwell <larz@larz-laptop.(none)>
-Luke Arduini <luke.arduini@gmail.com>
-Marcel Klehr <mklehr@gmx.net>
-Mathias Bynens <mathias@qiwi.be>
-Matt Lunn <matt@mattlunn.me.uk>
-Matt McClure <matt.mcclure@mapmyfitness.com>
-Nirk Niggler <nirk.niggler@gmail.com>
-Paolo Fragomeni <paolo@async.ly>
-Jake Verbaten (Raynos) <raynos2@gmail.com>
-Robert Kowalski <rok@kowalski.gd>
-Schabse Laks <Dev@SLaks.net>
-Stuart Knightley <stuart@stuartk.com>
-Stuart P. Bentley <stuart@testtrack4.com>
-Vaz Allen <vaz@tryptid.com>
-elisee <elisee@sparklin.org>
-Evan You <yyx990803@gmail.com>
-Wil Moore III <wil.moore@wilmoore.com>
-Dylan Greene <dylang@gmail.com>
-zeke <zeke@sikelianos.com>
-Andrew Horton <andrew.j.horton@gmail.com>
-Denis Gladkikh <outcoldman@gmail.com>
-Daniel Santiago <daniel.santiago@highlevelwebs.com>
-Alex Kocharin <alex@kocharin.ru>
-Evan Lucas <evanlucas@me.com>
-Steve Mason <stevem@brandwatch.com>
-Quinn Slack <qslack@qslack.com>
-Sébastien Santoro <dereckson@espace-win.org>
-CamilleM <camille.moulin@alterway.fr>
-Tom Huang <hzlhu.dargon@gmail.com>
-Sergey Belov <peimei@ya.ru>
-Younghoon Park <sola92@gmail.com>
-Yazhong Liu <yorkiefixer@gmail.com>
-Mikola Lysenko <mikolalysenko@gmail.com>
-Rafael de Oleza <rafa@spotify.com>
-Yeonghoon Park <sola92@gmail.com>
-Franck Cuny <franck.cuny@gmail.com>
-Alan Shaw <alan@freestyle-developments.co.uk>
-Alex Rodionov <p0deje@gmail.com>
-Alexej Yaroshevich <alex@qfox.ru>
-Elan Shanker <elan.shanker@gmail.com>
-François Frisch <francoisfrisch@gmail.com>
-Gabriel Falkenberg <gabriel.falkenberg@gmail.com>
-Jason Diamond <jason@diamond.name>
-Jess Martin <jessmartin@gmail.com>
-Jon Spencer <jon@jonspencer.ca>
-Matt Colyer <matt@colyer.name>
-Matt McClure <matt.mcclure@mapmyfitness.com>
-Maximilian Antoni <maximilian.antoni@juliusbaer.com>
-Nicholas Kinsey <pyro@feisty.io>
-Paulo Cesar <pauloc062@gmail.com>
-Quim Calpe <quim@kalpe.com>
-Robert Gieseke <robert.gieseke@gmail.com>
-Spain Train <michael.spainhower@opower.com>
-TJ Holowaychuk <tj@vision-media.ca>
-Thom Blake <tblake@brightroll.com>
-Trevor Burnham <tburnham@hubspot.com>
-bitspill <bitspill+github@bitspill.net>
-Neil Gentleman <ngentleman@gmail.com>
+timoweiss <timoweiss@Timo-MBP.local>
+Christopher Hiller <chiller@badwing.com>
+Olivier Melcher <olivier.melcher@gmail.com>
+Tomaž Muraus <kami@k5-storitve.net>
+### v2.5.1 (2015-02-06):
+
+This release doesn't look like much, but considerable effort went into ensuring
+that npm's tests will pass on io.js 1.1.0 and Node 0.11.16 / 0.12.0 on both OS
+X and Linux.
+
+**NOTE:** there are no actual changes to npm's code in `npm@2.5.1`. Only test
+code (and the upgrade of `request` to the latest version) has changed.
+
+#### `npm-registry-mock@1.0.0`:
+
+* [`0e8d473`](https://github.com/npm/npm/commit/0e8d4736a1cbdda41ae8eba8a02c7ff7ce80c2ff)
+ [#7281](https://github.com/npm/npm/issues/7281) `npm-registry-mock@1.0.0`:
+ Clean up API, set `connection: close`.
+ ([@robertkowalski](https://github.com/robertkowalski))
+* [`4707bba`](https://github.com/npm/npm/commit/4707bba7d44dfab85cc45c2ecafa9c1601ba2e9a)
+ Further update tests to work with `npm-registry-mock@1.0.0`.
+ ([@othiym23](https://github.com/othiym23))
+* [`41a0f89`](https://github.com/npm/npm/commit/41a0f8959d4e02af9661588afa7d2b4543cc21b6)
+ Got rid of completely gratuitous global config manipulation in tests.
+ ([@othiym23](https://github.com/othiym23))
+
+#### MINOR DEPENDENCY TWEAK
+
+* [`a4c7af9`](https://github.com/npm/npm/commit/a4c7af9c692f250c0fd017397ed9514fc263b752)
+ `request@2.53.0`: Tweaks to tunneling proxy behavior.
+ ([@nylen](https://github.com/nylen))
+
+### v2.5.0 (2015-01-29):
+
+#### SMALL FEATURE I HAVE ALREADY USED TO MAINTAIN NPM ITSELF
+
+* [`9d61e96`](https://github.com/npm/npm/commit/9d61e96fb1f48687a85c211e4e0cd44c7f95a38e)
+ `npm outdated --long` now includes a column showing the type of dependency.
+ ([@watilde](https://github.com/watilde))
+
+#### BUG FIXES & TWEAKS
+
+* [`fec4c96`](https://github.com/npm/npm/commit/fec4c967ee235030bf31393e8605e9e2811f4a39)
+ Allow `--no-proxy` to override `HTTP_PROXY` setting in environment.
+ ([@othiym23](https://github.com/othiym23))
+* [`589acb9`](https://github.com/npm/npm/commit/589acb9714f395c2ad0d98cb0ac4236f1842d2cc)
+ Only set `access` when publshing when it's explicitly set.
+ ([@othiym23](https://github.com/othiym23))
+* [`1027087`](https://github.com/npm/npm/commit/102708704c8c4f0ea99775d38f8d1efecf584940)
+ Add script and `Makefile` stanza to update AUTHORS.
+ ([@KenanY](https://github.com/KenanY))
+* [`eeff04d`](https://github.com/npm/npm/commit/eeff04da7979a0181becd36b8777d607e7aa1787)
+ Add `NPMOPTS` to top-level install in `Makefile` to override `userconfig`.
+ ([@aredridel](https://github.com/aredridel))
+* [`0d17328`](https://github.com/npm/npm/commit/0d173287336650606d4c91818bb7bcfb0c5d57a1)
+ `fstream@1.0.4`: Run chown only when necessary.
+ ([@silkentrance](https://github.com/silkentrance))
+* [`9aa4622`](https://github.com/npm/npm/commit/9aa46226ee63b9e183fd49fc72d9bdb0fae9605e)
+ `columnify@1.4.1`: ES6ified! ([@timoxley](https://github.com/timoxley))
+* [`51b2fd1`](https://github.com/npm/npm/commit/51b2fd1974e38b825ac5ca4a852ab3c4142624cc)
+ Update default version in `docs/npm-config.md`.
+ ([@lucthev](https://github.com/lucthev))
+
+#### `npm-registry-client@6.0.7`:
+
+* [`f9313a0`](https://github.com/npm/npm/commit/f9313a066c9889a0ee898d8a35676e40b8101e7f)
+ [#7226](https://github.com/npm/npm/issues/7226) Ensure that all request
+ settings are copied onto the agent.
+ ([@othiym23](https://github.com/othiym23))
+* [`e186f6e`](https://github.com/npm/npm/commit/e186f6e7cfeb4db9c94d7375638f0b2f0d472947)
+ Only set `access` on publish when it differs from the norm.
+ ([@othiym23](https://github.com/othiym23))
+* [`f9313a0`](https://github.com/npm/npm/commit/f9313a066c9889a0ee898d8a35676e40b8101e7f)
+ Allow overriding request's environment-based proxy handling.
+ ([@othiym23](https://github.com/othiym23))
+* [`f9313a0`](https://github.com/npm/npm/commit/f9313a066c9889a0ee898d8a35676e40b8101e7f)
+ Properly handle retry failures on fetch.
+ ([@othiym23](https://github.com/othiym23))
+
### v2.4.1 (2015-01-23):
![bridge that doesn't meet in the middle](http://www.static-18.themodernnomad.com/wp-content/uploads/2011/08/bridge-fail.jpg)
@echo "Installing latest published npm"
@echo "Use 'make install' or 'make link' to install the code"
@echo "in this folder that you're looking at right now."
- node cli.js install -g -f npm
+ node cli.js install -g -f npm ${NPMOPTS}
install: all
- node cli.js install -g -f
+ node cli.js install -g -f ${NPMOPTS}
# backwards compat
dev: install
tag:
npm tag npm@$(PUBLISHTAG) latest
-publish: link doc
+authors:
+ @bash scripts/update-authors.sh &&\
+ git add AUTHORS &&\
+ git commit -m "update AUTHORS" || true
+
+publish: link doc authors
@git push origin :v$(shell npm -v) 2>&1 || true
git clean -fd &&\
git push origin $(BRANCH) &&\
sandwich:
@[ $$(whoami) = "root" ] && (echo "ok"; echo "ham" > sandwich) || (echo "make it yourself" && exit 13)
-.PHONY: all latest install dev link doc clean uninstall test man doc-clean docclean release
+.PHONY: all latest install dev link doc clean uninstall test man doc-clean docclean release authors
"version": "0.0.1",
"dependencies": {
"C": {
- "version": "0.1.0"
+ "version": "0.0.1"
}
}
}
root, the shrinkwrap file (rather than package.json files) completely
drives the installation of that package and all of its dependencies
(recursively). So now the author publishes A@0.1.0, and subsequent
-installs of this package will use B@0.0.1 and C@0.1.0, regardless the
+installs of this package will use B@0.0.1 and C@0.0.1, regardless the
dependencies and versions listed in A's, B's, and C's package.json
files.
{
"name": "tea-latte",
- "version": "1.3.5"
+ "version": "1.3.5",
"peerDependencies": {
"tea": "2.x"
}
* `-m`: `--message`
* `-p`, `--porcelain`: `--parseable`
* `-reg`: `--registry`
-* `-v`: `--version`
* `-f`: `--force`
* `-desc`: `--description`
* `-S`: `--save`
### init-version
-* Default: "0.0.0"
+* Default: "1.0.0"
* Type: semver
The value that `npm init` should use by default for the package
Configure how versions of packages installed to a package.json file via
`--save` or `--save-dev` get prefixed.
-For example if a package has version `1.2.3`, by default it's version is
+For example if a package has version `1.2.3`, by default its version is
set to `^1.2.3` which allows minor upgrades for that package, but after
`npm config set save-prefix='~'` it would be set to `~1.2.3` which only allows
patch upgrades.
## SEE ALSO
* npm-config(1)
-* npm-config(7)
* npmrc(5)
* npm-scripts(7)
* npm-folders(5)
<p>If you have a complaint about a package in the public npm registry,
and cannot <a href="https://docs.npmjs.com/misc/disputes">resolve it with the package
owner</a>, please email
-<a href="mailto:support@npmjs.com">support@npmjs.com</a> and explain the situation.</p>
+<a href="mailto:support@npmjs.com">support@npmjs.com</a> and explain the situation.</p>
<p>Any data published to The npm Registry (including user account
information) may be removed or modified at the sole discretion of the
npm server administrators.</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer"><a href="../doc/README.html">README</a> — npm@2.4.1</p>
+<p id="footer"><a href="../doc/README.html">README</a> — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-bin — npm@2.4.1</p>
+<p id="footer">npm-bin — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-bugs — npm@2.4.1</p>
+<p id="footer">npm-bugs — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-cache — npm@2.4.1</p>
+<p id="footer">npm-cache — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-commands — npm@2.4.1</p>
+<p id="footer">npm-commands — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-config — npm@2.4.1</p>
+<p id="footer">npm-config — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-deprecate — npm@2.4.1</p>
+<p id="footer">npm-deprecate — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-docs — npm@2.4.1</p>
+<p id="footer">npm-docs — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-edit — npm@2.4.1</p>
+<p id="footer">npm-edit — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-explore — npm@2.4.1</p>
+<p id="footer">npm-explore — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-help-search — npm@2.4.1</p>
+<p id="footer">npm-help-search — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-init — npm@2.4.1</p>
+<p id="footer">npm-init — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-install — npm@2.4.1</p>
+<p id="footer">npm-install — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-link — npm@2.4.1</p>
+<p id="footer">npm-link — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-load — npm@2.4.1</p>
+<p id="footer">npm-load — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-ls — npm@2.4.1</p>
+<p id="footer">npm-ls — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-outdated — npm@2.4.1</p>
+<p id="footer">npm-outdated — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-owner — npm@2.4.1</p>
+<p id="footer">npm-owner — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-pack — npm@2.4.1</p>
+<p id="footer">npm-pack — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-prefix — npm@2.4.1</p>
+<p id="footer">npm-prefix — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-prune — npm@2.4.1</p>
+<p id="footer">npm-prune — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-publish — npm@2.4.1</p>
+<p id="footer">npm-publish — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-rebuild — npm@2.4.1</p>
+<p id="footer">npm-rebuild — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-repo — npm@2.4.1</p>
+<p id="footer">npm-repo — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-restart — npm@2.4.1</p>
+<p id="footer">npm-restart — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-root — npm@2.4.1</p>
+<p id="footer">npm-root — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-run-script — npm@2.4.1</p>
+<p id="footer">npm-run-script — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-search — npm@2.4.1</p>
+<p id="footer">npm-search — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-shrinkwrap — npm@2.4.1</p>
+<p id="footer">npm-shrinkwrap — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-start — npm@2.4.1</p>
+<p id="footer">npm-start — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-stop — npm@2.4.1</p>
+<p id="footer">npm-stop — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-tag — npm@2.4.1</p>
+<p id="footer">npm-tag — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-test — npm@2.4.1</p>
+<p id="footer">npm-test — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-uninstall — npm@2.4.1</p>
+<p id="footer">npm-uninstall — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-unpublish — npm@2.4.1</p>
+<p id="footer">npm-unpublish — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-update — npm@2.4.1</p>
+<p id="footer">npm-update — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-version — npm@2.4.1</p>
+<p id="footer">npm-version — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-view — npm@2.4.1</p>
+<p id="footer">npm-view — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-whoami — npm@2.4.1</p>
+<p id="footer">npm-whoami — npm@2.5.1</p>
npm.commands.install(["package"], cb)
})
</code></pre><h2 id="version">VERSION</h2>
-<p>2.4.1</p>
+<p>2.5.1</p>
<h2 id="description">DESCRIPTION</h2>
<p>This is the API documentation for npm.
To find documentation of the command line
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm — npm@2.4.1</p>
+<p id="footer">npm — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-access — npm@2.4.1</p>
+<p id="footer">npm-access — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-adduser — npm@2.4.1</p>
+<p id="footer">npm-adduser — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-bin — npm@2.4.1</p>
+<p id="footer">npm-bin — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-bugs — npm@2.4.1</p>
+<p id="footer">npm-bugs — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-build — npm@2.4.1</p>
+<p id="footer">npm-build — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-bundle — npm@2.4.1</p>
+<p id="footer">npm-bundle — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-cache — npm@2.4.1</p>
+<p id="footer">npm-cache — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-completion — npm@2.4.1</p>
+<p id="footer">npm-completion — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-config — npm@2.4.1</p>
+<p id="footer">npm-config — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-dedupe — npm@2.4.1</p>
+<p id="footer">npm-dedupe — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-deprecate — npm@2.4.1</p>
+<p id="footer">npm-deprecate — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-dist-tag — npm@2.4.1</p>
+<p id="footer">npm-dist-tag — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-docs — npm@2.4.1</p>
+<p id="footer">npm-docs — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-edit — npm@2.4.1</p>
+<p id="footer">npm-edit — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-explore — npm@2.4.1</p>
+<p id="footer">npm-explore — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-help-search — npm@2.4.1</p>
+<p id="footer">npm-help-search — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-help — npm@2.4.1</p>
+<p id="footer">npm-help — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-init — npm@2.4.1</p>
+<p id="footer">npm-init — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-install — npm@2.4.1</p>
+<p id="footer">npm-install — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-link — npm@2.4.1</p>
+<p id="footer">npm-link — npm@2.5.1</p>
limit the results to only the paths to the packages named. Note that
nested packages will <em>also</em> show the paths to the specified packages.
For example, running <code>npm ls promzard</code> in npm's source tree will show:</p>
-<pre><code>npm@2.4.1 /path/to/npm
+<pre><code>npm@2.5.1 /path/to/npm
└─┬ init-package-json@0.0.4
└── promzard@0.1.5
</code></pre><p>It will print out extraneous, missing, and invalid packages.</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-ls — npm@2.4.1</p>
+<p id="footer">npm-ls — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-outdated — npm@2.4.1</p>
+<p id="footer">npm-outdated — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-owner — npm@2.4.1</p>
+<p id="footer">npm-owner — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-pack — npm@2.4.1</p>
+<p id="footer">npm-pack — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-prefix — npm@2.4.1</p>
+<p id="footer">npm-prefix — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-prune — npm@2.4.1</p>
+<p id="footer">npm-prune — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-publish — npm@2.4.1</p>
+<p id="footer">npm-publish — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-rebuild — npm@2.4.1</p>
+<p id="footer">npm-rebuild — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-repo — npm@2.4.1</p>
+<p id="footer">npm-repo — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-restart — npm@2.4.1</p>
+<p id="footer">npm-restart — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-rm — npm@2.4.1</p>
+<p id="footer">npm-rm — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-root — npm@2.4.1</p>
+<p id="footer">npm-root — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-run-script — npm@2.4.1</p>
+<p id="footer">npm-run-script — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-search — npm@2.4.1</p>
+<p id="footer">npm-search — npm@2.5.1</p>
"version": "0.0.1",
"dependencies": {
"C": {
- "version": "0.1.0"
+ "version": "0.0.1"
}
}
}
root, the shrinkwrap file (rather than package.json files) completely
drives the installation of that package and all of its dependencies
(recursively). So now the author publishes A@0.1.0, and subsequent
-installs of this package will use B@0.0.1 and C@0.1.0, regardless the
+installs of this package will use B@0.0.1 and C@0.0.1, regardless the
dependencies and versions listed in A's, B's, and C's package.json
files.</p>
<h3 id="using-shrinkwrapped-packages">Using shrinkwrapped packages</h3>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-shrinkwrap — npm@2.4.1</p>
+<p id="footer">npm-shrinkwrap — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-star — npm@2.4.1</p>
+<p id="footer">npm-star — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-stars — npm@2.4.1</p>
+<p id="footer">npm-stars — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-start — npm@2.4.1</p>
+<p id="footer">npm-start — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-stop — npm@2.4.1</p>
+<p id="footer">npm-stop — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-tag — npm@2.4.1</p>
+<p id="footer">npm-tag — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-test — npm@2.4.1</p>
+<p id="footer">npm-test — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-uninstall — npm@2.4.1</p>
+<p id="footer">npm-uninstall — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-unpublish — npm@2.4.1</p>
+<p id="footer">npm-unpublish — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-update — npm@2.4.1</p>
+<p id="footer">npm-update — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-version — npm@2.4.1</p>
+<p id="footer">npm-version — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-view — npm@2.4.1</p>
+<p id="footer">npm-view — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-whoami — npm@2.4.1</p>
+<p id="footer">npm-whoami — npm@2.5.1</p>
<h2 id="synopsis">SYNOPSIS</h2>
<pre><code>npm <command> [args]
</code></pre><h2 id="version">VERSION</h2>
-<p>2.4.1</p>
+<p>2.5.1</p>
<h2 id="description">DESCRIPTION</h2>
<p>npm is the package manager for the Node JavaScript platform. It puts
modules in place so that node can find them, and manages dependency
the issues list or ask on the mailing list.</p>
<ul>
<li><a href="http://github.com/npm/npm/issues">http://github.com/npm/npm/issues</a></li>
-<li><a href="mailto:npm-@googlegroups.com">npm-@googlegroups.com</a></li>
+<li><a href="mailto:npm-@googlegroups.com">npm-@googlegroups.com</a></li>
</ul>
<h2 id="bugs">BUGS</h2>
<p>When you find issues, please report them:</p>
<li>web:
<a href="http://github.com/npm/npm/issues">http://github.com/npm/npm/issues</a></li>
<li>email:
-<a href="mailto:npm-@googlegroups.com">npm-@googlegroups.com</a></li>
+<a href="mailto:npm-@googlegroups.com">npm-@googlegroups.com</a></li>
</ul>
<p>Be sure to include <em>all</em> of the output from the npm command that didn't work
as expected. The <code>npm-debug.log</code> file is also helpful to provide.</p>
<p><a href="http://blog.izs.me/">Isaac Z. Schlueter</a> ::
<a href="https://github.com/isaacs/">isaacs</a> ::
<a href="http://twitter.com/izs">@izs</a> ::
-<a href="mailto:i@izs.me">i@izs.me</a></p>
+<a href="mailto:i@izs.me">i@izs.me</a></p>
<h2 id="see-also">SEE ALSO</h2>
<ul>
<li><a href="../cli/npm-help.html"><a href="../cli/npm-help.html">npm-help(1)</a></a></li>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm — npm@2.4.1</p>
+<p id="footer">npm — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-folders — npm@2.4.1</p>
+<p id="footer">npm-folders — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-global — npm@2.4.1</p>
+<p id="footer">npm-global — npm@2.5.1</p>
<p>For example:</p>
<pre><code>{
"name": "tea-latte",
- "version": "1.3.5"
+ "version": "1.3.5",
"peerDependencies": {
"tea": "2.x"
}
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-json — npm@2.4.1</p>
+<p id="footer">npm-json — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npmrc — npm@2.4.1</p>
+<p id="footer">npmrc — npm@2.5.1</p>
<p>For example:</p>
<pre><code>{
"name": "tea-latte",
- "version": "1.3.5"
+ "version": "1.3.5",
"peerDependencies": {
"tea": "2.x"
}
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">package.json — npm@2.4.1</p>
+<p id="footer">package.json — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">index — npm@2.4.1</p>
+<p id="footer">index — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-coding-style — npm@2.4.1</p>
+<p id="footer">npm-coding-style — npm@2.5.1</p>
<li><code>-m</code>: <code>--message</code></li>
<li><code>-p</code>, <code>--porcelain</code>: <code>--parseable</code></li>
<li><code>-reg</code>: <code>--registry</code></li>
-<li><code>-v</code>: <code>--version</code></li>
<li><code>-f</code>: <code>--force</code></li>
<li><code>-desc</code>: <code>--description</code></li>
<li><code>-S</code>: <code>--save</code></li>
<p>The value <code>npm init</code> should use by default for the package license.</p>
<h3 id="init-version">init-version</h3>
<ul>
-<li>Default: "0.0.0"</li>
+<li>Default: "1.0.0"</li>
<li>Type: semver</li>
</ul>
<p>The value that <code>npm init</code> should use by default for the package
</ul>
<p>Configure how versions of packages installed to a package.json file via
<code>--save</code> or <code>--save-dev</code> get prefixed.</p>
-<p>For example if a package has version <code>1.2.3</code>, by default it's version is
+<p>For example if a package has version <code>1.2.3</code>, by default its version is
set to <code>^1.2.3</code> which allows minor upgrades for that package, but after
<code>npm config set save-prefix='~'</code> it would be set to <code>~1.2.3</code> which only allows
patch upgrades.</p>
<h2 id="see-also">SEE ALSO</h2>
<ul>
<li><a href="../cli/npm-config.html"><a href="../cli/npm-config.html">npm-config(1)</a></a></li>
-<li><a href="../misc/npm-config.html"><a href="../misc/npm-config.html">npm-config(7)</a></a></li>
<li><a href="../files/npmrc.html"><a href="../files/npmrc.html">npmrc(5)</a></a></li>
<li><a href="../misc/npm-scripts.html"><a href="../misc/npm-scripts.html">npm-scripts(7)</a></a></li>
<li><a href="../files/npm-folders.html"><a href="../files/npm-folders.html">npm-folders(5)</a></a></li>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-config — npm@2.4.1</p>
+<p id="footer">npm-config — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-developers — npm@2.4.1</p>
+<p id="footer">npm-developers — npm@2.5.1</p>
<h2 id="synopsis">SYNOPSIS</h2>
<ol>
<li>Get the author email with <code>npm owner ls <pkgname></code></li>
-<li>Email the author, CC <a href="mailto:support@npmjs.com">support@npmjs.com</a></li>
+<li>Email the author, CC <a href="mailto:support@npmjs.com">support@npmjs.com</a></li>
<li>After a few weeks, if there's no resolution, we'll sort it out.</li>
</ol>
<p>Don't squat on package names. Publish code or move out of the way.</p>
owner (Bob).</li>
<li>Joe emails Bob, explaining the situation <strong>as respectfully as
possible</strong>, and what he would like to do with the module name. He
-adds the npm support staff <a href="mailto:support@npmjs.com">support@npmjs.com</a> to the CC list of
+adds the npm support staff <a href="mailto:support@npmjs.com">support@npmjs.com</a> to the CC list of
the email. Mention in the email that Bob can run <code>npm owner add
joe foo</code> to add Joe as an owner of the <code>foo</code> package.</li>
<li>After a reasonable amount of time, if Bob has not responded, or if
Bob and Joe can't come to any sort of resolution, email support
-<a href="mailto:support@npmjs.com">support@npmjs.com</a> and we'll sort it out. ("Reasonable" is
+<a href="mailto:support@npmjs.com">support@npmjs.com</a> and we'll sort it out. ("Reasonable" is
usually at least 4 weeks, but extra time is allowed around common
holidays.)</li>
</ol>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-disputes — npm@2.4.1</p>
+<p id="footer">npm-disputes — npm@2.5.1</p>
<p>To check if the registry is down, open up
<a href="https://registry.npmjs.org/">https://registry.npmjs.org/</a> in a web browser. This will also tell
you if you are just unable to access the internet for some reason.</p>
-<p>If the registry IS down, let us know by emailing <a href="mailto:support@npmjs.com">support@npmjs.com</a>
+<p>If the registry IS down, let us know by emailing <a href="mailto:support@npmjs.com">support@npmjs.com</a>
or posting an issue at <a href="https://github.com/npm/npm/issues">https://github.com/npm/npm/issues</a>. If it's
down for the world (and not just on your local network) then we're
probably already being pinged about it.</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-faq — npm@2.4.1</p>
+<p id="footer">npm-faq — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-index — npm@2.4.1</p>
+<p id="footer">npm-index — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-registry — npm@2.4.1</p>
+<p id="footer">npm-registry — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-scope — npm@2.4.1</p>
+<p id="footer">npm-scope — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">npm-scripts — npm@2.4.1</p>
+<p id="footer">npm-scripts — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">removing-npm — npm@2.4.1</p>
+<p id="footer">removing-npm — npm@2.5.1</p>
<tr><td style="width:60px;height:10px;background:rgb(237,127,127)" colspan=6> </td><td colspan=10 style="width:10px;height:10px;background:rgb(237,127,127)"> </td></tr>
<tr><td colspan=5 style="width:50px;height:10px;background:#fff"> </td><td style="width:40px;height:10px;background:rgb(237,127,127)" colspan=4> </td><td style="width:90px;height:10px;background:#fff" colspan=9> </td></tr>
</table>
-<p id="footer">semver — npm@2.4.1</p>
+<p id="footer">semver — npm@2.5.1</p>
<p>If you have a complaint about a package in the public npm registry,
and cannot <a href="https://docs.npmjs.com/misc/disputes">resolve it with the package
owner</a>, please email
-<a href="mailto:support@npmjs.com">support@npmjs.com</a> and explain the situation.</p>
+<a href="mailto:support@npmjs.com">support@npmjs.com</a> and explain the situation.</p>
<p>Any data published to The npm Registry (including user account
information) may be removed or modified at the sole discretion of the
npm server administrators.</p>
npm.commands.install(["package"], cb)
})
</code></pre><h2 id="version">VERSION</h2>
-<p>2.4.1</p>
+<p>2.5.1</p>
<h2 id="description">DESCRIPTION</h2>
<p>This is the API documentation for npm.
To find documentation of the command line
limit the results to only the paths to the packages named. Note that
nested packages will <em>also</em> show the paths to the specified packages.
For example, running <code>npm ls promzard</code> in npm's source tree will show:</p>
-<pre><code>npm@2.4.1 /path/to/npm
+<pre><code>npm@2.5.1 /path/to/npm
└─┬ init-package-json@0.0.4
└── promzard@0.1.5
</code></pre><p>It will print out extraneous, missing, and invalid packages.</p>
"version": "0.0.1",
"dependencies": {
"C": {
- "version": "0.1.0"
+ "version": "0.0.1"
}
}
}
root, the shrinkwrap file (rather than package.json files) completely
drives the installation of that package and all of its dependencies
(recursively). So now the author publishes A@0.1.0, and subsequent
-installs of this package will use B@0.0.1 and C@0.1.0, regardless the
+installs of this package will use B@0.0.1 and C@0.0.1, regardless the
dependencies and versions listed in A's, B's, and C's package.json
files.</p>
<h3 id="using-shrinkwrapped-packages">Using shrinkwrapped packages</h3>
<h2 id="synopsis">SYNOPSIS</h2>
<pre><code>npm <command> [args]
</code></pre><h2 id="version">VERSION</h2>
-<p>2.4.1</p>
+<p>2.5.1</p>
<h2 id="description">DESCRIPTION</h2>
<p>npm is the package manager for the Node JavaScript platform. It puts
modules in place so that node can find them, and manages dependency
the issues list or ask on the mailing list.</p>
<ul>
<li><a href="http://github.com/npm/npm/issues">http://github.com/npm/npm/issues</a></li>
-<li><a href="mailto:npm-@googlegroups.com">npm-@googlegroups.com</a></li>
+<li><a href="mailto:npm-@googlegroups.com">npm-@googlegroups.com</a></li>
</ul>
<h2 id="bugs">BUGS</h2>
<p>When you find issues, please report them:</p>
<li>web:
<a href="http://github.com/npm/npm/issues">http://github.com/npm/npm/issues</a></li>
<li>email:
-<a href="mailto:npm-@googlegroups.com">npm-@googlegroups.com</a></li>
+<a href="mailto:npm-@googlegroups.com">npm-@googlegroups.com</a></li>
</ul>
<p>Be sure to include <em>all</em> of the output from the npm command that didn't work
as expected. The <code>npm-debug.log</code> file is also helpful to provide.</p>
<p><a href="http://blog.izs.me/">Isaac Z. Schlueter</a> ::
<a href="https://github.com/isaacs/">isaacs</a> ::
<a href="http://twitter.com/izs">@izs</a> ::
-<a href="mailto:i@izs.me">i@izs.me</a></p>
+<a href="mailto:i@izs.me">i@izs.me</a></p>
<h2 id="see-also">SEE ALSO</h2>
<ul>
<li><a href="../cli/npm-help.html">npm-help(1)</a></li>
<p>For example:</p>
<pre><code>{
"name": "tea-latte",
- "version": "1.3.5"
+ "version": "1.3.5",
"peerDependencies": {
"tea": "2.x"
}
<p>For example:</p>
<pre><code>{
"name": "tea-latte",
- "version": "1.3.5"
+ "version": "1.3.5",
"peerDependencies": {
"tea": "2.x"
}
<li><code>-m</code>: <code>--message</code></li>
<li><code>-p</code>, <code>--porcelain</code>: <code>--parseable</code></li>
<li><code>-reg</code>: <code>--registry</code></li>
-<li><code>-v</code>: <code>--version</code></li>
<li><code>-f</code>: <code>--force</code></li>
<li><code>-desc</code>: <code>--description</code></li>
<li><code>-S</code>: <code>--save</code></li>
<p>The value <code>npm init</code> should use by default for the package license.</p>
<h3 id="init-version">init-version</h3>
<ul>
-<li>Default: "0.0.0"</li>
+<li>Default: "1.0.0"</li>
<li>Type: semver</li>
</ul>
<p>The value that <code>npm init</code> should use by default for the package
</ul>
<p>Configure how versions of packages installed to a package.json file via
<code>--save</code> or <code>--save-dev</code> get prefixed.</p>
-<p>For example if a package has version <code>1.2.3</code>, by default it's version is
+<p>For example if a package has version <code>1.2.3</code>, by default its version is
set to <code>^1.2.3</code> which allows minor upgrades for that package, but after
<code>npm config set save-prefix='~'</code> it would be set to <code>~1.2.3</code> which only allows
patch upgrades.</p>
<h2 id="see-also">SEE ALSO</h2>
<ul>
<li><a href="../cli/npm-config.html">npm-config(1)</a></li>
-<li><a href="../misc/npm-config.html">npm-config(7)</a></li>
<li><a href="../files/npmrc.html">npmrc(5)</a></li>
<li><a href="../misc/npm-scripts.html">npm-scripts(7)</a></li>
<li><a href="../files/npm-folders.html">npm-folders(5)</a></li>
<h2 id="synopsis">SYNOPSIS</h2>
<ol>
<li>Get the author email with <code>npm owner ls <pkgname></code></li>
-<li>Email the author, CC <a href="mailto:support@npmjs.com">support@npmjs.com</a></li>
+<li>Email the author, CC <a href="mailto:support@npmjs.com">support@npmjs.com</a></li>
<li>After a few weeks, if there's no resolution, we'll sort it out.</li>
</ol>
<p>Don't squat on package names. Publish code or move out of the way.</p>
owner (Bob).</li>
<li>Joe emails Bob, explaining the situation <strong>as respectfully as
possible</strong>, and what he would like to do with the module name. He
-adds the npm support staff <a href="mailto:support@npmjs.com">support@npmjs.com</a> to the CC list of
+adds the npm support staff <a href="mailto:support@npmjs.com">support@npmjs.com</a> to the CC list of
the email. Mention in the email that Bob can run <code>npm owner add
joe foo</code> to add Joe as an owner of the <code>foo</code> package.</li>
<li>After a reasonable amount of time, if Bob has not responded, or if
Bob and Joe can't come to any sort of resolution, email support
-<a href="mailto:support@npmjs.com">support@npmjs.com</a> and we'll sort it out. ("Reasonable" is
+<a href="mailto:support@npmjs.com">support@npmjs.com</a> and we'll sort it out. ("Reasonable" is
usually at least 4 weeks, but extra time is allowed around common
holidays.)</li>
</ol>
<p>To check if the registry is down, open up
<a href="https://registry.npmjs.org/">https://registry.npmjs.org/</a> in a web browser. This will also tell
you if you are just unable to access the internet for some reason.</p>
-<p>If the registry IS down, let us know by emailing <a href="mailto:support@npmjs.com">support@npmjs.com</a>
+<p>If the registry IS down, let us know by emailing <a href="mailto:support@npmjs.com">support@npmjs.com</a>
or posting an issue at <a href="https://github.com/npm/npm/issues">https://github.com/npm/npm/issues</a>. If it's
down for the world (and not just on your local network) then we're
probably already being pinged about it.</p>
}
defaults = {
- access : "restricted"
+ access : null
, "always-auth" : false
, "bin-links" : true
}})
exports.types =
- { access : ["restricted", "public"]
+ { access : [null, "restricted", "public"]
, "always-auth" : Boolean
, "bin-links": Boolean
, browser : [null, String]
, prefix: path
, production: Boolean
, "proprietary-attribs": Boolean
- , proxy : [null, url]
+ , proxy : [null, false, url] // allow proxy to be disabled explicitly
, "rebuild-bundle" : Boolean
, registry : [null, url]
, rollback : Boolean
, mapToRegistry = require("./utils/map-to-registry.js")
, npa = require("npm-package-arg")
, readInstalled = require("read-installed")
+ , long = npm.config.get("long")
function outdated (args, silent, cb) {
if (typeof cb !== "function") cb = silent, silent = false
console.log(makeParseable(list))
} else {
var outList = list.map(makePretty)
- var outTable = [[ "Package"
- , "Current"
- , "Wanted"
- , "Latest"
- , "Location"
- ]].concat(outList)
+ var outHead = [ "Package"
+ , "Current"
+ , "Wanted"
+ , "Latest"
+ , "Location"
+ ]
+ if (long) outHead.push("Package Type")
+ var outTable = [outHead].concat(outList)
if (npm.color) {
outTable[0] = outTable[0].map(function(heading) {
})
}
-// [[ dir, dep, has, want, latest ]]
+// [[ dir, dep, has, want, latest, type ]]
function makePretty (p) {
var dep = p[1]
, dir = path.resolve(p[0], "node_modules", dep)
, has = p[2]
, want = p[3]
, latest = p[4]
+ , type = p[6]
if (!npm.config.get("global")) {
dir = path.relative(process.cwd(), dir)
, latest
, dirToPrettyLocation(dir)
]
+ if (long) columns[5] = type
if (npm.color) {
columns[0] = color[has === want ? "yellow" : "red"](columns[0]) // dep
columns[2] = color.green(columns[2]) // want
columns[3] = color.magenta(columns[3]) // latest
columns[4] = color.brightBlack(columns[4]) // dir
+ if (long) columns[5] = color.brightBlack(columns[5]) // type
}
return columns
function makeParseable (list) {
return list.map(function (p) {
+
var dep = p[1]
, dir = path.resolve(p[0], "node_modules", dep)
, has = p[2]
, want = p[3]
, latest = p[4]
+ , type = p[6]
- return [ dir
+ var out = [ dir
, dep + "@" + want
, (has ? (dep + "@" + has) : "MISSING")
, dep + "@" + latest
- ].join(":")
+ ]
+ if (long) out.push(type)
+
+ return out.join(":")
}).join(os.EOL)
}
, latest: p[4]
, location: dir
}
+ if (long) out[p[1]].type = p[6]
})
return JSON.stringify(out, null, 2)
}
return cb(null, [])
}
var deps = null
+ var types = {}
readJson(path.resolve(dir, "package.json"), function (er, d) {
d = d || {}
if (er && er.code !== "ENOENT" && er.code !== "ENOTDIR") return cb(er)
deps = (er) ? true : (d.dependencies || {})
+ if (!er) {
+ Object.keys(deps).forEach(function (k) {
+ types[k] = "dependencies"
+ })
+ }
if (npm.config.get("save-dev")) {
deps = d.devDependencies || {}
+ Object.keys(deps).forEach(function (k) {
+ types[k] = "devDependencies"
+ })
+
return next()
}
if (npm.config.get("save-optional")) {
deps = d.optionalDependencies || {}
+ Object.keys(deps).forEach(function (k) {
+ types[k] = "optionalDependencies"
+ })
return next()
}
Object.keys(d.devDependencies || {}).forEach(function (k) {
if (!(k in parentHas)) {
deps[k] = d.devDependencies[k]
+ types[k] = "devDependencies"
}
})
}
// if has[dep] !== shouldHave[dep], then cb with the data
// otherwise dive into the folder
asyncMap(Object.keys(deps), function (dep, cb) {
- shouldUpdate(args, dir, dep, has, deps[dep], depth, cb)
+ if (!long) return shouldUpdate(args, dir, dep, has, deps[dep], depth, cb)
+
+ shouldUpdate(args, dir, dep, has, deps[dep], depth, cb, types[dep])
}, cb)
}
}
-function shouldUpdate (args, dir, dep, has, req, depth, cb) {
+function shouldUpdate (args, dir, dep, has, req, depth, cb, type) {
// look up the most recent version.
// if that's what we already have, or if it's not on the args list,
// then dive into it. Otherwise, cb() with the data.
}
function doIt (wanted, latest) {
- cb(null, [[ dir, dep, curr && curr.version, wanted, latest, req ]])
- }
-
- if (args.length && args.indexOf(dep) === -1) {
- return skip()
+ if (!long) {
+ return cb(null, [[ dir, dep, curr && curr.version, wanted, latest, req]])
+ }
+ cb(null, [[ dir, dep, curr && curr.version, wanted, latest, req, type]])
}
- if (npa(req).type === "git")
- return doIt("git", "git")
+ if (args.length && args.indexOf(dep) === -1) return skip()
+ if (npa(req).type === "git") return doIt("git", "git")
// search for the latest package
mapToRegistry(dep, npm.config, function (er, uri, auth) {
if (!curr || dFromUrl && cFromUrl && d._from !== curr.from
|| d.version !== curr.version
- || d.version !== l.version)
+ || d.version !== l.version) {
doIt(d.version, l.version)
- else
+ }
+ else {
skip()
+ }
}
}
}
// registry-frontdoor cares about the access level, which is only
// configurable for scoped packages
- if (npa(data.name).scope) {
+ if (config.get("access")) {
+ if (!npa(data.name).scope && config.get("access") === "restricted") {
+ return cb(new Error("Can't restrict access to unscoped packages."))
+ }
+
params.access = config.get("access")
}
- else {
- params.access = "public"
- }
registry.publish(registryBase, params, function (er) {
if (er && er.code === "EPUBLISHCONFLICT" &&
-.TH "NPM" "1" "January 2015" "" ""
+.TH "NPM" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm\fR \- a JavaScript package manager
.P
-.TH "NPM\-ACCESS" "1" "January 2015" "" ""
+.TH "NPM\-ACCESS" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-access\fR \- Set access level on published packages
.SH SYNOPSIS
-.TH "NPM\-ADDUSER" "1" "January 2015" "" ""
+.TH "NPM\-ADDUSER" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-adduser\fR \- Add a registry user account
.SH SYNOPSIS
-.TH "NPM\-BIN" "1" "January 2015" "" ""
+.TH "NPM\-BIN" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-bin\fR \- Display npm bin folder
.SH SYNOPSIS
-.TH "NPM\-BUGS" "1" "January 2015" "" ""
+.TH "NPM\-BUGS" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-bugs\fR \- Bugs for a package in a web browser maybe
.SH SYNOPSIS
-.TH "NPM\-BUILD" "1" "January 2015" "" ""
+.TH "NPM\-BUILD" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-build\fR \- Build a package
.SH SYNOPSIS
-.TH "NPM\-BUNDLE" "1" "January 2015" "" ""
+.TH "NPM\-BUNDLE" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-bundle\fR \- REMOVED
.SH DESCRIPTION
-.TH "NPM\-CACHE" "1" "January 2015" "" ""
+.TH "NPM\-CACHE" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-cache\fR \- Manipulates packages cache
.SH SYNOPSIS
-.TH "NPM\-COMPLETION" "1" "January 2015" "" ""
+.TH "NPM\-COMPLETION" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-completion\fR \- Tab Completion for npm
.SH SYNOPSIS
-.TH "NPM\-CONFIG" "1" "January 2015" "" ""
+.TH "NPM\-CONFIG" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-config\fR \- Manage the npm configuration files
.SH SYNOPSIS
-.TH "NPM\-DEDUPE" "1" "January 2015" "" ""
+.TH "NPM\-DEDUPE" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-dedupe\fR \- Reduce duplication
.SH SYNOPSIS
-.TH "NPM\-DEPRECATE" "1" "January 2015" "" ""
+.TH "NPM\-DEPRECATE" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-deprecate\fR \- Deprecate a version of a package
.SH SYNOPSIS
-.TH "NPM\-DIST\-TAG" "1" "January 2015" "" ""
+.TH "NPM\-DIST\-TAG" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-dist-tag\fR \- Modify package distribution tags
.SH SYNOPSIS
-.TH "NPM\-DOCS" "1" "January 2015" "" ""
+.TH "NPM\-DOCS" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-docs\fR \- Docs for a package in a web browser maybe
.SH SYNOPSIS
-.TH "NPM\-EDIT" "1" "January 2015" "" ""
+.TH "NPM\-EDIT" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-edit\fR \- Edit an installed package
.SH SYNOPSIS
-.TH "NPM\-EXPLORE" "1" "January 2015" "" ""
+.TH "NPM\-EXPLORE" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-explore\fR \- Browse an installed package
.SH SYNOPSIS
-.TH "NPM\-HELP\-SEARCH" "1" "January 2015" "" ""
+.TH "NPM\-HELP\-SEARCH" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-help-search\fR \- Search npm help documentation
.SH SYNOPSIS
-.TH "NPM\-HELP" "1" "January 2015" "" ""
+.TH "NPM\-HELP" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-help\fR \- Get help on npm
.SH SYNOPSIS
-.TH "NPM\-INIT" "1" "January 2015" "" ""
+.TH "NPM\-INIT" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-init\fR \- Interactively create a package\.json file
.SH SYNOPSIS
-.TH "NPM\-INSTALL" "1" "January 2015" "" ""
+.TH "NPM\-INSTALL" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-install\fR \- Install a package
.SH SYNOPSIS
-.TH "NPM\-LINK" "1" "January 2015" "" ""
+.TH "NPM\-LINK" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-link\fR \- Symlink a package folder
.SH SYNOPSIS
-.TH "NPM\-LS" "1" "January 2015" "" ""
+.TH "NPM\-LS" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-ls\fR \- List installed packages
.SH SYNOPSIS
.P
.RS 2
.nf
-npm@2.4.1 /path/to/npm
+npm@2.5.1 /path/to/npm
└─┬ init\-package\-json@0\.0\.4
└── promzard@0\.1\.5
.fi
-.TH "NPM\-OUTDATED" "1" "January 2015" "" ""
+.TH "NPM\-OUTDATED" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-outdated\fR \- Check for outdated packages
.SH SYNOPSIS
-.TH "NPM\-OWNER" "1" "January 2015" "" ""
+.TH "NPM\-OWNER" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-owner\fR \- Manage package owners
.SH SYNOPSIS
-.TH "NPM\-PACK" "1" "January 2015" "" ""
+.TH "NPM\-PACK" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-pack\fR \- Create a tarball from a package
.SH SYNOPSIS
-.TH "NPM\-PREFIX" "1" "January 2015" "" ""
+.TH "NPM\-PREFIX" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-prefix\fR \- Display prefix
.SH SYNOPSIS
-.TH "NPM\-PRUNE" "1" "January 2015" "" ""
+.TH "NPM\-PRUNE" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-prune\fR \- Remove extraneous packages
.SH SYNOPSIS
-.TH "NPM\-PUBLISH" "1" "January 2015" "" ""
+.TH "NPM\-PUBLISH" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-publish\fR \- Publish a package
.SH SYNOPSIS
-.TH "NPM\-REBUILD" "1" "January 2015" "" ""
+.TH "NPM\-REBUILD" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-rebuild\fR \- Rebuild a package
.SH SYNOPSIS
-.TH "NPM\-REPO" "1" "January 2015" "" ""
+.TH "NPM\-REPO" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-repo\fR \- Open package repository page in the browser
.SH SYNOPSIS
-.TH "NPM\-RESTART" "1" "January 2015" "" ""
+.TH "NPM\-RESTART" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-restart\fR \- Restart a package
.SH SYNOPSIS
-.TH "NPM\-RM" "1" "January 2015" "" ""
+.TH "NPM\-RM" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-rm\fR \- Remove a package
.SH SYNOPSIS
-.TH "NPM\-ROOT" "1" "January 2015" "" ""
+.TH "NPM\-ROOT" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-root\fR \- Display npm root
.SH SYNOPSIS
-.TH "NPM\-RUN\-SCRIPT" "1" "January 2015" "" ""
+.TH "NPM\-RUN\-SCRIPT" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-run-script\fR \- Run arbitrary package scripts
.SH SYNOPSIS
-.TH "NPM\-SEARCH" "1" "January 2015" "" ""
+.TH "NPM\-SEARCH" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-search\fR \- Search for packages
.SH SYNOPSIS
-.TH "NPM\-SHRINKWRAP" "1" "January 2015" "" ""
+.TH "NPM\-SHRINKWRAP" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-shrinkwrap\fR \- Lock down dependency versions
.SH SYNOPSIS
"version": "0\.0\.1",
"dependencies": {
"C": {
- "version": "0\.1\.0"
+ "version": "0\.0\.1"
}
}
}
root, the shrinkwrap file (rather than package\.json files) completely
drives the installation of that package and all of its dependencies
(recursively)\. So now the author publishes A@0\.1\.0, and subsequent
-installs of this package will use B@0\.0\.1 and C@0\.1\.0, regardless the
+installs of this package will use B@0\.0\.1 and C@0\.0\.1, regardless the
dependencies and versions listed in A's, B's, and C's package\.json
files\.
.SS Using shrinkwrapped packages
-.TH "NPM\-STAR" "1" "January 2015" "" ""
+.TH "NPM\-STAR" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-star\fR \- Mark your favorite packages
.SH SYNOPSIS
-.TH "NPM\-STARS" "1" "January 2015" "" ""
+.TH "NPM\-STARS" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-stars\fR \- View packages marked as favorites
.SH SYNOPSIS
-.TH "NPM\-START" "1" "January 2015" "" ""
+.TH "NPM\-START" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-start\fR \- Start a package
.SH SYNOPSIS
-.TH "NPM\-STOP" "1" "January 2015" "" ""
+.TH "NPM\-STOP" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-stop\fR \- Stop a package
.SH SYNOPSIS
-.TH "NPM\-TAG" "1" "January 2015" "" ""
+.TH "NPM\-TAG" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-tag\fR \- Tag a published version
.SH SYNOPSIS
-.TH "NPM\-TEST" "1" "January 2015" "" ""
+.TH "NPM\-TEST" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-test\fR \- Test a package
.SH SYNOPSIS
-.TH "NPM\-RM" "1" "January 2015" "" ""
+.TH "NPM\-RM" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-rm\fR \- Remove a package
.SH SYNOPSIS
-.TH "NPM\-UNPUBLISH" "1" "January 2015" "" ""
+.TH "NPM\-UNPUBLISH" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-unpublish\fR \- Remove a package from the registry
.SH SYNOPSIS
-.TH "NPM\-UPDATE" "1" "January 2015" "" ""
+.TH "NPM\-UPDATE" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-update\fR \- Update a package
.SH SYNOPSIS
-.TH "NPM\-VERSION" "1" "January 2015" "" ""
+.TH "NPM\-VERSION" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-version\fR \- Bump a package version
.SH SYNOPSIS
-.TH "NPM\-VIEW" "1" "January 2015" "" ""
+.TH "NPM\-VIEW" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-view\fR \- View registry info
.SH SYNOPSIS
-.TH "NPM\-WHOAMI" "1" "January 2015" "" ""
+.TH "NPM\-WHOAMI" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-whoami\fR \- Display npm username
.SH SYNOPSIS
-.TH "NPM" "1" "January 2015" "" ""
+.TH "NPM" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm\fR \- javascript package manager
.SH SYNOPSIS
.RE
.SH VERSION
.P
-2.4.1
+2.5.1
.SH DESCRIPTION
.P
npm is the package manager for the Node JavaScript platform\. It puts
-.TH "NPM\-BIN" "3" "January 2015" "" ""
+.TH "NPM\-BIN" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-bin\fR \- Display npm bin folder
.SH SYNOPSIS
-.TH "NPM\-BUGS" "3" "January 2015" "" ""
+.TH "NPM\-BUGS" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-bugs\fR \- Bugs for a package in a web browser maybe
.SH SYNOPSIS
-.TH "NPM\-CACHE" "3" "January 2015" "" ""
+.TH "NPM\-CACHE" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-cache\fR \- manage the npm cache programmatically
.SH SYNOPSIS
-.TH "NPM\-COMMANDS" "3" "January 2015" "" ""
+.TH "NPM\-COMMANDS" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-commands\fR \- npm commands
.SH SYNOPSIS
-.TH "NPM\-CONFIG" "3" "January 2015" "" ""
+.TH "NPM\-CONFIG" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-config\fR \- Manage the npm configuration files
.SH SYNOPSIS
-.TH "NPM\-DEPRECATE" "3" "January 2015" "" ""
+.TH "NPM\-DEPRECATE" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-deprecate\fR \- Deprecate a version of a package
.SH SYNOPSIS
-.TH "NPM\-DOCS" "3" "January 2015" "" ""
+.TH "NPM\-DOCS" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-docs\fR \- Docs for a package in a web browser maybe
.SH SYNOPSIS
-.TH "NPM\-EDIT" "3" "January 2015" "" ""
+.TH "NPM\-EDIT" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-edit\fR \- Edit an installed package
.SH SYNOPSIS
-.TH "NPM\-EXPLORE" "3" "January 2015" "" ""
+.TH "NPM\-EXPLORE" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-explore\fR \- Browse an installed package
.SH SYNOPSIS
-.TH "NPM\-HELP\-SEARCH" "3" "January 2015" "" ""
+.TH "NPM\-HELP\-SEARCH" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-help-search\fR \- Search the help pages
.SH SYNOPSIS
-.TH "NPM" "" "January 2015" "" ""
+.TH "NPM" "" "February 2015" "" ""
.SH "NAME"
\fBnpm\fR
.SH SYNOPSIS
-.TH "NPM\-INSTALL" "3" "January 2015" "" ""
+.TH "NPM\-INSTALL" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-install\fR \- install a package programmatically
.SH SYNOPSIS
-.TH "NPM\-LINK" "3" "January 2015" "" ""
+.TH "NPM\-LINK" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-link\fR \- Symlink a package folder
.SH SYNOPSIS
-.TH "NPM\-LOAD" "3" "January 2015" "" ""
+.TH "NPM\-LOAD" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-load\fR \- Load config settings
.SH SYNOPSIS
-.TH "NPM\-LS" "3" "January 2015" "" ""
+.TH "NPM\-LS" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-ls\fR \- List installed packages
.SH SYNOPSIS
-.TH "NPM\-OUTDATED" "3" "January 2015" "" ""
+.TH "NPM\-OUTDATED" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-outdated\fR \- Check for outdated packages
.SH SYNOPSIS
-.TH "NPM\-OWNER" "3" "January 2015" "" ""
+.TH "NPM\-OWNER" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-owner\fR \- Manage package owners
.SH SYNOPSIS
-.TH "NPM\-PACK" "3" "January 2015" "" ""
+.TH "NPM\-PACK" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-pack\fR \- Create a tarball from a package
.SH SYNOPSIS
-.TH "NPM\-PREFIX" "3" "January 2015" "" ""
+.TH "NPM\-PREFIX" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-prefix\fR \- Display prefix
.SH SYNOPSIS
-.TH "NPM\-PRUNE" "3" "January 2015" "" ""
+.TH "NPM\-PRUNE" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-prune\fR \- Remove extraneous packages
.SH SYNOPSIS
-.TH "NPM\-PUBLISH" "3" "January 2015" "" ""
+.TH "NPM\-PUBLISH" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-publish\fR \- Publish a package
.SH SYNOPSIS
-.TH "NPM\-REBUILD" "3" "January 2015" "" ""
+.TH "NPM\-REBUILD" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-rebuild\fR \- Rebuild a package
.SH SYNOPSIS
-.TH "NPM\-REPO" "3" "January 2015" "" ""
+.TH "NPM\-REPO" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-repo\fR \- Open package repository page in the browser
.SH SYNOPSIS
-.TH "NPM\-RESTART" "3" "January 2015" "" ""
+.TH "NPM\-RESTART" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-restart\fR \- Restart a package
.SH SYNOPSIS
-.TH "NPM\-ROOT" "3" "January 2015" "" ""
+.TH "NPM\-ROOT" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-root\fR \- Display npm root
.SH SYNOPSIS
-.TH "NPM\-RUN\-SCRIPT" "3" "January 2015" "" ""
+.TH "NPM\-RUN\-SCRIPT" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-run-script\fR \- Run arbitrary package scripts
.SH SYNOPSIS
-.TH "NPM\-SEARCH" "3" "January 2015" "" ""
+.TH "NPM\-SEARCH" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-search\fR \- Search for packages
.SH SYNOPSIS
-.TH "NPM\-SHRINKWRAP" "3" "January 2015" "" ""
+.TH "NPM\-SHRINKWRAP" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-shrinkwrap\fR \- programmatically generate package shrinkwrap file
.SH SYNOPSIS
-.TH "NPM\-START" "3" "January 2015" "" ""
+.TH "NPM\-START" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-start\fR \- Start a package
.SH SYNOPSIS
-.TH "NPM\-STOP" "3" "January 2015" "" ""
+.TH "NPM\-STOP" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-stop\fR \- Stop a package
.SH SYNOPSIS
-.TH "NPM\-TAG" "3" "January 2015" "" ""
+.TH "NPM\-TAG" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-tag\fR \- Tag a published version
.SH SYNOPSIS
-.TH "NPM\-TEST" "3" "January 2015" "" ""
+.TH "NPM\-TEST" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-test\fR \- Test a package
.SH SYNOPSIS
-.TH "NPM\-UNINSTALL" "3" "January 2015" "" ""
+.TH "NPM\-UNINSTALL" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-uninstall\fR \- uninstall a package programmatically
.SH SYNOPSIS
-.TH "NPM\-UNPUBLISH" "3" "January 2015" "" ""
+.TH "NPM\-UNPUBLISH" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-unpublish\fR \- Remove a package from the registry
.SH SYNOPSIS
-.TH "NPM\-UPDATE" "3" "January 2015" "" ""
+.TH "NPM\-UPDATE" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-update\fR \- Update a package
.SH SYNOPSIS
npm\.commands\.update(packages, callback)
.fi
.RE
-.TH "DESCRIPTION" "" "January 2015" "" ""
+.TH "DESCRIPTION" "" "February 2015" "" ""
.SH "NAME"
\fBDESCRIPTION\fR
.P
-.TH "NPM\-VERSION" "3" "January 2015" "" ""
+.TH "NPM\-VERSION" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-version\fR \- Bump a package version
.SH SYNOPSIS
-.TH "NPM\-VIEW" "3" "January 2015" "" ""
+.TH "NPM\-VIEW" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-view\fR \- View registry info
.SH SYNOPSIS
-.TH "NPM\-WHOAMI" "3" "January 2015" "" ""
+.TH "NPM\-WHOAMI" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm-whoami\fR \- Display npm username
.SH SYNOPSIS
-.TH "NPM" "3" "January 2015" "" ""
+.TH "NPM" "3" "February 2015" "" ""
.SH "NAME"
\fBnpm\fR \- javascript package manager
.SH SYNOPSIS
.RE
.SH VERSION
.P
-2.4.1
+2.5.1
.SH DESCRIPTION
.P
This is the API documentation for npm\.
-.TH "NPM\-FOLDERS" "5" "January 2015" "" ""
+.TH "NPM\-FOLDERS" "5" "February 2015" "" ""
.SH "NAME"
\fBnpm-folders\fR \- Folder Structures Used by npm
.SH DESCRIPTION
-.TH "NPM\-FOLDERS" "5" "January 2015" "" ""
+.TH "NPM\-FOLDERS" "5" "February 2015" "" ""
.SH "NAME"
\fBnpm-folders\fR \- Folder Structures Used by npm
.SH DESCRIPTION
-.TH "PACKAGE\.JSON" "5" "January 2015" "" ""
+.TH "PACKAGE\.JSON" "5" "February 2015" "" ""
.SH "NAME"
\fBpackage.json\fR \- Specifics of npm's package\.json handling
.SH DESCRIPTION
.nf
{
"name": "tea\-latte",
- "version": "1\.3\.5"
+ "version": "1\.3\.5",
"peerDependencies": {
"tea": "2\.x"
}
-.TH "NPMRC" "5" "January 2015" "" ""
+.TH "NPMRC" "5" "February 2015" "" ""
.SH "NAME"
\fBnpmrc\fR \- The npm config files
.SH DESCRIPTION
-.TH "PACKAGE\.JSON" "5" "January 2015" "" ""
+.TH "PACKAGE\.JSON" "5" "February 2015" "" ""
.SH "NAME"
\fBpackage.json\fR \- Specifics of npm's package\.json handling
.SH DESCRIPTION
.nf
{
"name": "tea\-latte",
- "version": "1\.3\.5"
+ "version": "1\.3\.5",
"peerDependencies": {
"tea": "2\.x"
}
-.TH "NPM\-CODING\-STYLE" "7" "January 2015" "" ""
+.TH "NPM\-CODING\-STYLE" "7" "February 2015" "" ""
.SH "NAME"
\fBnpm-coding-style\fR \- npm's "funny" coding style
.SH DESCRIPTION
-.TH "NPM\-CONFIG" "7" "January 2015" "" ""
+.TH "NPM\-CONFIG" "7" "February 2015" "" ""
.SH "NAME"
\fBnpm-config\fR \- More than you probably want to know about npm configuration
.SH DESCRIPTION
.IP \(bu 2
\fB\-reg\fR: \fB\-\-registry\fR
.IP \(bu 2
-\fB\-v\fR: \fB\-\-version\fR
-.IP \(bu 2
\fB\-f\fR: \fB\-\-force\fR
.IP \(bu 2
\fB\-desc\fR: \fB\-\-description\fR
.SS init\-version
.RS 0
.IP \(bu 2
-Default: "0\.0\.0"
+Default: "1\.0\.0"
.IP \(bu 2
Type: semver
Configure how versions of packages installed to a package\.json file via
\fB\-\-save\fR or \fB\-\-save\-dev\fR get prefixed\.
.P
-For example if a package has version \fB1\.2\.3\fR, by default it's version is
+For example if a package has version \fB1\.2\.3\fR, by default its version is
set to \fB^1\.2\.3\fR which allows minor upgrades for that package, but after
\fBnpm config set save\-prefix='~'\fR it would be set to \fB~1\.2\.3\fR which only allows
patch upgrades\.
.IP \(bu 2
npm help config
.IP \(bu 2
-npm help 7 config
-.IP \(bu 2
npm help 5 npmrc
.IP \(bu 2
npm help 7 scripts
-.TH "NPM\-DEVELOPERS" "7" "January 2015" "" ""
+.TH "NPM\-DEVELOPERS" "7" "February 2015" "" ""
.SH "NAME"
\fBnpm-developers\fR \- Developer Guide
.SH DESCRIPTION
-.TH "NPM\-DISPUTES" "7" "January 2015" "" ""
+.TH "NPM\-DISPUTES" "7" "February 2015" "" ""
.SH "NAME"
\fBnpm-disputes\fR \- Handling Module Name Disputes
.SH SYNOPSIS
-.TH "NPM\-FAQ" "7" "January 2015" "" ""
+.TH "NPM\-FAQ" "7" "February 2015" "" ""
.SH "NAME"
\fBnpm-faq\fR \- Frequently Asked Questions
.SH Where can I find these docs in HTML?
-.TH "NPM\-INDEX" "7" "January 2015" "" ""
+.TH "NPM\-INDEX" "7" "February 2015" "" ""
.SH "NAME"
\fBnpm-index\fR \- Index of all npm documentation
.SS npm help README
-.TH "NPM\-REGISTRY" "7" "January 2015" "" ""
+.TH "NPM\-REGISTRY" "7" "February 2015" "" ""
.SH "NAME"
\fBnpm-registry\fR \- The JavaScript Package Registry
.SH DESCRIPTION
-.TH "NPM\-SCOPE" "7" "January 2015" "" ""
+.TH "NPM\-SCOPE" "7" "February 2015" "" ""
.SH "NAME"
\fBnpm-scope\fR \- Scoped packages
.SH DESCRIPTION
-.TH "NPM\-SCRIPTS" "7" "January 2015" "" ""
+.TH "NPM\-SCRIPTS" "7" "February 2015" "" ""
.SH "NAME"
\fBnpm-scripts\fR \- How npm handles the "scripts" field
.SH DESCRIPTION
-.TH "NPM\-REMOVAL" "1" "January 2015" "" ""
+.TH "NPM\-REMOVAL" "1" "February 2015" "" ""
.SH "NAME"
\fBnpm-removal\fR \- Cleaning the Slate
.SH SYNOPSIS
-.TH "SEMVER" "7" "January 2015" "" ""
+.TH "SEMVER" "7" "February 2015" "" ""
.SH "NAME"
\fBsemver\fR \- The semantic versioner for npm
.SH Usage
--- /dev/null
+
+all: columnify.js
+
+prepublish: all
+
+columnify.js: index.js package.json
+ 6to5 index.js > columnify.js
+
+.PHONY: all prepublish
# columnify
[![Build Status](https://travis-ci.org/timoxley/columnify.png?branch=master)](https://travis-ci.org/timoxley/columnify)
+[![NPM Version](https://img.shields.io/npm/v/columnify.svg?style=flat)](https://npmjs.org/package/columnify)
+[![License](http://img.shields.io/npm/l/columnify.svg?style=flat)](LICENSE)
+[![Dependency Status](https://david-dm.org/timoxley/columnify.svg)](https://david-dm.org/timoxley/columnify)
+[![devDependency Status](https://david-dm.org/timoxley/columnify/dev-status.svg)](https://david-dm.org/timoxley/columnify#info=devDependencies)
Create text-based columns suitable for console output from objects or
arrays of objects.
Objects are converted to a list of key/value pairs:
```javascript
-
var data = {
"commander@0.6.1": 1,
"minimatch@0.2.14": 3,
module2 0.2.0
```
-### Wrapping Column Cells
+### Filtering & Ordering Columns
-You can define the maximum width before wrapping for individual cells in
-columns. Minimum width is also supported. Wrapping will happen at word
-boundaries. Empty cells or those which do not fill the max/min width
-will be padded with spaces.
+By default, all properties are converted into columns, whether or not
+they exist on every object or not.
+
+To explicitly specify which columns to include, and in which order,
+supply a "columns" or "include" array ("include" is just an alias).
```javascript
+var data = [{
+ name: 'module1',
+ description: 'some description',
+ version: '0.0.1',
+}, {
+ name: 'module2',
+ description: 'another description',
+ version: '0.2.0',
+}]
+var columns = columnify(data, {
+ columns: ['name', 'version']
+})
+
+console.log(columns)
+```
+
+#### Output:
+```
+NAME VERSION
+module1 0.0.1
+module2 0.2.0
+```
+
+## Global and Per Column Options
+You can set a number of options at a global level (ie. for all columns) or on a per column basis.
+
+Set options on a per column basis by using the `config` option to specify individual columns:
+
+```javascript
+var columns = columnify(data, {
+ optionName: optionValue,
+ config: {
+ columnName: {optionName: optionValue},
+ columnName: {optionName: optionValue},
+ }
+})
+```
+
+### Maximum and Minimum Column Widths
+As with all options, you can define the `maxWidth` and `minWidth` globally, or for specified columns. By default, wrapping will happen at word boundaries. Empty cells or those which do not fill the `minWidth` will be padded with spaces.
+
+```javascript
var columns = columnify([{
name: 'mod1',
description: 'some description which happens to be far larger than the max',
name: 'module-two',
description: 'another description larger than the max',
version: '0.2.0',
+}], {
+ minWidth: 20,
+ config: {
+ description: {maxWidth: 30}
+ }
})
console.log(columns)
```
+
#### Output:
```
-NAME DESCRIPTION VERSION
-mod1 some description which happens 0.0.1
- to be far larger than the max
-module-two another description larger 0.2.0
- than the max
+NAME DESCRIPTION VERSION
+mod1 some description which happens 0.0.1
+ to be far larger than the max
+module-two another description larger 0.2.0
+ than the max
```
-### Truncating Column Cells
+#### Maximum Line Width
+
+You can set a hard maximum line width using the `maxLineWidth` option.
+Beyond this value data is unceremoniously truncated with no truncation
+marker.
+
+This can either be a number or 'auto' to set the value to the width of
+stdout.
+
+Setting this value to 'auto' prevent TTY-imposed line-wrapping when
+lines exceed the screen width.
+
+#### Truncating Column Cells Instead of Wrapping
You can disable wrapping and instead truncate content at the maximum
-column width. Truncation respects word boundaries. A truncation marker,
-`…` will appear next to the last word in any truncated line.
+column width by using the `truncate` option. Truncation respects word boundaries. A truncation marker, `…`, will appear next to the last word in any truncated line.
```javascript
var columns = columnify(data, {
module-two another description… 0.2.0
```
-### Filtering & Ordering Columns
-
-By default, all properties are converted into columns, whether or not
-they exist on every object or not.
-
-To explicitly specify which columns to include, and in which order,
-supply a "columns" or "include" array ("include" is just an alias).
-
-```javascript
-var data = [{
- name: 'module1',
- description: 'some description',
- version: '0.0.1',
-}, {
- name: 'module2',
- description: 'another description',
- version: '0.2.0',
-}]
-
-var columns = columnify(data, {
- columns: ['name', 'version'] // note description not included
-})
-
-console.log(columns)
-```
-
-#### Output:
-```
-NAME VERSION
-module1 0.0.1
-module2 0.2.0
-```
-
-
-## Other Configuration Options
### Align Right/Center
+You can set the alignment of the column data by using the `align` option.
```js
var data = {
debug@0.8.1 1
```
-Align Center works in a similar way.
+`align: 'center'` works in a similar way.
+
+### Padding Character
-### Padding
+Set a character to fill whitespace within columns with the `paddingChr` option.
```js
var data = {
veryVeryVeryVeryVeryLongKey shortVal...................
```
-### Preserve existing newlines
+### Preserve Existing Newlines
By default, `columnify` sanitises text by replacing any occurance of 1 or more whitespace characters with a single space.
### Custom Truncation Marker
You can change the truncation marker to something other than the default
-`…`.
+`…` by using the `truncateMarker` option.
```javascript
var columns = columnify(data, {
### Custom Column Splitter
If your columns need some bling, you can split columns with custom
-characters.
+characters by using the `columnSplitter` option.
```javascript
-
var columns = columnify(data, {
columnSplitter: ' | '
})
module-two | another description larger than the max | 0.2.0
```
+### Control Header Display
+
+Control whether column headers are displayed by using the `showHeaders` option.
+
+```javascript
+var columns = columnify(data, {
+ showHeaders: false
+})
+```
+
+### Transforming Column Data and Headers
+If you need to modify the presentation of column content or heading content there are two useful options for doing that: `dataTransform` and `headerTransform`. Both of these take a function and need to return a valid string.
+
+```javascript
+var columns = columnify([{
+ name: 'mod1',
+ description: 'SOME DESCRIPTION TEXT.'
+}, {
+ name: 'module-two',
+ description: 'SOME SLIGHTLY LONGER DESCRIPTION TEXT.'
+}], {
+ dataTransform: function(data) {
+ return data.toLowerCase()
+ },
+ config: {
+ name: {
+ headingTransform: function(heading) {
+ heading = "module " + heading
+ return "*" + heading.toUpperCase() + "*"
+ }
+ }
+ }
+})
+```
+#### Output:
+```
+*MODULE NAME* DESCRIPTION
+mod1 some description text.
+module-two some slightly longer description text.
+```
+
+
## Multibyte Character Support
`columnify` uses [mycoboco/wcwidth.js](https://github.com/mycoboco/wcwidth.js) to calculate length of multibyte characters:
这是一个很长的名字的模块 这真的是一个描述的内容这个描述很长 0.3.3
```
+## Contributions
+
+```
+ project : columnify
+ repo age : 1 year, 2 months
+ active : 32 days
+ commits : 120
+ files : 54
+ authors :
+ 90 Tim Oxley 75.0%
+ 8 Tim 6.7%
+ 7 Arjun Mehta 5.8%
+ 6 Dany 5.0%
+ 5 Wei Gao 4.2%
+ 2 Dany Shaanan 1.7%
+ 1 Seth Miller 0.8%
+ 1 Isaac Z. Schlueter 0.8%
+```
+
## License
MIT
--- /dev/null
+"use strict";
+
+var _toArray = function (arr) { return Array.isArray(arr) ? arr : Array.from(arr); };
+
+var wcwidth = require("./width");
+var _require = require("./utils");
+
+var padRight = _require.padRight;
+var padCenter = _require.padCenter;
+var padLeft = _require.padLeft;
+var splitIntoLines = _require.splitIntoLines;
+var splitLongWords = _require.splitLongWords;
+var truncateString = _require.truncateString;
+
+
+var DEFAULT_HEADING_TRANSFORM = function (key) {
+ return key.toUpperCase();
+};
+
+var DEFAULT_DATA_TRANSFORM = function (cell, column, index) {
+ return cell;
+};
+
+var DEFAULTS = Object.freeze({
+ maxWidth: Infinity,
+ minWidth: 0,
+ columnSplitter: " ",
+ truncate: false,
+ truncateMarker: "…",
+ preserveNewLines: false,
+ paddingChr: " ",
+ showHeaders: true,
+ headingTransform: DEFAULT_HEADING_TRANSFORM,
+ dataTransform: DEFAULT_DATA_TRANSFORM
+});
+
+module.exports = function (items) {
+ var options = arguments[1] === undefined ? {} : arguments[1];
+
+
+ var columnConfigs = options.config || {};
+ delete options.config; // remove config so doesn't appear on every column.
+
+ var maxLineWidth = options.maxLineWidth || Infinity;
+ if (maxLineWidth === "auto") maxLineWidth = process.stdout.columns || Infinity;
+ delete options.maxLineWidth; // this is a line control option, don't pass it to column
+
+ // Option defaults inheritance:
+ // options.config[columnName] => options => DEFAULTS
+ options = mixin({}, DEFAULTS, options);
+
+ options.config = options.config || Object.create(null);
+
+ options.spacing = options.spacing || "\n"; // probably useless
+ options.preserveNewLines = !!options.preserveNewLines;
+ options.showHeaders = !!options.showHeaders;
+ options.columns = options.columns || options.include; // alias include/columns, prefer columns if supplied
+ var columnNames = options.columns || []; // optional user-supplied columns to include
+
+ items = toArray(items, columnNames);
+
+ // if not suppled column names, automatically determine columns from data keys
+ if (!columnNames.length) {
+ items.forEach(function (item) {
+ for (var columnName in item) {
+ if (columnNames.indexOf(columnName) === -1) columnNames.push(columnName);
+ }
+ });
+ }
+
+ // initialize column defaults (each column inherits from options.config)
+ var columns = columnNames.reduce(function (columns, columnName) {
+ var column = Object.create(options);
+ columns[columnName] = mixin(column, columnConfigs[columnName]);
+ return columns;
+ }, Object.create(null));
+
+ // sanitize column settings
+ columnNames.forEach(function (columnName) {
+ var column = columns[columnName];
+ column.name = columnName;
+ column.maxWidth = Math.ceil(column.maxWidth);
+ column.minWidth = Math.ceil(column.minWidth);
+ column.truncate = !!column.truncate;
+ column.align = column.align || "left";
+ });
+
+ // sanitize data
+ items = items.map(function (item) {
+ var result = Object.create(null);
+ columnNames.forEach(function (columnName) {
+ // null/undefined -> ''
+ result[columnName] = item[columnName] != null ? item[columnName] : "";
+ // toString everything
+ result[columnName] = "" + result[columnName];
+ if (columns[columnName].preserveNewLines) {
+ // merge non-newline whitespace chars
+ result[columnName] = result[columnName].replace(/[^\S\n]/gmi, " ");
+ } else {
+ // merge all whitespace chars
+ result[columnName] = result[columnName].replace(/\s/gmi, " ");
+ }
+ });
+ return result;
+ });
+
+ // transform data cells
+ columnNames.forEach(function (columnName) {
+ var column = columns[columnName];
+ items = items.map(function (item, index) {
+ var col = Object.create(column);
+ item[columnName] = column.dataTransform(item[columnName], col, index);
+
+ var changedKeys = Object.keys(col);
+ // disable default heading transform if we wrote to column.name
+ if (changedKeys.indexOf("name") !== -1) {
+ if (column.headingTransform !== DEFAULT_HEADING_TRANSFORM) return;
+ column.headingTransform = function (heading) {
+ return heading;
+ };
+ }
+ changedKeys.forEach(function (key) {
+ return column[key] = col[key];
+ });
+ return item;
+ });
+ });
+
+ // add headers
+ var headers = {};
+ if (options.showHeaders) {
+ columnNames.forEach(function (columnName) {
+ var column = columns[columnName];
+ headers[columnName] = column.headingTransform(column.name);
+ });
+ items.unshift(headers);
+ }
+ // get actual max-width between min & max
+ // based on length of data in columns
+ columnNames.forEach(function (columnName) {
+ var column = columns[columnName];
+ column.width = items.map(function (item) {
+ return item[columnName];
+ }).reduce(function (min, cur) {
+ return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))));
+ }, 0);
+ });
+
+ // split long words so they can break onto multiple lines
+ columnNames.forEach(function (columnName) {
+ var column = columns[columnName];
+ items = items.map(function (item) {
+ item[columnName] = splitLongWords(item[columnName], column.width, column.truncateMarker);
+ return item;
+ });
+ });
+
+ // wrap long lines. each item is now an array of lines.
+ columnNames.forEach(function (columnName) {
+ var column = columns[columnName];
+ items = items.map(function (item, index) {
+ var cell = item[columnName];
+ item[columnName] = splitIntoLines(cell, column.width);
+
+ // if truncating required, only include first line + add truncation char
+ if (column.truncate && item[columnName].length > 1) {
+ item[columnName] = splitIntoLines(cell, column.width - wcwidth(column.truncateMarker));
+ var firstLine = item[columnName][0];
+ if (!endsWith(firstLine, column.truncateMarker)) item[columnName][0] += column.truncateMarker;
+ item[columnName] = item[columnName].slice(0, 1);
+ }
+ return item;
+ });
+ });
+
+ // recalculate column widths from truncated output/lines
+ columnNames.forEach(function (columnName) {
+ var column = columns[columnName];
+ column.width = items.map(function (item) {
+ return item[columnName].reduce(function (min, cur) {
+ return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))));
+ }, 0);
+ }).reduce(function (min, cur) {
+ return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, cur)));
+ }, 0);
+ });
+
+
+ var rows = createRows(items, columns, columnNames, options.paddingChr); // merge lines into rows
+ // conceive output
+ return rows.reduce(function (output, row) {
+ return output.concat(row.reduce(function (rowOut, line) {
+ return rowOut.concat(line.join(options.columnSplitter));
+ }, []));
+ }, []).map(function (line) {
+ return truncateString(line, maxLineWidth);
+ }).join(options.spacing);
+};
+
+/**
+ * Convert wrapped lines into rows with padded values.
+ *
+ * @param Array items data to process
+ * @param Array columns column width settings for wrapping
+ * @param Array columnNames column ordering
+ * @return Array items wrapped in arrays, corresponding to lines
+ */
+
+function createRows(items, columns, columnNames, paddingChr) {
+ return items.map(function (item) {
+ var row = [];
+ var numLines = 0;
+ columnNames.forEach(function (columnName) {
+ numLines = Math.max(numLines, item[columnName].length);
+ });
+ // combine matching lines of each rows
+ for (var i = 0; i < numLines; i++) {
+ (function (i) {
+ row[i] = row[i] || [];
+ columnNames.forEach(function (columnName) {
+ var column = columns[columnName];
+ var val = item[columnName][i] || ""; // || '' ensures empty columns get padded
+ if (column.align === "right") row[i].push(padLeft(val, column.width, paddingChr));else if (column.align === "center" || column.align === "centre") row[i].push(padCenter(val, column.width, paddingChr));else row[i].push(padRight(val, column.width, paddingChr));
+ });
+ })(i);
+ }
+ return row;
+ });
+}
+
+/**
+ * Object.assign
+ *
+ * @return Object Object with properties mixed in.
+ */
+
+function mixin() {
+ for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
+ args[_key] = arguments[_key];
+ }
+
+ if (Object.assign) return Object.assign.apply(Object, _toArray(args));
+ return ObjectAssign.apply(undefined, _toArray(args));
+}
+
+function ObjectAssign(target, firstSource) {
+ "use strict";
+ if (target === undefined || target === null) throw new TypeError("Cannot convert first argument to object");
+
+ var to = Object(target);
+
+ var hasPendingException = false;
+ var pendingException;
+
+ for (var i = 1; i < arguments.length; i++) {
+ var nextSource = arguments[i];
+ if (nextSource === undefined || nextSource === null) continue;
+
+ var keysArray = Object.keys(Object(nextSource));
+ for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
+ var nextKey = keysArray[nextIndex];
+ try {
+ var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
+ if (desc !== undefined && desc.enumerable) to[nextKey] = nextSource[nextKey];
+ } catch (e) {
+ if (!hasPendingException) {
+ hasPendingException = true;
+ pendingException = e;
+ }
+ }
+ }
+
+ if (hasPendingException) throw pendingException;
+ }
+ return to;
+}
+
+/**
+ * Adapted from String.prototype.endsWith polyfill.
+ */
+
+function endsWith(target, searchString, position) {
+ position = position || target.length;
+ position = position - searchString.length;
+ var lastIndex = target.lastIndexOf(searchString);
+ return lastIndex !== -1 && lastIndex === position;
+}
+
+
+function toArray(items, columnNames) {
+ if (Array.isArray(items)) return items;
+ var rows = [];
+ for (var key in items) {
+ var item = {};
+ item[columnNames[0] || "key"] = key;
+ item[columnNames[1] || "value"] = items[key];
+ rows.push(item);
+ }
+ return rows;
+}
"use strict"
-var wcwidth = require('./width')
-var utils = require('./utils')
-var padRight = utils.padRight
-var padCenter = utils.padCenter
-var padLeft = utils.padLeft
-var splitIntoLines = utils.splitIntoLines
-var splitLongWords = utils.splitLongWords
-var truncateString = utils.truncateString
-
-var DEFAULT_HEADING_TRANSFORM = function(key) {
- return key.toUpperCase()
-}
+const wcwidth = require('./width')
+const {
+ padRight,
+ padCenter,
+ padLeft,
+ splitIntoLines,
+ splitLongWords,
+ truncateString
+} = require('./utils')
-var DEFAULT_DATA_TRANSFORM = function(cell, column, index) {
- return cell
-}
+const DEFAULT_HEADING_TRANSFORM = key => key.toUpperCase()
+
+const DEFAULT_DATA_TRANSFORM = (cell, column, index) => cell
-var DEFAULTS = {
+const DEFAULTS = Object.freeze({
maxWidth: Infinity,
minWidth: 0,
columnSplitter: ' ',
showHeaders: true,
headingTransform: DEFAULT_HEADING_TRANSFORM,
dataTransform: DEFAULT_DATA_TRANSFORM
-}
-
-module.exports = function(items, options) {
+})
- options = options || {}
+module.exports = function(items, options = {}) {
- var columnConfigs = options.config || {}
+ let columnConfigs = options.config || {}
delete options.config // remove config so doesn't appear on every column.
- var maxLineWidth = options.maxLineWidth || Infinity
+ let maxLineWidth = options.maxLineWidth || Infinity
+ if (maxLineWidth === 'auto') maxLineWidth = process.stdout.columns || Infinity
delete options.maxLineWidth // this is a line control option, don't pass it to column
// Option defaults inheritance:
// options.config[columnName] => options => DEFAULTS
- options = mixin(options, DEFAULTS)
+ options = mixin({}, DEFAULTS, options)
+
options.config = options.config || Object.create(null)
options.spacing = options.spacing || '\n' // probably useless
options.preserveNewLines = !!options.preserveNewLines
options.showHeaders = !!options.showHeaders;
options.columns = options.columns || options.include // alias include/columns, prefer columns if supplied
- var columnNames = options.columns || [] // optional user-supplied columns to include
+ let columnNames = options.columns || [] // optional user-supplied columns to include
items = toArray(items, columnNames)
// if not suppled column names, automatically determine columns from data keys
if (!columnNames.length) {
items.forEach(function(item) {
- for (var columnName in item) {
+ for (let columnName in item) {
if (columnNames.indexOf(columnName) === -1) columnNames.push(columnName)
}
})
}
// initialize column defaults (each column inherits from options.config)
- var columns = columnNames.reduce(function(columns, columnName) {
- var column = Object.create(options)
+ let columns = columnNames.reduce((columns, columnName) => {
+ let column = Object.create(options)
columns[columnName] = mixin(column, columnConfigs[columnName])
return columns
}, Object.create(null))
// sanitize column settings
- columnNames.forEach(function(columnName) {
- var column = columns[columnName]
+ columnNames.forEach(columnName => {
+ let column = columns[columnName]
column.name = columnName
column.maxWidth = Math.ceil(column.maxWidth)
column.minWidth = Math.ceil(column.minWidth)
})
// sanitize data
- items = items.map(function(item) {
- var result = Object.create(null)
- columnNames.forEach(function(columnName) {
+ items = items.map(item => {
+ let result = Object.create(null)
+ columnNames.forEach(columnName => {
// null/undefined -> ''
result[columnName] = item[columnName] != null ? item[columnName] : ''
// toString everything
})
// transform data cells
- columnNames.forEach(function(columnName) {
- var column = columns[columnName]
- items = items.map(function(item, index) {
- var col = Object.create(column)
+ columnNames.forEach(columnName => {
+ let column = columns[columnName]
+ items = items.map((item, index) => {
+ let col = Object.create(column)
item[columnName] = column.dataTransform(item[columnName], col, index)
- var changedKeys = Object.keys(col)
+ let changedKeys = Object.keys(col)
// disable default heading transform if we wrote to column.name
if (changedKeys.indexOf('name') !== -1) {
if (column.headingTransform !== DEFAULT_HEADING_TRANSFORM) return
- column.headingTransform = function(heading) {return heading}
+ column.headingTransform = heading => heading
}
- changedKeys.forEach(function(key) {
- column[key] = col[key]
- })
+ changedKeys.forEach(key => column[key] = col[key])
return item
})
})
// add headers
- var headers = {}
+ let headers = {}
if(options.showHeaders) {
- columnNames.forEach(function(columnName) {
- var column = columns[columnName]
+ columnNames.forEach(columnName => {
+ let column = columns[columnName]
headers[columnName] = column.headingTransform(column.name)
})
items.unshift(headers)
}
// get actual max-width between min & max
// based on length of data in columns
- columnNames.forEach(function(columnName) {
- var column = columns[columnName]
- column.width = items.map(function(item) {
- return item[columnName]
- }).reduce(function(min, cur) {
+ columnNames.forEach(columnName => {
+ let column = columns[columnName]
+ column.width = items
+ .map(item => item[columnName])
+ .reduce((min, cur) => {
return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))))
}, 0)
})
// split long words so they can break onto multiple lines
- columnNames.forEach(function(columnName) {
- var column = columns[columnName]
- items = items.map(function(item) {
+ columnNames.forEach(columnName => {
+ let column = columns[columnName]
+ items = items.map(item => {
item[columnName] = splitLongWords(item[columnName], column.width, column.truncateMarker)
return item
})
})
// wrap long lines. each item is now an array of lines.
- columnNames.forEach(function(columnName) {
- var column = columns[columnName]
- items = items.map(function(item, index) {
- var cell = item[columnName]
+ columnNames.forEach(columnName => {
+ let column = columns[columnName]
+ items = items.map((item, index) => {
+ let cell = item[columnName]
item[columnName] = splitIntoLines(cell, column.width)
// if truncating required, only include first line + add truncation char
if (column.truncate && item[columnName].length > 1) {
- item[columnName] = splitIntoLines(cell, column.width - wcwidth(column.truncateMarker))
- var firstLine = item[columnName][0]
- if (!endsWith(firstLine, column.truncateMarker)) item[columnName][0] += column.truncateMarker
- item[columnName] = item[columnName].slice(0, 1)
+ item[columnName] = splitIntoLines(cell, column.width - wcwidth(column.truncateMarker))
+ let firstLine = item[columnName][0]
+ if (!endsWith(firstLine, column.truncateMarker)) item[columnName][0] += column.truncateMarker
+ item[columnName] = item[columnName].slice(0, 1)
}
return item
})
})
// recalculate column widths from truncated output/lines
- columnNames.forEach(function(columnName) {
- var column = columns[columnName]
- column.width = items.map(function(item) {
- return item[columnName].reduce(function(min, cur) {
+ columnNames.forEach(columnName => {
+ let column = columns[columnName]
+ column.width = items.map(item => {
+ return item[columnName].reduce((min, cur) => {
return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, wcwidth(cur))))
}, 0)
- }).reduce(function(min, cur) {
+ }).reduce((min, cur) => {
return Math.max(min, Math.min(column.maxWidth, Math.max(column.minWidth, cur)))
}, 0)
})
- var rows = createRows(items, columns, columnNames, options.paddingChr) // merge lines into rows
+ let rows = createRows(items, columns, columnNames, options.paddingChr) // merge lines into rows
// conceive output
- return rows.reduce(function(output, row) {
- return output.concat(row.reduce(function(rowOut, line) {
+ return rows.reduce((output, row) => {
+ return output.concat(row.reduce((rowOut, line) => {
return rowOut.concat(line.join(options.columnSplitter))
}, []))
- }, []).map(function(line) {
- return truncateString(line, maxLineWidth)
- }).join(options.spacing)
+ }, [])
+ .map(line => truncateString(line, maxLineWidth))
+ .join(options.spacing)
}
/**
*/
function createRows(items, columns, columnNames, paddingChr) {
- return items.map(function(item) {
- var row = []
- var numLines = 0
- columnNames.forEach(function(columnName) {
+ return items.map(item => {
+ let row = []
+ let numLines = 0
+ columnNames.forEach(columnName => {
numLines = Math.max(numLines, item[columnName].length)
})
// combine matching lines of each rows
- for (var i = 0; i < numLines; i++) {
+ for (let i = 0; i < numLines; i++) {
row[i] = row[i] || []
- columnNames.forEach(function(columnName) {
- var column = columns[columnName]
- var val = item[columnName][i] || '' // || '' ensures empty columns get padded
+ columnNames.forEach(columnName => {
+ let column = columns[columnName]
+ let val = item[columnName][i] || '' // || '' ensures empty columns get padded
if (column.align === 'right') row[i].push(padLeft(val, column.width, paddingChr))
else if (column.align === 'center' || column.align === 'centre') row[i].push(padCenter(val, column.width, paddingChr))
else row[i].push(padRight(val, column.width, paddingChr))
}
/**
- * Generic source->target mixin.
- * Copy properties from `source` into `target` if target doesn't have them.
- * Destructive. Modifies `target`.
+ * Object.assign
*
- * @param target Object target for mixin properties.
- * @param source Object source of mixin properties.
- * @return Object `target` after mixin applied.
+ * @return Object Object with properties mixed in.
*/
-function mixin(target, source) {
- source = source || {}
- for (var key in source) {
- if (target.hasOwnProperty(key)) continue
- target[key] = source[key]
+function mixin(...args) {
+ if (Object.assign) return Object.assign(...args)
+ return ObjectAssign(...args)
+}
+
+function ObjectAssign(target, firstSource) {
+ "use strict";
+ if (target === undefined || target === null)
+ throw new TypeError("Cannot convert first argument to object");
+
+ var to = Object(target);
+
+ var hasPendingException = false;
+ var pendingException;
+
+ for (var i = 1; i < arguments.length; i++) {
+ var nextSource = arguments[i];
+ if (nextSource === undefined || nextSource === null)
+ continue;
+
+ var keysArray = Object.keys(Object(nextSource));
+ for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
+ var nextKey = keysArray[nextIndex];
+ try {
+ var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
+ if (desc !== undefined && desc.enumerable)
+ to[nextKey] = nextSource[nextKey];
+ } catch (e) {
+ if (!hasPendingException) {
+ hasPendingException = true;
+ pendingException = e;
+ }
+ }
+ }
+
+ if (hasPendingException)
+ throw pendingException;
}
- return target
+ return to;
}
/**
function endsWith(target, searchString, position) {
position = position || target.length;
position = position - searchString.length;
- var lastIndex = target.lastIndexOf(searchString);
+ let lastIndex = target.lastIndexOf(searchString);
return lastIndex !== -1 && lastIndex === position;
}
function toArray(items, columnNames) {
if (Array.isArray(items)) return items
- var rows = []
- for (var key in items) {
- var item = {}
+ let rows = []
+ for (let key in items) {
+ let item = {}
item[columnNames[0] || 'key'] = key
item[columnNames[1] || 'value'] = items[key]
rows.push(item)
return;
}
-if (process.stdin.isTTY) {
- if (!input) {
- help();
- return;
- }
+if (!input && process.stdin.isTTY) {
+ help();
+ return;
+}
+if (input) {
init(fs.readFileSync(input, 'utf8'));
} else {
process.stdin.setEncoding('utf8');
{
"name": "strip-ansi",
- "version": "2.0.0",
+ "version": "2.0.1",
"description": "Strip ANSI escape codes",
"license": "MIT",
"repository": {
"type": "git",
- "url": "git://github.com/sindresorhus/strip-ansi"
+ "url": "https://github.com/sindresorhus/strip-ansi"
},
"author": {
"name": "Sindre Sorhus",
"devDependencies": {
"mocha": "*"
},
- "gitHead": "c5e780acc07532f5d651cfb6ea035198095c6c74",
+ "gitHead": "1eff0936c01f89efa312d9d51deed137259871a1",
"bugs": {
"url": "https://github.com/sindresorhus/strip-ansi/issues"
},
"homepage": "https://github.com/sindresorhus/strip-ansi",
- "_id": "strip-ansi@2.0.0",
- "_shasum": "fa8d69432e97674746f55f51d076ae78b18df13f",
+ "_id": "strip-ansi@2.0.1",
+ "_shasum": "df62c1aa94ed2f114e1d0f21fd1d50482b79a60e",
"_from": "strip-ansi@>=2.0.0 <3.0.0",
- "_npmVersion": "1.4.14",
+ "_npmVersion": "1.4.28",
"_npmUser": {
"name": "sindresorhus",
"email": "sindresorhus@gmail.com"
}
],
"dist": {
- "shasum": "fa8d69432e97674746f55f51d076ae78b18df13f",
- "tarball": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-2.0.0.tgz"
+ "shasum": "df62c1aa94ed2f114e1d0f21fd1d50482b79a60e",
+ "tarball": "http://registry.npmjs.org/strip-ansi/-/strip-ansi-2.0.1.tgz"
},
"directories": {},
- "_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-2.0.0.tgz",
- "readme": "ERROR: No README data found!"
+ "_resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-2.0.1.tgz"
}
```js
var stripAnsi = require('strip-ansi');
-stripAnsi('\x1b[4mcake\x1b[0m');
+stripAnsi('\u001b[4mcake\u001b[0m');
//=> 'cake'
```
```sh
$ strip-ansi --help
-Usage
- $ strip-ansi <input-file> > <output-file>
- $ cat <input-file> | strip-ansi > <output-file>
+ Usage
+ strip-ansi <input-file> > <output-file>
+ cat <input-file> | strip-ansi > <output-file>
-Example
- $ strip-ansi unicorn.txt > unicorn-stripped.txt
+ Example
+ strip-ansi unicorn.txt > unicorn-stripped.txt
```
"shasum": "02d059ff7a8fc741e0f6b5da1e69b2b40daeca6f",
"tarball": "http://registry.npmjs.org/wcwidth/-/wcwidth-1.0.0.tgz"
},
- "_resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.0.tgz"
+ "_resolved": "https://registry.npmjs.org/wcwidth/-/wcwidth-1.0.0.tgz",
+ "readme": "ERROR: No README data found!"
}
{
"name": "columnify",
- "version": "1.3.2",
+ "version": "1.4.1",
"description": "Render data in text columns. supports in-column text-wrap.",
- "main": "index.js",
+ "main": "columnify.js",
"scripts": {
"pretest": "npm prune",
- "test": "tape test/*.js | tap-spec",
- "bench": "npm test && node bench"
+ "test": "make prepublish && tape test/*.js | tap-spec",
+ "bench": "npm test && node bench",
+ "prepublish": "make prepublish"
},
"author": {
"name": "Tim Oxley"
},
"license": "MIT",
"devDependencies": {
+ "6to5": "^3.0.9",
"chalk": "^0.5.1",
"tap-spec": "^2.1.1",
"tape": "^3.0.3"
"directories": {
"test": "test"
},
- "gitHead": "5c7d4363a8d6178f0d415e8bdaf692281fe71975",
- "_id": "columnify@1.3.2",
- "_shasum": "61bd578a9269ae6fd949ce36fff589f3702c7867",
- "_from": "columnify@>=1.3.2 <1.4.0",
- "_npmVersion": "2.1.10",
- "_nodeVersion": "0.10.33",
+ "gitHead": "24371e9c12287ce4d28f19d704a28059f3acd42b",
+ "_id": "columnify@1.4.1",
+ "_shasum": "30555796379865b016189c228cb0061764270ed0",
+ "_from": "columnify@>=1.4.1 <1.5.0",
+ "_npmVersion": "2.3.0",
+ "_nodeVersion": "0.10.35",
"_npmUser": {
"name": "timoxley",
"email": "secoif@gmail.com"
}
],
"dist": {
- "shasum": "61bd578a9269ae6fd949ce36fff589f3702c7867",
- "tarball": "http://registry.npmjs.org/columnify/-/columnify-1.3.2.tgz"
+ "shasum": "30555796379865b016189c228cb0061764270ed0",
+ "tarball": "http://registry.npmjs.org/columnify/-/columnify-1.4.1.tgz"
},
- "_resolved": "https://registry.npmjs.org/columnify/-/columnify-1.3.2.tgz"
+ "_resolved": "https://registry.npmjs.org/columnify/-/columnify-1.4.1.tgz"
}
function endChown (me, want, current, path, cb) {
// Don't even try it unless root. Too easy to EPERM.
if (process.platform === "win32") return cb()
- if (!process.getuid || !process.getuid() === 0) return cb()
+ if (!process.getuid || process.getuid() !== 0) return cb()
if (typeof want.uid !== "number" &&
typeof want.gid !== "number" ) return cb()
},
"name": "fstream",
"description": "Advanced file system stream things",
- "version": "1.0.3",
+ "version": "1.0.4",
"repository": {
"type": "git",
"url": "git://github.com/isaacs/fstream.git"
"license": "BSD",
"readme": "Like FS streams, but with stat on them, and supporting directories and\nsymbolic links, as well as normal files. Also, you can use this to set\nthe stats on a file, even if you don't change its contents, or to create\na symlink, etc.\n\nSo, for example, you can \"write\" a directory, and it'll call `mkdir`. You\ncan specify a uid and gid, and it'll call `chown`. You can specify a\n`mtime` and `atime`, and it'll call `utimes`. You can call it a symlink\nand provide a `linkpath` and it'll call `symlink`.\n\nNote that it won't automatically resolve symbolic links. So, if you\ncall `fstream.Reader('/some/symlink')` then you'll get an object\nthat stats and then ends immediately (since it has no data). To follow\nsymbolic links, do this: `fstream.Reader({path:'/some/symlink', follow:\ntrue })`.\n\nThere are various checks to make sure that the bytes emitted are the\nsame as the intended size, if the size is set.\n\n## Examples\n\n```javascript\nfstream\n .Writer({ path: \"path/to/file\"\n , mode: 0755\n , size: 6\n })\n .write(\"hello\\n\")\n .end()\n```\n\nThis will create the directories if they're missing, and then write\n`hello\\n` into the file, chmod it to 0755, and assert that 6 bytes have\nbeen written when it's done.\n\n```javascript\nfstream\n .Writer({ path: \"path/to/file\"\n , mode: 0755\n , size: 6\n , flags: \"a\"\n })\n .write(\"hello\\n\")\n .end()\n```\n\nYou can pass flags in, if you want to append to a file.\n\n```javascript\nfstream\n .Writer({ path: \"path/to/symlink\"\n , linkpath: \"./file\"\n , SymbolicLink: true\n , mode: \"0755\" // octal strings supported\n })\n .end()\n```\n\nIf isSymbolicLink is a function, it'll be called, and if it returns\ntrue, then it'll treat it as a symlink. If it's not a function, then\nany truish value will make a symlink, or you can set `type:\n'SymbolicLink'`, which does the same thing.\n\nNote that the linkpath is relative to the symbolic link location, not\nthe parent dir or cwd.\n\n```javascript\nfstream\n .Reader(\"path/to/dir\")\n .pipe(fstream.Writer(\"path/to/other/dir\"))\n```\n\nThis will do like `cp -Rp path/to/dir path/to/other/dir`. If the other\ndir exists and isn't a directory, then it'll emit an error. It'll also\nset the uid, gid, mode, etc. to be identical. In this way, it's more\nlike `rsync -a` than simply a copy.\n",
"readmeFilename": "README.md",
- "gitHead": "d205397b27d93eee5314e9d2d87693e82b560106",
+ "gitHead": "0bdcf1db6f9b04755b644f8268fc3726875367a6",
"bugs": {
"url": "https://github.com/isaacs/fstream/issues"
},
"homepage": "https://github.com/isaacs/fstream",
- "_id": "fstream@1.0.3",
- "_shasum": "5ce69767710d7a39c8cd9232470d9426790195da",
- "_from": "fstream@>=1.0.3 <1.1.0"
+ "_id": "fstream@1.0.4",
+ "_shasum": "6c52298473fd6351fd22fc4bf9254fcfebe80f2b",
+ "_from": "fstream@>=1.0.4 <1.1.0"
}
'-luuid.lib',
'-lodbc32.lib',
'-lDelayImp.lib',
- '-l"<(node_root_dir)/$(ConfigurationName)/iojs.lib"'
+ '-l"<(node_root_dir)/$(ConfigurationName)/node.lib"'
],
# warning C4251: 'node::ObjectWrap::handle_' : class 'v8::Persistent<T>'
# needs to have dll-interface to be used by clients of class 'node::ObjectWrap'
}
/**
- * Copies the iojs.lib file for the current target architecture into the
+ * Copies the node.lib file for the current target architecture into the
* current proper dev dir location.
*/
if (!win || !copyDevLib) return doBuild()
var buildDir = path.resolve(nodeDir, buildType)
- , archNodeLibPath = path.resolve(nodeDir, arch, 'iojs.lib')
- , buildNodeLibPath = path.resolve(buildDir, 'iojs.lib')
+ , archNodeLibPath = path.resolve(nodeDir, arch, 'node.lib')
+ , buildNodeLibPath = path.resolve(buildDir, 'node.lib')
mkdirp(buildDir, function (err, isNew) {
if (err) return callback(err)
log.verbose('"' + buildType + '" dir needed to be created?', isNew)
var rs = fs.createReadStream(archNodeLibPath)
, ws = fs.createWriteStream(buildNodeLibPath)
- log.verbose('copying "iojs.lib" for ' + arch, buildNodeLibPath)
+ log.verbose('copying "node.lib" for ' + arch, buildNodeLibPath)
rs.pipe(ws)
rs.on('error', callback)
ws.on('error', callback)
}
}
- var distUrl = gyp.opts['dist-url'] || gyp.opts.disturl || 'https://iojs.org/dist'
+ var distUrl = gyp.opts['dist-url'] || gyp.opts.disturl || 'http://nodejs.org/dist'
// Determine which node dev files version we are installing
// now download the node tarball
var tarPath = gyp.opts['tarball']
- var tarballUrl = tarPath ? tarPath : distUrl + '/v' + version + '/iojs-v' + version + '.tar.gz'
+ var tarballUrl = tarPath ? tarPath : distUrl + '/v' + version + '/node-v' + version + '.tar.gz'
, badDownload = false
, extractCount = 0
, gunzip = zlib.createGunzip()
var async = 0
if (win) {
- // need to download iojs.lib
+ // need to download node.lib
async++
downloadNodeLib(deref)
}
// check content shasums
for (var k in contentShasums) {
log.verbose('validating download checksum for ' + k, '(%s == %s)', contentShasums[k], expectShasums[k])
- // TODO(piscisaureus) re-enable checksum verification when the correct files are in place.
- if (false || contentShasums[k] !== expectShasums[k]) {
+ if (contentShasums[k] !== expectShasums[k]) {
cb(new Error(k + ' local checksum ' + contentShasums[k] + ' not match remote ' + expectShasums[k]))
return
}
}
function downloadNodeLib (done) {
- log.verbose('on Windows; need to download `iojs.lib`...')
+ log.verbose('on Windows; need to download `node.lib`...')
var dir32 = path.resolve(devDir, 'ia32')
, dir64 = path.resolve(devDir, 'x64')
- , nodeLibPath32 = path.resolve(dir32, 'iojs.lib')
- , nodeLibPath64 = path.resolve(dir64, 'iojs.lib')
- , nodeLibUrl32 = distUrl + '/v' + version + '/win-x86/iojs.lib'
- , nodeLibUrl64 = distUrl + '/v' + version + '/win-x64/iojs.lib'
+ , nodeLibPath32 = path.resolve(dir32, 'node.lib')
+ , nodeLibPath64 = path.resolve(dir64, 'node.lib')
+ , nodeLibUrl32 = distUrl + '/v' + version + '/node.lib'
+ , nodeLibUrl64 = distUrl + '/v' + version + '/x64/node.lib'
- log.verbose('32-bit iojs.lib dir', dir32)
- log.verbose('64-bit iojs.lib dir', dir64)
- log.verbose('`iojs.lib` 32-bit url', nodeLibUrl32)
- log.verbose('`iojs.lib` 64-bit url', nodeLibUrl64)
+ log.verbose('32-bit node.lib dir', dir32)
+ log.verbose('64-bit node.lib dir', dir64)
+ log.verbose('`node.lib` 32-bit url', nodeLibUrl32)
+ log.verbose('`node.lib` 64-bit url', nodeLibUrl64)
var async = 2
mkdir(dir32, function (err) {
if (err) return done(err)
- log.verbose('streaming 32-bit iojs.lib to:', nodeLibPath32)
+ log.verbose('streaming 32-bit node.lib to:', nodeLibPath32)
var req = download(nodeLibUrl32)
if (!req) return
req.on('error', done)
req.on('response', function (res) {
if (res.statusCode !== 200) {
- done(new Error(res.statusCode + ' status code downloading 32-bit iojs.lib'))
+ done(new Error(res.statusCode + ' status code downloading 32-bit node.lib'))
return
}
getContentSha(res, function (_, checksum) {
- contentShasums['win-x86/iojs.lib'] = checksum
- log.verbose('content checksum', 'win-x86/iojs.lib', checksum)
+ contentShasums['node.lib'] = checksum
+ log.verbose('content checksum', 'node.lib', checksum)
})
var ws = fs.createWriteStream(nodeLibPath32)
})
mkdir(dir64, function (err) {
if (err) return done(err)
- log.verbose('streaming 64-bit iojs.lib to:', nodeLibPath64)
+ log.verbose('streaming 64-bit node.lib to:', nodeLibPath64)
var req = download(nodeLibUrl64)
if (!req) return
req.on('error', done)
req.on('response', function (res) {
if (res.statusCode !== 200) {
- done(new Error(res.statusCode + ' status code downloading 64-bit iojs.lib'))
+ done(new Error(res.statusCode + ' status code downloading 64-bit node.lib'))
return
}
getContentSha(res, function (_, checksum) {
- contentShasums['win-x64/iojs.lib'] = checksum
- log.verbose('content checksum', 'win-x64/iojs.lib', checksum)
+ contentShasums['x64/node.lib'] = checksum
+ log.verbose('content checksum', 'x64/node.lib', checksum)
})
var ws = fs.createWriteStream(nodeLibPath64)
if (operation.retry(er)) {
client.log.info("retry", "will retry, error on last attempt: " + er)
}
+ else {
+ cb(er)
+ }
})
req.on("response", function (res) {
var pkg = require("../package.json")
-var httpAgent = new HttpAgent({ keepAlive : true })
-var httpsAgent = new HttpsAgent({ keepAlive : true })
+var httpAgent
+var httpsAgent
module.exports = initialize
strictSSL : this.config.ssl.strict,
cert : this.config.ssl.certificate,
key : this.config.ssl.key,
- ca : this.config.ssl.ca
+ ca : this.config.ssl.ca,
+ agent : getAgent(uri.protocol, this.config)
}
- // request will not pay attention to the NOPROXY environment variable if a
- // config value named proxy is passed in, even if it's set to null.
- var proxy
- if (uri.protocol === "https:") {
- proxy = this.config.proxy.https
- opts.agent = httpsAgent
+ // allow explicit disabling of proxy in environment via CLI
+ //
+ // how false gets here is the CLI's problem (it's gross)
+ if (this.config.proxy.http === false) {
+ opts.proxy = null
}
else {
- proxy = this.config.proxy.http
- opts.agent = httpAgent
+ // request will not pay attention to the NOPROXY environment variable if a
+ // config value named proxy is passed in, even if it's set to null.
+ var proxy
+ if (uri.protocol === "https:") {
+ proxy = this.config.proxy.https
+ }
+ else {
+ proxy = this.config.proxy.http
+ }
+ if (typeof proxy === "string") opts.proxy = proxy
}
- if (typeof proxy === "string") opts.proxy = proxy
headers.version = this.version || pkg.version
headers.accept = accept
return opts
}
+
+function getAgent (protocol, config) {
+ if (protocol === "https:") {
+ if (!httpsAgent) {
+ httpsAgent = new HttpsAgent({
+ keepAlive : true,
+ localAddress : config.proxy.localAddress,
+ rejectUnauthorized : config.ssl.strict,
+ ca : config.ssl.ca,
+ cert : config.ssl.cert,
+ key : config.ssl.key
+ })
+ }
+
+ return httpsAgent
+ }
+ else {
+ if (!httpAgent) {
+ httpAgent = new HttpAgent({
+ keepAlive : true,
+ localAddress : config.proxy.localAddress
+ })
+ }
+
+ return httpAgent
+ }
+}
assert(typeof cb === "function", "must pass callback to publish")
var access = params.access
- assert(access && typeof access === "string", "must pass access for package")
assert(
- ["public", "restricted"].indexOf(access) !== -1,
- "access level must be either 'public' or 'restricted'"
+ (!access) || ["public", "restricted"].indexOf(access) !== -1,
+ "if present, access level must be either 'public' or 'restricted'"
)
var auth = params.auth
{ _id : data.name
, name : data.name
, description : data.description
- , access : access
, "dist-tags" : {}
, versions : {}
, readme: data.readme || ""
}
+ if (access) root.access = access
+
if (!auth.token) {
root.maintainers = [{name : auth.username, email : auth.email}]
data.maintainers = JSON.parse(JSON.stringify(root.maintainers))
if (params.lastModified && params.method === "GET") {
this.log.verbose("lastModified", params.lastModified)
- headers["if-modified-since"] = params.lastModified;
+ headers["if-modified-since"] = params.lastModified
}
// figure out wth body is
parsed._etag = response.headers.etag
}
- if (parsed && response.headers['last-modified']) {
- parsed._lastModified = response.headers['last-modified']
+ if (parsed && response.headers["last-modified"]) {
+ parsed._lastModified = response.headers["last-modified"]
}
// for the search endpoint, the "error" property can be an object
"gitHead": "153325f997813ebf8a7ae07b322b4fa89aa25f7d",
"_id": "hosted-git-info@1.5.3",
"_shasum": "1f46e25e9c0e207852fb7a4b94422ed5f09a03f5",
- "_from": "hosted-git-info@>=1.4.0 <2.0.0",
+ "_from": "hosted-git-info@>=1.5.3 <2.0.0",
"_npmVersion": "2.4.0",
"_nodeVersion": "0.10.33",
"_npmUser": {
{
"name": "npm-package-arg",
- "version": "3.0.0",
+ "version": "3.1.0",
"description": "Parse the things that can be arguments to `npm install`",
"main": "npa.js",
"directories": {
"test": "test"
},
"dependencies": {
- "hosted-git-info": "^1.4.0",
+ "hosted-git-info": "^1.5.3",
"semver": "4"
},
"devDependencies": {
"url": "https://github.com/npm/npm-package-arg/issues"
},
"homepage": "https://github.com/npm/npm-package-arg",
- "gitHead": "263fd43295ac8f6eca046be108782cfbf9a78bfe",
- "_id": "npm-package-arg@3.0.0",
- "_shasum": "84e91836fa2e4e35ae26dc984440b1e5b5aee1ee",
+ "gitHead": "3d5c7f91c5e90e4b9792d881080c462f718f4747",
+ "_id": "npm-package-arg@3.1.0",
+ "_shasum": "8ce9d8ad83ae9fcc433783ca813e4e91f885703e",
"_from": "npm-package-arg@>=3.0.0 <4.0.0",
- "_npmVersion": "1.4.28",
+ "_npmVersion": "2.4.1",
+ "_nodeVersion": "1.0.4",
"_npmUser": {
"name": "iarna",
"email": "me@re-becca.org"
}
],
"dist": {
- "shasum": "84e91836fa2e4e35ae26dc984440b1e5b5aee1ee",
- "tarball": "http://registry.npmjs.org/npm-package-arg/-/npm-package-arg-3.0.0.tgz"
+ "shasum": "8ce9d8ad83ae9fcc433783ca813e4e91f885703e",
+ "tarball": "http://registry.npmjs.org/npm-package-arg/-/npm-package-arg-3.1.0.tgz"
},
- "_resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-3.0.0.tgz",
+ "_resolved": "https://registry.npmjs.org/npm-package-arg/-/npm-package-arg-3.1.0.tgz",
"readme": "ERROR: No README data found!"
}
},
"name": "npm-registry-client",
"description": "Client for the npm registry",
- "version": "6.0.3",
+ "version": "6.0.7",
"repository": {
"url": "git://github.com/isaacs/npm-registry-client"
},
"npmlog": ""
},
"license": "ISC",
- "gitHead": "7d3d14eb825aa376c63854a08e67d2c9b3415927",
"readme": "# npm-registry-client\n\nThe code that npm uses to talk to the registry.\n\nIt handles all the caching and HTTP calls.\n\n## Usage\n\n```javascript\nvar RegClient = require('npm-registry-client')\nvar client = new RegClient(config)\nvar uri = \"npm://registry.npmjs.org/npm\"\nvar params = {timeout: 1000}\n\nclient.get(uri, params, function (error, data, raw, res) {\n // error is an error if there was a problem.\n // data is the parsed data object\n // raw is the json string\n // res is the response from couch\n})\n```\n\n# Registry URLs\n\nThe registry calls take either a full URL pointing to a resource in the\nregistry, or a base URL for the registry as a whole (including the registry\npath – but be sure to terminate the path with `/`). `http` and `https` URLs are\nthe only ones supported.\n\n## Using the client\n\nEvery call to the client follows the same pattern:\n\n* `uri` {String} The *fully-qualified* URI of the registry API method being\n invoked.\n* `params` {Object} Per-request parameters.\n* `callback` {Function} Callback to be invoked when the call is complete.\n\n### Credentials\n\nMany requests to the registry can by authenticated, and require credentials\nfor authorization. These credentials always look the same:\n\n* `username` {String}\n* `password` {String}\n* `email` {String}\n* `alwaysAuth` {Boolean} Whether calls to the target registry are always\n authed.\n\n**or**\n\n* `token` {String}\n* `alwaysAuth` {Boolean} Whether calls to the target registry are always\n authed.\n\n## API\n\n### client.access(uri, params, cb)\n\n* `uri` {String} Registry URL for the package's access API endpoint.\n Looks like `/-/package/<package name>/access`.\n* `params` {Object} Object containing per-request properties.\n * `access` {String} New access level for the package. Can be either\n `public` or `restricted`. Registry will raise an error if trying\n to change the access level of an unscoped package.\n * `auth` {Credentials}\n\nSet the access level for scoped packages. For now, there are only two\naccess levels: \"public\" and \"restricted\".\n\n### client.adduser(uri, params, cb)\n\n* `uri` {String} Base registry URL.\n* `params` {Object} Object containing per-request properties.\n * `auth` {Credentials}\n* `cb` {Function}\n * `error` {Error | null}\n * `data` {Object} the parsed data object\n * `raw` {String} the json\n * `res` {Response Object} response from couch\n\nAdd a user account to the registry, or verify the credentials.\n\n### client.deprecate(uri, params, cb)\n\n* `uri` {String} Full registry URI for the deprecated package.\n* `params` {Object} Object containing per-request properties.\n * `version` {String} Semver version range.\n * `message` {String} The message to use as a deprecation warning.\n * `auth` {Credentials}\n* `cb` {Function}\n\nDeprecate a version of a package in the registry.\n\n### client.distTags.fetch(uri, params, cb)\n\n* `uri` {String} Base URL for the registry.\n* `params` {Object} Object containing per-request properties.\n * `package` {String} Name of the package.\n * `auth` {Credentials}\n* `cb` {Function}\n\nFetch all of the `dist-tags` for the named package.\n\n### client.distTags.add(uri, params, cb)\n\n* `uri` {String} Base URL for the registry.\n* `params` {Object} Object containing per-request properties.\n * `package` {String} Name of the package.\n * `distTag` {String} Name of the new `dist-tag`.\n * `version` {String} Exact version to be mapped to the `dist-tag`.\n * `auth` {Credentials}\n* `cb` {Function}\n\nAdd (or replace) a single dist-tag onto the named package.\n\n### client.distTags.set(uri, params, cb)\n\n* `uri` {String} Base URL for the registry.\n* `params` {Object} Object containing per-request properties.\n * `package` {String} Name of the package.\n * `distTags` {Object} Object containing a map from tag names to package\n versions.\n * `auth` {Credentials}\n* `cb` {Function}\n\nSet all of the `dist-tags` for the named package at once, creating any\n`dist-tags` that do not already exit. Any `dist-tags` not included in the\n`distTags` map will be removed.\n\n### client.distTags.update(uri, params, cb)\n\n* `uri` {String} Base URL for the registry.\n* `params` {Object} Object containing per-request properties.\n * `package` {String} Name of the package.\n * `distTags` {Object} Object containing a map from tag names to package\n versions.\n * `auth` {Credentials}\n* `cb` {Function}\n\nUpdate the values of multiple `dist-tags`, creating any `dist-tags` that do\nnot already exist. Any pre-existing `dist-tags` not included in the `distTags`\nmap will be left alone.\n\n### client.distTags.rm(uri, params, cb)\n\n* `uri` {String} Base URL for the registry.\n* `params` {Object} Object containing per-request properties.\n * `package` {String} Name of the package.\n * `distTag` {String} Name of the new `dist-tag`.\n * `auth` {Credentials}\n* `cb` {Function}\n\nRemove a single `dist-tag` from the named package.\n\n### client.get(uri, params, cb)\n\n* `uri` {String} The complete registry URI to fetch\n* `params` {Object} Object containing per-request properties.\n * `timeout` {Number} Duration before the request times out. Optional\n (default: never).\n * `follow` {Boolean} Follow 302/301 responses. Optional (default: true).\n * `staleOk` {Boolean} If there's cached data available, then return that to\n the callback quickly, and update the cache the background. Optional\n (default: false).\n * `auth` {Credentials} Optional.\n* `cb` {Function}\n\nFetches data from the registry via a GET request, saving it in the cache folder\nwith the ETag or the \"Last Modified\" timestamp.\n\n### client.publish(uri, params, cb)\n\n* `uri` {String} The registry URI for the package to publish.\n* `params` {Object} Object containing per-request properties.\n * `metadata` {Object} Package metadata.\n * `access` {String} Access for the package. Can be `public` or `restricted` (no default).\n * `body` {Stream} Stream of the package body / tarball.\n * `auth` {Credentials}\n* `cb` {Function}\n\nPublish a package to the registry.\n\nNote that this does not create the tarball from a folder.\n\n### client.star(uri, params, cb)\n\n* `uri` {String} The complete registry URI for the package to star.\n* `params` {Object} Object containing per-request properties.\n * `starred` {Boolean} True to star the package, false to unstar it. Optional\n (default: false).\n * `auth` {Credentials}\n* `cb` {Function}\n\nStar or unstar a package.\n\nNote that the user does not have to be the package owner to star or unstar a\npackage, though other writes do require that the user be the package owner.\n\n### client.stars(uri, params, cb)\n\n* `uri` {String} The base URL for the registry.\n* `params` {Object} Object containing per-request properties.\n * `username` {String} Name of user to fetch starred packages for. Optional\n (default: user in `auth`).\n * `auth` {Credentials} Optional (required if `username` is omitted).\n* `cb` {Function}\n\nView your own or another user's starred packages.\n\n### client.tag(uri, params, cb)\n\n* `uri` {String} The complete registry URI to tag\n* `params` {Object} Object containing per-request properties.\n * `version` {String} Version to tag.\n * `tag` {String} Tag name to apply.\n * `auth` {Credentials}\n* `cb` {Function}\n\nMark a version in the `dist-tags` hash, so that `pkg@tag` will fetch the\nspecified version.\n\n### client.unpublish(uri, params, cb)\n\n* `uri` {String} The complete registry URI of the package to unpublish.\n* `params` {Object} Object containing per-request properties.\n * `version` {String} version to unpublish. Optional – omit to unpublish all\n versions.\n * `auth` {Credentials}\n* `cb` {Function}\n\nRemove a version of a package (or all versions) from the registry. When the\nlast version us unpublished, the entire document is removed from the database.\n\n### client.whoami(uri, params, cb)\n\n* `uri` {String} The base registry for the URI.\n* `params` {Object} Object containing per-request properties.\n * `auth` {Credentials}\n* `cb` {Function}\n\nSimple call to see who the registry thinks you are. Especially useful with\ntoken-based auth.\n\n\n## PLUMBING\n\nThe below are primarily intended for use by the rest of the API, or by the npm\ncaching logic directly.\n\n### client.request(uri, params, cb)\n\n* `uri` {String} URI pointing to the resource to request.\n* `params` {Object} Object containing per-request properties.\n * `method` {String} HTTP method. Optional (default: \"GET\").\n * `body` {Stream | Buffer | String | Object} The request body. Objects\n that are not Buffers or Streams are encoded as JSON. Optional – body\n only used for write operations.\n * `etag` {String} The cached ETag. Optional.\n * `lastModified` {String} The cached Last-Modified timestamp. Optional.\n * `follow` {Boolean} Follow 302/301 responses. Optional (default: true).\n * `auth` {Credentials} Optional.\n* `cb` {Function}\n * `error` {Error | null}\n * `data` {Object} the parsed data object\n * `raw` {String} the json\n * `res` {Response Object} response from couch\n\nMake a generic request to the registry. All the other methods are wrappers\naround `client.request`.\n\n### client.fetch(uri, params, cb)\n\n* `uri` {String} The complete registry URI to upload to\n* `params` {Object} Object containing per-request properties.\n * `headers` {Stream} HTTP headers to be included with the request. Optional.\n * `auth` {Credentials} Optional.\n* `cb` {Function}\n\nFetch a package from a URL, with auth set appropriately if included. Used to\ncache remote tarballs as well as request package tarballs from the registry.\n\n# Configuration\n\nThe client uses its own configuration, which is just passed in as a simple\nnested object. The following are the supported values (with their defaults, if\nany):\n\n* `proxy.http` {URL} The URL to proxy HTTP requests through.\n* `proxy.https` {URL} The URL to proxy HTTPS requests through. Defaults to be\n the same as `proxy.http` if unset.\n* `proxy.localAddress` {IP} The local address to use on multi-homed systems.\n* `ssl.ca` {String} Certificate signing authority certificates to trust.\n* `ssl.certificate` {String} Client certificate (PEM encoded). Enable access\n to servers that require client certificates.\n* `ssl.key` {String} Private key (PEM encoded) for client certificate.\n* `ssl.strict` {Boolean} Whether or not to be strict with SSL certificates.\n Default = `true`\n* `retry.count` {Number} Number of times to retry on GET failures. Default = 2.\n* `retry.factor` {Number} `factor` setting for `node-retry`. Default = 10.\n* `retry.minTimeout` {Number} `minTimeout` setting for `node-retry`.\n Default = 10000 (10 seconds)\n* `retry.maxTimeout` {Number} `maxTimeout` setting for `node-retry`.\n Default = 60000 (60 seconds)\n* `userAgent` {String} User agent header to send. Default =\n `\"node/{process.version}\"`\n* `log` {Object} The logger to use. Defaults to `require(\"npmlog\")` if\n that works, otherwise logs are disabled.\n* `defaultTag` {String} The default tag to use when publishing new packages.\n Default = `\"latest\"`\n* `couchToken` {Object} A token for use with\n [couch-login](https://npmjs.org/package/couch-login).\n* `sessionToken` {string} A random identifier for this set of client requests.\n Default = 8 random hexadecimal bytes.\n",
"readmeFilename": "README.md",
+ "gitHead": "8691eaf8ca1f4c8a4d16389da6e8f6d0a0042ed9",
"bugs": {
"url": "https://github.com/isaacs/npm-registry-client/issues"
},
"homepage": "https://github.com/isaacs/npm-registry-client",
- "_id": "npm-registry-client@6.0.3",
- "_shasum": "ae19f33b1cd6b4f5e81b7614bde7b97393c57cdc",
- "_from": "npm-registry-client@>=6.0.3 <6.1.0"
+ "_id": "npm-registry-client@6.0.7",
+ "_shasum": "c9f36f727f0b72f47a9ed11a539829770565e0fb",
+ "_from": "npm-registry-client@>=6.0.7 <6.1.0"
}
--- /dev/null
+var test = require("tap").test
+
+// var server = require("./lib/server.js")
+var Client = require("../")
+
+test("defaulted initialization", function (t) {
+ var client = new Client()
+ var options = client.initialize(
+ "http://localhost:1337/",
+ "GET",
+ "application/json",
+ {}
+ )
+
+ t.equal(options.url, "http://localhost:1337/", "URLs match")
+ t.equal(options.method, "GET", "methods match")
+ t.equal(options.proxy, undefined, "proxy won't overwrite environment")
+ t.equal(options.localAddress, undefined, "localAddress has no default value")
+ t.equal(options.strictSSL, true, "SSL is strict by default")
+
+ t.equal(options.headers.accept, "application/json", "accept header set")
+ t.equal(
+ options.headers.version,
+ require("../package.json").version,
+ "npm-registry-client version is present in headers"
+ )
+ t.ok(options.headers["npm-session"], "request ID generated")
+ t.ok(options.headers["user-agent"], "user-agent preset")
+
+ var HttpAgent = require("http").Agent
+ t.ok(options.agent instanceof HttpAgent, "got an HTTP agent for an HTTP URL")
+
+ t.end()
+})
+
+test("referer set on client", function (t) {
+ var client = new Client()
+ client.refer = "xtestx"
+ var options = client.initialize(
+ "http://localhost:1337/",
+ "GET",
+ "application/json",
+ {}
+ )
+
+ t.equal(options.headers.referer, "xtestx", "referer header set")
+
+ t.end()
+})
+
+test("initializing with proxy explicitly disabled", function (t) {
+ var client = new Client({ proxy : { http : false }})
+ var options = client.initialize(
+ "http://localhost:1337/",
+ "GET",
+ "application/json",
+ {}
+ )
+ t.ok("proxy" in options, "proxy overridden by explicitly setting to false")
+ t.equal(options.proxy, null, "request will override proxy when empty proxy passed in")
+ t.end()
+})
+
+test("initializing with proxy undefined", function (t) {
+ var client = new Client({ proxy : { http : undefined }})
+ var options = client.initialize(
+ "http://localhost:1337/",
+ "GET",
+ "application/json",
+ {}
+ )
+ t.notOk("proxy" in options, "proxy can be read from env.PROXY by request")
+ t.end()
+})
function () {
var params = {
metadata : METADATA,
- body : BODY,
- auth : AUTH
- }
- client.publish(URI, params, nop)
- },
- { name : "AssertionError", message : "must pass access for package" },
- "params must include access for package"
- )
-
- t.throws(
- function () {
- var params = {
- metadata : METADATA,
access : ACCESS,
auth : AUTH
}
},
{
name : "AssertionError",
- message : "access level must be either 'public' or 'restricted'"
+ message : "if present, access level must be either 'public' or 'restricted'"
},
"access level must be 'public' or 'restricted'"
)
+coverage
tests
node_modules
on_success: change # options: [always|never|change] default: always
on_failure: always # options: [always|never|change] default: always
on_start: false # default: false
+sudo: false
## Change Log
+### v2.53.0 (2015/02/02)
+- [#1396](https://github.com/request/request/pull/1396) Do not rfc3986 escape JSON bodies (@nylen, @simov)
+- [#1392](https://github.com/request/request/pull/1392) Improve `timeout` option description (@watson)
+
+### v2.52.0 (2015/02/02)
+- [#1383](https://github.com/request/request/pull/1383) Add missing HTTPS options that were not being passed to tunnel (@brichard19) (@nylen, @brichard19)
+- [#1388](https://github.com/request/request/pull/1388) Upgrade mime-types package version (@roderickhsiao)
+- [#1389](https://github.com/request/request/pull/1389) Revise Setup Tunnel Function (@seanstrom)
+- [#1374](https://github.com/request/request/pull/1374) Allow explicitly disabling tunneling for proxied https destinations (@nylen)
+- [#1376](https://github.com/request/request/pull/1376) Use karma-browserify for tests. Add browser test coverage reporter. (@eiriksm)
+- [#1366](https://github.com/request/request/pull/1366) Refactor OAuth into separate module (@simov)
+- [#1373](https://github.com/request/request/pull/1373) Rewrite tunnel test to be pure Node.js (@nylen)
+- [#1371](https://github.com/request/request/pull/1371) Upgrade test reporter (@nylen)
+- [#1360](https://github.com/request/request/pull/1360) Refactor basic, bearer, digest auth logic into separate class (@simov)
+- [#1354](https://github.com/request/request/pull/1354) Remove circular dependency from debugging code (@nylen)
+- [#1351](https://github.com/request/request/pull/1351) Move digest auth into private prototype method (@simov)
+- [#1352](https://github.com/request/request/pull/1352) Update hawk dependency to ~2.3.0 (@mridgway)
+- [#1353](https://github.com/request/request/pull/1353) Correct travis-ci badge (@dogancelik)
+- [#1349](https://github.com/request/request/pull/1349) Make sure we return on errored browser requests. (@eiriksm)
+- [#1346](https://github.com/request/request/pull/1346) getProxyFromURI Extraction Refactor (@seanstrom)
+- [#1337](https://github.com/request/request/pull/1337) Standardize test ports on 6767 (@nylen)
+- [#1341](https://github.com/request/request/pull/1341) Emit FormData error events as Request error events (@nylen, @rwky)
+- [#1343](https://github.com/request/request/pull/1343) Clean up readme badges, and add Travis and Coveralls badges (@nylen)
+- [#1345](https://github.com/request/request/pull/1345) Update README.md (@Aaron-Hartwig)
+- [#1338](https://github.com/request/request/pull/1338) Always wait for server.close() callback in tests (@nylen)
+- [#1342](https://github.com/request/request/pull/1342) Add mock https server and redo start of browser tests for this purpose. (@eiriksm)
+- [#1339](https://github.com/request/request/pull/1339) Improve auth docs (@nylen)
+- [#1335](https://github.com/request/request/pull/1335) Add support for OAuth plaintext signature method (@simov)
+- [#1332](https://github.com/request/request/pull/1332) Add clean script to remove test-browser.js after the tests run (@seanstrom)
+- [#1327](https://github.com/request/request/pull/1327) Fix errors generating coverage reports. (@nylen)
+- [#1330](https://github.com/request/request/pull/1330) Return empty buffer upon empty response body and encoding is set to null (@seanstrom)
+- [#1326](https://github.com/request/request/pull/1326) Use faster container-based infrastructure on Travis (@nylen)
+- [#1315](https://github.com/request/request/pull/1315) Implement rfc3986 option (@simov)
+- [#1314](https://github.com/request/request/pull/1314) Detect urlencoded form data header via regex (@simov)
+- [#1317](https://github.com/request/request/pull/1317) Improve OAuth1.0 server side flow example (@simov)
+
### v2.51.0 (2014/12/10)
- [#1310](https://github.com/request/request/pull/1310) Revert changes introduced in https://github.com/request/request/pull/1282 (@simov)
- [#987](https://github.com/request/request/pull/987) Show optional modules as being loaded by the module that reqeusted them (@iarna)
### v2.39.0 (2014/07/24)
-- [#976](https://github.com/request/request/pull/976) Update README.md (@fosco-maestro)
+- [#976](https://github.com/request/request/pull/976) Update README.md (@pvoznenko)
### v2.38.0 (2014/07/22)
- [#952](https://github.com/request/request/pull/952) Adding support to client certificate with proxy use case (@ofirshaked)
# Request — Simplified HTTP client
-[![NPM](https://nodei.co/npm/request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/request/)
+[![npm package](https://nodei.co/npm/request.png?downloads=true&downloadRank=true&stars=true)](https://nodei.co/npm/request/)
-[![Gitter](https://badges.gitter.im/Join Chat.svg)](https://gitter.im/request/request?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
+[![Build status](https://img.shields.io/travis/request/request.svg?style=flat)](https://travis-ci.org/request/request)
+[![Coverage](https://img.shields.io/coveralls/request/request.svg?style=flat)](https://coveralls.io/r/request/request)
+[![Gitter](https://img.shields.io/badge/gitter-join_chat-blue.svg?style=flat)](https://gitter.im/request/request?utm_source=badge)
## Super simple to use
var request = require('request');
request('http://www.google.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
- console.log(body) // Print the google web page.
+ console.log(body) // Show the HTML for the Google homepage.
}
})
```
straightforward HTTP proxy in this case. However, if you would like
to force a tunneling proxy, you may set the `tunnel` option to `true`.
+You can also make a standard proxied `http` request by explicitly setting
+`tunnel : false`, but **note that this will allow the proxy to see the traffic
+to/from the destination server**.
+
If you are using a tunneling proxy, you may set the
`proxyHeaderWhiteList` to share certain headers with the proxy.
});
```
-If passed as an option, `auth` should be a hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). The method form takes parameters `auth(username, password, sendImmediately)`.
+If passed as an option, `auth` should be a hash containing values:
+
+- `user` || `username`
+- `pass` || `password`
+- `sendImmediately` (optional)
+- `bearer` (optional)
-`sendImmediately` defaults to `true`, which causes a basic authentication header to be sent. If `sendImmediately` is `false`, then `request` will retry with a proper authentication header after receiving a `401` response from the server (which must contain a `WWW-Authenticate` header indicating the required authentication method).
+The method form takes parameters
+`auth(username, password, sendImmediately, bearer)`.
-Note that you can also use for basic authentication a trick using the URL itself, as specified in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt).
-Simply pass the `user:password` before the host with an `@` sign.
+`sendImmediately` defaults to `true`, which causes a basic or bearer
+authentication header to be sent. If `sendImmediately` is `false`, then
+`request` will retry with a proper authentication header after receiving a
+`401` response from the server (which must contain a `WWW-Authenticate` header
+indicating the required authentication method).
+
+Note that you can also specify basic authentication using the URL itself, as
+detailed in [RFC 1738](http://www.ietf.org/rfc/rfc1738.txt). Simply pass the
+`user:password` before the host with an `@` sign:
```javascript
var username = 'username',
});
```
-Digest authentication is supported, but it only works with `sendImmediately` set to `false`; otherwise `request` will send basic authentication on the initial request, which will probably cause the request to fail.
+Digest authentication is supported, but it only works with `sendImmediately`
+set to `false`; otherwise `request` will send basic authentication on the
+initial request, which will probably cause the request to fail.
-Bearer authentication is supported, and is activated when the `bearer` value is available. The value may be either a `String` or a `Function` returning a `String`. Using a function to supply the bearer token is particularly useful if used in conjuction with `defaults` to allow a single function to supply the last known token at the time or sending a request or to compute one on the fly.
+Bearer authentication is supported, and is activated when the `bearer` value is
+available. The value may be either a `String` or a `Function` returning a
+`String`. Using a function to supply the bearer token is particularly useful if
+used in conjuction with `defaults` to allow a single function to supply the
+last known token at the time of sending a request, or to compute one on the fly.
## OAuth Signing
[HMAC-SHA1](https://tools.ietf.org/html/rfc5849#section-3.4.2):
```javascript
-// Twitter OAuth
+// OAuth1.0 - 3-legged server side flow (Twitter example)
+// step 1
var qs = require('querystring')
, oauth =
{ callback: 'http://mysite.com/callback/'
// and construct a URL that a user clicks on (like a sign in button).
// The verifier is only available in the response after a user has
// verified with twitter that they are authorizing your app.
- var access_token = qs.parse(body)
+
+ // step 2
+ var req_data = qs.parse(body)
+ var uri = 'https://api.twitter.com/oauth/authenticate'
+ + '?' + qs.stringify({oauth_token: req_data.oauth_token})
+ // redirect the user to the authorize uri
+
+ // step 3
+ // after the user is redirected back to your server
+ var auth_data = qs.parse(body)
, oauth =
{ consumer_key: CONSUMER_KEY
, consumer_secret: CONSUMER_SECRET
- , token: access_token.oauth_token
- , verifier: access_token.oauth_verifier
+ , token: auth_data.oauth_token
+ , token_secret: req_data.oauth_token_secret
+ , verifier: auth_data.oauth_verifier
}
, url = 'https://api.twitter.com/oauth/access_token'
;
request.post({url:url, oauth:oauth}, function (e, r, body) {
- var perm_token = qs.parse(body)
+ // ready to make signed requests on behalf of the user
+ var perm_data = qs.parse(body)
, oauth =
{ consumer_key: CONSUMER_KEY
, consumer_secret: CONSUMER_SECRET
- , token: perm_token.oauth_token
- , token_secret: perm_token.oauth_token_secret
+ , token: perm_data.oauth_token
+ , token_secret: perm_data.oauth_token_secret
}
- , url = 'https://api.twitter.com/1.1/users/show.json?'
- , params =
- { screen_name: perm_token.screen_name
- , user_id: perm_token.user_id
+ , url = 'https://api.twitter.com/1.1/users/show.json'
+ , qs =
+ { screen_name: perm_data.screen_name
+ , user_id: perm_data.user_id
}
;
- url += qs.stringify(params)
request.get({url:url, oauth:oauth, json:true}, function (e, r, user) {
console.log(user)
})
* Instead of `consumer_secret`, specify a `private_key` string in
[PEM format](http://how2ssl.com/articles/working_with_pem_files/)
+For [PLAINTEXT signing](http://oauth.net/core/1.0/#anchor22), make
+the following changes to the OAuth options object:
+* Pass `signature_method : 'PLAINTEXT'`
+
+To send OAuth parameters via query params or in a post body as described in The
+[Consumer Request Parameters](http://oauth.net/core/1.0/#consumer_req_param)
+section of the oauth1 spec:
+* Pass `transport_method : 'query'` or `transport_method : 'body'` in the OAuth
+ options object.
+* `transport_method` defaults to `'header'`
+
## Custom HTTP Headers
HTTP Headers, such as `User-Agent`, can be set in the `options` object.
* Alternatively you can pass in an object `{chunked: false, data: []}` where
`chunked` is used to specify whether the request is sent in
[chunked transfer encoding](https://en.wikipedia.org/wiki/Chunked_transfer_encoding)
- (the default is `chunked: true`). In non-chunked requests, data items with
- body streams are not allowed.
+ In non-chunked requests, data items with body streams are not allowed.
* `auth` - A hash containing values `user` || `username`, `pass` || `password`, and `sendImmediately` (optional). See documentation above.
* `json` - sets `body` but to JSON representation of value and adds `Content-type: application/json` header. Additionally, parses the response body as JSON.
* `jsonReviver` - a [reviver function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse) that will be passed to `JSON.parse()` when parsing a JSON response body.
work around this, either use [`request.defaults`](#requestdefaultsoptions)
with your pool options or create the pool object with the `maxSockets`
property outside of the loop.
-* `timeout` - Integer containing the number of milliseconds to wait for a request to respond before aborting the request
+* `timeout` - Integer containing the number of milliseconds to wait for a
+ request to respond before aborting the request. Note that if the underlying
+ TCP connection cannot be established, the OS-wide TCP connection timeout will
+ overrule the `timeout` option ([the default in Linux is around 20 seconds](http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout)).
* `proxy` - An HTTP proxy to be used. Supports proxy Auth with Basic Auth, identical to support for the `url` parameter (by embedding the auth info in the `uri`)
* `oauth` - Options for OAuth HMAC-SHA1 signing. See documentation above.
* `hawk` - Options for [Hawk signing](https://github.com/hueniverse/hawk). The `credentials` key must contain the necessary signing info, [see hawk docs for details](https://github.com/hueniverse/hawk#usage-example).
* `httpSignature` - Options for the [HTTP Signature Scheme](https://github.com/joyent/node-http-signature/blob/master/http_signing.md) using [Joyent's library](https://github.com/joyent/node-http-signature). The `keyId` and `key` properties must be specified. See the docs for other options.
* `localAddress` - Local interface to bind for network connections.
* `gzip` - If `true`, add an `Accept-Encoding` header to request compressed content encodings from the server (if not already present) and decode supported content encodings in the response. **Note:** Automatic decoding of the response content is performed on the body data returned through `request` (both through the `request` stream and passed to the callback function) but is not performed on the `response` stream (available from the `response` event) which is the unmodified `http.IncomingMessage` object which may contain compressed data. See example below.
-* `tunnel` - If `true`, then *always* use a tunneling proxy. If
- `false` (default), then tunneling will only be used if the
- destination is `https`, or if a previous request in the redirect
- chain used a tunneling proxy.
+* `tunnel` - controls the behavior of
+ [HTTP `CONNECT` tunneling](https://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_tunneling)
+ as follows:
+ * `undefined` (default) - `true` if the destination is `https` or a previous
+ request in the redirect chain used a tunneling proxy, `false` otherwise
+ * `true` - always tunnel to the destination by making a `CONNECT` request to
+ the proxy
+ * `false` - request the destination as a `GET` request.
* `proxyHeaderWhiteList` - A whitelist of headers to send to a
tunneling proxy.
* `proxyHeaderExclusiveList` - A whitelist of headers to send
### request.head
-Same as request() but defaults to `method: "HEAD"`.
+Same as `request()`, but defaults to `method: "HEAD"`.
```javascript
request.head(url)
module.exports = request
request.Request = require('./request')
-request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
request.initParams = initParams
+
+// Backwards compatibility for request.debug
+Object.defineProperty(request, 'debug', {
+ enumerable : true,
+ get : function() {
+ return request.Request.debug
+ },
+ set : function(debug) {
+ request.Request.debug = debug
+ }
+})
--- /dev/null
+'use strict'
+
+var caseless = require('caseless')
+ , uuid = require('node-uuid')
+ , helpers = require('./helpers')
+
+var md5 = helpers.md5
+ , toBase64 = helpers.toBase64
+
+
+function Auth () {
+ // define all public properties here
+ this.hasAuth = false
+ this.sentAuth = false
+ this.bearerToken = null
+ this.user = null
+ this.pass = null
+}
+
+Auth.prototype.basic = function (user, pass, sendImmediately) {
+ var self = this
+ if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
+ throw new Error('auth() received invalid user or password')
+ }
+ self.user = user
+ self.pass = pass
+ self.hasAuth = true
+ var header = typeof pass !== 'undefined' ? user + ':' + pass : user
+ if (sendImmediately || typeof sendImmediately === 'undefined') {
+ var authHeader = 'Basic ' + toBase64(header)
+ self.sentAuth = true
+ return authHeader
+ }
+}
+
+Auth.prototype.bearer = function (bearer, sendImmediately) {
+ var self = this
+ self.bearerToken = bearer
+ self.hasAuth = true
+ if (sendImmediately || typeof sendImmediately === 'undefined') {
+ if (typeof bearer === 'function') {
+ bearer = bearer()
+ }
+ var authHeader = 'Bearer ' + bearer
+ self.sentAuth = true
+ return authHeader
+ }
+}
+
+Auth.prototype.digest = function (method, path, authHeader) {
+ // TODO: More complete implementation of RFC 2617.
+ // - check challenge.algorithm
+ // - support algorithm="MD5-sess"
+ // - handle challenge.domain
+ // - support qop="auth-int" only
+ // - handle Authentication-Info (not necessarily?)
+ // - check challenge.stale (not necessarily?)
+ // - increase nc (not necessarily?)
+ // For reference:
+ // http://tools.ietf.org/html/rfc2617#section-3
+ // https://github.com/bagder/curl/blob/master/lib/http_digest.c
+
+ var self = this
+
+ var challenge = {}
+ var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
+ for (;;) {
+ var match = re.exec(authHeader)
+ if (!match) {
+ break
+ }
+ challenge[match[1]] = match[2] || match[3]
+ }
+
+ var ha1 = md5(self.user + ':' + challenge.realm + ':' + self.pass)
+ var ha2 = md5(method + ':' + path)
+ var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
+ var nc = qop && '00000001'
+ var cnonce = qop && uuid().replace(/-/g, '')
+ var digestResponse = qop
+ ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2)
+ : md5(ha1 + ':' + challenge.nonce + ':' + ha2)
+ var authValues = {
+ username: self.user,
+ realm: challenge.realm,
+ nonce: challenge.nonce,
+ uri: path,
+ qop: qop,
+ response: digestResponse,
+ nc: nc,
+ cnonce: cnonce,
+ algorithm: challenge.algorithm,
+ opaque: challenge.opaque
+ }
+
+ authHeader = []
+ for (var k in authValues) {
+ if (authValues[k]) {
+ if (k === 'qop' || k === 'nc' || k === 'algorithm') {
+ authHeader.push(k + '=' + authValues[k])
+ } else {
+ authHeader.push(k + '="' + authValues[k] + '"')
+ }
+ }
+ }
+ authHeader = 'Digest ' + authHeader.join(', ')
+ self.sentAuth = true
+ return authHeader
+}
+
+Auth.prototype.response = function (method, path, headers) {
+ var self = this
+ if (!self.hasAuth || self.sentAuth) { return null }
+
+ var c = caseless(headers)
+
+ var authHeader = c.get('www-authenticate')
+ var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase()
+ // debug('reauth', authVerb)
+
+ switch (authVerb) {
+ case 'basic':
+ return self.basic(self.user, self.pass, true)
+
+ case 'bearer':
+ return self.bearer(self.bearerToken, true)
+
+ case 'digest':
+ return self.digest(method, path, authHeader)
+ }
+}
+
+exports.Auth = Auth
+++ /dev/null
-'use strict'
-
-var util = require('util')
- , request = require('../index')
-
-
-module.exports = function debug() {
- if (request.debug) {
- console.error('REQUEST %s', util.format.apply(util, arguments))
- }
-}
--- /dev/null
+'use strict'
+
+function formatHostname(hostname) {
+ // canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
+ return hostname.replace(/^\.*/, '.').toLowerCase()
+}
+
+function parseNoProxyZone(zone) {
+ zone = zone.trim().toLowerCase()
+
+ var zoneParts = zone.split(':', 2)
+ , zoneHost = formatHostname(zoneParts[0])
+ , zonePort = zoneParts[1]
+ , hasPort = zone.indexOf(':') > -1
+
+ return {hostname: zoneHost, port: zonePort, hasPort: hasPort}
+}
+
+function uriInNoProxy(uri, noProxy) {
+ var port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
+ , hostname = formatHostname(uri.hostname)
+ , noProxyList = noProxy.split(',')
+
+ // iterate through the noProxyList until it finds a match.
+ return noProxyList.map(parseNoProxyZone).some(function(noProxyZone) {
+ var isMatchedAt = hostname.indexOf(noProxyZone.hostname)
+ , hostnameMatched = (
+ isMatchedAt > -1 &&
+ (isMatchedAt === hostname.length - noProxyZone.hostname.length)
+ )
+
+ if (noProxyZone.hasPort) {
+ return (port === noProxyZone.port) && hostnameMatched
+ }
+
+ return hostnameMatched
+ })
+}
+
+function getProxyFromURI(uri) {
+ // Decide the proper request proxy to use based on the request URI object and the
+ // environmental variables (NO_PROXY, HTTP_PROXY, etc.)
+ // respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html)
+
+ var noProxy = process.env.NO_PROXY || process.env.no_proxy || ''
+
+ // if the noProxy is a wildcard then return null
+
+ if (noProxy === '*') {
+ return null
+ }
+
+ // if the noProxy is not empty and the uri is found return null
+
+ if (noProxy !== '' && uriInNoProxy(uri, noProxy)) {
+ return null
+ }
+
+ // Check for HTTP or HTTPS Proxy in environment Else default to null
+
+ if (uri.protocol === 'http:') {
+ return process.env.HTTP_PROXY ||
+ process.env.http_proxy || null
+ }
+
+ if (uri.protocol === 'https:') {
+ return process.env.HTTPS_PROXY ||
+ process.env.https_proxy ||
+ process.env.HTTP_PROXY ||
+ process.env.http_proxy || null
+ }
+
+ // if none of that works, return null
+ // (What uri protocol are you using then?)
+
+ return null
+}
+
+module.exports = getProxyFromURI
--- /dev/null
+'use strict'
+
+var querystring = require('querystring')
+ , qs = require('qs')
+ , caseless = require('caseless')
+ , uuid = require('node-uuid')
+ , oauth = require('oauth-sign')
+
+
+exports.buildParams = function (_oauth, uri, method, query, form, qsLib) {
+ var oa = {}
+ for (var i in _oauth) {
+ oa['oauth_' + i] = _oauth[i]
+ }
+ if (!oa.oauth_version) {
+ oa.oauth_version = '1.0'
+ }
+ if (!oa.oauth_timestamp) {
+ oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString()
+ }
+ if (!oa.oauth_nonce) {
+ oa.oauth_nonce = uuid().replace(/-/g, '')
+ }
+ if (!oa.oauth_signature_method) {
+ oa.oauth_signature_method = 'HMAC-SHA1'
+ }
+
+ var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key
+ delete oa.oauth_consumer_secret
+ delete oa.oauth_private_key
+
+ var token_secret = oa.oauth_token_secret
+ delete oa.oauth_token_secret
+
+ var realm = oa.oauth_realm
+ delete oa.oauth_realm
+ delete oa.oauth_transport_method
+
+ var baseurl = uri.protocol + '//' + uri.host + uri.pathname
+ var params = qsLib.parse([].concat(query, form, qsLib.stringify(oa)).join('&'))
+
+ oa.oauth_signature = oauth.sign(
+ oa.oauth_signature_method,
+ method,
+ baseurl,
+ params,
+ consumer_secret_or_private_key,
+ token_secret)
+
+ if (realm) {
+ oa.realm = realm
+ }
+
+ return oa
+}
+
+exports.concatParams = function (oa, sep, wrap) {
+ wrap = wrap || ''
+
+ var params = Object.keys(oa).filter(function (i) {
+ return i !== 'realm' && i !== 'oauth_signature'
+ }).sort()
+
+ if (oa.realm) {
+ params.splice(0, 1, 'realm')
+ }
+ params.push('oauth_signature')
+
+ return params.map(function (i) {
+ return i + '=' + wrap + oauth.rfc3986(oa[i]) + wrap
+ }).join(sep)
+}
+
+exports.oauth = function (args) {
+ var uri = args.uri || {}
+ , method = args.method || ''
+ , headers = caseless(args.headers)
+ , body = args.body || ''
+ , _oauth = args.oauth || {}
+ , qsLib = args.qsLib || qs
+
+ var form
+ , query
+ , contentType = headers.get('content-type') || ''
+ , formContentType = 'application/x-www-form-urlencoded'
+ , transport = _oauth.transport_method || 'header'
+
+ if (contentType.slice(0, formContentType.length) === formContentType) {
+ contentType = formContentType
+ form = body
+ }
+ if (uri.query) {
+ query = uri.query
+ }
+ if (transport === 'body' && (method !== 'POST' || contentType !== formContentType)) {
+ throw new Error('oauth: transport_method of \'body\' requires \'POST\' ' +
+ 'and content-type \'' + formContentType + '\'')
+ }
+
+ var oa = this.buildParams(_oauth, uri, method, query, form, qsLib)
+
+ var data
+ switch (transport) {
+ case 'header':
+ data = 'OAuth ' + this.concatParams(oa, ',', '"')
+ break
+
+ case 'query':
+ data = (query ? '&' : '?') + this.concatParams(oa, '&')
+ break
+
+ case 'body':
+ data = (form ? form + '&' : '') + this.concatParams(oa, '&')
+ break
+
+ default:
+ throw new Error('oauth: transport_method invalid')
+ }
+
+ return {oauth:data, transport:transport}
+}
=======
-## License
+<a name="license"></a>
+## License & copyright
-**bl** is Copyright (c) 2013 Rod Vagg [@rvagg](https://twitter.com/rvagg) and licenced under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.
+Copyright (c) 2013-2014 bl contributors (listed above).
+
+bl is licensed under the MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.
-var DuplexStream = require('readable-stream').Duplex
+var DuplexStream = require('readable-stream/duplex')
, util = require('util')
function BufferList (callback) {
{
"name": "bl",
- "version": "0.9.3",
+ "version": "0.9.4",
"description": "Buffer List: collect buffers and access with a standard readable Buffer interface, streamable too!",
"main": "bl.js",
"scripts": {
"faucet": "~0.0.1",
"brtapsauce": "~0.3.0"
},
- "gitHead": "4987a76bf6bafd7616e62c7023c955e62f3a9461",
+ "gitHead": "e7f90703c5f90ca26f60455ea6ad0b6be4a9feee",
"bugs": {
"url": "https://github.com/rvagg/bl/issues"
},
- "_id": "bl@0.9.3",
- "_shasum": "c41eff3e7cb31bde107c8f10076d274eff7f7d44",
+ "_id": "bl@0.9.4",
+ "_shasum": "4702ddf72fbe0ecd82787c00c113aea1935ad0e7",
"_from": "bl@>=0.9.0 <0.10.0",
- "_npmVersion": "1.4.27",
+ "_npmVersion": "2.1.18",
+ "_nodeVersion": "1.0.3",
"_npmUser": {
"name": "rvagg",
"email": "rod@vagg.org"
}
],
"dist": {
- "shasum": "c41eff3e7cb31bde107c8f10076d274eff7f7d44",
- "tarball": "http://registry.npmjs.org/bl/-/bl-0.9.3.tgz"
+ "shasum": "4702ddf72fbe0ecd82787c00c113aea1935ad0e7",
+ "tarball": "http://registry.npmjs.org/bl/-/bl-0.9.4.tgz"
},
"directories": {},
- "_resolved": "https://registry.npmjs.org/bl/-/bl-0.9.3.tgz",
+ "_resolved": "https://registry.npmjs.org/bl/-/bl-0.9.4.tgz",
"readme": "ERROR: No README data found!"
}
function Caseless (dict) {
- this.dict = dict
+ this.dict = dict || {}
}
Caseless.prototype.set = function (name, value, clobber) {
if (typeof name === 'object') {
{
"name": "caseless",
- "version": "0.8.0",
+ "version": "0.9.0",
"description": "Caseless object set/get/has, very useful when working with HTTP headers.",
"main": "index.js",
"scripts": {
"devDependencies": {
"tape": "^2.10.2"
},
- "gitHead": "1bfbf01d4481c057738a64ba284749222a944176",
+ "gitHead": "5ff0ccebbbf14dad5dc91def1f274887801db3e3",
"homepage": "https://github.com/mikeal/caseless",
- "_id": "caseless@0.8.0",
- "_shasum": "5bca2881d41437f54b2407ebe34888c7b9ad4f7d",
- "_from": "caseless@>=0.8.0 <0.9.0",
- "_npmVersion": "2.0.0",
+ "_id": "caseless@0.9.0",
+ "_shasum": "b7b65ce6bf1413886539cfd533f0b30effa9cf88",
+ "_from": "caseless@>=0.9.0 <0.10.0",
+ "_npmVersion": "1.4.14",
"_npmUser": {
- "name": "mikeal",
- "email": "mikeal.rogers@gmail.com"
+ "name": "nylen",
+ "email": "jnylen@gmail.com"
},
"maintainers": [
{
"name": "mikeal",
"email": "mikeal.rogers@gmail.com"
+ },
+ {
+ "name": "nylen",
+ "email": "jnylen@gmail.com"
}
],
"dist": {
- "shasum": "5bca2881d41437f54b2407ebe34888c7b9ad4f7d",
- "tarball": "http://registry.npmjs.org/caseless/-/caseless-0.8.0.tgz"
+ "shasum": "b7b65ce6bf1413886539cfd533f0b30effa9cf88",
+ "tarball": "http://registry.npmjs.org/caseless/-/caseless-0.9.0.tgz"
},
"directories": {},
- "_resolved": "https://registry.npmjs.org/caseless/-/caseless-0.8.0.tgz",
+ "_resolved": "https://registry.npmjs.org/caseless/-/caseless-0.9.0.tgz",
"readme": "ERROR: No README data found!"
}
+++ /dev/null
-
-The MIT License (MIT)
-
-Copyright (c) 2014 Jonathan Ong me@jongleberry.com
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in
-all copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-THE SOFTWARE.
+++ /dev/null
-# mime-types
-
-[![NPM Version][npm-image]][npm-url]
-[![NPM Downloads][downloads-image]][downloads-url]
-[![Node.js Version][node-version-image]][node-version-url]
-[![Build Status][travis-image]][travis-url]
-[![Test Coverage][coveralls-image]][coveralls-url]
-
-The ultimate javascript content-type utility.
-
-Similar to [node-mime](https://github.com/broofa/node-mime), except:
-
-- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`,
- so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`.
-- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`.
-- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db)
-- No `.define()` functionality
-
-Otherwise, the API is compatible.
-
-## Install
-
-```sh
-$ npm install mime-types
-```
-
-## Adding Types
-
-All mime types are based on [mime-db](https://github.com/jshttp/mime-db),
-so open a PR there if you'd like to add mime types.
-
-## API
-
-```js
-var mime = require('mime-types')
-```
-
-All functions return `false` if input is invalid or not found.
-
-### mime.lookup(path)
-
-Lookup the content-type associated with a file.
-
-```js
-mime.lookup('json') // 'application/json'
-mime.lookup('.md') // 'text/x-markdown'
-mime.lookup('file.html') // 'text/html'
-mime.lookup('folder/file.js') // 'application/javascript'
-
-mime.lookup('cats') // false
-```
-
-### mime.contentType(type)
-
-Create a full content-type header given a content-type or extension.
-
-```js
-mime.contentType('markdown') // 'text/x-markdown; charset=utf-8'
-mime.contentType('file.json') // 'application/json; charset=utf-8'
-```
-
-### mime.extension(type)
-
-Get the default extension for a content-type.
-
-```js
-mime.extension('application/octet-stream') // 'bin'
-```
-
-### mime.charset(type)
-
-Lookup the implied default charset of a content-type.
-
-```js
-mime.charset('text/x-markdown') // 'UTF-8'
-```
-
-### var type = mime.types[extension]
-
-A map of content-types by extension.
-
-### [extensions...] = mime.extensions[type]
-
-A map of extensions by content-type.
-
-## License
-
-[MIT](LICENSE)
-
-[npm-image]: https://img.shields.io/npm/v/mime-types.svg?style=flat
-[npm-url]: https://npmjs.org/package/mime-types
-[node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat
-[node-version-url]: http://nodejs.org/download/
-[travis-image]: https://img.shields.io/travis/jshttp/mime-types.svg?style=flat
-[travis-url]: https://travis-ci.org/jshttp/mime-types
-[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-types.svg?style=flat
-[coveralls-url]: https://coveralls.io/r/jshttp/mime-types
-[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg?style=flat
-[downloads-url]: https://npmjs.org/package/mime-types
+++ /dev/null
-{
- "name": "mime-types",
- "description": "The ultimate javascript content-type utility.",
- "version": "2.0.4",
- "contributors": [
- {
- "name": "Jeremiah Senkpiel",
- "email": "fishrock123@rocketmail.com",
- "url": "https://searchbeam.jit.su"
- },
- {
- "name": "Jonathan Ong",
- "email": "me@jongleberry.com",
- "url": "http://jongleberry.com"
- }
- ],
- "license": "MIT",
- "keywords": [
- "mime",
- "types"
- ],
- "repository": {
- "type": "git",
- "url": "https://github.com/jshttp/mime-types"
- },
- "dependencies": {
- "mime-db": "~1.3.0"
- },
- "devDependencies": {
- "istanbul": "0",
- "mocha": "~1.21.5"
- },
- "files": [
- "HISTORY.md",
- "LICENSE",
- "index.js"
- ],
- "engines": {
- "node": ">= 0.6"
- },
- "scripts": {
- "test": "mocha --reporter spec test/test.js",
- "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/test.js",
- "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot test/test.js"
- },
- "gitHead": "63a9b82e6e364d62428ed5459e5486504c489bf2",
- "bugs": {
- "url": "https://github.com/jshttp/mime-types/issues"
- },
- "homepage": "https://github.com/jshttp/mime-types",
- "_id": "mime-types@2.0.4",
- "_shasum": "855a612979141d806ba5104294a28c731c6ea790",
- "_from": "mime-types@>=2.0.3 <2.1.0",
- "_npmVersion": "1.4.21",
- "_npmUser": {
- "name": "dougwilson",
- "email": "doug@somethingdoug.com"
- },
- "maintainers": [
- {
- "name": "jongleberry",
- "email": "jonathanrichardong@gmail.com"
- },
- {
- "name": "fishrock123",
- "email": "fishrock123@rocketmail.com"
- },
- {
- "name": "dougwilson",
- "email": "doug@somethingdoug.com"
- }
- ],
- "dist": {
- "shasum": "855a612979141d806ba5104294a28c731c6ea790",
- "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.0.4.tgz"
- },
- "directories": {},
- "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.0.4.tgz",
- "readme": "ERROR: No README data found!"
-}
-.idea\r
-*.iml\r
-npm-debug.log\r
-dump.rdb\r
-node_modules\r
-results.tap\r
-results.xml\r
-npm-shrinkwrap.json\r
-config.json\r
-.DS_Store\r
-*/.DS_Store\r
-*/*/.DS_Store\r
-._*\r
-*/._*\r
-*/*/._*\r
-coverage.*\r
-lib-cov\r
-\r
+.idea
+*.iml
+npm-debug.log
+dump.rdb
+node_modules
+components
+build
+results.tap
+results.xml
+npm-shrinkwrap.json
+config.json
+.DS_Store
+*/.DS_Store
+*/*/.DS_Store
+._*
+*/._*
+*/*/._*
+coverage.*
+lib-cov
-language: node_js\r
-\r
-node_js:\r
- - 0.10\r
-\r
+language: node_js
+
+node_js:
+ - 0.10
-Copyright (c) 2012-2013, Eran Hammer.
+Copyright (c) 2012-2014, Eran Hammer and other contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- * Neither the name of Eran Hammer nor the
- names of its contributors may be used to endorse or promote products
- derived from this software without specific prior written permission.
+ * The names of any contributors may not be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL ERAN HAMMER BE LIABLE FOR ANY
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ * * *
+
+The complete list of contributors can be found at: https://github.com/hueniverse/hawk/graphs/contributors
test:
- @node node_modules/lab/bin/lab
+ @node node_modules/lab/bin/lab -a code
test-cov:
- @node node_modules/lab/bin/lab -r threshold -t 100
+ @node node_modules/lab/bin/lab -a code -t 100
test-cov-html:
- @node node_modules/lab/bin/lab -r html -o coverage.html
-complexity:
- @node node_modules/complexity-report/src/cli.js -o complexity.md -f markdown lib
+ @node node_modules/lab/bin/lab -a code -r html -o coverage.html
-.PHONY: test test-cov test-cov-html complexity
+.PHONY: test test-cov test-cov-html
<img align="right" src="https://raw.github.com/hueniverse/hawk/master/images/logo.png" /> **Hawk** is an HTTP authentication scheme using a message authentication code (MAC) algorithm to provide partial
HTTP request cryptographic verification. For more complex use cases such as access delegation, see [Oz](https://github.com/hueniverse/oz).
-Current version: **1.0**
+Current version: **2.3**
+
+Note: 2.x is the same exact protocol as 1.1. The version increment reflects a change in the internal error format
+used by the module and used by the node API.
[![Build Status](https://secure.travis-ci.org/hueniverse/hawk.png)](http://travis-ci.org/hueniverse/hawk)
<p></p>
- [**Frequently Asked Questions**](#frequently-asked-questions)
<p></p>
+- [**Implementations**](#implementations)
- [**Acknowledgements**](#acknowledgements)
# Introduction
## Browser Support and Considerations
-A browser script is provided for including using a `<script>` tag in [lib/browser.js](/lib/browser.js).
+A browser script is provided for including using a `<script>` tag in [lib/browser.js](/lib/browser.js). It's also a [component](http://component.io/hueniverse/hawk).
**Hawk** relies on the _Server-Authorization_ and _WWW-Authenticate_ headers in its response to communicate with the client.
Therefore, in case of CORS requests, it is important to consider sending _Access-Control-Expose-Headers_ with the value
### Is it done?
-At if version 0.10.0, **Hawk** is feature-complete. However, until this module reaches version 1.0.0 it is considered experimental
+As of version 0.10.0, **Hawk** is feature-complete. However, until this module reaches version 1.0.0 it is considered experimental
and is likely to change. This also means your feedback and contribution are very welcome. Feel free to open issues with questions
and suggestions.
When calculating a hash or MAC, a static prefix (tag) is added. The prefix is used to prevent MAC values from being
used or reused for a purpose other than what they were created for (i.e. prevents switching MAC values between a request,
-response, and a bewit use cases). It also protects against expliots created after a potential change in how the protocol
+response, and a bewit use cases). It also protects against exploits created after a potential change in how the protocol
creates the normalized string. For example, if a future version would switch the order of nonce and timestamp, it
can create an exploit opportunity for cases where the nonce is similar in format to a timestamp.
**Hawk** provides a simple HTTP authentication scheme for making client-server requests. It does not address the OAuth use case
of delegating access to a third party. If you are looking for an OAuth alternative, check out [Oz](https://github.com/hueniverse/oz).
+# Implementations
+
+- [Logibit Hawk in F#/.Net](https://github.com/logibit/logibit.hawk/)
+- [Tent Hawk in Ruby](https://github.com/tent/hawk-ruby)
+- [Wealdtech in Java](https://github.com/wealdtech/hawk)
+- [Kumar's Mohawk in Python](https://github.com/kumar303/mohawk/)
# Acknowledgements
--- /dev/null
+{
+ "name": "hawk",
+ "main": "lib/browser.js",
+ "license": "./LICENSE",
+ "ignore": [
+ "!lib",
+ "lib/*",
+ "!lib/browser.js",
+ "index.js"
+ ],
+ "keywords": [
+ "http",
+ "authentication",
+ "scheme",
+ "hawk"
+ ],
+ "authors": [
+ "Eran Hammer <eran@hammer.io>"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "git://github.com/hueniverse/hawk.git"
+ }
+}
--- /dev/null
+{
+ "name": "hawk",
+ "repo": "hueniverse/hawk",
+ "description": "HTTP Hawk Authentication Scheme",
+ "version": "1.0.0",
+ "keywords": [
+ "http",
+ "authentication",
+ "scheme",
+ "hawk"
+ ],
+ "dependencies": {},
+ "development": {},
+ "license": "BSD",
+ "main": "lib/browser.js",
+ "scripts": [
+ "lib/browser.js"
+ ]
+}
\ No newline at end of file
/*
HTTP Hawk Authentication Scheme
- Copyright (c) 2012-2013, Eran Hammer <eran@hueniverse.com>
- MIT Licensed
+ Copyright (c) 2012-2014, Eran Hammer <eran@hammer.io>
+ BSD Licensed
*/
// Declare namespace
-var hawk = {};
-
-
-// Export if used as a module
+var hawk = {
+ internals: {}
+};
-if (typeof module !== "undefined" && module.exports) {
- module.exports = hawk;
-}
hawk.client = {
// Generate an Authorization header for a given request
/*
- uri: 'http://example.com/resource?a=b'
+ uri: 'http://example.com/resource?a=b' or object generated by hawk.utils.parseUri()
method: HTTP verb (e.g. 'GET', 'POST')
options: {
// Application time
- var timestamp = options.timestamp || Math.floor((hawk.utils.now() + (options.localtimeOffsetMsec || 0)) / 1000)
+ var timestamp = options.timestamp || hawk.utils.now(options.localtimeOffsetMsec);
// Validate credentials
!credentials.key ||
!credentials.algorithm) {
- result.err = 'Invalid credential object';
+ result.err = 'Invalid credentials object';
return result;
}
// Calculate payload hash
if (!artifacts.hash &&
- options.hasOwnProperty('payload')) {
+ (options.payload || options.payload === '')) {
artifacts.hash = hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
}
return result;
},
+ // Generate a bewit value for a given URI
+
+ /*
+ uri: 'http://example.com/resource?a=b'
+ options: {
+
+ // Required
+
+ credentials: {
+ id: 'dh37fgj492je',
+ key: 'aoijedoaijsdlaksjdl',
+ algorithm: 'sha256' // 'sha1', 'sha256'
+ },
+ ttlSec: 60 * 60, // TTL in seconds
+
+ // Optional
+
+ ext: 'application-specific', // Application specific data sent via the ext attribute
+ localtimeOffsetMsec: 400 // Time offset to sync with server time
+ };
+ */
+
+ bewit: function (uri, options) {
+
+ // Validate inputs
+
+ if (!uri ||
+ (typeof uri !== 'string') ||
+ !options ||
+ typeof options !== 'object' ||
+ !options.ttlSec) {
+
+ return '';
+ }
+
+ options.ext = (options.ext === null || options.ext === undefined ? '' : options.ext); // Zero is valid value
+
+ // Application time
+
+ var now = hawk.utils.now(options.localtimeOffsetMsec);
+
+ // Validate credentials
+
+ var credentials = options.credentials;
+ if (!credentials ||
+ !credentials.id ||
+ !credentials.key ||
+ !credentials.algorithm) {
+
+ return '';
+ }
+
+ if (hawk.crypto.algorithms.indexOf(credentials.algorithm) === -1) {
+ return '';
+ }
+
+ // Parse URI
+
+ uri = hawk.utils.parseUri(uri);
+
+ // Calculate signature
+
+ var exp = now + options.ttlSec;
+ var mac = hawk.crypto.calculateMac('bewit', credentials, {
+ ts: exp,
+ nonce: '',
+ method: 'GET',
+ resource: uri.relative, // Maintain trailing '?' and query params
+ host: uri.hostname,
+ port: uri.port,
+ ext: options.ext
+ });
+
+ // Construct bewit: id\exp\mac\ext
+
+ var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext;
+ return hawk.utils.base64urlEncode(bewit);
+ },
// Validate server response
/*
request: object created via 'new XMLHttpRequest()' after response received
- artifacts: object recieved from header().artifacts
+ artifacts: object received from header().artifacts
options: {
payload: optional payload received
required: specifies if a Server-Authorization header is required. Defaults to 'false'
options = options || {};
- if (request.getResponseHeader('www-authenticate')) {
+ var getHeader = function (name) {
+
+ return request.getResponseHeader ? request.getResponseHeader(name) : request.getHeader(name);
+ };
+
+ var wwwAuthenticate = getHeader('www-authenticate');
+ if (wwwAuthenticate) {
// Parse HTTP WWW-Authenticate header
- var attributes = hawk.utils.parseAuthorizationHeader(request.getResponseHeader('www-authenticate'), ['ts', 'tsm', 'error']);
+ var attributes = hawk.utils.parseAuthorizationHeader(wwwAuthenticate, ['ts', 'tsm', 'error']);
if (!attributes) {
return false;
}
return false;
}
- hawk.utils.setNtpOffset(attributes.ts - Math.floor(Date.now() / 1000)); // Keep offset at 1 second precision
+ hawk.utils.setNtpOffset(attributes.ts - Math.floor((new Date()).getTime() / 1000)); // Keep offset at 1 second precision
}
}
// Parse HTTP Server-Authorization header
- if (!request.getResponseHeader('server-authorization') &&
+ var serverAuthorization = getHeader('server-authorization');
+ if (!serverAuthorization &&
!options.required) {
return true;
}
- var attributes = hawk.utils.parseAuthorizationHeader(request.getResponseHeader('server-authorization'), ['mac', 'ext', 'hash']);
+ var attributes = hawk.utils.parseAuthorizationHeader(serverAuthorization, ['mac', 'ext', 'hash']);
if (!attributes) {
return false;
}
return false;
}
- if (!options.hasOwnProperty('payload')) {
+ if (!options.payload &&
+ options.payload !== '') {
+
return true;
}
return false;
}
- var calculatedHash = hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, request.getResponseHeader('content-type'));
+ var calculatedHash = hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, getHeader('content-type'));
return (calculatedHash === attributes.hash);
},
// Application time
- var timestamp = options.timestamp || Math.floor((hawk.utils.now() + (options.localtimeOffsetMsec || 0)) / 1000)
+ var timestamp = options.timestamp || hawk.utils.now(options.localtimeOffsetMsec);
// Validate credentials
}
if (updateClock !== false) {
- hawk.utils.setNtpOffset(message.ts - Math.floor(Date.now() / 1000)); // Keep offset at 1 second precision
+ hawk.utils.setNtpOffset(message.ts - Math.floor((new Date()).getTime() / 1000)); // Keep offset at 1 second precision
}
return true;
var hash = CryptoJS.algo[algorithm.toUpperCase()].create();
hash.update('hawk.' + hawk.crypto.headerVersion + '.payload\n');
hash.update(hawk.utils.parseContentType(contentType) + '\n');
- hash.update(payload || '');
+ hash.update(payload);
hash.update('\n');
return hash.finalize().toString(CryptoJS.enc.Base64);
},
};
-hawk.utils = {
+// localStorage compatible interface
- storage: { // localStorage compatible interface
- _cache: {},
- setItem: function (key, value) {
+hawk.internals.LocalStorage = function () {
- hawk.utils.storage._cache[key] = value;
- },
- getItem: function (key) {
+ this._cache = {};
+ this.length = 0;
- return hawk.utils.storage._cache[key];
- }
- },
+ this.getItem = function (key) {
+
+ return this._cache.hasOwnProperty(key) ? String(this._cache[key]) : null;
+ };
+
+ this.setItem = function (key, value) {
+
+ this._cache[key] = String(value);
+ this.length = Object.keys(this._cache).length;
+ };
+
+ this.removeItem = function (key) {
+
+ delete this._cache[key];
+ this.length = Object.keys(this._cache).length;
+ };
+
+ this.clear = function () {
+
+ this._cache = {};
+ this.length = 0;
+ };
+
+ this.key = function (i) {
+
+ return Object.keys(this._cache)[i || 0];
+ };
+};
+
+
+hawk.utils = {
+
+ storage: new hawk.internals.LocalStorage(),
setStorage: function (storage) {
- var ntpOffset = hawk.utils.getNtpOffset() || 0;
+ var ntpOffset = hawk.utils.storage.getItem('hawk_ntp_offset');
hawk.utils.storage = storage;
- hawk.utils.setNtpOffset(ntpOffset);
+ if (ntpOffset) {
+ hawk.utils.setNtpOffset(ntpOffset);
+ }
},
setNtpOffset: function (offset) {
try {
- hawk.utils.storage.setItem('hawk_ntp_offset', offset);
+ hawk.utils.storage.setItem('hawk_ntp_offset', offset);
}
catch (err) {
- console.error('[hawk] could not write to storage.');
- console.error(err);
+ console.error('[hawk] could not write to storage.');
+ console.error(err);
}
},
getNtpOffset: function () {
- return parseInt(hawk.utils.storage.getItem('hawk_ntp_offset') || '0', 10);
+ var offset = hawk.utils.storage.getItem('hawk_ntp_offset');
+ if (!offset) {
+ return 0;
+ }
+
+ return parseInt(offset, 10);
},
- now: function () {
+ now: function (localtimeOffsetMsec) {
- return Date.now() + hawk.utils.getNtpOffset();
+ return Math.floor(((new Date()).getTime() + (localtimeOffsetMsec || 0)) / 1000) + hawk.utils.getNtpOffset();
},
escapeHeaderAttribute: function (attribute) {
return '';
}
- return header.split(';')[0].trim().toLowerCase();
+ return header.split(';')[0].replace(/^\s+|\s+$/g, '').toLowerCase();
},
parseAuthorizationHeader: function (header, keys) {
var keys = ['source', 'protocol', 'authority', 'userInfo', 'user', 'password', 'hostname', 'port', 'resource', 'relative', 'pathname', 'directory', 'file', 'query', 'fragment'];
var uriRegex = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?(((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?)(?:#(.*))?)/;
- var uriByNumber = uriRegex.exec(input);
+ var uriByNumber = input.match(uriRegex);
var uri = {};
- var i = 15;
- while (i--) {
+ for (var i = 0, il = keys.length; i < il; ++i) {
uri[keys[i]] = uriByNumber[i] || '';
}
- if (uri.port === null ||
- uri.port === '') {
-
+ if (uri.port === '') {
uri.port = (uri.protocol.toLowerCase() === 'http' ? '80' : (uri.protocol.toLowerCase() === 'https' ? '443' : ''));
}
return uri;
+ },
+
+ base64urlEncode: function (value) {
+
+ var wordArray = CryptoJS.enc.Utf8.parse(value);
+ var encoded = CryptoJS.enc.Base64.stringify(wordArray);
+ return encoded.replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
}
};
+// $lab:coverage:off$
+
// Based on: Crypto-JS v3.1.2
// Copyright (c) 2009-2013, Jeff Mott. All rights reserved.
// http://code.google.com/p/crypto-js/
// http://code.google.com/p/crypto-js/wiki/License
-var CryptoJS=CryptoJS||function(h,r){var k={},l=k.lib={},n=function(){},f=l.Base={extend:function(a){n.prototype=this;var b=new n;a&&b.mixIn(a);b.hasOwnProperty("init")||(b.init=function(){b.$super.init.apply(this,arguments)});b.init.prototype=b;b.$super=this;return b},create:function(){var a=this.extend();a.init.apply(a,arguments);return a},init:function(){},mixIn:function(a){for(var b in a)a.hasOwnProperty(b)&&(this[b]=a[b]);a.hasOwnProperty("toString")&&(this.toString=a.toString)},clone:function(){return this.init.prototype.extend(this)}},j=l.WordArray=f.extend({init:function(a,b){a=this.words=a||[];this.sigBytes=b!=r?b:4*a.length},toString:function(a){return(a||s).stringify(this)},concat:function(a){var b=this.words,d=a.words,c=this.sigBytes;a=a.sigBytes;this.clamp();if(c%4)for(var e=0;e<a;e++)b[c+e>>>2]|=(d[e>>>2]>>>24-8*(e%4)&255)<<24-8*((c+e)%4);else if(65535<d.length)for(e=0;e<a;e+=4)b[c+e>>>2]=d[e>>>2];else b.push.apply(b,d);this.sigBytes+=a;return this},clamp:function(){var a=this.words,b=this.sigBytes;a[b>>>2]&=4294967295<<32-8*(b%4);a.length=h.ceil(b/4)},clone:function(){var a=f.clone.call(this);a.words=this.words.slice(0);return a},random:function(a){for(var b=[],d=0;d<a;d+=4)b.push(4294967296*h.random()|0);return new j.init(b,a)}}),m=k.enc={},s=m.Hex={stringify:function(a){var b=a.words;a=a.sigBytes;for(var d=[],c=0;c<a;c++){var e=b[c>>>2]>>>24-8*(c%4)&255;d.push((e>>>4).toString(16));d.push((e&15).toString(16))}return d.join("")},parse:function(a){for(var b=a.length,d=[],c=0;c<b;c+=2)d[c>>>3]|=parseInt(a.substr(c,2),16)<<24-4*(c%8);return new j.init(d,b/2)}},p=m.Latin1={stringify:function(a){var b=a.words;a=a.sigBytes;for(var d=[],c=0;c<a;c++)d.push(String.fromCharCode(b[c>>>2]>>>24-8*(c%4)&255));return d.join("")},parse:function(a){for(var b=a.length,d=[],c=0;c<b;c++)d[c>>>2]|=(a.charCodeAt(c)&255)<<24-8*(c%4);return new j.init(d,b)}},t=m.Utf8={stringify:function(a){try{return decodeURIComponent(escape(p.stringify(a)))}catch(b){throw Error("Malformed UTF-8 data");}},parse:function(a){return p.parse(unescape(encodeURIComponent(a)))}},q=l.BufferedBlockAlgorithm=f.extend({reset:function(){this._data=new j.init;this._nDataBytes=0},_append:function(a){"string"==typeof a&&(a=t.parse(a));this._data.concat(a);this._nDataBytes+=a.sigBytes},_process:function(a){var b=this._data,d=b.words,c=b.sigBytes,e=this.blockSize,f=c/(4*e),f=a?h.ceil(f):h.max((f|0)-this._minBufferSize,0);a=f*e;c=h.min(4*a,c);if(a){for(var g=0;g<a;g+=e)this._doProcessBlock(d,g);g=d.splice(0,a);b.sigBytes-=c}return new j.init(g,c)},clone:function(){var a=f.clone.call(this);a._data=this._data.clone();return a},_minBufferSize:0});l.Hasher=q.extend({cfg:f.extend(),init:function(a){this.cfg=this.cfg.extend(a);this.reset()},reset:function(){q.reset.call(this);this._doReset()},update:function(a){this._append(a);this._process();return this},finalize:function(a){a&&this._append(a);return this._doFinalize()},blockSize:16,_createHelper:function(a){return function(b,d){return(new a.init(d)).finalize(b)}},_createHmacHelper:function(a){return function(b,d){return(new u.HMAC.init(a,d)).finalize(b)}}});var u=k.algo={};return k}(Math);
+var CryptoJS = CryptoJS || function (h, r) { var k = {}, l = k.lib = {}, n = function () { }, f = l.Base = { extend: function (a) { n.prototype = this; var b = new n; a && b.mixIn(a); b.hasOwnProperty("init") || (b.init = function () { b.$super.init.apply(this, arguments) }); b.init.prototype = b; b.$super = this; return b }, create: function () { var a = this.extend(); a.init.apply(a, arguments); return a }, init: function () { }, mixIn: function (a) { for (var b in a) a.hasOwnProperty(b) && (this[b] = a[b]); a.hasOwnProperty("toString") && (this.toString = a.toString) }, clone: function () { return this.init.prototype.extend(this) } }, j = l.WordArray = f.extend({ init: function (a, b) { a = this.words = a || []; this.sigBytes = b != r ? b : 4 * a.length }, toString: function (a) { return (a || s).stringify(this) }, concat: function (a) { var b = this.words, d = a.words, c = this.sigBytes; a = a.sigBytes; this.clamp(); if (c % 4) for (var e = 0; e < a; e++) b[c + e >>> 2] |= (d[e >>> 2] >>> 24 - 8 * (e % 4) & 255) << 24 - 8 * ((c + e) % 4); else if (65535 < d.length) for (e = 0; e < a; e += 4) b[c + e >>> 2] = d[e >>> 2]; else b.push.apply(b, d); this.sigBytes += a; return this }, clamp: function () { var a = this.words, b = this.sigBytes; a[b >>> 2] &= 4294967295 << 32 - 8 * (b % 4); a.length = h.ceil(b / 4) }, clone: function () { var a = f.clone.call(this); a.words = this.words.slice(0); return a }, random: function (a) { for (var b = [], d = 0; d < a; d += 4) b.push(4294967296 * h.random() | 0); return new j.init(b, a) } }), m = k.enc = {}, s = m.Hex = { stringify: function (a) { var b = a.words; a = a.sigBytes; for (var d = [], c = 0; c < a; c++) { var e = b[c >>> 2] >>> 24 - 8 * (c % 4) & 255; d.push((e >>> 4).toString(16)); d.push((e & 15).toString(16)) } return d.join("") }, parse: function (a) { for (var b = a.length, d = [], c = 0; c < b; c += 2) d[c >>> 3] |= parseInt(a.substr(c, 2), 16) << 24 - 4 * (c % 8); return new j.init(d, b / 2) } }, p = m.Latin1 = { stringify: function (a) { var b = a.words; a = a.sigBytes; for (var d = [], c = 0; c < a; c++) d.push(String.fromCharCode(b[c >>> 2] >>> 24 - 8 * (c % 4) & 255)); return d.join("") }, parse: function (a) { for (var b = a.length, d = [], c = 0; c < b; c++) d[c >>> 2] |= (a.charCodeAt(c) & 255) << 24 - 8 * (c % 4); return new j.init(d, b) } }, t = m.Utf8 = { stringify: function (a) { try { return decodeURIComponent(escape(p.stringify(a))) } catch (b) { throw Error("Malformed UTF-8 data"); } }, parse: function (a) { return p.parse(unescape(encodeURIComponent(a))) } }, q = l.BufferedBlockAlgorithm = f.extend({ reset: function () { this._data = new j.init; this._nDataBytes = 0 }, _append: function (a) { "string" == typeof a && (a = t.parse(a)); this._data.concat(a); this._nDataBytes += a.sigBytes }, _process: function (a) { var b = this._data, d = b.words, c = b.sigBytes, e = this.blockSize, f = c / (4 * e), f = a ? h.ceil(f) : h.max((f | 0) - this._minBufferSize, 0); a = f * e; c = h.min(4 * a, c); if (a) { for (var g = 0; g < a; g += e) this._doProcessBlock(d, g); g = d.splice(0, a); b.sigBytes -= c } return new j.init(g, c) }, clone: function () { var a = f.clone.call(this); a._data = this._data.clone(); return a }, _minBufferSize: 0 }); l.Hasher = q.extend({ cfg: f.extend(), init: function (a) { this.cfg = this.cfg.extend(a); this.reset() }, reset: function () { q.reset.call(this); this._doReset() }, update: function (a) { this._append(a); this._process(); return this }, finalize: function (a) { a && this._append(a); return this._doFinalize() }, blockSize: 16, _createHelper: function (a) { return function (b, d) { return (new a.init(d)).finalize(b) } }, _createHmacHelper: function (a) { return function (b, d) { return (new u.HMAC.init(a, d)).finalize(b) } } }); var u = k.algo = {}; return k }(Math);
(function () { var k = CryptoJS, b = k.lib, m = b.WordArray, l = b.Hasher, d = [], b = k.algo.SHA1 = l.extend({ _doReset: function () { this._hash = new m.init([1732584193, 4023233417, 2562383102, 271733878, 3285377520]) }, _doProcessBlock: function (n, p) { for (var a = this._hash.words, e = a[0], f = a[1], h = a[2], j = a[3], b = a[4], c = 0; 80 > c; c++) { if (16 > c) d[c] = n[p + c] | 0; else { var g = d[c - 3] ^ d[c - 8] ^ d[c - 14] ^ d[c - 16]; d[c] = g << 1 | g >>> 31 } g = (e << 5 | e >>> 27) + b + d[c]; g = 20 > c ? g + ((f & h | ~f & j) + 1518500249) : 40 > c ? g + ((f ^ h ^ j) + 1859775393) : 60 > c ? g + ((f & h | f & j | h & j) - 1894007588) : g + ((f ^ h ^ j) - 899497514); b = j; j = h; h = f << 30 | f >>> 2; f = e; e = g } a[0] = a[0] + e | 0; a[1] = a[1] + f | 0; a[2] = a[2] + h | 0; a[3] = a[3] + j | 0; a[4] = a[4] + b | 0 }, _doFinalize: function () { var b = this._data, d = b.words, a = 8 * this._nDataBytes, e = 8 * b.sigBytes; d[e >>> 5] |= 128 << 24 - e % 32; d[(e + 64 >>> 9 << 4) + 14] = Math.floor(a / 4294967296); d[(e + 64 >>> 9 << 4) + 15] = a; b.sigBytes = 4 * d.length; this._process(); return this._hash }, clone: function () { var b = l.clone.call(this); b._hash = this._hash.clone(); return b } }); k.SHA1 = l._createHelper(b); k.HmacSHA1 = l._createHmacHelper(b) })();
(function (k) { for (var g = CryptoJS, h = g.lib, v = h.WordArray, j = h.Hasher, h = g.algo, s = [], t = [], u = function (q) { return 4294967296 * (q - (q | 0)) | 0 }, l = 2, b = 0; 64 > b;) { var d; a: { d = l; for (var w = k.sqrt(d), r = 2; r <= w; r++) if (!(d % r)) { d = !1; break a } d = !0 } d && (8 > b && (s[b] = u(k.pow(l, 0.5))), t[b] = u(k.pow(l, 1 / 3)), b++); l++ } var n = [], h = h.SHA256 = j.extend({ _doReset: function () { this._hash = new v.init(s.slice(0)) }, _doProcessBlock: function (q, h) { for (var a = this._hash.words, c = a[0], d = a[1], b = a[2], k = a[3], f = a[4], g = a[5], j = a[6], l = a[7], e = 0; 64 > e; e++) { if (16 > e) n[e] = q[h + e] | 0; else { var m = n[e - 15], p = n[e - 2]; n[e] = ((m << 25 | m >>> 7) ^ (m << 14 | m >>> 18) ^ m >>> 3) + n[e - 7] + ((p << 15 | p >>> 17) ^ (p << 13 | p >>> 19) ^ p >>> 10) + n[e - 16] } m = l + ((f << 26 | f >>> 6) ^ (f << 21 | f >>> 11) ^ (f << 7 | f >>> 25)) + (f & g ^ ~f & j) + t[e] + n[e]; p = ((c << 30 | c >>> 2) ^ (c << 19 | c >>> 13) ^ (c << 10 | c >>> 22)) + (c & d ^ c & b ^ d & b); l = j; j = g; g = f; f = k + m | 0; k = b; b = d; d = c; c = m + p | 0 } a[0] = a[0] + c | 0; a[1] = a[1] + d | 0; a[2] = a[2] + b | 0; a[3] = a[3] + k | 0; a[4] = a[4] + f | 0; a[5] = a[5] + g | 0; a[6] = a[6] + j | 0; a[7] = a[7] + l | 0 }, _doFinalize: function () { var d = this._data, b = d.words, a = 8 * this._nDataBytes, c = 8 * d.sigBytes; b[c >>> 5] |= 128 << 24 - c % 32; b[(c + 64 >>> 9 << 4) + 14] = k.floor(a / 4294967296); b[(c + 64 >>> 9 << 4) + 15] = a; d.sigBytes = 4 * b.length; this._process(); return this._hash }, clone: function () { var b = j.clone.call(this); b._hash = this._hash.clone(); return b } }); g.SHA256 = j._createHelper(h); g.HmacSHA256 = j._createHmacHelper(h) })(Math);
-(function(){var c=CryptoJS,k=c.enc.Utf8;c.algo.HMAC=c.lib.Base.extend({init:function(a,b){a=this._hasher=new a.init;"string"==typeof b&&(b=k.parse(b));var c=a.blockSize,e=4*c;b.sigBytes>e&&(b=a.finalize(b));b.clamp();for(var f=this._oKey=b.clone(),g=this._iKey=b.clone(),h=f.words,j=g.words,d=0;d<c;d++)h[d]^=1549556828,j[d]^=909522486;f.sigBytes=g.sigBytes=e;this.reset()},reset:function(){var a=this._hasher;a.reset();a.update(this._iKey)},update:function(a){this._hasher.update(a);return this},finalize:function(a){var b=this._hasher;a=b.finalize(a);b.reset();return b.finalize(this._oKey.clone().concat(a))}})})();
-(function(){var h=CryptoJS,j=h.lib.WordArray;h.enc.Base64={stringify:function(b){var e=b.words,f=b.sigBytes,c=this._map;b.clamp();b=[];for(var a=0;a<f;a+=3)for(var d=(e[a>>>2]>>>24-8*(a%4)&255)<<16|(e[a+1>>>2]>>>24-8*((a+1)%4)&255)<<8|e[a+2>>>2]>>>24-8*((a+2)%4)&255,g=0;4>g&&a+0.75*g<f;g++)b.push(c.charAt(d>>>6*(3-g)&63));if(e=c.charAt(64))for(;b.length%4;)b.push(e);return b.join("")},parse:function(b){var e=b.length,f=this._map,c=f.charAt(64);c&&(c=b.indexOf(c),-1!=c&&(e=c));for(var c=[],a=0,d=0;d<e;d++)if(d%4){var g=f.indexOf(b.charAt(d-1))<<2*(d%4),h=f.indexOf(b.charAt(d))>>>6-2*(d%4);c[a>>>2]|=(g|h)<<24-8*(a%4);a++}return j.create(c,a)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})();
+(function () { var c = CryptoJS, k = c.enc.Utf8; c.algo.HMAC = c.lib.Base.extend({ init: function (a, b) { a = this._hasher = new a.init; "string" == typeof b && (b = k.parse(b)); var c = a.blockSize, e = 4 * c; b.sigBytes > e && (b = a.finalize(b)); b.clamp(); for (var f = this._oKey = b.clone(), g = this._iKey = b.clone(), h = f.words, j = g.words, d = 0; d < c; d++) h[d] ^= 1549556828, j[d] ^= 909522486; f.sigBytes = g.sigBytes = e; this.reset() }, reset: function () { var a = this._hasher; a.reset(); a.update(this._iKey) }, update: function (a) { this._hasher.update(a); return this }, finalize: function (a) { var b = this._hasher; a = b.finalize(a); b.reset(); return b.finalize(this._oKey.clone().concat(a)) } }) })();
+(function () { var h = CryptoJS, j = h.lib.WordArray; h.enc.Base64 = { stringify: function (b) { var e = b.words, f = b.sigBytes, c = this._map; b.clamp(); b = []; for (var a = 0; a < f; a += 3) for (var d = (e[a >>> 2] >>> 24 - 8 * (a % 4) & 255) << 16 | (e[a + 1 >>> 2] >>> 24 - 8 * ((a + 1) % 4) & 255) << 8 | e[a + 2 >>> 2] >>> 24 - 8 * ((a + 2) % 4) & 255, g = 0; 4 > g && a + 0.75 * g < f; g++) b.push(c.charAt(d >>> 6 * (3 - g) & 63)); if (e = c.charAt(64)) for (; b.length % 4;) b.push(e); return b.join("") }, parse: function (b) { var e = b.length, f = this._map, c = f.charAt(64); c && (c = b.indexOf(c), -1 != c && (e = c)); for (var c = [], a = 0, d = 0; d < e; d++) if (d % 4) { var g = f.indexOf(b.charAt(d - 1)) << 2 * (d % 4), h = f.indexOf(b.charAt(d)) >>> 6 - 2 * (d % 4); c[a >>> 2] |= (g | h) << 24 - 8 * (a % 4); a++ } return j.create(c, a) }, _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=" } })();
+
+hawk.crypto.internals = CryptoJS;
+
+
+// Export if used as a module
+
+if (typeof module !== 'undefined' && module.exports) {
+ module.exports = hawk;
+}
+
+// $lab:coverage:on$
// Application time
- var timestamp = options.timestamp || Math.floor((Utils.now() + (options.localtimeOffsetMsec || 0)) / 1000)
+ var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
// Validate credentials
// Calculate payload hash
if (!artifacts.hash &&
- options.hasOwnProperty('payload')) {
+ (options.payload || options.payload === '')) {
artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
}
'", ts="' + artifacts.ts +
'", nonce="' + artifacts.nonce +
(artifacts.hash ? '", hash="' + artifacts.hash : '') +
- (hasExt ? '", ext="' + Utils.escapeHeaderAttribute(artifacts.ext) : '') +
+ (hasExt ? '", ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) : '') +
'", mac="' + mac + '"';
if (artifacts.app) {
/*
res: node's response object
- artifacts: object recieved from header().artifacts
+ artifacts: object received from header().artifacts
options: {
payload: optional payload received
required: specifies if a Server-Authorization header is required. Defaults to 'false'
return false;
}
- if (!options.hasOwnProperty('payload')) {
+ if (!options.payload &&
+ options.payload !== '') {
+
return true;
}
// Generate a bewit value for a given URI
/*
- * credentials is an object with the following keys: 'id, 'key', 'algorithm'.
- * options is an object with the following optional keys: 'ext', 'localtimeOffsetMsec'
- */
-/*
uri: 'http://example.com/resource?a=b' or object from Url.parse()
options: {
// Application time
- var now = Utils.now() + (options.localtimeOffsetMsec || 0);
+ var now = Utils.now(options.localtimeOffsetMsec);
// Validate credentials
// Construct bewit: id\exp\mac\ext
var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + options.ext;
- return Utils.base64urlEncode(bewit);
+ return Hoek.base64urlEncode(bewit);
};
// Application time
- var timestamp = options.timestamp || Math.floor((Utils.now() + (options.localtimeOffsetMsec || 0)) / 1000)
+ var timestamp = options.timestamp || Utils.nowSecs(options.localtimeOffsetMsec);
// Validate credentials
exports.generateNormalizedString = function (type, options) {
+ var resource = options.resource || '';
+ if (resource &&
+ resource[0] !== '/') {
+
+ var url = Url.parse(resource, false);
+ resource = url.path; // Includes query
+ }
+
var normalized = 'hawk.' + exports.headerVersion + '.' + type + '\n' +
options.ts + '\n' +
options.nonce + '\n' +
(options.method || '').toUpperCase() + '\n' +
- (options.resource || '') + '\n' +
+ resource + '\n' +
options.host.toLowerCase() + '\n' +
options.port + '\n' +
(options.hash || '') + '\n';
exports.timestampMessage = function (credentials, localtimeOffsetMsec) {
- var now = Math.floor((Utils.now() + (localtimeOffsetMsec || 0)) / 1000);
+ var now = Utils.nowSecs(localtimeOffsetMsec);
var tsm = exports.calculateTsMac(now, credentials);
return { ts: now, tsm: tsm };
};
exports.authenticate = function (req, credentialsFunc, options, callback) {
- callback = Utils.nextTick(callback);
+ callback = Hoek.nextTick(callback);
// Default options
// Application time
- var now = Utils.now() + (options.localtimeOffsetMsec || 0); // Measure now before any other processing
+ var now = Utils.now(options.localtimeOffsetMsec); // Measure now before any other processing
// Convert node Http request object to a request configuration object
// Check payload hash
- if (options.payload !== null &&
- options.payload !== undefined) { // '' is valid
+ if (options.payload ||
+ options.payload === '') {
if (!attributes.hash) {
return callback(Boom.unauthorized('Missing required payload hash', 'Hawk'), credentials, artifacts);
};
+// Authenticate payload hash - used when payload cannot be provided during authenticate()
+
+/*
+ calculatedHash: the payload hash calculated using Crypto.calculatePayloadHash()
+ artifacts: from authenticate callback
+*/
+
+exports.authenticatePayloadHash = function (calculatedHash, artifacts) {
+
+ return Cryptiles.fixedTimeComparison(calculatedHash, artifacts.hash);
+};
+
+
// Generate a Server-Authorization header for a given response
/*
// Calculate payload hash
if (!artifacts.hash &&
- options.hasOwnProperty('payload')) {
+ (options.payload || options.payload === '')) {
artifacts.hash = Crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
}
artifacts.ext !== undefined &&
artifacts.ext !== '') { // Other falsey values allowed
- header += ', ext="' + Utils.escapeHeaderAttribute(artifacts.ext) + '"';
+ header += ', ext="' + Hoek.escapeHeaderAttribute(artifacts.ext) + '"';
}
return header;
exports.authenticateBewit = function (req, credentialsFunc, options, callback) {
- callback = Utils.nextTick(callback);
+ callback = Hoek.nextTick(callback);
// Application time
- var now = Utils.now() + (options.localtimeOffsetMsec || 0);
+ var now = Utils.now(options.localtimeOffsetMsec);
// Convert node Http request object to a request configuration object
// No other authentication
if (request.authorization) {
- return callback(Boom.badRequest('Multiple authentications', 'Hawk'));
+ return callback(Boom.badRequest('Multiple authentications'));
}
// Parse bewit
- var bewitString = Utils.base64urlDecode(resource[3]);
+ var bewitString = Hoek.base64urlDecode(resource[3]);
if (bewitString instanceof Error) {
return callback(Boom.badRequest('Invalid bewit encoding'));
}
// Bewit format: id\exp\mac\ext ('\' is used because it is a reserved header attribute character)
var bewitParts = bewitString.split('\\');
- if (!bewitParts ||
- bewitParts.length !== 4) {
-
+ if (bewitParts.length !== 4) {
return callback(Boom.badRequest('Invalid bewit structure'));
}
exports.authenticateMessage = function (host, port, message, authorization, credentialsFunc, options, callback) {
- callback = Utils.nextTick(callback);
+ callback = Hoek.nextTick(callback);
// Default options
// Application time
- var now = Utils.now() + (options.localtimeOffsetMsec || 0); // Measure now before any other processing
+ var now = Utils.now(options.localtimeOffsetMsec); // Measure now before any other processing
// Validate authorization
// Load modules
-var Hoek = require('hoek');
var Sntp = require('sntp');
var Boom = require('boom');
var internals = {};
-// Import Hoek Utilities
-
-internals.import = function () {
-
- for (var i in Hoek) {
- if (Hoek.hasOwnProperty(i)) {
- exports[i] = Hoek[i];
- }
- }
-};
-
-internals.import();
-
-
-// Hawk version
-
exports.version = function () {
- return exports.loadPackage(__dirname + '/..').version;
+ return require('../package.json').version;
};
// Extract host and port from request
+// $1 $2
+internals.hostHeaderRegex = /^(?:(?:\r\n)?\s)*((?:[^:]+)|(?:\[[^\]]+\]))(?::(\d+))?(?:(?:\r\n)?\s)*$/; // (IPv4, hostname)|(IPv6)
+
+
exports.parseHost = function (req, hostHeaderName) {
hostHeaderName = (hostHeaderName ? hostHeaderName.toLowerCase() : 'host');
return null;
}
- var hostHeaderRegex;
- if (hostHeader[0] === '[') {
- hostHeaderRegex = /^(?:(?:\r\n)?\s)*(\[[^\]]+\])(?::(\d+))?(?:(?:\r\n)?\s)*$/; // IPv6
- }
- else {
- hostHeaderRegex = /^(?:(?:\r\n)?\s)*([^:]+)(?::(\d+))?(?:(?:\r\n)?\s)*$/; // IPv4, hostname
- }
-
- var hostParts = hostHeader.match(hostHeaderRegex);
-
- if (!hostParts ||
- hostParts.length !== 3 ||
- !hostParts[1]) {
-
+ var hostParts = hostHeader.match(internals.hostHeaderRegex);
+ if (!hostParts) {
return null;
}
};
-exports.now = function () {
+exports.now = function (localtimeOffsetMsec) {
+
+ return Sntp.now() + (localtimeOffsetMsec || 0);
+};
+
+
+exports.nowSecs = function (localtimeOffsetMsec) {
- return Sntp.now();
+ return Math.floor(exports.now(localtimeOffsetMsec) / 1000);
};
--- /dev/null
+Please view our [hapijs contributing guide](https://github.com/hapijs/hapi/blob/master/CONTRIBUTING.md).
-Copyright (c) 2012-2013, Walmart.
+Copyright (c) 2012-2014, Walmart and other contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- * Neither the name of Walmart nor the
- names of its contributors may be used to endorse or promote products
- derived from this software without specific prior written permission.
+ * The names of any contributors may not be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL WALMART BE LIABLE FOR ANY
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ * * *
+
+The complete list of contributors can be found at: https://github.com/hapijs/boom/graphs/contributors
\ No newline at end of file
test:
- @node node_modules/lab/bin/lab
-test-cov:
- @node node_modules/lab/bin/lab -r threshold -t 100
+ @node node_modules/lab/bin/lab -a code
+test-cov:
+ @node node_modules/lab/bin/lab -a code -t 100
test-cov-html:
- @node node_modules/lab/bin/lab -r html -o coverage.html
-complexity:
- @node node_modules/complexity-report/src/cli.js -o complexity.md -f markdown lib
+ @node node_modules/lab/bin/lab -a code -r html -o coverage.html
-.PHONY: test test-cov test-cov-html complexity
+.PHONY: test test-cov test-cov-html
-<a href="https://github.com/spumko"><img src="https://raw.github.com/spumko/spumko/master/images/from.png" align="right" /></a>
-![boom Logo](https://raw.github.com/spumko/boom/master/images/boom.png)
+![boom Logo](https://raw.github.com/hapijs/boom/master/images/boom.png)
HTTP-friendly error objects
-[![Build Status](https://secure.travis-ci.org/spumko/boom.png)](http://travis-ci.org/spumko/boom)
+[![Build Status](https://secure.travis-ci.org/hapijs/boom.png)](http://travis-ci.org/hapijs/boom)
+
+Lead Maintainer: [Adam Bretz](https://github.com/arb)
+
+**boom** provides a set of utilities for returning HTTP errors. Each utility returns a `Boom` error response
+object (instance of `Error`) which includes the following properties:
+- `isBoom` - if `true`, indicates this is a `Boom` object instance.
+- `message` - the error message.
+- `output` - the formatted response. Can be directly manipulated after object construction to return a custom
+ error response. Allowed root keys:
+ - `statusCode` - the HTTP status code (typically 4xx or 5xx).
+ - `headers` - an object containing any HTTP headers where each key is a header name and value is the header content.
+ - `payload` - the formatted object used as the response payload (stringified). Can be directly manipulated but any
+ changes will be lost
+ if `reformat()` is called. Any content allowed and by default includes the following content:
+ - `statusCode` - the HTTP status code, derived from `error.output.statusCode`.
+ - `error` - the HTTP status message (e.g. 'Bad Request', 'Internal Server Error') derived from `statusCode`.
+ - `message` - the error message derived from `error.message`.
+- inherited `Error` properties.
+
+The `Boom` object also supports the following method:
+- `reformat()` - rebuilds `error.output` using the other object properties.
+
+## Helper Methods
+
+### `wrap(error, [statusCode], [message])`
+
+Decorates an error with the **boom** properties where:
+- `error` - the error object to wrap. If `error` is already a **boom** object, returns back the same object.
+- `statusCode` - optional HTTP status code. Defaults to `500`.
+- `message` - optional message string. If the error already has a message, it adds the message as a prefix.
+ Defaults to no message.
+
+```js
+var error = new Error('Unexpected input');
+Boom.wrap(error, 400);
+```
+
+### `create(statusCode, [message], [data])`
+
+Generates an `Error` object with the **boom** decorations where:
+- `statusCode` - an HTTP error code number. Must be greater or equal 400.
+- `message` - optional message string.
+- `data` - additional error data set to `error.data` property.
+
+```js
+var error = Boom.create(400, 'Bad request', { timestamp: Date.now() });
+```
+
+## HTTP 4xx Errors
+
+### `Boom.badRequest([message], [data])`
+
+Returns a 400 Bad Request error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.badRequest('invalid query');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 400,
+ "error": "Bad Request",
+ "message": "invalid query"
+}
+```
+
+### `Boom.unauthorized([message], [scheme], [attributes])`
+
+Returns a 401 Unauthorized error where:
+- `message` - optional message.
+- `scheme` can be one of the following:
+ - an authentication scheme name
+ - an array of string values. These values will be separated by ', ' and set to the 'WWW-Authenticate' header.
+- `attributes` - an object of values to use while setting the 'WWW-Authenticate' header. This value is only used when `schema` is a string, otherwise it is ignored. Every key/value pair will be included in the 'WWW-Authenticate' in the format of 'key="value"'. `null` and `undefined` will be replaced with an empty string. If `attributes` is set, `message` will be used as the 'error' segment of the 'WWW-Authenticate' header. If `message` is unset, the 'error' segment of the header will not be present and `isMissing` will be true on the error object.
+
+If either `scheme` or `attributes` are set, the resultant `Boom` object will have the 'WWW-Authenticate' header set for the response.
+
+```js
+Boom.unauthorized('invalid password');
+```
+
+Generates the following response:
+
+```json
+"payload": {
+ "statusCode": 401,
+ "error": "Unauthorized",
+ "message": "invalid password"
+},
+"headers" {}
+```
+
+```js
+Boom.unauthorized('invalid password', 'sample');
+```
+
+Generates the following response:
+
+```json
+"payload": {
+ "statusCode": 401,
+ "error": "Unauthorized",
+ "message": "invalid password"
+},
+"headers" {
+ "WWW-Authenticate": "sample error=\"invalid password\""
+}
+```
+
+```js
+Boom.unauthorized('invalid password', 'sample', { ttl: 0, cache: null, foo: 'bar' });
+```
+
+Generates the following response:
+
+```json
+"payload": {
+ "statusCode": 401,
+ "error": "Unauthorized",
+ "message": "invalid password"
+},
+"headers" {
+ "WWW-Authenticate": "sample ttl=\"0\", cache=\"\", foo=\"bar\", error=\"invalid password\""
+}
+```
+
+### `Boom.forbidden([message], [data])`
+
+Returns a 403 Forbidden error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.forbidden('try again some time');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 403,
+ "error": "Forbidden",
+ "message": "try again some time"
+}
+```
+
+### `Boom.notFound([message], [data])`
+
+Returns a 404 Not Found error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.notFound('missing');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 404,
+ "error": "Not Found",
+ "message": "missing"
+}
+```
+
+### `Boom.methodNotAllowed([message], [data])`
+
+Returns a 405 Method Not Allowed error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.methodNotAllowed('that method is not allowed');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 405,
+ "error": "Method Not Allowed",
+ "message": "that method is not allowed"
+}
+```
+
+### `Boom.notAcceptable([message], [data])`
+
+Returns a 406 Not Acceptable error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.notAcceptable('unacceptable');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 406,
+ "error": "Not Acceptable",
+ "message": "unacceptable"
+}
+```
+
+### `Boom.proxyAuthRequired([message], [data])`
+
+Returns a 407 Proxy Authentication Required error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.proxyAuthRequired('auth missing');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 407,
+ "error": "Proxy Authentication Required",
+ "message": "auth missing"
+}
+```
+
+### `Boom.clientTimeout([message], [data])`
+
+Returns a 408 Request Time-out error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.clientTimeout('timed out');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 408,
+ "error": "Request Time-out",
+ "message": "timed out"
+}
+```
+
+### `Boom.conflict([message], [data])`
+
+Returns a 409 Conflict error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.conflict('there was a conflict');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 409,
+ "error": "Conflict",
+ "message": "there was a conflict"
+}
+```
+
+### `Boom.resourceGone([message], [data])`
+
+Returns a 410 Gone error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.resourceGone('it is gone');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 410,
+ "error": "Gone",
+ "message": "it is gone"
+}
+```
+
+### `Boom.lengthRequired([message], [data])`
+
+Returns a 411 Length Required error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.lengthRequired('length needed');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 411,
+ "error": "Length Required",
+ "message": "length needed"
+}
+```
+
+### `Boom.preconditionFailed([message], [data])`
+
+Returns a 412 Precondition Failed error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.preconditionFailed();
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 412,
+ "error": "Precondition Failed"
+}
+```
+
+### `Boom.entityTooLarge([message], [data])`
+
+Returns a 413 Request Entity Too Large error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.entityTooLarge('too big');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 413,
+ "error": "Request Entity Too Large",
+ "message": "too big"
+}
+```
+
+### `Boom.uriTooLong([message], [data])`
+
+Returns a 414 Request-URI Too Large error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.uriTooLong('uri is too long');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 414,
+ "error": "Request-URI Too Large",
+ "message": "uri is too long"
+}
+```
+
+### `Boom.unsupportedMediaType([message], [data])`
+
+Returns a 415 Unsupported Media Type error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.unsupportedMediaType('that media is not supported');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 415,
+ "error": "Unsupported Media Type",
+ "message": "that media is not supported"
+}
+```
+
+### `Boom.rangeNotSatisfiable([message], [data])`
+
+Returns a 416 Requested Range Not Satisfiable error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.rangeNotSatisfiable();
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 416,
+ "error": "Requested Range Not Satisfiable"
+}
+```
+
+### `Boom.expectationFailed([message], [data])`
+
+Returns a 417 Expectation Failed error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.expectationFailed('expected this to work');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 417,
+ "error": "Expectation Failed",
+ "message": "expected this to work"
+}
+```
+
+### `Boom.badData([message], [data])`
+
+Returns a 422 Unprocessable Entity error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.badData('your data is bad and you should feel bad');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 422,
+ "error": "Unprocessable Entity",
+ "message": "your data is bad and you should feel bad"
+}
+```
+
+### `Boom.tooManyRequests([message], [data])`
+
+Returns a 422 Too Many Requests error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.tooManyRequests('you have exceeded your request limit');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 429,
+ "error": "Too Many Requests",
+ "message": "you have exceeded your request limit"
+}
+```
+
+## HTTP 5xx Errors
+
+All 500 errors hide your message from the end user. Your message is recorded in the server log.
+
+### `Boom.notImplemented([message], [data])`
+
+Returns a 501 Not Implemented error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.notImplemented('method not implemented');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 501,
+ "error": "Not Implemented",
+ "message": "method not implemented"
+}
+```
+
+### `Boom.badGateway([message], [data])`
+
+Returns a 502 Bad Gateway error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.badGateway('that is a bad gateway');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 502,
+ "error": "Bad Gateway",
+ "message": "that is a bad gateway"
+}
+```
+
+### `Boom.serverTimeout([message], [data])`
+
+Returns a 503 Service Unavailable error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.serverTimeout('unavailable');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 503,
+ "error": "Service Unavailable",
+ "message": "unavailable"
+}
+```
+
+### `Boom.gatewayTimeout([message], [data])`
+
+Returns a 504 Gateway Time-out error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.gatewayTimeout();
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 504,
+ "error": "Gateway Time-out"
+}
+```
+
+### `Boom.badImplementation([message], [data])`
+
+Returns a 500 Internal Server Error error where:
+- `message` - optional message.
+- `data` - optional additional error data.
+
+```js
+Boom.badImplementation('terrible implementation');
+```
+
+Generates the following response payload:
+
+```json
+{
+ "statusCode": 500,
+ "error": "Internal Server Error",
+ "message": "An internal server error occurred"
+}
+```
// Load modules
var Http = require('http');
-var NodeUtil = require('util');
var Hoek = require('hoek');
var internals = {};
-exports = module.exports = internals.Boom = function (/* (new Error) or (code, message) */) {
+exports.wrap = function (error, statusCode, message) {
- var self = this;
+ Hoek.assert(error instanceof Error, 'Cannot wrap non-Error object');
+ return (error.isBoom ? error : internals.initialize(error, statusCode || 500, message));
+};
- Hoek.assert(this.constructor === internals.Boom, 'Error must be instantiated using new');
- Error.call(this);
- this.isBoom = true;
+exports.create = function (statusCode, message, data) {
- this.response = {
- code: 0,
- payload: {},
- headers: {}
- // type: 'content-type'
- };
+ var error = new Error(message ? message : undefined); // Avoids settings null message
+ error.data = data || null;
+ internals.initialize(error, statusCode);
+ return error;
+};
- if (arguments[0] instanceof Error) {
- // Error
+internals.initialize = function (error, statusCode, message) {
- var error = arguments[0];
+ Hoek.assert(!isNaN(parseFloat(statusCode)) && isFinite(statusCode) && statusCode >= 400, 'First argument must be a number (400+):', statusCode);
- this.data = error;
- this.response.code = error.code || 500;
- if (error.message) {
- this.message = error.message;
- }
+ error.isBoom = true;
+
+ if (!error.hasOwnProperty('data')) {
+ error.data = null;
}
- else {
- // code, message
+ error.output = {
+ statusCode: statusCode,
+ payload: {},
+ headers: {}
+ };
- var code = arguments[0];
- var message = arguments[1];
+ error.reformat = internals.reformat;
+ error.reformat();
- Hoek.assert(!isNaN(parseFloat(code)) && isFinite(code) && code >= 400, 'First argument must be a number (400+)');
+ if (!message &&
+ !error.message) {
- this.response.code = code;
- if (message) {
- this.message = message;
- }
+ message = error.output.payload.error;
}
- // Response format
-
- this.reformat();
+ if (message) {
+ error.message = (message + (error.message ? ': ' + error.message : ''));
+ }
- return this;
+ return error;
};
-NodeUtil.inherits(internals.Boom, Error);
+internals.reformat = function () {
-internals.Boom.prototype.reformat = function () {
+ this.output.payload.statusCode = this.output.statusCode;
+ this.output.payload.error = Http.STATUS_CODES[this.output.statusCode] || 'Unknown';
- this.response.payload.code = this.response.code;
- this.response.payload.error = Http.STATUS_CODES[this.response.code] || 'Unknown';
- if (this.message) {
- this.response.payload.message = Hoek.escapeHtml(this.message); // Prevent XSS from error message
+ if (this.output.statusCode === 500) {
+ this.output.payload.message = 'An internal server error occurred'; // Hide actual error from user
+ }
+ else if (this.message) {
+ this.output.payload.message = this.message;
}
};
-// Utilities
+// 4xx Client Errors
-internals.Boom.badRequest = function (message) {
+exports.badRequest = function (message, data) {
- return new internals.Boom(400, message);
+ return exports.create(400, message, data);
};
-internals.Boom.unauthorized = function (message, scheme, attributes) { // Or function (message, wwwAuthenticate[])
+exports.unauthorized = function (message, scheme, attributes) { // Or function (message, wwwAuthenticate[])
- var err = new internals.Boom(401, message);
+ var err = exports.create(401, message);
if (!scheme) {
return err;
}
var wwwAuthenticate = '';
+ var i = 0;
+ var il = 0;
if (typeof scheme === 'string') {
wwwAuthenticate = scheme;
if (attributes) {
var names = Object.keys(attributes);
- for (var i = 0, il = names.length; i < il; ++i) {
+ for (i = 0, il = names.length; i < il; ++i) {
if (i) {
wwwAuthenticate += ',';
}
// function (message, wwwAuthenticate[])
var wwwArray = scheme;
- for (var i = 0, il = wwwArray.length; i < il; ++i) {
+ for (i = 0, il = wwwArray.length; i < il; ++i) {
if (i) {
wwwAuthenticate += ', ';
}
}
}
- err.response.headers['WWW-Authenticate'] = wwwAuthenticate;
+ err.output.headers['WWW-Authenticate'] = wwwAuthenticate;
return err;
};
-internals.Boom.clientTimeout = function (message) {
+exports.forbidden = function (message, data) {
- return new internals.Boom(408, message);
+ return exports.create(403, message, data);
};
-internals.Boom.serverTimeout = function (message) {
+exports.notFound = function (message, data) {
- return new internals.Boom(503, message);
+ return exports.create(404, message, data);
};
-internals.Boom.forbidden = function (message) {
+exports.methodNotAllowed = function (message, data) {
- return new internals.Boom(403, message);
+ return exports.create(405, message, data);
};
-internals.Boom.notFound = function (message) {
+exports.notAcceptable = function (message, data) {
- return new internals.Boom(404, message);
+ return exports.create(406, message, data);
};
-internals.Boom.internal = function (message, data) {
+exports.proxyAuthRequired = function (message, data) {
- var err = new internals.Boom(500, message);
+ return exports.create(407, message, data);
+};
- if (data && data.stack) {
- err.trace = data.stack.split('\n');
- err.outterTrace = Hoek.displayStack(1);
- }
- else {
- err.trace = Hoek.displayStack(1);
+
+exports.clientTimeout = function (message, data) {
+
+ return exports.create(408, message, data);
+};
+
+
+exports.conflict = function (message, data) {
+
+ return exports.create(409, message, data);
+};
+
+
+exports.resourceGone = function (message, data) {
+
+ return exports.create(410, message, data);
+};
+
+
+exports.lengthRequired = function (message, data) {
+
+ return exports.create(411, message, data);
+};
+
+
+exports.preconditionFailed = function (message, data) {
+
+ return exports.create(412, message, data);
+};
+
+
+exports.entityTooLarge = function (message, data) {
+
+ return exports.create(413, message, data);
+};
+
+
+exports.uriTooLong = function (message, data) {
+
+ return exports.create(414, message, data);
+};
+
+
+exports.unsupportedMediaType = function (message, data) {
+
+ return exports.create(415, message, data);
+};
+
+
+exports.rangeNotSatisfiable = function (message, data) {
+
+ return exports.create(416, message, data);
+};
+
+
+exports.expectationFailed = function (message, data) {
+
+ return exports.create(417, message, data);
+};
+
+exports.badData = function (message, data) {
+
+ return exports.create(422, message, data);
+};
+
+
+exports.tooManyRequests = function (message, data) {
+
+ return exports.create(429, message, data);
+};
+
+
+// 5xx Server Errors
+
+exports.internal = function (message, data, statusCode) {
+
+ var error = (data instanceof Error ? exports.wrap(data, statusCode, message) : exports.create(statusCode || 500, message));
+
+ if (data instanceof Error === false) {
+ error.data = data;
}
- err.data = data;
- err.response.payload.message = 'An internal server error occurred'; // Hide actual error from user
+ return error;
+};
- return err;
+
+exports.notImplemented = function (message, data) {
+
+ return exports.internal(message, data, 501);
};
-internals.Boom.passThrough = function (code, payload, contentType, headers) {
+exports.badGateway = function (message, data) {
- var err = new internals.Boom(500, 'Pass-through'); // 500 code is only used to initialize
+ return exports.internal(message, data, 502);
+};
- err.data = {
- code: code,
- payload: payload,
- type: contentType
- };
- err.response.code = code;
- err.response.type = contentType;
- err.response.headers = headers;
- err.response.payload = payload;
+exports.serverTimeout = function (message, data) {
- return err;
+ return exports.internal(message, data, 503);
+};
+
+
+exports.gatewayTimeout = function (message, data) {
+
+ return exports.internal(message, data, 504);
};
+exports.badImplementation = function (message, data) {
+
+ var err = exports.internal(message, data, 500);
+ err.isDeveloperError = true;
+ return err;
+};
{
"name": "boom",
"description": "HTTP-friendly error objects",
- "version": "0.4.2",
- "author": {
- "name": "Eran Hammer",
- "email": "eran@hueniverse.com",
- "url": "http://hueniverse.com"
- },
- "contributors": [],
+ "version": "2.6.1",
"repository": {
"type": "git",
- "url": "git://github.com/spumko/boom"
+ "url": "git://github.com/hapijs/boom"
},
"main": "index",
"keywords": [
"node": ">=0.8.0"
},
"dependencies": {
- "hoek": "0.9.x"
+ "hoek": "2.x.x"
},
"devDependencies": {
- "lab": "0.1.x",
- "complexity-report": "0.x.x"
+ "code": "1.x.x",
+ "lab": "5.x.x"
},
"scripts": {
"test": "make test-cov"
"licenses": [
{
"type": "BSD",
- "url": "http://github.com/spumko/boom/raw/master/LICENSE"
+ "url": "http://github.com/hapijs/boom/raw/master/LICENSE"
}
],
- "_id": "boom@0.4.2",
- "dist": {
- "shasum": "7a636e9ded4efcefb19cef4947a3c67dfaee911b",
- "tarball": "http://registry.npmjs.org/boom/-/boom-0.4.2.tgz"
+ "gitHead": "860d6f8b0db89b263418b8575c65560482cbd1ba",
+ "bugs": {
+ "url": "https://github.com/hapijs/boom/issues"
},
- "_from": "boom@>=0.4.0 <0.5.0",
- "_npmVersion": "1.2.18",
+ "homepage": "https://github.com/hapijs/boom",
+ "_id": "boom@2.6.1",
+ "_shasum": "4dc8ef9b6dfad9c43bbbfbe71fa4c21419f22753",
+ "_from": "boom@>=2.0.0 <3.0.0",
+ "_npmVersion": "1.4.28",
"_npmUser": {
"name": "hueniverse",
"email": "eran@hueniverse.com"
{
"name": "hueniverse",
"email": "eran@hueniverse.com"
+ },
+ {
+ "name": "wyatt",
+ "email": "wpreul@gmail.com"
+ },
+ {
+ "name": "arb",
+ "email": "arbretz@gmail.com"
}
],
- "directories": {},
- "_shasum": "7a636e9ded4efcefb19cef4947a3c67dfaee911b",
- "_resolved": "https://registry.npmjs.org/boom/-/boom-0.4.2.tgz",
- "bugs": {
- "url": "https://github.com/spumko/boom/issues"
+ "dist": {
+ "shasum": "4dc8ef9b6dfad9c43bbbfbe71fa4c21419f22753",
+ "tarball": "http://registry.npmjs.org/boom/-/boom-2.6.1.tgz"
},
- "readme": "ERROR: No README data found!",
- "homepage": "https://github.com/spumko/boom"
+ "directories": {},
+ "_resolved": "https://registry.npmjs.org/boom/-/boom-2.6.1.tgz",
+ "readme": "ERROR: No README data found!"
}
// Load modules
-var Lab = require('lab');
+var Util = require('util');
+var Code = require('code');
var Boom = require('../lib');
+var Lab = require('lab');
// Declare internals
// Test shortcuts
-var expect = Lab.expect;
-var before = Lab.before;
-var after = Lab.after;
-var describe = Lab.experiment;
-var it = Lab.test;
+var lab = exports.lab = Lab.script();
+var describe = lab.describe;
+var it = lab.it;
+var expect = Code.expect;
+
+
+it('returns the same object when already boom', function (done) {
+
+ var error = Boom.badRequest();
+ var wrapped = Boom.wrap(error);
+ expect(error).to.equal(wrapped);
+ done();
+});
+it('returns an error with info when constructed using another error', function (done) {
+
+ var error = new Error('ka-boom');
+ error.xyz = 123;
+ var err = Boom.wrap(error);
+ expect(err.xyz).to.equal(123);
+ expect(err.message).to.equal('ka-boom');
+ expect(err.output).to.deep.equal({
+ statusCode: 500,
+ payload: {
+ statusCode: 500,
+ error: 'Internal Server Error',
+ message: 'An internal server error occurred'
+ },
+ headers: {}
+ });
+ expect(err.data).to.equal(null);
+ done();
+});
-describe('Boom', function () {
+it('does not override data when constructed using another error', function (done) {
+
+ var error = new Error('ka-boom');
+ error.data = { useful: 'data' };
+ var err = Boom.wrap(error);
+ expect(err.data).to.equal(error.data);
+ done();
+});
- it('returns an error with info when constructed using another error', function (done) {
+it('sets new message when none exists', function (done) {
- var error = new Error('ka-boom');
- error.xyz = 123;
- var err = new Boom(error);
- expect(err.data.xyz).to.equal(123);
- expect(err.message).to.equal('ka-boom');
- expect(err.response).to.deep.equal({
- code: 500,
- payload: {
- code: 500,
- error: 'Internal Server Error',
- message: 'ka-boom'
- },
- headers: {}
- });
+ var error = new Error();
+ var wrapped = Boom.wrap(error, 400, 'something bad');
+ expect(wrapped.message).to.equal('something bad');
+ done();
+});
+
+it('throws when statusCode is not a number', function (done) {
+
+ expect(function () {
+
+ Boom.create('x');
+ }).to.throw('First argument must be a number (400+): x');
+ done();
+});
+
+it('throws when statusCode is not finite', function (done) {
+
+ expect(function () {
+
+ Boom.create(1 / 0);
+ }).to.throw('First argument must be a number (400+): null');
+ done();
+});
+
+it('sets error code to unknown', function (done) {
+
+ var err = Boom.create(999);
+ expect(err.output.payload.error).to.equal('Unknown');
+ done();
+});
+
+describe('create()', function () {
+
+ it('does not sets null message', function (done) {
+
+ var error = Boom.unauthorized(null);
+ expect(error.output.payload.message).to.not.exist();
done();
});
- describe('#isBoom', function () {
+ it('sets message and data', function (done) {
- it('returns true for Boom object', function (done) {
+ var error = Boom.badRequest('Missing data', { type: 'user' });
+ expect(error.data.type).to.equal('user');
+ expect(error.output.payload.message).to.equal('Missing data');
+ done();
+ });
+});
- expect(Boom.badRequest().isBoom).to.equal(true);
- done();
- });
+describe('isBoom()', function () {
- it('returns false for Error object', function (done) {
+ it('returns true for Boom object', function (done) {
- expect(new Error().isBoom).to.not.exist;
- done();
- });
+ expect(Boom.badRequest().isBoom).to.equal(true);
+ done();
});
- describe('#badRequest', function () {
+ it('returns false for Error object', function (done) {
- it('returns a 400 error code', function (done) {
+ expect((new Error()).isBoom).to.not.exist();
+ done();
+ });
+});
- expect(Boom.badRequest().response.code).to.equal(400);
- done();
- });
+describe('badRequest()', function () {
- it('sets the message with the passed in message', function (done) {
+ it('returns a 400 error statusCode', function (done) {
- expect(Boom.badRequest('my message').message).to.equal('my message');
- done();
- });
+ expect(Boom.badRequest().output.statusCode).to.equal(400);
+ done();
});
- describe('#unauthorized', function () {
+ it('sets the message with the passed in message', function (done) {
- it('returns a 401 error code', function (done) {
+ expect(Boom.badRequest('my message').message).to.equal('my message');
+ done();
+ });
- var err = Boom.unauthorized();
- expect(err.response.code).to.equal(401);
- expect(err.response.headers).to.deep.equal({});
- done();
- });
+ it('sets the message to HTTP status if none provided', function (done) {
- it('sets the message with the passed in message', function (done) {
+ expect(Boom.badRequest().message).to.equal('Bad Request');
+ done();
+ });
+});
- expect(Boom.unauthorized('my message').message).to.equal('my message');
- done();
- });
+describe('unauthorized()', function () {
- it('returns a WWW-Authenticate header when passed a scheme', function (done) {
+ it('returns a 401 error statusCode', function (done) {
- var err = Boom.unauthorized('boom', 'Test');
- expect(err.response.code).to.equal(401);
- expect(err.response.headers['WWW-Authenticate']).to.equal('Test error="boom"');
- done();
- });
+ var err = Boom.unauthorized();
+ expect(err.output.statusCode).to.equal(401);
+ expect(err.output.headers).to.deep.equal({});
+ done();
+ });
- it('returns a WWW-Authenticate header when passed a scheme and attributes', function (done) {
+ it('sets the message with the passed in message', function (done) {
- var err = Boom.unauthorized('boom', 'Test', { a: 1, b: 'something', c: null, d: 0 });
- expect(err.response.code).to.equal(401);
- expect(err.response.headers['WWW-Authenticate']).to.equal('Test a="1", b="something", c="", d="0", error="boom"');
- done();
- });
+ expect(Boom.unauthorized('my message').message).to.equal('my message');
+ done();
+ });
- it('sets the isMissing flag when error message is empty', function (done) {
+ it('returns a WWW-Authenticate header when passed a scheme', function (done) {
- var err = Boom.unauthorized('', 'Basic');
- expect(err.isMissing).to.equal(true);
- done();
- });
+ var err = Boom.unauthorized('boom', 'Test');
+ expect(err.output.statusCode).to.equal(401);
+ expect(err.output.headers['WWW-Authenticate']).to.equal('Test error="boom"');
+ done();
+ });
- it('does not set the isMissing flag when error message is not empty', function (done) {
+ it('returns a WWW-Authenticate header set to the schema array value', function (done) {
- var err = Boom.unauthorized('message', 'Basic');
- expect(err.isMissing).to.equal(undefined);
- done();
- });
+ var err = Boom.unauthorized(null, ['Test','one','two']);
+ expect(err.output.statusCode).to.equal(401);
+ expect(err.output.headers['WWW-Authenticate']).to.equal('Test, one, two');
+ done();
+ });
- it('sets a WWW-Authenticate when passed as an array', function (done) {
+ it('returns a WWW-Authenticate header when passed a scheme and attributes', function (done) {
- var err = Boom.unauthorized('message', ['Basic', 'Example e="1"', 'Another x="3", y="4"']);
- expect(err.response.headers['WWW-Authenticate']).to.equal('Basic, Example e="1", Another x="3", y="4"');
- done();
- });
+ var err = Boom.unauthorized('boom', 'Test', { a: 1, b: 'something', c: null, d: 0 });
+ expect(err.output.statusCode).to.equal(401);
+ expect(err.output.headers['WWW-Authenticate']).to.equal('Test a="1", b="something", c="", d="0", error="boom"');
+ done();
});
- describe('#clientTimeout', function () {
+ it('returns a WWW-Authenticate header when passed attributes, missing error', function (done) {
- it('returns a 408 error code', function (done) {
+ var err = Boom.unauthorized(null, 'Test', { a: 1, b: 'something', c: null, d: 0 });
+ expect(err.output.statusCode).to.equal(401);
+ expect(err.output.headers['WWW-Authenticate']).to.equal('Test a="1", b="something", c="", d="0"');
+ expect(err.isMissing).to.equal(true);
+ done();
+ });
- expect(Boom.clientTimeout().response.code).to.equal(408);
- done();
- });
+ it('sets the isMissing flag when error message is empty', function (done) {
- it('sets the message with the passed in message', function (done) {
+ var err = Boom.unauthorized('', 'Basic');
+ expect(err.isMissing).to.equal(true);
+ done();
+ });
- expect(Boom.clientTimeout('my message').message).to.equal('my message');
- done();
- });
+ it('does not set the isMissing flag when error message is not empty', function (done) {
+
+ var err = Boom.unauthorized('message', 'Basic');
+ expect(err.isMissing).to.equal(undefined);
+ done();
});
- describe('#serverTimeout', function () {
+ it('sets a WWW-Authenticate when passed as an array', function (done) {
- it('returns a 503 error code', function (done) {
+ var err = Boom.unauthorized('message', ['Basic', 'Example e="1"', 'Another x="3", y="4"']);
+ expect(err.output.headers['WWW-Authenticate']).to.equal('Basic, Example e="1", Another x="3", y="4"');
+ done();
+ });
+});
- expect(Boom.serverTimeout().response.code).to.equal(503);
- done();
- });
- it('sets the message with the passed in message', function (done) {
+describe('methodNotAllowed()', function () {
- expect(Boom.serverTimeout('my message').message).to.equal('my message');
- done();
- });
+ it('returns a 405 error statusCode', function (done) {
+
+ expect(Boom.methodNotAllowed().output.statusCode).to.equal(405);
+ done();
});
- describe('#forbidden', function () {
+ it('sets the message with the passed in message', function (done) {
- it('returns a 403 error code', function (done) {
+ expect(Boom.methodNotAllowed('my message').message).to.equal('my message');
+ done();
+ });
+});
- expect(Boom.forbidden().response.code).to.equal(403);
- done();
- });
- it('sets the message with the passed in message', function (done) {
+describe('notAcceptable()', function () {
- expect(Boom.forbidden('my message').message).to.equal('my message');
- done();
- });
+ it('returns a 406 error statusCode', function (done) {
+
+ expect(Boom.notAcceptable().output.statusCode).to.equal(406);
+ done();
});
- describe('#notFound', function () {
+ it('sets the message with the passed in message', function (done) {
- it('returns a 404 error code', function (done) {
+ expect(Boom.notAcceptable('my message').message).to.equal('my message');
+ done();
+ });
+});
- expect(Boom.notFound().response.code).to.equal(404);
- done();
- });
- it('sets the message with the passed in message', function (done) {
+describe('proxyAuthRequired()', function () {
- expect(Boom.notFound('my message').message).to.equal('my message');
- done();
- });
+ it('returns a 407 error statusCode', function (done) {
+
+ expect(Boom.proxyAuthRequired().output.statusCode).to.equal(407);
+ done();
});
- describe('#internal', function () {
+ it('sets the message with the passed in message', function (done) {
- it('returns a 500 error code', function (done) {
+ expect(Boom.proxyAuthRequired('my message').message).to.equal('my message');
+ done();
+ });
+});
- expect(Boom.internal().response.code).to.equal(500);
- done();
- });
- it('sets the message with the passed in message', function (done) {
+describe('clientTimeout()', function () {
- var err = Boom.internal('my message');
- expect(err.message).to.equal('my message');
- expect(err.response.payload.message).to.equal('An internal server error occurred');
- done();
- });
+ it('returns a 408 error statusCode', function (done) {
- it('passes data on the callback if its passed in', function (done) {
+ expect(Boom.clientTimeout().output.statusCode).to.equal(408);
+ done();
+ });
- expect(Boom.internal('my message', { my: 'data' }).data.my).to.equal('data');
- done();
- });
+ it('sets the message with the passed in message', function (done) {
- it('uses passed in stack if its available', function (done) {
+ expect(Boom.clientTimeout('my message').message).to.equal('my message');
+ done();
+ });
+});
- var error = new Error();
- error.stack = 'my stack line\nmy second stack line';
- expect(Boom.internal('my message', error).trace[0]).to.equal('my stack line');
- done();
- });
+
+describe('conflict()', function () {
+
+ it('returns a 409 error statusCode', function (done) {
+
+ expect(Boom.conflict().output.statusCode).to.equal(409);
+ done();
});
- describe('#passThrough', function () {
+ it('sets the message with the passed in message', function (done) {
- it('returns a pass-through error', function (done) {
+ expect(Boom.conflict('my message').message).to.equal('my message');
+ done();
+ });
+});
- var err = Boom.passThrough(499, { a: 1 }, 'application/text', { 'X-Test': 'Boom' });
- expect(err.response.code).to.equal(499);
- expect(err.message).to.equal('Pass-through');
- expect(err.response).to.deep.equal({
- code: 499,
- payload: { a: 1 },
- headers: { 'X-Test': 'Boom' },
- type: 'application/text'
- });
- done();
- });
+
+describe('resourceGone()', function () {
+
+ it('returns a 410 error statusCode', function (done) {
+
+ expect(Boom.resourceGone().output.statusCode).to.equal(410);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.resourceGone('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('lengthRequired()', function () {
+
+ it('returns a 411 error statusCode', function (done) {
+
+ expect(Boom.lengthRequired().output.statusCode).to.equal(411);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.lengthRequired('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('preconditionFailed()', function () {
+
+ it('returns a 412 error statusCode', function (done) {
+
+ expect(Boom.preconditionFailed().output.statusCode).to.equal(412);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.preconditionFailed('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('entityTooLarge()', function () {
+
+ it('returns a 413 error statusCode', function (done) {
+
+ expect(Boom.entityTooLarge().output.statusCode).to.equal(413);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.entityTooLarge('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('uriTooLong()', function () {
+
+ it('returns a 414 error statusCode', function (done) {
+
+ expect(Boom.uriTooLong().output.statusCode).to.equal(414);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.uriTooLong('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('unsupportedMediaType()', function () {
+
+ it('returns a 415 error statusCode', function (done) {
+
+ expect(Boom.unsupportedMediaType().output.statusCode).to.equal(415);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.unsupportedMediaType('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('rangeNotSatisfiable()', function () {
+
+ it('returns a 416 error statusCode', function (done) {
+
+ expect(Boom.rangeNotSatisfiable().output.statusCode).to.equal(416);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.rangeNotSatisfiable('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('expectationFailed()', function () {
+
+ it('returns a 417 error statusCode', function (done) {
+
+ expect(Boom.expectationFailed().output.statusCode).to.equal(417);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.expectationFailed('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('badData()', function () {
+
+ it('returns a 422 error statusCode', function (done) {
+
+ expect(Boom.badData().output.statusCode).to.equal(422);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.badData('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('tooManyRequests()', function () {
+
+ it('returns a 429 error statusCode', function (done) {
+
+ expect(Boom.tooManyRequests().output.statusCode).to.equal(429);
+ done();
+ });
+
+ it('sets the message with the passed-in message', function (done) {
+
+ expect(Boom.tooManyRequests('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+describe('serverTimeout()', function () {
+
+ it('returns a 503 error statusCode', function (done) {
+
+ expect(Boom.serverTimeout().output.statusCode).to.equal(503);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.serverTimeout('my message').message).to.equal('my message');
+ done();
});
+});
+
+describe('forbidden()', function () {
+
+ it('returns a 403 error statusCode', function (done) {
- describe('#reformat', function () {
+ expect(Boom.forbidden().output.statusCode).to.equal(403);
+ done();
+ });
- it('encodes any HTML markup in the response payload', function (done) {
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.forbidden('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+describe('notFound()', function () {
+
+ it('returns a 404 error statusCode', function (done) {
+
+ expect(Boom.notFound().output.statusCode).to.equal(404);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.notFound('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+describe('internal()', function () {
+
+ it('returns a 500 error statusCode', function (done) {
+
+ expect(Boom.internal().output.statusCode).to.equal(500);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ var err = Boom.internal('my message');
+ expect(err.message).to.equal('my message');
+ expect(err.output.payload.message).to.equal('An internal server error occurred');
+ done();
+ });
+
+ it('passes data on the callback if its passed in', function (done) {
+
+ expect(Boom.internal('my message', { my: 'data' }).data.my).to.equal('data');
+ done();
+ });
- var boom = new Boom(new Error('<script>alert(1)</script>'));
- expect(boom.response.payload.message).to.not.contain('<script>');
+ it('returns an error with composite message', function (done) {
+
+ try {
+ JSON.parse('{');
+ }
+ catch (err) {
+ var boom = Boom.internal('Someting bad', err);
+ expect(boom.message).to.equal('Someting bad: Unexpected end of input');
done();
- });
+ }
+ });
+});
+
+describe('notImplemented()', function () {
+
+ it('returns a 501 error statusCode', function (done) {
+
+ expect(Boom.notImplemented().output.statusCode).to.equal(501);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.notImplemented('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+
+describe('badGateway()', function () {
+
+ it('returns a 502 error statusCode', function (done) {
+
+ expect(Boom.badGateway().output.statusCode).to.equal(502);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.badGateway('my message').message).to.equal('my message');
+ done();
+ });
+});
+
+describe('gatewayTimeout()', function () {
+
+ it('returns a 504 error statusCode', function (done) {
+
+ expect(Boom.gatewayTimeout().output.statusCode).to.equal(504);
+ done();
+ });
+
+ it('sets the message with the passed in message', function (done) {
+
+ expect(Boom.gatewayTimeout('my message').message).to.equal('my message');
+ done();
});
});
+describe('badImplementation()', function () {
+ it('returns a 500 error statusCode', function (done) {
+
+ var err = Boom.badImplementation();
+ expect(err.output.statusCode).to.equal(500);
+ expect(err.isDeveloperError).to.equal(true);
+ done();
+ });
+});
-.idea\r
-*.iml\r
-npm-debug.log\r
-dump.rdb\r
-node_modules\r
-results.tap\r
-results.xml\r
-npm-shrinkwrap.json\r
-config.json\r
-.DS_Store\r
-*/.DS_Store\r
-*/*/.DS_Store\r
-._*\r
-*/._*\r
-*/*/._*\r
-coverage.*\r
-lib-cov\r
-\r
+.idea
+*.iml
+npm-debug.log
+dump.rdb
+node_modules
+results.tap
+results.xml
+npm-shrinkwrap.json
+config.json
+.DS_Store
+*/.DS_Store
+*/*/.DS_Store
+._*
+*/._*
+*/*/._*
+coverage.*
+lib-cov
-language: node_js\r
-\r
-node_js:\r
- - 0.10\r
-\r
+language: node_js
+
+node_js:
+ - 0.10
-Copyright (c) 2012-2013, Eran Hammer.
+Copyright (c) 2014, Eran Hammer and other contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- * Neither the name of Eran Hammer nor the
- names of its contributors may be used to endorse or promote products
- derived from this software without specific prior written permission.
+ * The names of any contributors may not be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL ERAN HAMMER BE LIABLE FOR ANY
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ * * *
+
+The complete list of contributors can be found at: https://github.com/hueniverse/cryptiles/graphs/contributors
test:
- @./node_modules/.bin/lab
+ node node_modules/lab/bin/lab
test-cov:
- @./node_modules/.bin/lab -r threshold -t 100
+ node node_modules/lab/bin/lab -t 100
test-cov-html:
- @./node_modules/.bin/lab -r html -o coverage.html
-complexity:
- @./node_modules/.bin/cr -o complexity.md -f markdown lib
+ node node_modules/lab/bin/lab -r html -o coverage.html
-.PHONY: test test-cov test-cov-html complexity
+.PHONY: test test-cov test-cov-html
General purpose crypto utilities
-[![Build Status](https://secure.travis-ci.org/hueniverse/cryptiles.png)](http://travis-ci.org/hueniverse/cryptiles)
+[![Build Status](https://secure.travis-ci.org/hapijs/cryptiles.png)](http://travis-ci.org/hapijs/cryptiles)
+
+## Methods
+
+### `randomString(<Number> size)`
+Returns a cryptographically strong pseudo-random data string. Takes a size argument for the length of the string.
+
+### `fixedTimeComparison(<String> a, <String> b)`
+Compare two strings using fixed time algorithm (to prevent time-based analysis of MAC digest match). Returns `true` if the strings match, `false` if they differ.
for (var i = 0, il = a.length; i < il; ++i) {
var ac = a.charCodeAt(i);
var bc = b.charCodeAt(i);
- mismatch += (ac === bc ? 0 : 1);
+ mismatch |= (ac ^ bc);
}
return (mismatch === 0);
{
"name": "cryptiles",
"description": "General purpose crypto utilities",
- "version": "0.2.2",
+ "version": "2.0.4",
"author": {
"name": "Eran Hammer",
- "email": "eran@hueniverse.com",
+ "email": "eran@hammer.io",
"url": "http://hueniverse.com"
},
"contributors": [],
"repository": {
"type": "git",
- "url": "git://github.com/hueniverse/cryptiles"
+ "url": "git://github.com/hapijs/cryptiles"
},
"main": "index",
"keywords": [
"node": ">=0.8.0"
},
"dependencies": {
- "boom": "0.4.x"
+ "boom": "2.x.x"
},
"devDependencies": {
- "lab": "0.1.x",
- "complexity-report": "0.x.x"
+ "lab": "4.x.x"
},
"scripts": {
"test": "make test-cov"
"licenses": [
{
"type": "BSD",
- "url": "http://github.com/hueniverse/cryptiles/raw/master/LICENSE"
+ "url": "http://github.com/hapijs/cryptiles/raw/master/LICENSE"
}
],
+ "gitHead": "944263dbb628b9b3da542d35600d587f861eeaf0",
"bugs": {
- "url": "https://github.com/hueniverse/cryptiles/issues"
+ "url": "https://github.com/hapijs/cryptiles/issues"
},
- "_id": "cryptiles@0.2.2",
- "dist": {
- "shasum": "ed91ff1f17ad13d3748288594f8a48a0d26f325c",
- "tarball": "http://registry.npmjs.org/cryptiles/-/cryptiles-0.2.2.tgz"
- },
- "_from": "cryptiles@>=0.2.0 <0.3.0",
- "_npmVersion": "1.2.24",
+ "homepage": "https://github.com/hapijs/cryptiles",
+ "_id": "cryptiles@2.0.4",
+ "_shasum": "09ea1775b9e1c7de7e60a99d42ab6f08ce1a1285",
+ "_from": "cryptiles@>=2.0.0 <3.0.0",
+ "_npmVersion": "1.4.23",
"_npmUser": {
"name": "hueniverse",
"email": "eran@hueniverse.com"
"email": "eran@hueniverse.com"
}
],
+ "dist": {
+ "shasum": "09ea1775b9e1c7de7e60a99d42ab6f08ce1a1285",
+ "tarball": "http://registry.npmjs.org/cryptiles/-/cryptiles-2.0.4.tgz"
+ },
"directories": {},
- "_shasum": "ed91ff1f17ad13d3748288594f8a48a0d26f325c",
- "_resolved": "https://registry.npmjs.org/cryptiles/-/cryptiles-0.2.2.tgz",
- "readme": "ERROR: No README data found!",
- "homepage": "https://github.com/hueniverse/cryptiles"
+ "_resolved": "https://registry.npmjs.org/cryptiles/-/cryptiles-2.0.4.tgz",
+ "readme": "ERROR: No README data found!"
}
// Test shortcuts
+var lab = exports.lab = Lab.script();
+var before = lab.before;
+var after = lab.after;
+var describe = lab.experiment;
+var it = lab.test;
var expect = Lab.expect;
-var before = Lab.before;
-var after = Lab.after;
-var describe = Lab.experiment;
-var it = Lab.test;
describe('Cryptiles', function () {
expect(Cryptiles.fixedTimeComparison('x', null)).to.equal(false);
done();
});
+
+ it('should return false when not a string (left)', function (done) {
+
+ expect(Cryptiles.fixedTimeComparison(null, 'x')).to.equal(false);
+ done();
+ });
});
});
-.idea\r
-*.iml\r
-npm-debug.log\r
-dump.rdb\r
-node_modules\r
-results.tap\r
-results.xml\r
-npm-shrinkwrap.json\r
-config.json\r
-.DS_Store\r
-*/.DS_Store\r
-*/*/.DS_Store\r
-._*\r
-*/._*\r
-*/*/._*\r
-coverage.*\r
-lib-cov\r
-complexity.md\r
+.idea
+*.iml
+npm-debug.log
+dump.rdb
+node_modules
+results.tap
+results.xml
+npm-shrinkwrap.json
+config.json
+.DS_Store
+*/.DS_Store
+*/*/.DS_Store
+._*
+*/._*
+*/*/._*
+coverage.*
+lib-cov
+complexity.md
-language: node_js\r
-\r
-node_js:\r
- - 0.10\r
-\r
+language: node_js
+
+node_js:
+ - 0.10
--- /dev/null
+Please view our [hapijs contributing guide](https://github.com/hapijs/hapi/blob/master/CONTRIBUTING.md).
-Copyright (c) 2011-2013, Walmart.\r
-All rights reserved.\r
-\r
-Redistribution and use in source and binary forms, with or without\r
-modification, are permitted provided that the following conditions are met:\r
- * Redistributions of source code must retain the above copyright\r
- notice, this list of conditions and the following disclaimer.\r
- * Redistributions in binary form must reproduce the above copyright\r
- notice, this list of conditions and the following disclaimer in the\r
- documentation and/or other materials provided with the distribution.\r
- * Neither the name of Walmart nor the\r
- names of its contributors may be used to endorse or promote products\r
- derived from this software without specific prior written permission.\r
-\r
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND\r
-ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED\r
-WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE\r
-DISCLAIMED. IN NO EVENT SHALL WALMART BE LIABLE FOR ANY\r
-DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES\r
-(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;\r
-LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND\r
-ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT\r
-(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS\r
-SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.\r
-\r
-\r
- * * *\r
-\r
-\r
-Portions of this project were initially based on Postmile, Copyright (c) 2011, Yahoo Inc.\r
-Postmile is published at https://github.com/yahoo/postmile and its licensing terms are\r
-published at https://github.com/yahoo/postmile/blob/master/LICENSE.\r
-\r
+Copyright (c) 2011-2014, Walmart and other contributors.
+Copyright (c) 2011, Yahoo Inc.
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+ * Redistributions of source code must retain the above copyright
+ notice, this list of conditions and the following disclaimer.
+ * Redistributions in binary form must reproduce the above copyright
+ notice, this list of conditions and the following disclaimer in the
+ documentation and/or other materials provided with the distribution.
+ * The names of any contributors may not be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
+DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ * * *
+
+The complete list of contributors can be found at: https://github.com/hapijs/hapi/graphs/contributors
+Portions of this project were initially based on the Yahoo! Inc. Postmile project,
+published at https://github.com/yahoo/postmile.
-test:\r
- @node node_modules/lab/bin/lab\r
-test-cov: \r
- @node node_modules/lab/bin/lab -r threshold -t 100\r
-test-cov-html:\r
- @node node_modules/lab/bin/lab -r html -o coverage.html\r
-complexity:\r
- @node node_modules/complexity-report/src/cli.js -o complexity.md -f markdown lib\r
-\r
-.PHONY: test test-cov test-cov-html complexity\r
+test:
+ @node node_modules/lab/bin/lab -a code
+test-cov:
+ @node node_modules/lab/bin/lab -a code -t 100 -L
+test-cov-html:
+ @node node_modules/lab/bin/lab -a code -r html -o coverage.html
+
+.PHONY: test test-cov test-cov-html
-<a href="https://github.com/spumko"><img src="https://raw.github.com/spumko/spumko/master/images/from.png" align="right" /></a>\r
-![hoek Logo](https://raw.github.com/spumko/hoek/master/images/hoek.png)\r
-\r
-General purpose node utilities\r
-\r
-[![Build Status](https://secure.travis-ci.org/spumko/hoek.png)](http://travis-ci.org/spumko/hoek)\r
-\r
-# Table of Contents\r
-\r
-* [Introduction](#introduction "Introduction")\r
-* [Object](#object "Object")\r
- * [clone](#cloneobj "clone")\r
- * [merge](#mergetarget-source-isnulloverride-ismergearrays "merge")\r
- * [applyToDefaults](#applytodefaultsdefaults-options "applyToDefaults")\r
- * [unique](#uniquearray-key "unique")\r
- * [mapToObject](#maptoobjectarray-key "mapToObject")\r
- * [intersect](#intersectarray1-array2 "intersect")\r
- * [matchKeys](#matchkeysobj-keys "matchKeys")\r
- * [flatten](#flattenarray-target "flatten")\r
- * [removeKeys](#removekeysobject-keys "removeKeys")\r
- * [reach](#reachobj-chain "reach")\r
- * [inheritAsync](#inheritasyncself-obj-keys "inheritAsync")\r
- * [rename](#renameobj-from-to "rename")\r
-* [Timer](#timer "Timer")\r
-* [Binary Encoding/Decoding](#binary "Binary Encoding/Decoding")\r
- * [base64urlEncode](#binary64urlEncodevalue "binary64urlEncode")\r
- * [base64urlDecode](#binary64urlDecodevalue "binary64urlDecode")\r
-* [Escaping Characters](#escaped "Escaping Characters")\r
- * [escapeHtml](#escapeHtmlstring "escapeHtml")\r
- * [escapeHeaderAttribute](#escapeHeaderAttributeattribute "escapeHeaderAttribute")\r
- * [escapeRegex](#escapeRegexstring "escapeRegex")\r
-* [Errors](#errors "Errors")\r
- * [assert](#assertmessage "assert")\r
- * [abort](#abortmessage "abort")\r
- * [displayStack](#displayStackslice "displayStack")\r
- * [callStack](#callStackslice "callStack")\r
- * [toss](#tosscondition "toss")\r
-* [Load files](#load-files "Load Files")\r
- * [loadPackage](#loadPackagedir "loadpackage")\r
- * [loadDirModules](#loadDirModulespath-excludefiles-target "loaddirmodules")\r
-\r
-\r
-\r
-# Introduction\r
-\r
-The *Hoek* general purpose node utilities library is used to aid in a variety of manners. It comes with useful methods for Arrays (clone, merge, applyToDefaults), Objects (removeKeys, copy), Asserting and more. \r
-\r
-For example, to use Hoek to set configuration with default options:\r
-```javascript\r
-var Hoek = require('hoek');\r
-\r
-var default = {url : "www.github.com", port : "8000", debug : true}\r
-\r
-var config = Hoek.applyToDefaults(default, {port : "3000", admin : true});\r
-\r
-// In this case, config would be { url: 'www.github.com', port: '3000', debug: true, admin: true }\r
-```\r
-\r
-Under each of the sections (such as Array), there are subsections which correspond to Hoek methods. Each subsection will explain how to use the corresponding method. In each js excerpt below, the var Hoek = require('hoek') is omitted for brevity.\r
-\r
-## Object\r
-\r
-Hoek provides several helpful methods for objects and arrays.\r
-\r
-### clone(obj)\r
-\r
-This method is used to clone an object or an array. A *deep copy* is made (duplicates everything, including values that are objects). \r
-\r
-```javascript\r
-\r
-var nestedObj = {\r
- w: /^something$/ig,\r
- x: {\r
- a: [1, 2, 3],\r
- b: 123456,\r
- c: new Date()\r
- },\r
- y: 'y',\r
- z: new Date()\r
- };\r
-\r
-var copy = Hoek.clone(nestedObj);\r
-\r
-copy.x.b = 100;\r
-\r
-console.log(copy.y) // results in 'y'\r
-console.log(nestedObj.x.b) // results in 123456\r
-console.log(copy.x.b) // results in 100\r
-```\r
-\r
-### merge(target, source, isNullOverride, isMergeArrays)\r
-isNullOverride, isMergeArrays default to true\r
-\r
-Merge all the properties of source into target, source wins in conflic, and by default null and undefined from source are applied\r
-\r
-\r
-```javascript\r
-\r
-var target = {a: 1, b : 2}\r
-var source = {a: 0, c: 5}\r
-var source2 = {a: null, c: 5}\r
-\r
-var targetArray = [1, 2, 3];\r
-var sourceArray = [4, 5];\r
-\r
-var newTarget = Hoek.merge(target, source); // results in {a: 0, b: 2, c: 5}\r
-newTarget = Hoek.merge(target, source2); // results in {a: null, b: 2, c: 5}\r
-newTarget = Hoek.merge(target, source2, false); // results in {a: 1, b: 2, c: 5}\r
-\r
-newTarget = Hoek.merge(targetArray, sourceArray) // results in [1, 2, 3, 4, 5]\r
-newTarget = Hoek.merge(targetArray, sourceArray, true, false) // results in [4, 5]\r
-\r
-\r
-\r
-\r
-```\r
-\r
-### applyToDefaults(defaults, options)\r
-\r
-Apply options to a copy of the defaults\r
-\r
-```javascript\r
-\r
-var defaults = {host: "localhost", port: 8000};\r
-var options = {port: 8080};\r
-\r
-var config = Hoek.applyToDefaults(defaults, options); // results in {host: "localhost", port: 8080};\r
-\r
-\r
-```\r
-\r
-### unique(array, key)\r
-\r
-Remove duplicate items from Array\r
-\r
-```javascript\r
-\r
-var array = [1, 2, 2, 3, 3, 4, 5, 6];\r
-\r
-var newArray = Hoek.unique(array); // results in [1,2,3,4,5,6];\r
-\r
-array = [{id: 1}, {id: 1}, {id: 2}];\r
-\r
-newArray = Hoek.unique(array, "id") // results in [{id: 1}, {id: 2}]\r
-\r
-```\r
-\r
-### mapToObject(array, key)\r
-\r
-Convert an Array into an Object\r
-\r
-```javascript\r
-\r
-var array = [1,2,3];\r
-var newObject = Hoek.mapToObject(array); // results in [{"1": true}, {"2": true}, {"3": true}]\r
-\r
-array = [{id: 1}, {id: 2}];\r
-newObject = Hoek.mapToObject(array, "id") // results in [{"id": 1}, {"id": 2}]\r
-\r
-```\r
-### intersect(array1, array2)\r
-\r
-Find the common unique items in two arrays\r
-\r
-```javascript\r
-\r
-var array1 = [1, 2, 3];\r
-var array2 = [1, 4, 5];\r
-\r
-var newArray = Hoek.intersect(array1, array2) // results in [1]\r
-\r
-```\r
-\r
-### matchKeys(obj, keys) \r
-\r
-Find which keys are present\r
-\r
-```javascript\r
-\r
-var obj = {a: 1, b: 2, c: 3};\r
-var keys = ["a", "e"];\r
-\r
-Hoek.matchKeys(obj, keys) // returns ["a"]\r
-\r
-```\r
-\r
-### flatten(array, target)\r
-\r
-Flatten an array\r
-\r
-```javascript\r
-\r
-var array = [1, 2, 3];\r
-var target = [4, 5]; \r
-\r
-var flattenedArray = Hoek.flatten(array, target) // results in [4, 5, 1, 2, 3];\r
-\r
-```\r
-\r
-### removeKeys(object, keys)\r
-\r
-Remove keys\r
-\r
-```javascript\r
-\r
-var object = {a: 1, b: 2, c: 3, d: 4};\r
-\r
-var keys = ["a", "b"];\r
-\r
-Hoek.removeKeys(object, keys) // object is now {c: 3, d: 4}\r
-\r
-```\r
-\r
-### reach(obj, chain)\r
-\r
-Converts an object key chain string to reference\r
-\r
-```javascript\r
-\r
-var chain = 'a.b.c';\r
-var obj = {a : {b : { c : 1}}};\r
-\r
-Hoek.reach(obj, chain) // returns 1\r
-\r
-```\r
-\r
-### inheritAsync(self, obj, keys) \r
-\r
-Inherits a selected set of methods from an object, wrapping functions in asynchronous syntax and catching errors\r
-\r
-```javascript\r
-\r
-var targetFunc = function () { };\r
-\r
-var proto = {\r
- a: function () {\r
- return 'a!';\r
- },\r
- b: function () {\r
- return 'b!';\r
- },\r
- c: function () {\r
- throw new Error('c!');\r
- }\r
- };\r
-\r
-var keys = ['a', 'c'];\r
-\r
-Hoek.inheritAsync(targetFunc, proto, ['a', 'c']);\r
-\r
-var target = new targetFunc();\r
-\r
-target.a(function(err, result){console.log(result)} // returns 'a!' \r
-\r
-target.c(function(err, result){console.log(result)} // returns undefined\r
-\r
-target.b(function(err, result){console.log(result)} // gives error: Object [object Object] has no method 'b'\r
-\r
-```\r
-\r
-### rename(obj, from, to)\r
-\r
-Rename a key of an object\r
-\r
-```javascript\r
-\r
-var obj = {a : 1, b : 2};\r
-\r
-Hoek.rename(obj, "a", "c"); // obj is now {c : 1, b : 2}\r
-\r
-```\r
-\r
-\r
-# Timer\r
-\r
-A Timer object. Initializing a new timer object sets the ts to the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.\r
-\r
-```javascript\r
-\r
-\r
-example : \r
-\r
-\r
-var timerObj = new Hoek.Timer();\r
-console.log("Time is now: " + timerObj.ts)\r
-console.log("Elapsed time from initialization: " + timerObj.elapsed() + 'milliseconds')\r
-\r
-```\r
-\r
-# Binary Encoding/Decoding\r
-\r
-### base64urlEncode(value)\r
-\r
-Encodes value in Base64 or URL encoding\r
-\r
-### base64urlDecode(value)\r
-\r
-Decodes data in Base64 or URL encoding.\r
-# Escaping Characters\r
-\r
-Hoek provides convenient methods for escaping html characters. The escaped characters are as followed:\r
-\r
-```javascript\r
-\r
-internals.htmlEscaped = {\r
- '&': '&',\r
- '<': '<',\r
- '>': '>',\r
- '"': '"',\r
- "'": ''',\r
- '`': '`'\r
-};\r
-\r
-```\r
-\r
-### escapeHtml(string)\r
-\r
-```javascript\r
-\r
-var string = '<html> hey </html>';\r
-var escapedString = Hoek.escapeHtml(string); // returns <html> hey </html>\r
-\r
-```\r
-\r
-### escapeHeaderAttribute(attribute)\r
-\r
-Escape attribute value for use in HTTP header\r
-\r
-```javascript\r
-\r
-var a = Hoek.escapeHeaderAttribute('I said "go w\\o me"'); //returns I said \"go w\\o me\"\r
-\r
-\r
-```\r
-\r
-\r
-### escapeRegex(string)\r
-\r
-Escape string for Regex construction\r
-\r
-```javascript\r
-\r
-var a = Hoek.escapeRegex('4^f$s.4*5+-_?%=#!:@|~\\/`"(>)[<]d{}s,'); // returns 4\^f\$s\.4\*5\+\-_\?%\=#\!\:@\|~\\\/`"\(>\)\[<\]d\{\}s\,\r
-\r
-\r
-\r
-```\r
-\r
-# Errors\r
-\r
-### assert(message)\r
-\r
-```javascript\r
-\r
-var a = 1, b =2;\r
-\r
-Hoek.assert(a === b, 'a should equal b'); // ABORT: a should equal b\r
-\r
-```\r
-\r
-### abort(message)\r
-\r
-First checks if process.env.NODE_ENV === 'test', and if so, throws error message. Otherwise,\r
-displays most recent stack and then exits process.\r
-\r
-\r
-\r
-### displayStack(slice)\r
-\r
-Displays the trace stack\r
-\r
-```javascript\r
-\r
-var stack = Hoek.displayStack();\r
-console.log(stack) // returns something like:\r
-\r
-[ 'null (/Users/user/Desktop/hoek/test.js:4:18)',\r
- 'Module._compile (module.js:449:26)',\r
- 'Module._extensions..js (module.js:467:10)',\r
- 'Module.load (module.js:356:32)',\r
- 'Module._load (module.js:312:12)',\r
- 'Module.runMain (module.js:492:10)',\r
- 'startup.processNextTick.process._tickCallback (node.js:244:9)' ]\r
-\r
-```\r
-\r
-### callStack(slice)\r
-\r
-Returns a trace stack array.\r
-\r
-```javascript\r
-\r
-var stack = Hoek.callStack();\r
-console.log(stack) // returns something like:\r
-\r
-[ [ '/Users/user/Desktop/hoek/test.js', 4, 18, null, false ],\r
- [ 'module.js', 449, 26, 'Module._compile', false ],\r
- [ 'module.js', 467, 10, 'Module._extensions..js', false ],\r
- [ 'module.js', 356, 32, 'Module.load', false ],\r
- [ 'module.js', 312, 12, 'Module._load', false ],\r
- [ 'module.js', 492, 10, 'Module.runMain', false ],\r
- [ 'node.js',\r
- 244,\r
- 9,\r
- 'startup.processNextTick.process._tickCallback',\r
- false ] ]\r
-\r
-\r
-```\r
-\r
-### toss(condition)\r
-\r
-toss(condition /*, [message], callback */)\r
-\r
-Return an error as first argument of a callback\r
-\r
-\r
-# Load Files\r
-\r
-### loadPackage(dir)\r
-\r
-Load and parse package.json process root or given directory\r
-\r
-```javascript\r
-\r
-var pack = Hoek.loadPackage(); // pack.name === 'hoek'\r
-\r
-```\r
-\r
-### loadDirModules(path, excludeFiles, target) \r
-\r
-Loads modules from a given path; option to exclude files (array).\r
-\r
-\r
-\r
-\r
+![hoek Logo](https://raw.github.com/hapijs/hoek/master/images/hoek.png)
+
+Utility methods for the hapi ecosystem. This module is not intended to solve every problem for everyone, but rather as a central place to store hapi-specific methods. If you're looking for a general purpose utility module, check out [lodash](https://github.com/lodash/lodash) or [underscore](https://github.com/jashkenas/underscore).
+
+[![Build Status](https://secure.travis-ci.org/hapijs/hoek.png)](http://travis-ci.org/hapijs/hoek)
+
+Lead Maintainer: [Nathan LaFreniere](https://github.com/nlf)
+
+# Table of Contents
+
+* [Introduction](#introduction "Introduction")
+* [Object](#object "Object")
+ * [clone](#cloneobj "clone")
+ * [cloneWithShallow](#clonewithshallowobj-keys "cloneWithShallow")
+ * [merge](#mergetarget-source-isnulloverride-ismergearrays "merge")
+ * [applyToDefaults](#applytodefaultsdefaults-options "applyToDefaults")
+ * [applyToDefaultsWithShallow](#applytodefaultswithshallowdefaults-options-keys "applyToDefaultsWithShallow")
+ * [deepEqual](#deepequala-b "deepEqual")
+ * [unique](#uniquearray-key "unique")
+ * [mapToObject](#maptoobjectarray-key "mapToObject")
+ * [intersect](#intersectarray1-array2 "intersect")
+ * [contain](#containref-values-options "contain")
+ * [flatten](#flattenarray-target "flatten")
+ * [reach](#reachobj-chain-options "reach")
+ * [transform](#transformobj-transform-options "transform")
+ * [shallow](#shallowobj "shallow")
+ * [stringify](#stringifyobj "stringify")
+* [Timer](#timer "Timer")
+* [Bench](#bench "Bench")
+* [Binary Encoding/Decoding](#binary-encodingdecoding "Binary Encoding/Decoding")
+ * [base64urlEncode](#base64urlencodevalue "binary64urlEncode")
+ * [base64urlDecode](#base64urldecodevalue "binary64urlDecode")
+* [Escaping Characters](#escaping-characters "Escaping Characters")
+ * [escapeHtml](#escapehtmlstring "escapeHtml")
+ * [escapeHeaderAttribute](#escapeheaderattributeattribute "escapeHeaderAttribute")
+ * [escapeRegex](#escaperegexstring "escapeRegex")
+* [Errors](#errors "Errors")
+ * [assert](#assertcondition-message "assert")
+ * [abort](#abortmessage "abort")
+ * [displayStack](#displaystackslice "displayStack")
+ * [callStack](#callstackslice "callStack")
+* [Function](#function "Function")
+ * [nextTick](#nexttickfn "nextTick")
+ * [once](#oncefn "once")
+ * [ignore](#ignore "ignore")
+* [Miscellaneous](#miscellaneous "Miscellaneous")
+ * [uniqueFilename](#uniquefilename "uniqueFilename")
+ * [isInteger](#isInteger "isInteger")
+
+
+
+# Introduction
+
+The *Hoek* library contains some common functions used within the hapi ecosystem. It comes with useful methods for Arrays (clone, merge, applyToDefaults), Objects (removeKeys, copy), Asserting and more.
+
+For example, to use Hoek to set configuration with default options:
+```javascript
+var Hoek = require('hoek');
+
+var default = {url : "www.github.com", port : "8000", debug : true};
+
+var config = Hoek.applyToDefaults(default, {port : "3000", admin : true});
+
+// In this case, config would be { url: 'www.github.com', port: '3000', debug: true, admin: true }
+```
+
+Under each of the sections (such as Array), there are subsections which correspond to Hoek methods. Each subsection will explain how to use the corresponding method. In each js excerpt below, the `var Hoek = require('hoek');` is omitted for brevity.
+
+## Object
+
+Hoek provides several helpful methods for objects and arrays.
+
+### clone(obj)
+
+This method is used to clone an object or an array. A *deep copy* is made (duplicates everything, including values that are objects).
+
+```javascript
+
+var nestedObj = {
+ w: /^something$/ig,
+ x: {
+ a: [1, 2, 3],
+ b: 123456,
+ c: new Date()
+ },
+ y: 'y',
+ z: new Date()
+ };
+
+var copy = Hoek.clone(nestedObj);
+
+copy.x.b = 100;
+
+console.log(copy.y); // results in 'y'
+console.log(nestedObj.x.b); // results in 123456
+console.log(copy.x.b); // results in 100
+```
+
+### cloneWithShallow(obj, keys)
+keys is an array of key names to shallow copy
+
+This method is also used to clone an object or array, however any keys listed in the `keys` array are shallow copied while those not listed are deep copied.
+
+```javascript
+
+var nestedObj = {
+ w: /^something$/ig,
+ x: {
+ a: [1, 2, 3],
+ b: 123456,
+ c: new Date()
+ },
+ y: 'y',
+ z: new Date()
+ };
+
+var copy = Hoek.cloneWithShallow(nestedObj, ['x']);
+
+copy.x.b = 100;
+
+console.log(copy.y); // results in 'y'
+console.log(nestedObj.x.b); // results in 100
+console.log(copy.x.b); // results in 100
+```
+
+### merge(target, source, isNullOverride, isMergeArrays)
+isNullOverride, isMergeArrays default to true
+
+Merge all the properties of source into target, source wins in conflict, and by default null and undefined from source are applied.
+Merge is destructive where the target is modified. For non destructive merge, use `applyToDefaults`.
+
+
+```javascript
+
+var target = {a: 1, b : 2};
+var source = {a: 0, c: 5};
+var source2 = {a: null, c: 5};
+
+Hoek.merge(target, source); // results in {a: 0, b: 2, c: 5}
+Hoek.merge(target, source2); // results in {a: null, b: 2, c: 5}
+Hoek.merge(target, source2, false); // results in {a: 1, b: 2, c: 5}
+
+var targetArray = [1, 2, 3];
+var sourceArray = [4, 5];
+
+Hoek.merge(targetArray, sourceArray); // results in [1, 2, 3, 4, 5]
+Hoek.merge(targetArray, sourceArray, true, false); // results in [4, 5]
+```
+
+### applyToDefaults(defaults, options)
+
+Apply options to a copy of the defaults
+
+```javascript
+
+var defaults = { host: "localhost", port: 8000 };
+var options = { port: 8080 };
+
+var config = Hoek.applyToDefaults(defaults, options); // results in { host: "localhost", port: 8080 }
+```
+
+### applyToDefaultsWithShallow(defaults, options, keys)
+keys is an array of key names to shallow copy
+
+Apply options to a copy of the defaults. Keys specified in the last parameter are shallow copied from options instead of merged.
+
+```javascript
+
+var defaults = {
+ server: {
+ host: "localhost",
+ port: 8000
+ },
+ name: 'example'
+ };
+
+var options = { server: { port: 8080 } };
+
+var config = Hoek.applyToDefaults(defaults, options); // results in { server: { port: 8080 }, name: 'example' }
+```
+
+### deepEqual(b, a)
+
+Performs a deep comparison of the two values including support for circular dependencies, prototype, and properties.
+
+```javascript
+Hoek.deepEqual({ a: [1, 2], b: 'string', c: { d: true } }, { a: [1, 2], b: 'string', c: { d: true } });
+```
+
+### unique(array, key)
+
+Remove duplicate items from Array
+
+```javascript
+
+var array = [1, 2, 2, 3, 3, 4, 5, 6];
+
+var newArray = Hoek.unique(array); // results in [1,2,3,4,5,6]
+
+array = [{id: 1}, {id: 1}, {id: 2}];
+
+newArray = Hoek.unique(array, "id"); // results in [{id: 1}, {id: 2}]
+```
+
+### mapToObject(array, key)
+
+Convert an Array into an Object
+
+```javascript
+
+var array = [1,2,3];
+var newObject = Hoek.mapToObject(array); // results in [{"1": true}, {"2": true}, {"3": true}]
+
+array = [{id: 1}, {id: 2}];
+newObject = Hoek.mapToObject(array, "id"); // results in [{"id": 1}, {"id": 2}]
+```
+
+### intersect(array1, array2)
+
+Find the common unique items in two arrays
+
+```javascript
+
+var array1 = [1, 2, 3];
+var array2 = [1, 4, 5];
+
+var newArray = Hoek.intersect(array1, array2); // results in [1]
+```
+
+### contain(ref, values, [options])
+
+Tests if the reference value contains the provided values where:
+- `ref` - the reference string, array, or object.
+- `values` - a single or array of values to find within the `ref` value. If `ref` is an object, `values` can be a key name,
+ an array of key names, or an object with key-value pairs to compare.
+- `options` - an optional object with the following optional settings:
+ - `deep` - if `true`, performed a deep comparison of the values.
+ - `once` - if `true`, allows only one occurrence of each value.
+ - `only` - if `true`, does not allow values not explicitly listed.
+ - `part` - if `true`, allows partial match of the values (at least one must always match).
+
+Note: comparing a string to overlapping values will result in failed comparison (e.g. `contain('abc', ['ab', 'bc'])`).
+Also, if an object key's value does not match the provided value, `false` is returned even when `part` is specified.
+
+```javascript
+Hoek.contain('aaa', 'a', { only: true }); // true
+Hoek.contain([{ a: 1 }], [{ a: 1 }], { deep: true }); // true
+Hoek.contain([1, 2, 2], [1, 2], { once: true }); // false
+Hoek.contain({ a: 1, b: 2, c: 3 }, { a: 1, d: 4 }, { part: true }); // true
+```
+
+### flatten(array, [target])
+
+Flatten an array
+
+```javascript
+
+var array = [1, [2, 3]];
+
+var flattenedArray = Hoek.flatten(array); // results in [1, 2, 3]
+
+array = [1, [2, 3]];
+target = [4, [5]];
+
+flattenedArray = Hoek.flatten(array, target); // results in [4, [5], 1, 2, 3]
+```
+
+### reach(obj, chain, [options])
+
+Converts an object key chain string to reference
+
+- `options` - optional settings
+ - `separator` - string to split chain path on, defaults to '.'
+ - `default` - value to return if the path or value is not present, default is `undefined`
+ - `strict` - if `true`, will throw an error on missing member, default is `false`
+ - `functions` - if `true` allow traversing functions for properties. `false` will throw an error if a function is part of the chain.
+
+A chain including negative numbers will work like negative indices on an
+array.
+
+```javascript
+
+var chain = 'a.b.c';
+var obj = {a : {b : { c : 1}}};
+
+Hoek.reach(obj, chain); // returns 1
+
+var chain = 'a.b.-1';
+var obj = {a : {b : [2,3,6]}};
+
+Hoek.reach(obj, chain); // returns 6
+```
+
+### transform(obj, transform, [options])
+
+Transforms an existing object into a new one based on the supplied `obj` and `transform` map. `options` are the same as the `reach` options.
+
+```javascript
+var source = {
+ address: {
+ one: '123 main street',
+ two: 'PO Box 1234'
+ },
+ title: 'Warehouse',
+ state: 'CA'
+};
+
+var result = Hoek.transform(source, {
+ 'person.address.lineOne': 'address.one',
+ 'person.address.lineTwo': 'address.two',
+ 'title': 'title',
+ 'person.address.region': 'state'
+});
+// Results in
+// {
+// person: {
+// address: {
+// lineOne: '123 main street',
+// lineTwo: 'PO Box 1234',
+// region: 'CA'
+// }
+// },
+// title: 'Warehouse'
+// }
+```
+
+### shallow(obj)
+
+Performs a shallow copy by copying the references of all the top level children where:
+- `obj` - the object to be copied.
+
+```javascript
+var shallow = Hoek.shallow({ a: { b: 1 } });
+```
+
+### stringify(obj)
+
+Converts an object to string using the built-in `JSON.stringify()` method with the difference that any errors are caught
+and reported back in the form of the returned string. Used as a shortcut for displaying information to the console (e.g. in
+error message) without the need to worry about invalid conversion.
+
+```javascript
+var a = {};
+a.b = a;
+Hoek.stringify(a); // Returns '[Cannot display object: Converting circular structure to JSON]'
+```
+
+# Timer
+
+A Timer object. Initializing a new timer object sets the ts to the number of milliseconds elapsed since 1 January 1970 00:00:00 UTC.
+
+```javascript
+
+var timerObj = new Hoek.Timer();
+console.log("Time is now: " + timerObj.ts);
+console.log("Elapsed time from initialization: " + timerObj.elapsed() + 'milliseconds');
+```
+
+
+# Bench
+
+Same as Timer with the exception that `ts` stores the internal node clock which is not related to `Date.now()` and cannot be used to display
+human-readable timestamps. More accurate for benchmarking or internal timers.
+
+# Binary Encoding/Decoding
+
+### base64urlEncode(value)
+
+Encodes value in Base64 or URL encoding
+
+### base64urlDecode(value)
+
+Decodes data in Base64 or URL encoding.
+# Escaping Characters
+
+Hoek provides convenient methods for escaping html characters. The escaped characters are as followed:
+
+```javascript
+
+internals.htmlEscaped = {
+ '&': '&',
+ '<': '<',
+ '>': '>',
+ '"': '"',
+ "'": ''',
+ '`': '`'
+};
+```
+
+### escapeHtml(string)
+
+```javascript
+
+var string = '<html> hey </html>';
+var escapedString = Hoek.escapeHtml(string); // returns <html> hey </html>
+```
+
+### escapeHeaderAttribute(attribute)
+
+Escape attribute value for use in HTTP header
+
+```javascript
+
+var a = Hoek.escapeHeaderAttribute('I said "go w\\o me"'); //returns I said \"go w\\o me\"
+```
+
+
+### escapeRegex(string)
+
+Escape string for Regex construction
+
+```javascript
+
+var a = Hoek.escapeRegex('4^f$s.4*5+-_?%=#!:@|~\\/`"(>)[<]d{}s,'); // returns 4\^f\$s\.4\*5\+\-_\?%\=#\!\:@\|~\\\/`"\(>\)\[<\]d\{\}s\,
+```
+
+# Errors
+
+### assert(condition, message)
+
+```javascript
+
+var a = 1, b = 2;
+
+Hoek.assert(a === b, 'a should equal b'); // Throws 'a should equal b'
+```
+
+Note that you may also pass an already created Error object as the second parameter, and `assert` will throw that object.
+
+```javascript
+
+var a = 1, b = 2;
+
+Hoek.assert(a === b, new Error('a should equal b')); // Throws the given error object
+```
+
+### abort(message)
+
+First checks if `process.env.NODE_ENV === 'test'`, and if so, throws error message. Otherwise,
+displays most recent stack and then exits process.
+
+
+
+### displayStack(slice)
+
+Displays the trace stack
+
+```javascript
+
+var stack = Hoek.displayStack();
+console.log(stack); // returns something like:
+
+[ 'null (/Users/user/Desktop/hoek/test.js:4:18)',
+ 'Module._compile (module.js:449:26)',
+ 'Module._extensions..js (module.js:467:10)',
+ 'Module.load (module.js:356:32)',
+ 'Module._load (module.js:312:12)',
+ 'Module.runMain (module.js:492:10)',
+ 'startup.processNextTick.process._tickCallback (node.js:244:9)' ]
+```
+
+### callStack(slice)
+
+Returns a trace stack array.
+
+```javascript
+
+var stack = Hoek.callStack();
+console.log(stack); // returns something like:
+
+[ [ '/Users/user/Desktop/hoek/test.js', 4, 18, null, false ],
+ [ 'module.js', 449, 26, 'Module._compile', false ],
+ [ 'module.js', 467, 10, 'Module._extensions..js', false ],
+ [ 'module.js', 356, 32, 'Module.load', false ],
+ [ 'module.js', 312, 12, 'Module._load', false ],
+ [ 'module.js', 492, 10, 'Module.runMain', false ],
+ [ 'node.js',
+ 244,
+ 9,
+ 'startup.processNextTick.process._tickCallback',
+ false ] ]
+```
+
+## Function
+
+### nextTick(fn)
+
+Returns a new function that wraps `fn` in `process.nextTick`.
+
+```javascript
+
+var myFn = function () {
+ console.log('Do this later');
+};
+
+var nextFn = Hoek.nextTick(myFn);
+
+nextFn();
+console.log('Do this first');
+
+// Results in:
+//
+// Do this first
+// Do this later
+```
+
+### once(fn)
+
+Returns a new function that can be run multiple times, but makes sure `fn` is only run once.
+
+```javascript
+
+var myFn = function () {
+ console.log('Ran myFn');
+};
+
+var onceFn = Hoek.once(myFn);
+onceFn(); // results in "Ran myFn"
+onceFn(); // results in undefined
+```
+
+### ignore
+
+A simple no-op function. It does nothing at all.
+
+## Miscellaneous
+
+### uniqueFilename(path, extension)
+`path` to prepend with the randomly generated file name. `extension` is the optional file extension, defaults to `''`.
+
+Returns a randomly generated file name at the specified `path`. The result is a fully resolved path to a file.
+
+```javascript
+var result = Hoek.uniqueFilename('./test/modules', 'txt'); // results in "full/path/test/modules/{random}.txt"
+```
+
+### isInteger(value)
+
+Check `value` to see if it is an integer. Returns true/false.
+
+```javascript
+var result = Hoek.isInteger('23')
+```
-module.exports = require('./lib');
\ No newline at end of file
+module.exports = require('./lib');
-// Declare internals\r
-\r
-var internals = {};\r
-\r
-\r
-exports.escapeJavaScript = function (input) {\r
-\r
- if (!input) {\r
- return '';\r
- }\r
-\r
- var escaped = '';\r
-\r
- for (var i = 0, il = input.length; i < il; ++i) {\r
-\r
- var charCode = input.charCodeAt(i);\r
-\r
- if (internals.isSafe(charCode)) {\r
- escaped += input[i];\r
- }\r
- else {\r
- escaped += internals.escapeJavaScriptChar(charCode);\r
- }\r
- }\r
-\r
- return escaped;\r
-};\r
-\r
-\r
-exports.escapeHtml = function (input) {\r
-\r
- if (!input) {\r
- return '';\r
- }\r
-\r
- var escaped = '';\r
-\r
- for (var i = 0, il = input.length; i < il; ++i) {\r
-\r
- var charCode = input.charCodeAt(i);\r
-\r
- if (internals.isSafe(charCode)) {\r
- escaped += input[i];\r
- }\r
- else {\r
- escaped += internals.escapeHtmlChar(charCode);\r
- }\r
- }\r
-\r
- return escaped;\r
-};\r
-\r
-\r
-internals.escapeJavaScriptChar = function (charCode) {\r
-\r
- if (charCode >= 256) {\r
- return '\\u' + internals.padLeft('' + charCode, 4);\r
- }\r
-\r
- var hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');\r
- return '\\x' + internals.padLeft(hexValue, 2);\r
-};\r
-\r
-\r
-internals.escapeHtmlChar = function (charCode) {\r
-\r
- var namedEscape = internals.namedHtml[charCode];\r
- if (typeof namedEscape !== 'undefined') {\r
- return namedEscape;\r
- }\r
-\r
- if (charCode >= 256) {\r
- return '&#' + charCode + ';';\r
- }\r
-\r
- var hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');\r
- return '&#x' + internals.padLeft(hexValue, 2) + ';';\r
-};\r
-\r
-\r
-internals.padLeft = function (str, len) {\r
-\r
- while (str.length < len) {\r
- str = '0' + str;\r
- }\r
-\r
- return str;\r
-};\r
-\r
-\r
-internals.isSafe = function (charCode) {\r
-\r
- return (typeof internals.safeCharCodes[charCode] !== 'undefined');\r
-};\r
-\r
-\r
-internals.namedHtml = {\r
- '38': '&',\r
- '60': '<',\r
- '62': '>',\r
- '34': '"',\r
- '160': ' ',\r
- '162': '¢',\r
- '163': '£',\r
- '164': '¤',\r
- '169': '©',\r
- '174': '®'\r
-};\r
-\r
-\r
-internals.safeCharCodes = (function () {\r
-\r
- var safe = {};\r
-\r
- for (var i = 32; i < 123; ++i) {\r
-\r
- if ((i >= 97 && i <= 122) || // a-z\r
- (i >= 65 && i <= 90) || // A-Z\r
- (i >= 48 && i <= 57) || // 0-9\r
- i === 32 || // space\r
- i === 46 || // .\r
- i === 44 || // ,\r
- i === 45 || // -\r
- i === 58 || // :\r
- i === 95) { // _\r
-\r
- safe[i] = null;\r
- }\r
- }\r
-\r
- return safe;\r
-}());
\ No newline at end of file
+// Declare internals
+
+var internals = {};
+
+
+exports.escapeJavaScript = function (input) {
+
+ if (!input) {
+ return '';
+ }
+
+ var escaped = '';
+
+ for (var i = 0, il = input.length; i < il; ++i) {
+
+ var charCode = input.charCodeAt(i);
+
+ if (internals.isSafe(charCode)) {
+ escaped += input[i];
+ }
+ else {
+ escaped += internals.escapeJavaScriptChar(charCode);
+ }
+ }
+
+ return escaped;
+};
+
+
+exports.escapeHtml = function (input) {
+
+ if (!input) {
+ return '';
+ }
+
+ var escaped = '';
+
+ for (var i = 0, il = input.length; i < il; ++i) {
+
+ var charCode = input.charCodeAt(i);
+
+ if (internals.isSafe(charCode)) {
+ escaped += input[i];
+ }
+ else {
+ escaped += internals.escapeHtmlChar(charCode);
+ }
+ }
+
+ return escaped;
+};
+
+
+internals.escapeJavaScriptChar = function (charCode) {
+
+ if (charCode >= 256) {
+ return '\\u' + internals.padLeft('' + charCode, 4);
+ }
+
+ var hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');
+ return '\\x' + internals.padLeft(hexValue, 2);
+};
+
+
+internals.escapeHtmlChar = function (charCode) {
+
+ var namedEscape = internals.namedHtml[charCode];
+ if (typeof namedEscape !== 'undefined') {
+ return namedEscape;
+ }
+
+ if (charCode >= 256) {
+ return '&#' + charCode + ';';
+ }
+
+ var hexValue = new Buffer(String.fromCharCode(charCode), 'ascii').toString('hex');
+ return '&#x' + internals.padLeft(hexValue, 2) + ';';
+};
+
+
+internals.padLeft = function (str, len) {
+
+ while (str.length < len) {
+ str = '0' + str;
+ }
+
+ return str;
+};
+
+
+internals.isSafe = function (charCode) {
+
+ return (typeof internals.safeCharCodes[charCode] !== 'undefined');
+};
+
+
+internals.namedHtml = {
+ '38': '&',
+ '60': '<',
+ '62': '>',
+ '34': '"',
+ '160': ' ',
+ '162': '¢',
+ '163': '£',
+ '164': '¤',
+ '169': '©',
+ '174': '®'
+};
+
+
+internals.safeCharCodes = (function () {
+
+ var safe = {};
+
+ for (var i = 32; i < 123; ++i) {
+
+ if ((i >= 97) || // a-z
+ (i >= 65 && i <= 90) || // A-Z
+ (i >= 48 && i <= 57) || // 0-9
+ i === 32 || // space
+ i === 46 || // .
+ i === 44 || // ,
+ i === 45 || // -
+ i === 58 || // :
+ i === 95) { // _
+
+ safe[i] = null;
+ }
+ }
+
+ return safe;
+}());
-// Load modules\r
-\r
-var Fs = require('fs');\r
-var Escape = require('./escape');\r
-\r
-\r
-// Declare internals\r
-\r
-var internals = {};\r
-\r
-\r
-// Clone object or array\r
-\r
-exports.clone = function (obj, seen) {\r
-\r
- if (typeof obj !== 'object' ||\r
- obj === null) {\r
-\r
- return obj;\r
- }\r
-\r
- seen = seen || { orig: [], copy: [] };\r
-\r
- var lookup = seen.orig.indexOf(obj);\r
- if (lookup !== -1) {\r
- return seen.copy[lookup];\r
- }\r
-\r
- var newObj = (obj instanceof Array) ? [] : {};\r
-\r
- seen.orig.push(obj);\r
- seen.copy.push(newObj);\r
-\r
- for (var i in obj) {\r
- if (obj.hasOwnProperty(i)) {\r
- if (obj[i] instanceof Buffer) {\r
- newObj[i] = new Buffer(obj[i]);\r
- }\r
- else if (obj[i] instanceof Date) {\r
- newObj[i] = new Date(obj[i].getTime());\r
- }\r
- else if (obj[i] instanceof RegExp) {\r
- var flags = '' + (obj[i].global ? 'g' : '') + (obj[i].ignoreCase ? 'i' : '') + (obj[i].multiline ? 'm' : '');\r
- newObj[i] = new RegExp(obj[i].source, flags);\r
- }\r
- else {\r
- newObj[i] = exports.clone(obj[i], seen);\r
- }\r
- }\r
- }\r
-\r
- return newObj;\r
-};\r
-\r
-\r
-// Merge all the properties of source into target, source wins in conflic, and by default null and undefined from source are applied\r
-\r
-exports.merge = function (target, source, isNullOverride /* = true */, isMergeArrays /* = true */) {\r
-\r
- exports.assert(target && typeof target == 'object', 'Invalid target value: must be an object');\r
- exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object');\r
-\r
- if (!source) {\r
- return target;\r
- }\r
-\r
- if (source instanceof Array) {\r
- exports.assert(target instanceof Array, 'Cannot merge array onto an object');\r
- if (isMergeArrays === false) { // isMergeArrays defaults to true\r
- target.length = 0; // Must not change target assignment\r
- }\r
-\r
- for (var i = 0, il = source.length; i < il; ++i) {\r
- target.push(source[i]);\r
- }\r
-\r
- return target;\r
- }\r
-\r
- var keys = Object.keys(source);\r
- for (var k = 0, kl = keys.length; k < kl; ++k) {\r
- var key = keys[k];\r
- var value = source[key];\r
- if (value &&\r
- typeof value === 'object') {\r
-\r
- if (!target[key] ||\r
- typeof target[key] !== 'object') {\r
-\r
- target[key] = exports.clone(value);\r
- }\r
- else {\r
- exports.merge(target[key], source[key], isNullOverride, isMergeArrays);\r
- }\r
- }\r
- else {\r
- if (value !== null && value !== undefined) { // Explicit to preserve empty strings\r
- target[key] = value;\r
- }\r
- else if (isNullOverride !== false) { // Defaults to true\r
- target[key] = value;\r
- }\r
- }\r
- }\r
-\r
- return target;\r
-};\r
-\r
-\r
-// Apply options to a copy of the defaults\r
-\r
-exports.applyToDefaults = function (defaults, options) {\r
-\r
- exports.assert(defaults && typeof defaults == 'object', 'Invalid defaults value: must be an object');\r
- exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');\r
-\r
- if (!options) { // If no options, return null\r
- return null;\r
- }\r
-\r
- var copy = exports.clone(defaults);\r
-\r
- if (options === true) { // If options is set to true, use defaults\r
- return copy;\r
- }\r
-\r
- return exports.merge(copy, options, false, false);\r
-};\r
-\r
-\r
-// Remove duplicate items from array\r
-\r
-exports.unique = function (array, key) {\r
-\r
- var index = {};\r
- var result = [];\r
-\r
- for (var i = 0, il = array.length; i < il; ++i) {\r
- var id = (key ? array[i][key] : array[i]);\r
- if (index[id] !== true) {\r
-\r
- result.push(array[i]);\r
- index[id] = true;\r
- }\r
- }\r
-\r
- return result;\r
-};\r
-\r
-\r
-// Convert array into object\r
-\r
-exports.mapToObject = function (array, key) {\r
-\r
- if (!array) {\r
- return null;\r
- }\r
-\r
- var obj = {};\r
- for (var i = 0, il = array.length; i < il; ++i) {\r
- if (key) {\r
- if (array[i][key]) {\r
- obj[array[i][key]] = true;\r
- }\r
- }\r
- else {\r
- obj[array[i]] = true;\r
- }\r
- }\r
-\r
- return obj;\r
-};\r
-\r
-\r
-// Find the common unique items in two arrays\r
-\r
-exports.intersect = function (array1, array2, justFirst) {\r
-\r
- if (!array1 || !array2) {\r
- return [];\r
- }\r
-\r
- var common = [];\r
- var hash = (array1 instanceof Array ? exports.mapToObject(array1) : array1);\r
- var found = {};\r
- for (var i = 0, il = array2.length; i < il; ++i) {\r
- if (hash[array2[i]] && !found[array2[i]]) {\r
- if (justFirst) {\r
- return array2[i];\r
- }\r
-\r
- common.push(array2[i]);\r
- found[array2[i]] = true;\r
- }\r
- }\r
-\r
- return (justFirst ? null : common);\r
-};\r
-\r
-\r
-// Find which keys are present\r
-\r
-exports.matchKeys = function (obj, keys) {\r
-\r
- var matched = [];\r
- for (var i = 0, il = keys.length; i < il; ++i) {\r
- if (obj.hasOwnProperty(keys[i])) {\r
- matched.push(keys[i]);\r
- }\r
- }\r
- return matched;\r
-};\r
-\r
-\r
-// Flatten array\r
-\r
-exports.flatten = function (array, target) {\r
-\r
- var result = target || [];\r
-\r
- for (var i = 0, il = array.length; i < il; ++i) {\r
- if (Array.isArray(array[i])) {\r
- exports.flatten(array[i], result);\r
- }\r
- else {\r
- result.push(array[i]);\r
- }\r
- }\r
-\r
- return result;\r
-};\r
-\r
-\r
-// Remove keys\r
-\r
-exports.removeKeys = function (object, keys) {\r
-\r
- for (var i = 0, il = keys.length; i < il; i++) {\r
- delete object[keys[i]];\r
- }\r
-};\r
-\r
-\r
-// Convert an object key chain string ('a.b.c') to reference (object[a][b][c])\r
-\r
-exports.reach = function (obj, chain) {\r
-\r
- var path = chain.split('.');\r
- var ref = obj;\r
- for (var i = 0, il = path.length; i < il; ++i) {\r
- if (ref) {\r
- ref = ref[path[i]];\r
- }\r
- }\r
-\r
- return ref;\r
-};\r
-\r
-\r
-// Inherits a selected set of methods from an object, wrapping functions in asynchronous syntax and catching errors\r
-\r
-exports.inheritAsync = function (self, obj, keys) {\r
-\r
- keys = keys || null;\r
-\r
- for (var i in obj) {\r
- if (obj.hasOwnProperty(i)) {\r
- if (keys instanceof Array &&\r
- keys.indexOf(i) < 0) {\r
-\r
- continue;\r
- }\r
-\r
- self.prototype[i] = (function (fn) {\r
-\r
- return function (next) {\r
-\r
- var result = null;\r
- try {\r
- result = fn();\r
- }\r
- catch (err) {\r
- return next(err);\r
- }\r
-\r
- return next(null, result);\r
- };\r
- })(obj[i]);\r
- }\r
- }\r
-};\r
-\r
-\r
-exports.formatStack = function (stack) {\r
-\r
- var trace = [];\r
- for (var i = 0, il = stack.length; i < il; ++i) {\r
- var item = stack[i];\r
- trace.push([item.getFileName(), item.getLineNumber(), item.getColumnNumber(), item.getFunctionName(), item.isConstructor()]);\r
- }\r
-\r
- return trace;\r
-};\r
-\r
-\r
-exports.formatTrace = function (trace) {\r
-\r
- var display = [];\r
-\r
- for (var i = 0, il = trace.length; i < il; ++i) {\r
- var row = trace[i];\r
- display.push((row[4] ? 'new ' : '') + row[3] + ' (' + row[0] + ':' + row[1] + ':' + row[2] + ')');\r
- }\r
-\r
- return display;\r
-};\r
-\r
-\r
-exports.callStack = function (slice) {\r
-\r
- // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi\r
-\r
- var v8 = Error.prepareStackTrace;\r
- Error.prepareStackTrace = function (err, stack) {\r
-\r
- return stack;\r
- };\r
-\r
- var capture = {};\r
- Error.captureStackTrace(capture, arguments.callee);\r
- var stack = capture.stack;\r
-\r
- Error.prepareStackTrace = v8;\r
-\r
- var trace = exports.formatStack(stack);\r
-\r
- if (slice) {\r
- return trace.slice(slice);\r
- }\r
-\r
- return trace;\r
-};\r
-\r
-\r
-exports.displayStack = function (slice) {\r
-\r
- var trace = exports.callStack(slice === undefined ? 1 : slice + 1);\r
-\r
- return exports.formatTrace(trace);\r
-};\r
-\r
-\r
-exports.abortThrow = false;\r
-\r
-\r
-exports.abort = function (message, hideStack) {\r
-\r
- if (process.env.NODE_ENV === 'test' || exports.abortThrow === true) {\r
- throw new Error(message || 'Unknown error');\r
- }\r
-\r
- var stack = '';\r
- if (!hideStack) {\r
- stack = exports.displayStack(1).join('\n\t');\r
- }\r
- console.log('ABORT: ' + message + '\n\t' + stack);\r
- process.exit(1);\r
-};\r
-\r
-\r
-exports.assert = function (condition /*, msg1, msg2, msg3 */) {\r
-\r
- if (condition) {\r
- return;\r
- }\r
-\r
- var msgs = Array.prototype.slice.call(arguments, 1);\r
- msgs = msgs.map(function (msg) {\r
-\r
- return typeof msg === 'string' ? msg : msg instanceof Error ? msg.message : JSON.stringify(msg);\r
- });\r
- throw new Error(msgs.join(' ') || 'Unknown error');\r
-};\r
-\r
-\r
-exports.loadDirModules = function (path, excludeFiles, target) { // target(filename, name, capName)\r
-\r
- var exclude = {};\r
- for (var i = 0, il = excludeFiles.length; i < il; ++i) {\r
- exclude[excludeFiles[i] + '.js'] = true;\r
- }\r
-\r
- var files = Fs.readdirSync(path);\r
- for (i = 0, il = files.length; i < il; ++i) {\r
- var filename = files[i];\r
- if (/\.js$/.test(filename) &&\r
- !exclude[filename]) {\r
-\r
- var name = filename.substr(0, filename.lastIndexOf('.'));\r
- var capName = name.charAt(0).toUpperCase() + name.substr(1).toLowerCase();\r
-\r
- if (typeof target !== 'function') {\r
- target[capName] = require(path + '/' + name);\r
- }\r
- else {\r
- target(path + '/' + name, name, capName);\r
- }\r
- }\r
- }\r
-};\r
-\r
-\r
-exports.rename = function (obj, from, to) {\r
-\r
- obj[to] = obj[from];\r
- delete obj[from];\r
-};\r
-\r
-\r
-exports.Timer = function () {\r
-\r
- this.reset();\r
-};\r
-\r
-\r
-exports.Timer.prototype.reset = function () {\r
-\r
- this.ts = Date.now();\r
-};\r
-\r
-\r
-exports.Timer.prototype.elapsed = function () {\r
-\r
- return Date.now() - this.ts;\r
-};\r
-\r
-\r
-// Load and parse package.json process root or given directory\r
-\r
-exports.loadPackage = function (dir) {\r
-\r
- var result = {};\r
- var filepath = (dir || process.env.PWD) + '/package.json';\r
- if (Fs.existsSync(filepath)) {\r
- try {\r
- result = JSON.parse(Fs.readFileSync(filepath));\r
- }\r
- catch (e) { }\r
- }\r
-\r
- return result;\r
-};\r
-\r
-\r
-// Escape string for Regex construction\r
-\r
-exports.escapeRegex = function (string) {\r
-\r
- // Escape ^$.*+-?=!:|\/()[]{},\r
- return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');\r
-};\r
-\r
-\r
-// Return an error as first argument of a callback\r
-\r
-exports.toss = function (condition /*, [message], next */) {\r
-\r
- var message = (arguments.length === 3 ? arguments[1] : '');\r
- var next = (arguments.length === 3 ? arguments[2] : arguments[1]);\r
-\r
- var err = (message instanceof Error ? message : (message ? new Error(message) : (condition instanceof Error ? condition : new Error())));\r
-\r
- if (condition instanceof Error ||\r
- !condition) {\r
-\r
- return next(err);\r
- }\r
-};\r
-\r
-\r
-// Base64url (RFC 4648) encode\r
-\r
-exports.base64urlEncode = function (value) {\r
-\r
- return (new Buffer(value, 'binary')).toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');\r
-};\r
-\r
-\r
-// Base64url (RFC 4648) decode\r
-\r
-exports.base64urlDecode = function (encoded) {\r
-\r
- if (encoded &&\r
- !encoded.match(/^[\w\-]*$/)) {\r
-\r
- return new Error('Invalid character');\r
- }\r
-\r
- try {\r
- return (new Buffer(encoded.replace(/-/g, '+').replace(/:/g, '/'), 'base64')).toString('binary');\r
- }\r
- catch (err) {\r
- return err;\r
- }\r
-};\r
-\r
-\r
-// Escape attribute value for use in HTTP header\r
-\r
-exports.escapeHeaderAttribute = function (attribute) {\r
-\r
- // Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, "\r
-\r
- exports.assert(attribute.match(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/), 'Bad attribute value (' + attribute + ')');\r
-\r
- return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); // Escape quotes and slash\r
-};\r
-\r
-\r
-exports.escapeHtml = function (string) {\r
-\r
- return Escape.escapeHtml(string);\r
-};\r
-\r
-\r
-exports.escapeJavaScript = function (string) {\r
-\r
- return Escape.escapeJavaScript(string);\r
-};\r
-\r
-\r
-/*\r
-var event = {\r
- timestamp: now.getTime(),\r
- tags: ['tag'],\r
- data: { some: 'data' }\r
-};\r
-*/\r
-\r
-exports.consoleFunc = console.log;\r
-\r
-exports.printEvent = function (event) {\r
-\r
- var pad = function (value) {\r
-\r
- return (value < 10 ? '0' : '') + value;\r
- };\r
-\r
- var now = new Date(event.timestamp);\r
- var timestring = (now.getYear() - 100).toString() +\r
- pad(now.getMonth() + 1) +\r
- pad(now.getDate()) +\r
- '/' +\r
- pad(now.getHours()) +\r
- pad(now.getMinutes()) +\r
- pad(now.getSeconds()) +\r
- '.' +\r
- now.getMilliseconds();\r
-\r
- var data = event.data;\r
- if (typeof event.data !== 'string') {\r
- try {\r
- data = JSON.stringify(event.data);\r
- }\r
- catch (e) {\r
- data = 'JSON Error: ' + e.message;\r
- }\r
- }\r
-\r
- var output = timestring + ', ' + event.tags[0] + ', ' + data;\r
- exports.consoleFunc(output);\r
-};\r
-\r
-\r
-exports.nextTick = function (callback) {\r
-\r
- return function () {\r
-\r
- var args = arguments;\r
- process.nextTick(function () {\r
-\r
- callback.apply(null, args);\r
- });\r
- };\r
-};\r
+// Load modules
+
+var Crypto = require('crypto');
+var Path = require('path');
+var Util = require('util');
+var Escape = require('./escape');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Clone object or array
+
+exports.clone = function (obj, seen) {
+
+ if (typeof obj !== 'object' ||
+ obj === null) {
+
+ return obj;
+ }
+
+ seen = seen || { orig: [], copy: [] };
+
+ var lookup = seen.orig.indexOf(obj);
+ if (lookup !== -1) {
+ return seen.copy[lookup];
+ }
+
+ var newObj;
+ var cloneDeep = false;
+
+ if (!Array.isArray(obj)) {
+ if (Buffer.isBuffer(obj)) {
+ newObj = new Buffer(obj);
+ }
+ else if (obj instanceof Date) {
+ newObj = new Date(obj.getTime());
+ }
+ else if (obj instanceof RegExp) {
+ newObj = new RegExp(obj);
+ }
+ else {
+ var proto = Object.getPrototypeOf(obj);
+ if (!proto || proto.isImmutable) {
+ newObj = obj;
+ }
+ else {
+ newObj = Object.create(proto);
+ cloneDeep = true;
+ }
+ }
+ }
+ else {
+ newObj = [];
+ cloneDeep = true;
+ }
+
+ seen.orig.push(obj);
+ seen.copy.push(newObj);
+
+ if (cloneDeep) {
+ for (var i in obj) {
+ if (obj.hasOwnProperty(i)) {
+ var descriptor = Object.getOwnPropertyDescriptor(obj, i);
+ if (descriptor.get ||
+ descriptor.set) {
+
+ Object.defineProperty(newObj, i, descriptor);
+ }
+ else {
+ newObj[i] = exports.clone(obj[i], seen);
+ }
+ }
+ }
+ }
+
+ return newObj;
+};
+
+
+// Merge all the properties of source into target, source wins in conflict, and by default null and undefined from source are applied
+
+exports.merge = function (target, source, isNullOverride /* = true */, isMergeArrays /* = true */) {
+
+ exports.assert(target && typeof target === 'object', 'Invalid target value: must be an object');
+ exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source value: must be null, undefined, or an object');
+
+ if (!source) {
+ return target;
+ }
+
+ if (Array.isArray(source)) {
+ exports.assert(Array.isArray(target), 'Cannot merge array onto an object');
+ if (isMergeArrays === false) { // isMergeArrays defaults to true
+ target.length = 0; // Must not change target assignment
+ }
+
+ for (var i = 0, il = source.length; i < il; ++i) {
+ target.push(exports.clone(source[i]));
+ }
+
+ return target;
+ }
+
+ var keys = Object.keys(source);
+ for (var k = 0, kl = keys.length; k < kl; ++k) {
+ var key = keys[k];
+ var value = source[key];
+ if (value &&
+ typeof value === 'object') {
+
+ if (!target[key] ||
+ typeof target[key] !== 'object' ||
+ (Array.isArray(target[key]) ^ Array.isArray(value)) ||
+ value instanceof Date ||
+ Buffer.isBuffer(value) ||
+ value instanceof RegExp) {
+
+ target[key] = exports.clone(value);
+ }
+ else {
+ exports.merge(target[key], value, isNullOverride, isMergeArrays);
+ }
+ }
+ else {
+ if (value !== null &&
+ value !== undefined) { // Explicit to preserve empty strings
+
+ target[key] = value;
+ }
+ else if (isNullOverride !== false) { // Defaults to true
+ target[key] = value;
+ }
+ }
+ }
+
+ return target;
+};
+
+
+// Apply options to a copy of the defaults
+
+exports.applyToDefaults = function (defaults, options) {
+
+ exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
+ exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
+
+ if (!options) { // If no options, return null
+ return null;
+ }
+
+ var copy = exports.clone(defaults);
+
+ if (options === true) { // If options is set to true, use defaults
+ return copy;
+ }
+
+ return exports.merge(copy, options, false, false);
+};
+
+
+// Clone an object except for the listed keys which are shallow copied
+
+exports.cloneWithShallow = function (source, keys) {
+
+ if (!source ||
+ typeof source !== 'object') {
+
+ return source;
+ }
+
+ var storage = internals.store(source, keys); // Move shallow copy items to storage
+ var copy = exports.clone(source); // Deep copy the rest
+ internals.restore(copy, source, storage); // Shallow copy the stored items and restore
+ return copy;
+};
+
+
+internals.store = function (source, keys) {
+
+ var storage = {};
+ for (var i = 0, il = keys.length; i < il; ++i) {
+ var key = keys[i];
+ var value = exports.reach(source, key);
+ if (value !== undefined) {
+ storage[key] = value;
+ internals.reachSet(source, key, undefined);
+ }
+ }
+
+ return storage;
+};
+
+
+internals.restore = function (copy, source, storage) {
+
+ var keys = Object.keys(storage);
+ for (var i = 0, il = keys.length; i < il; ++i) {
+ var key = keys[i];
+ internals.reachSet(copy, key, storage[key]);
+ internals.reachSet(source, key, storage[key]);
+ }
+};
+
+
+internals.reachSet = function (obj, key, value) {
+
+ var path = key.split('.');
+ var ref = obj;
+ for (var i = 0, il = path.length; i < il; ++i) {
+ var segment = path[i];
+ if (i + 1 === il) {
+ ref[segment] = value;
+ }
+
+ ref = ref[segment];
+ }
+};
+
+
+// Apply options to defaults except for the listed keys which are shallow copied from option without merging
+
+exports.applyToDefaultsWithShallow = function (defaults, options, keys) {
+
+ exports.assert(defaults && typeof defaults === 'object', 'Invalid defaults value: must be an object');
+ exports.assert(!options || options === true || typeof options === 'object', 'Invalid options value: must be true, falsy or an object');
+ exports.assert(keys && Array.isArray(keys), 'Invalid keys');
+
+ if (!options) { // If no options, return null
+ return null;
+ }
+
+ var copy = exports.cloneWithShallow(defaults, keys);
+
+ if (options === true) { // If options is set to true, use defaults
+ return copy;
+ }
+
+ var storage = internals.store(options, keys); // Move shallow copy items to storage
+ exports.merge(copy, options, false, false); // Deep copy the rest
+ internals.restore(copy, options, storage); // Shallow copy the stored items and restore
+ return copy;
+};
+
+
+// Deep object or array comparison
+
+exports.deepEqual = function (obj, ref, seen) {
+
+ var type = typeof obj;
+ if (type !== typeof ref) {
+ return false;
+ }
+
+ if (type !== 'object' ||
+ obj === null ||
+ ref === null) {
+
+ if (obj === ref) { // Copied from Deep-eql, copyright(c) 2013 Jake Luer, jake@alogicalparadox.com, MIT Licensed, https://github.com/chaijs/deep-eql
+ return obj !== 0 || 1 / obj === 1 / ref; // -0 / +0
+ }
+
+ return obj !== obj && ref !== ref; // NaN
+ }
+
+ seen = seen || [];
+ if (seen.indexOf(obj) !== -1) {
+ return true; // If previous comparison failed, it would have stopped execution
+ }
+
+ seen.push(obj);
+
+ if (Array.isArray(obj)) {
+ if (!Array.isArray(ref)) {
+ return false;
+ }
+
+ if (obj.length !== ref.length) {
+ return false;
+ }
+
+ for (var i = 0, il = obj.length; i < il; ++i) {
+ if (!exports.deepEqual(obj[i], ref[i])) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ if (Buffer.isBuffer(obj)) {
+ if (!Buffer.isBuffer(ref)) {
+ return false;
+ }
+
+ if (obj.length !== ref.length) {
+ return false;
+ }
+
+ for (var j = 0, jl = obj.length; j < jl; ++j) {
+ if (obj[j] !== ref[j]) {
+ return false;
+ }
+ }
+
+ return true;
+ }
+
+ if (obj instanceof Date) {
+ return (ref instanceof Date && obj.getTime() === ref.getTime());
+ }
+
+ if (obj instanceof RegExp) {
+ return (ref instanceof RegExp && obj.toString() === ref.toString());
+ }
+
+ if (Object.getPrototypeOf(obj) !== Object.getPrototypeOf(ref)) {
+ return false;
+ }
+
+ var keys = Object.keys(obj);
+ for (var k = 0, kl = keys.length; k < kl; ++k) {
+ var key = keys[k];
+ var descriptor = Object.getOwnPropertyDescriptor(obj, key);
+ if (descriptor.get) {
+ if (!exports.deepEqual(descriptor, Object.getOwnPropertyDescriptor(ref, key), seen)) {
+ return false;
+ }
+ }
+ else if (!exports.deepEqual(obj[key], ref[key], seen)) {
+ return false;
+ }
+ }
+
+ return true;
+};
+
+
+// Remove duplicate items from array
+
+exports.unique = function (array, key) {
+
+ var index = {};
+ var result = [];
+
+ for (var i = 0, il = array.length; i < il; ++i) {
+ var id = (key ? array[i][key] : array[i]);
+ if (index[id] !== true) {
+
+ result.push(array[i]);
+ index[id] = true;
+ }
+ }
+
+ return result;
+};
+
+
+// Convert array into object
+
+exports.mapToObject = function (array, key) {
+
+ if (!array) {
+ return null;
+ }
+
+ var obj = {};
+ for (var i = 0, il = array.length; i < il; ++i) {
+ if (key) {
+ if (array[i][key]) {
+ obj[array[i][key]] = true;
+ }
+ }
+ else {
+ obj[array[i]] = true;
+ }
+ }
+
+ return obj;
+};
+
+
+// Find the common unique items in two arrays
+
+exports.intersect = function (array1, array2, justFirst) {
+
+ if (!array1 || !array2) {
+ return [];
+ }
+
+ var common = [];
+ var hash = (Array.isArray(array1) ? exports.mapToObject(array1) : array1);
+ var found = {};
+ for (var i = 0, il = array2.length; i < il; ++i) {
+ if (hash[array2[i]] && !found[array2[i]]) {
+ if (justFirst) {
+ return array2[i];
+ }
+
+ common.push(array2[i]);
+ found[array2[i]] = true;
+ }
+ }
+
+ return (justFirst ? null : common);
+};
+
+
+// Test if the reference contains the values
+
+exports.contain = function (ref, values, options) {
+
+ /*
+ string -> string(s)
+ array -> item(s)
+ object -> key(s)
+ object -> object (key:value)
+ */
+
+ var valuePairs = null;
+ if (typeof ref === 'object' &&
+ typeof values === 'object' &&
+ !Array.isArray(ref) &&
+ !Array.isArray(values)) {
+
+ valuePairs = values;
+ values = Object.keys(values);
+ }
+ else {
+ values = [].concat(values);
+ }
+
+ options = options || {}; // deep, once, only, part
+
+ exports.assert(arguments.length >= 2, 'Insufficient arguments');
+ exports.assert(typeof ref === 'string' || typeof ref === 'object', 'Reference must be string or an object');
+ exports.assert(values.length, 'Values array cannot be empty');
+
+ var compare = options.deep ? exports.deepEqual : function (a, b) { return a === b; };
+
+ var misses = false;
+ var matches = new Array(values.length);
+ for (var i = 0, il = matches.length; i < il; ++i) {
+ matches[i] = 0;
+ }
+
+ if (typeof ref === 'string') {
+ var pattern = '(';
+ for (i = 0, il = values.length; i < il; ++i) {
+ var value = values[i];
+ exports.assert(typeof value === 'string', 'Cannot compare string reference to non-string value');
+ pattern += (i ? '|' : '') + exports.escapeRegex(value);
+ }
+
+ var regex = new RegExp(pattern + ')', 'g');
+ var leftovers = ref.replace(regex, function ($0, $1) {
+
+ var index = values.indexOf($1);
+ ++matches[index];
+ return ''; // Remove from string
+ });
+
+ misses = !!leftovers;
+ }
+ else if (Array.isArray(ref)) {
+ for (i = 0, il = ref.length; i < il; ++i) {
+ for (var j = 0, jl = values.length, matched = false; j < jl && matched === false; ++j) {
+ matched = compare(ref[i], values[j]) && j;
+ }
+
+ if (matched !== false) {
+ ++matches[matched];
+ }
+ else {
+ misses = true;
+ }
+ }
+ }
+ else {
+ var keys = Object.keys(ref);
+ for (i = 0, il = keys.length; i < il; ++i) {
+ var key = keys[i];
+ var pos = values.indexOf(key);
+ if (pos !== -1) {
+ if (valuePairs &&
+ !compare(ref[key], valuePairs[key])) {
+
+ return false;
+ }
+
+ ++matches[pos];
+ }
+ else {
+ misses = true;
+ }
+ }
+ }
+
+ var result = false;
+ for (i = 0, il = matches.length; i < il; ++i) {
+ result = result || !!matches[i];
+ if ((options.once && matches[i] > 1) ||
+ (!options.part && !matches[i])) {
+
+ return false;
+ }
+ }
+
+ if (options.only &&
+ misses) {
+
+ return false;
+ }
+
+ return result;
+};
+
+
+// Flatten array
+
+exports.flatten = function (array, target) {
+
+ var result = target || [];
+
+ for (var i = 0, il = array.length; i < il; ++i) {
+ if (Array.isArray(array[i])) {
+ exports.flatten(array[i], result);
+ }
+ else {
+ result.push(array[i]);
+ }
+ }
+
+ return result;
+};
+
+
+// Convert an object key chain string ('a.b.c') to reference (object[a][b][c])
+
+exports.reach = function (obj, chain, options) {
+
+ options = options || {};
+ if (typeof options === 'string') {
+ options = { separator: options };
+ }
+
+ var path = chain.split(options.separator || '.');
+ var ref = obj;
+ for (var i = 0, il = path.length; i < il; ++i) {
+ var key = path[i];
+ if (key[0] === '-' && Array.isArray(ref)) {
+ key = key.slice(1, key.length);
+ key = ref.length - key;
+ }
+
+ if (!ref ||
+ !ref.hasOwnProperty(key) ||
+ (typeof ref !== 'object' && options.functions === false)) { // Only object and function can have properties
+
+ exports.assert(!options.strict || i + 1 === il, 'Missing segment', key, 'in reach path ', chain);
+ exports.assert(typeof ref === 'object' || options.functions === true || typeof ref !== 'function', 'Invalid segment', key, 'in reach path ', chain);
+ ref = options.default;
+ break;
+ }
+
+ ref = ref[key];
+ }
+
+ return ref;
+};
+
+
+exports.formatStack = function (stack) {
+
+ var trace = [];
+ for (var i = 0, il = stack.length; i < il; ++i) {
+ var item = stack[i];
+ trace.push([item.getFileName(), item.getLineNumber(), item.getColumnNumber(), item.getFunctionName(), item.isConstructor()]);
+ }
+
+ return trace;
+};
+
+
+exports.formatTrace = function (trace) {
+
+ var display = [];
+
+ for (var i = 0, il = trace.length; i < il; ++i) {
+ var row = trace[i];
+ display.push((row[4] ? 'new ' : '') + row[3] + ' (' + row[0] + ':' + row[1] + ':' + row[2] + ')');
+ }
+
+ return display;
+};
+
+
+exports.callStack = function (slice) {
+
+ // http://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
+
+ var v8 = Error.prepareStackTrace;
+ Error.prepareStackTrace = function (err, stack) {
+
+ return stack;
+ };
+
+ var capture = {};
+ Error.captureStackTrace(capture, arguments.callee); /*eslint no-caller:0 */
+ var stack = capture.stack;
+
+ Error.prepareStackTrace = v8;
+
+ var trace = exports.formatStack(stack);
+
+ if (slice) {
+ return trace.slice(slice);
+ }
+
+ return trace;
+};
+
+
+exports.displayStack = function (slice) {
+
+ var trace = exports.callStack(slice === undefined ? 1 : slice + 1);
+
+ return exports.formatTrace(trace);
+};
+
+
+exports.abortThrow = false;
+
+
+exports.abort = function (message, hideStack) {
+
+ if (process.env.NODE_ENV === 'test' || exports.abortThrow === true) {
+ throw new Error(message || 'Unknown error');
+ }
+
+ var stack = '';
+ if (!hideStack) {
+ stack = exports.displayStack(1).join('\n\t');
+ }
+ console.log('ABORT: ' + message + '\n\t' + stack);
+ process.exit(1);
+};
+
+
+exports.assert = function (condition /*, msg1, msg2, msg3 */) {
+
+ if (condition) {
+ return;
+ }
+
+ if (arguments.length === 2 && arguments[1] instanceof Error) {
+ throw arguments[1];
+ }
+
+ var msgs = [];
+ for (var i = 1, il = arguments.length; i < il; ++i) {
+ if (arguments[i] !== '') {
+ msgs.push(arguments[i]); // Avoids Array.slice arguments leak, allowing for V8 optimizations
+ }
+ }
+
+ msgs = msgs.map(function (msg) {
+
+ return typeof msg === 'string' ? msg : msg instanceof Error ? msg.message : exports.stringify(msg);
+ });
+ throw new Error(msgs.join(' ') || 'Unknown error');
+};
+
+
+exports.Timer = function () {
+
+ this.ts = 0;
+ this.reset();
+};
+
+
+exports.Timer.prototype.reset = function () {
+
+ this.ts = Date.now();
+};
+
+
+exports.Timer.prototype.elapsed = function () {
+
+ return Date.now() - this.ts;
+};
+
+
+exports.Bench = function () {
+
+ this.ts = 0;
+ this.reset();
+};
+
+
+exports.Bench.prototype.reset = function () {
+
+ this.ts = exports.Bench.now();
+};
+
+
+exports.Bench.prototype.elapsed = function () {
+
+ return exports.Bench.now() - this.ts;
+};
+
+
+exports.Bench.now = function () {
+
+ var ts = process.hrtime();
+ return (ts[0] * 1e3) + (ts[1] / 1e6);
+};
+
+
+// Escape string for Regex construction
+
+exports.escapeRegex = function (string) {
+
+ // Escape ^$.*+-?=!:|\/()[]{},
+ return string.replace(/[\^\$\.\*\+\-\?\=\!\:\|\\\/\(\)\[\]\{\}\,]/g, '\\$&');
+};
+
+
+// Base64url (RFC 4648) encode
+
+exports.base64urlEncode = function (value, encoding) {
+
+ var buf = (Buffer.isBuffer(value) ? value : new Buffer(value, encoding || 'binary'));
+ return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/\=/g, '');
+};
+
+
+// Base64url (RFC 4648) decode
+
+exports.base64urlDecode = function (value, encoding) {
+
+ if (value &&
+ !/^[\w\-]*$/.test(value)) {
+
+ return new Error('Invalid character');
+ }
+
+ try {
+ var buf = new Buffer(value, 'base64');
+ return (encoding === 'buffer' ? buf : buf.toString(encoding || 'binary'));
+ }
+ catch (err) {
+ return err;
+ }
+};
+
+
+// Escape attribute value for use in HTTP header
+
+exports.escapeHeaderAttribute = function (attribute) {
+
+ // Allowed value characters: !#$%&'()*+,-./:;<=>?@[]^_`{|}~ and space, a-z, A-Z, 0-9, \, "
+
+ exports.assert(/^[ \w\!#\$%&'\(\)\*\+,\-\.\/\:;<\=>\?@\[\]\^`\{\|\}~\"\\]*$/.test(attribute), 'Bad attribute value (' + attribute + ')');
+
+ return attribute.replace(/\\/g, '\\\\').replace(/\"/g, '\\"'); // Escape quotes and slash
+};
+
+
+exports.escapeHtml = function (string) {
+
+ return Escape.escapeHtml(string);
+};
+
+
+exports.escapeJavaScript = function (string) {
+
+ return Escape.escapeJavaScript(string);
+};
+
+
+exports.nextTick = function (callback) {
+
+ return function () {
+
+ var args = arguments;
+ process.nextTick(function () {
+
+ callback.apply(null, args);
+ });
+ };
+};
+
+
+exports.once = function (method) {
+
+ if (method._hoekOnce) {
+ return method;
+ }
+
+ var once = false;
+ var wrapped = function () {
+
+ if (!once) {
+ once = true;
+ method.apply(null, arguments);
+ }
+ };
+
+ wrapped._hoekOnce = true;
+
+ return wrapped;
+};
+
+
+exports.isAbsolutePath = function (path, platform) {
+
+ if (!path) {
+ return false;
+ }
+
+ if (Path.isAbsolute) { // node >= 0.11
+ return Path.isAbsolute(path);
+ }
+
+ platform = platform || process.platform;
+
+ // Unix
+
+ if (platform !== 'win32') {
+ return path[0] === '/';
+ }
+
+ // Windows
+
+ return !!/^(?:[a-zA-Z]:[\\\/])|(?:[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/])/.test(path); // C:\ or \\something\something
+};
+
+
+exports.isInteger = function (value) {
+
+ return (typeof value === 'number' &&
+ parseFloat(value) === parseInt(value, 10) &&
+ !isNaN(value));
+};
+
+
+exports.ignore = function () { };
+
+
+exports.inherits = Util.inherits;
+
+
+exports.format = Util.format;
+
+
+exports.transform = function (source, transform, options) {
+
+ exports.assert(source === null || source === undefined || typeof source === 'object', 'Invalid source object: must be null, undefined, or an object');
+
+ var result = {};
+ var keys = Object.keys(transform);
+
+ for (var k = 0, kl = keys.length; k < kl; ++k) {
+ var key = keys[k];
+ var path = key.split('.');
+ var sourcePath = transform[key];
+
+ exports.assert(typeof sourcePath === 'string', 'All mappings must be "." delineated strings');
+
+ var segment;
+ var res = result;
+
+ while (path.length > 1) {
+ segment = path.shift();
+ if (!res[segment]) {
+ res[segment] = {};
+ }
+ res = res[segment];
+ }
+ segment = path.shift();
+ res[segment] = exports.reach(source, sourcePath, options);
+ }
+
+ return result;
+};
+
+
+exports.uniqueFilename = function (path, extension) {
+
+ if (extension) {
+ extension = extension[0] !== '.' ? '.' + extension : extension;
+ }
+ else {
+ extension = '';
+ }
+
+ path = Path.resolve(path);
+ var name = [Date.now(), process.pid, Crypto.randomBytes(8).toString('hex')].join('-') + extension;
+ return Path.join(path, name);
+};
+
+
+exports.stringify = function () {
+
+ try {
+ return JSON.stringify.apply(null, arguments);
+ }
+ catch (err) {
+ return '[Cannot display object: ' + err.message + ']';
+ }
+};
+
+
+exports.shallow = function (source) {
+
+ var target = {};
+ var keys = Object.keys(source);
+ for (var i = 0, il = keys.length; i < il; ++i) {
+ var key = keys[i];
+ target[key] = source[key];
+ }
+
+ return target;
+};
{
"name": "hoek",
"description": "General purpose node utilities",
- "version": "0.9.1",
- "author": {
- "name": "Eran Hammer",
- "email": "eran@hueniverse.com",
- "url": "http://hueniverse.com"
- },
- "contributors": [
- {
- "name": "Van Nguyen",
- "email": "the.gol.effect@gmail.com"
- }
- ],
+ "version": "2.11.0",
"repository": {
"type": "git",
- "url": "git://github.com/spumko/hoek"
+ "url": "git://github.com/hapijs/hoek"
},
"main": "index",
"keywords": [
},
"dependencies": {},
"devDependencies": {
- "lab": "0.1.x",
- "complexity-report": "0.x.x"
+ "code": "1.x.x",
+ "lab": "5.x.x"
},
"scripts": {
"test": "make test-cov"
"licenses": [
{
"type": "BSD",
- "url": "http://github.com/spumko/hoek/raw/master/LICENSE"
+ "url": "http://github.com/hapijs/hoek/raw/master/LICENSE"
}
],
- "_id": "hoek@0.9.1",
- "dist": {
- "shasum": "3d322462badf07716ea7eb85baf88079cddce505",
- "tarball": "http://registry.npmjs.org/hoek/-/hoek-0.9.1.tgz"
+ "gitHead": "6f034aa12206f2ab740a9ea6ca64a4d5c7b7dfba",
+ "bugs": {
+ "url": "https://github.com/hapijs/hoek/issues"
},
- "_from": "hoek@>=0.9.0 <0.10.0",
- "_npmVersion": "1.2.18",
+ "homepage": "https://github.com/hapijs/hoek",
+ "_id": "hoek@2.11.0",
+ "_shasum": "e588ec66a6b405b0e7140308720e1e1cd4f035b7",
+ "_from": "hoek@>=2.0.0 <3.0.0",
+ "_npmVersion": "2.1.9",
+ "_nodeVersion": "0.10.32",
"_npmUser": {
- "name": "hueniverse",
- "email": "eran@hueniverse.com"
+ "name": "nlf",
+ "email": "quitlahok@gmail.com"
},
"maintainers": [
{
"email": "eran@hueniverse.com"
},
{
- "name": "thegoleffect",
- "email": "thegoleffect@gmail.com"
+ "name": "wyatt",
+ "email": "wpreul@gmail.com"
+ },
+ {
+ "name": "nlf",
+ "email": "quitlahok@gmail.com"
}
],
- "directories": {},
- "_shasum": "3d322462badf07716ea7eb85baf88079cddce505",
- "_resolved": "https://registry.npmjs.org/hoek/-/hoek-0.9.1.tgz",
- "bugs": {
- "url": "https://github.com/spumko/hoek/issues"
+ "dist": {
+ "shasum": "e588ec66a6b405b0e7140308720e1e1cd4f035b7",
+ "tarball": "http://registry.npmjs.org/hoek/-/hoek-2.11.0.tgz"
},
- "readme": "ERROR: No README data found!",
- "homepage": "https://github.com/spumko/hoek"
+ "directories": {},
+ "_resolved": "https://registry.npmjs.org/hoek/-/hoek-2.11.0.tgz",
+ "readme": "ERROR: No README data found!"
}
-// Load modules\r
-\r
-var Lab = require('lab');\r
-var Hoek = require('../lib');\r
-\r
-\r
-// Declare internals\r
-\r
-var internals = {};\r
-\r
-\r
-// Test shortcuts\r
-\r
-var expect = Lab.expect;\r
-var before = Lab.before;\r
-var after = Lab.after;\r
-var describe = Lab.experiment;\r
-var it = Lab.test;\r
-\r
-\r
-describe('Hoek', function () {\r
-\r
- describe('#escapeJavaScript', function () {\r
-\r
- it('encodes / characters', function (done) {\r
-\r
- var encoded = Hoek.escapeJavaScript('<script>alert(1)</script>');\r
- expect(encoded).to.equal('\\x3cscript\\x3ealert\\x281\\x29\\x3c\\x2fscript\\x3e');\r
- done();\r
- });\r
-\r
- it('encodes \' characters', function (done) {\r
-\r
- var encoded = Hoek.escapeJavaScript('something(\'param\')');\r
- expect(encoded).to.equal('something\\x28\\x27param\\x27\\x29');\r
- done();\r
- });\r
-\r
- it('encodes large unicode characters with the correct padding', function (done) {\r
-\r
- var encoded = Hoek.escapeJavaScript(String.fromCharCode(500) + String.fromCharCode(1000));\r
- expect(encoded).to.equal('\\u0500\\u1000');\r
- done();\r
- });\r
-\r
- it('doesn\'t throw an exception when passed null', function (done) {\r
-\r
- var encoded = Hoek.escapeJavaScript(null);\r
- expect(encoded).to.equal('');\r
- done();\r
- });\r
- });\r
-\r
- describe('#escapeHtml', function () {\r
-\r
- it('encodes / characters', function (done) {\r
-\r
- var encoded = Hoek.escapeHtml('<script>alert(1)</script>');\r
- expect(encoded).to.equal('<script>alert(1)</script>');\r
- done();\r
- });\r
-\r
- it('encodes < and > as named characters', function (done) {\r
-\r
- var encoded = Hoek.escapeHtml('<script><>');\r
- expect(encoded).to.equal('<script><>');\r
- done();\r
- });\r
-\r
- it('encodes large unicode characters', function (done) {\r
-\r
- var encoded = Hoek.escapeHtml(String.fromCharCode(500) + String.fromCharCode(1000));\r
- expect(encoded).to.equal('ǴϨ');\r
- done();\r
- });\r
-\r
- it('doesn\'t throw an exception when passed null', function (done) {\r
-\r
- var encoded = Hoek.escapeHtml(null);\r
- expect(encoded).to.equal('');\r
- done();\r
- });\r
- });\r
-});\r
-\r
-\r
+// Load modules
+
+var Code = require('code');
+var Hoek = require('../lib');
+var Lab = require('lab');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Test shortcuts
+
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
+
+
+describe('escapeJavaScript()', function () {
+
+ it('encodes / characters', function (done) {
+
+ var encoded = Hoek.escapeJavaScript('<script>alert(1)</script>');
+ expect(encoded).to.equal('\\x3cscript\\x3ealert\\x281\\x29\\x3c\\x2fscript\\x3e');
+ done();
+ });
+
+ it('encodes \' characters', function (done) {
+
+ var encoded = Hoek.escapeJavaScript('something(\'param\')');
+ expect(encoded).to.equal('something\\x28\\x27param\\x27\\x29');
+ done();
+ });
+
+ it('encodes large unicode characters with the correct padding', function (done) {
+
+ var encoded = Hoek.escapeJavaScript(String.fromCharCode(500) + String.fromCharCode(1000));
+ expect(encoded).to.equal('\\u0500\\u1000');
+ done();
+ });
+
+ it('doesn\'t throw an exception when passed null', function (done) {
+
+ var encoded = Hoek.escapeJavaScript(null);
+ expect(encoded).to.equal('');
+ done();
+ });
+});
+
+describe('escapeHtml()', function () {
+
+ it('encodes / characters', function (done) {
+
+ var encoded = Hoek.escapeHtml('<script>alert(1)</script>');
+ expect(encoded).to.equal('<script>alert(1)</script>');
+ done();
+ });
+
+ it('encodes < and > as named characters', function (done) {
+
+ var encoded = Hoek.escapeHtml('<script><>');
+ expect(encoded).to.equal('<script><>');
+ done();
+ });
+
+ it('encodes large unicode characters', function (done) {
+
+ var encoded = Hoek.escapeHtml(String.fromCharCode(500) + String.fromCharCode(1000));
+ expect(encoded).to.equal('ǴϨ');
+ done();
+ });
+
+ it('doesn\'t throw an exception when passed null', function (done) {
+
+ var encoded = Hoek.escapeHtml(null);
+ expect(encoded).to.equal('');
+ done();
+ });
+
+ it('encodes {} characters', function (done) {
+
+ var encoded = Hoek.escapeHtml('{}');
+ expect(encoded).to.equal('{}');
+ done();
+ });
+});
-// Load modules\r
-\r
-var Lab = require('lab');\r
-var Hoek = require('../lib');\r
-\r
-\r
-// Declare internals\r
-\r
-var internals = {};\r
-\r
-\r
-// Test shortcuts\r
-\r
-var expect = Lab.expect;\r
-var before = Lab.before;\r
-var after = Lab.after;\r
-var describe = Lab.experiment;\r
-var it = Lab.test;\r
-\r
-\r
-describe('Hoek', function () {\r
-\r
- var nestedObj = {\r
- v: [7,8,9],\r
- w: /^something$/igm,\r
- x: {\r
- a: [1, 2, 3],\r
- b: 123456,\r
- c: new Date(),\r
- d: /hi/igm,\r
- e: /hello/\r
- },\r
- y: 'y',\r
- z: new Date()\r
- };\r
-\r
- var dupsArray = [nestedObj, { z: 'z' }, nestedObj];\r
- var reducedDupsArray = [nestedObj, { z: 'z' }];\r
-\r
- describe('#clone', function () {\r
-\r
- it('should clone a nested object', function (done) {\r
-\r
- var a = nestedObj;\r
- var b = Hoek.clone(a);\r
-\r
- expect(a).to.deep.equal(b);\r
- expect(a.z.getTime()).to.equal(b.z.getTime());\r
- done();\r
- });\r
-\r
- it('should clone a null object', function (done) {\r
-\r
- var b = Hoek.clone(null);\r
-\r
- expect(b).to.equal(null);\r
- done();\r
- });\r
-\r
- it('should not convert undefined properties to null', function (done) {\r
-\r
- var obj = { something: undefined };\r
- var b = Hoek.clone(obj);\r
-\r
- expect(typeof b.something).to.equal('undefined');\r
- done();\r
- });\r
-\r
- it('should not throw on circular reference', function (done) {\r
-\r
- var a = {};\r
- a.x = a;\r
-\r
- var test = (function () {\r
-\r
- var b = Hoek.clone(a);\r
- });\r
-\r
- expect(test).to.not.throw();\r
- done();\r
- });\r
-\r
- it('should properly clone circular reference', function (done) {\r
-\r
- var x = {\r
- 'z': new Date()\r
- };\r
- x.y = x;\r
-\r
- var b = Hoek.clone(x);\r
- expect(Object.keys(b.y)).to.deep.equal(Object.keys(x))\r
- expect(b.z).to.not.equal(x.z);\r
- expect(b.y).to.not.equal(x.y);\r
- expect(b.y.z).to.not.equal(x.y.z);\r
- expect(b.y).to.equal(b);\r
- expect(b.y.y.y.y).to.equal(b);\r
- done();\r
- });\r
-\r
- it('should properly clone deeply nested object', function (done) {\r
-\r
- var a = {\r
- x: {\r
- y: {\r
- a: [1, 2, 3],\r
- b: 123456,\r
- c: new Date(),\r
- d: /hi/igm,\r
- e: /hello/\r
- },\r
- }\r
- };\r
-\r
- var b = Hoek.clone(a);\r
-\r
- expect(a).to.deep.equal(b);\r
- expect(a.x.y.c.getTime()).to.equal(b.x.y.c.getTime());\r
- done();\r
- });\r
-\r
- it('should properly clone arrays', function (done) {\r
-\r
- var a = [1,2,3];\r
-\r
- var b = Hoek.clone(a);\r
-\r
- expect(a).to.deep.equal(b);\r
- done();\r
- });\r
-\r
- it('should perform actual copy for shallow keys (no pass by reference)', function (done) {\r
-\r
- var x = Hoek.clone(nestedObj);\r
- var y = Hoek.clone(nestedObj);\r
-\r
- // Date\r
- expect(x.z).to.not.equal(nestedObj.z);\r
- expect(x.z).to.not.equal(y.z);\r
-\r
- // Regex\r
- expect(x.w).to.not.equal(nestedObj.w);\r
- expect(x.w).to.not.equal(y.w);\r
-\r
- // Array\r
- expect(x.v).to.not.equal(nestedObj.v);\r
- expect(x.v).to.not.equal(y.v);\r
-\r
- // Immutable(s)\r
- x.y = 5;\r
- expect(x.y).to.not.equal(nestedObj.y);\r
- expect(x.y).to.not.equal(y.y);\r
-\r
- done();\r
- });\r
-\r
- it('should perform actual copy for deep keys (no pass by reference)', function (done) {\r
-\r
- var x = Hoek.clone(nestedObj);\r
- var y = Hoek.clone(nestedObj);\r
-\r
- expect(x.x.c).to.not.equal(nestedObj.x.c);\r
- expect(x.x.c).to.not.equal(y.x.c);\r
-\r
- expect(x.x.c.getTime()).to.equal(nestedObj.x.c.getTime());\r
- expect(x.x.c.getTime()).to.equal(y.x.c.getTime());\r
- done();\r
- });\r
-\r
- it('copies functions with properties', function (done) {\r
-\r
- var a = {\r
- x: function () { return 1; },\r
- y: {}\r
- };\r
- a.x.z = 'string in function';\r
- a.x.v = function () { return 2; };\r
- a.y.u = a.x;\r
-\r
- var b = Hoek.clone(a);\r
- expect(b.x()).to.equal(1);\r
- expect(b.x.v()).to.equal(2);\r
- expect(b.y.u).to.equal(b.x);\r
- expect(b.x.z).to.equal('string in function');\r
- done();\r
- });\r
-\r
- it('should copy a buffer', function(done){\r
- var tls = {\r
- key: new Buffer([1,2,3,4,5]),\r
- cert: new Buffer([1,2,3,4,5,6,10])\r
- }\r
-\r
- copiedTls = Hoek.clone(tls);\r
- expect(Buffer.isBuffer(copiedTls.key)).to.equal(true);\r
- expect(JSON.stringify(copiedTls.key)).to.equal(JSON.stringify(tls.key))\r
- expect(Buffer.isBuffer(copiedTls.cert)).to.equal(true);\r
- expect(JSON.stringify(copiedTls.cert)).to.equal(JSON.stringify(tls.cert))\r
- done();\r
- });\r
- });\r
-\r
- describe('#merge', function () {\r
-\r
- it('does not throw if source is null', function (done) {\r
-\r
- var a = {};\r
- var b = null;\r
- var c = null;\r
-\r
- expect(function () {\r
-\r
- c = Hoek.merge(a, b);\r
- }).to.not.throw();\r
-\r
- expect(c).to.equal(a);\r
- done();\r
- });\r
-\r
- it('does not throw if source is undefined', function (done) {\r
-\r
- var a = {};\r
- var b = undefined;\r
- var c = null;\r
-\r
- expect(function () {\r
-\r
- c = Hoek.merge(a, b);\r
- }).to.not.throw();\r
-\r
- expect(c).to.equal(a);\r
- done();\r
- });\r
-\r
- it('throws if source is not an object', function (done) {\r
-\r
- expect(function () {\r
-\r
- var a = {};\r
- var b = 0;\r
-\r
- Hoek.merge(a, b);\r
- }).to.throw('Invalid source value: must be null, undefined, or an object');\r
- done();\r
- });\r
-\r
- it('throws if target is not an object', function (done) {\r
-\r
- expect(function () {\r
-\r
- var a = 0;\r
- var b = {};\r
-\r
- Hoek.merge(a, b);\r
- }).to.throw('Invalid target value: must be an object');\r
- done();\r
- });\r
-\r
- it('throws if target is not an array and source is', function (done) {\r
-\r
- expect(function () {\r
-\r
- var a = {};\r
- var b = [1, 2];\r
-\r
- Hoek.merge(a, b);\r
- }).to.throw('Cannot merge array onto an object');\r
- done();\r
- });\r
-\r
- it('returns the same object when merging arrays', function (done) {\r
-\r
- var a = [];\r
- var b = [1, 2];\r
-\r
- expect(Hoek.merge(a, b)).to.equal(a);\r
- done();\r
- });\r
-\r
- it('should combine an empty object with a non-empty object', function (done) {\r
-\r
- var a = {};\r
- var b = nestedObj;\r
-\r
- var c = Hoek.merge(a, b);\r
- expect(a).to.deep.equal(b);\r
- expect(c).to.deep.equal(b);\r
- done();\r
- });\r
-\r
- it('should override values in target', function (done) {\r
-\r
- var a = { x: 1, y: 2, z: 3, v: 5, t: 'test', m: 'abc' };\r
- var b = { x: null, z: 4, v: 0, t: { u: 6 }, m: '123' };\r
-\r
- var c = Hoek.merge(a, b);\r
- expect(c.x).to.equal(null);\r
- expect(c.y).to.equal(2);\r
- expect(c.z).to.equal(4);\r
- expect(c.v).to.equal(0);\r
- expect(c.m).to.equal('123');\r
- expect(c.t).to.deep.equal({ u: 6 });\r
- done();\r
- });\r
-\r
- it('should override values in target (flip)', function (done) {\r
-\r
- var a = { x: 1, y: 2, z: 3, v: 5, t: 'test', m: 'abc' };\r
- var b = { x: null, z: 4, v: 0, t: { u: 6 }, m: '123' };\r
-\r
- var d = Hoek.merge(b, a);\r
- expect(d.x).to.equal(1);\r
- expect(d.y).to.equal(2);\r
- expect(d.z).to.equal(3);\r
- expect(d.v).to.equal(5);\r
- expect(d.m).to.equal('abc');\r
- expect(d.t).to.deep.equal('test');\r
- done();\r
- });\r
- });\r
-\r
- describe('#applyToDefaults', function () {\r
-\r
- var defaults = {\r
- a: 1,\r
- b: 2,\r
- c: {\r
- d: 3,\r
- e: [5, 6]\r
- },\r
- f: 6,\r
- g: 'test'\r
- };\r
-\r
- it('should return null if options is false', function (done) {\r
-\r
- var result = Hoek.applyToDefaults(defaults, false);\r
- expect(result).to.equal(null);\r
- done();\r
- });\r
-\r
- it('should return a copy of defaults if options is true', function (done) {\r
-\r
- var result = Hoek.applyToDefaults(defaults, true);\r
- expect(result).to.deep.equal(result);\r
- done();\r
- });\r
-\r
- it('should apply object to defaults', function (done) {\r
-\r
- var obj = {\r
- a: null,\r
- c: {\r
- e: [4]\r
- },\r
- f: 0,\r
- g: {\r
- h: 5\r
- }\r
- };\r
-\r
- var result = Hoek.applyToDefaults(defaults, obj);\r
- expect(result.c.e).to.deep.equal([4]);\r
- expect(result.a).to.equal(1);\r
- expect(result.b).to.equal(2);\r
- expect(result.f).to.equal(0);\r
- expect(result.g).to.deep.equal({ h: 5 });\r
- done();\r
- });\r
- });\r
-\r
- describe('#unique', function () {\r
-\r
- it('should ensure uniqueness within array of objects based on subkey', function (done) {\r
-\r
- var a = Hoek.unique(dupsArray, 'x');\r
- expect(a).to.deep.equal(reducedDupsArray);\r
- done();\r
- });\r
-\r
- it('removes duplicated without key', function (done) {\r
-\r
- expect(Hoek.unique([1, 2, 3, 4, 2, 1, 5])).to.deep.equal([1, 2, 3, 4, 5]);\r
- done();\r
- });\r
- });\r
-\r
- describe('#mapToObject', function () {\r
-\r
- it('should return null on null array', function (done) {\r
-\r
- var a = Hoek.mapToObject(null);\r
- expect(a).to.equal(null);\r
- done();\r
- });\r
-\r
- it('should convert basic array to existential object', function (done) {\r
-\r
- var keys = [1, 2, 3, 4];\r
- var a = Hoek.mapToObject(keys);\r
- for (var i in keys) {\r
- expect(a[keys[i]]).to.equal(true);\r
- }\r
- done();\r
- });\r
-\r
- it('should convert array of objects to existential object', function (done) {\r
-\r
- var keys = [{ x: 1 }, { x: 2 }, { x: 3 }];\r
- var subkey = 'x';\r
- var a = Hoek.mapToObject(keys, subkey);\r
- for (var i in keys) {\r
- expect(a[keys[i][subkey]]).to.equal(true);\r
- }\r
- done();\r
- });\r
- });\r
-\r
- describe('#intersect', function () {\r
-\r
- it('should return the common objects of two arrays', function (done) {\r
-\r
- var array1 = [1, 2, 3, 4, 4, 5, 5];\r
- var array2 = [5, 4, 5, 6, 7];\r
- var common = Hoek.intersect(array1, array2);\r
- expect(common.length).to.equal(2);\r
- done();\r
- });\r
-\r
- it('should return just the first common object of two arrays', function (done) {\r
-\r
- var array1 = [1, 2, 3, 4, 4, 5, 5];\r
- var array2 = [5, 4, 5, 6, 7];\r
- var common = Hoek.intersect(array1, array2, true);\r
- expect(common).to.equal(5);\r
- done();\r
- });\r
-\r
- it('should return an empty array if either input is null', function (done) {\r
-\r
- expect(Hoek.intersect([1], null).length).to.equal(0);\r
- expect(Hoek.intersect(null, [1]).length).to.equal(0);\r
- done();\r
- });\r
-\r
- it('should return the common objects of object and array', function (done) {\r
-\r
- var array1 = [1, 2, 3, 4, 4, 5, 5];\r
- var array2 = [5, 4, 5, 6, 7];\r
- var common = Hoek.intersect(Hoek.mapToObject(array1), array2);\r
- expect(common.length).to.equal(2);\r
- done();\r
- });\r
- });\r
-\r
- describe('#matchKeys', function () {\r
-\r
- it('should match the existing object keys', function (done) {\r
-\r
- var obj = {\r
- a: 1,\r
- b: 2,\r
- c: 3,\r
- d: null\r
- };\r
-\r
- expect(Hoek.matchKeys(obj, ['b', 'c', 'd', 'e'])).to.deep.equal(['b', 'c', 'd']);\r
- done();\r
- });\r
- });\r
-\r
- describe('#flatten', function () {\r
-\r
- it('should return a flat array', function (done) {\r
-\r
- var result = Hoek.flatten([1, 2, [3, 4, [5, 6], [7], 8], [9], [10, [11, 12]], 13]);\r
- expect(result.length).to.equal(13);\r
- expect(result).to.deep.equal([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);\r
- done();\r
- });\r
- });\r
-\r
- describe('#removeKeys', function () {\r
-\r
- var objWithHiddenKeys = {\r
- location: {\r
- name: 'San Bruno'\r
- },\r
- company: {\r
- name: '@WalmartLabs'\r
- }\r
- };\r
-\r
- it('should delete params with definition\'s hide set to true', function (done) {\r
-\r
- var a = Hoek.removeKeys(objWithHiddenKeys, ['location']);\r
- expect(objWithHiddenKeys.location).to.not.exist;\r
- expect(objWithHiddenKeys.company).to.exist;\r
- done();\r
- });\r
- });\r
-\r
- describe('#reach', function () {\r
-\r
- var obj = {\r
- a: {\r
- b: {\r
- c: {\r
- d: 1,\r
- e: 2\r
- },\r
- f: 'hello'\r
- },\r
- g: {\r
- h: 3\r
- }\r
- },\r
- i: function () { }\r
- };\r
-\r
- it('returns a valid member', function (done) {\r
-\r
- expect(Hoek.reach(obj, 'a.b.c.d')).to.equal(1);\r
- done();\r
- });\r
-\r
- it('returns null on null object', function (done) {\r
-\r
- expect(Hoek.reach(null, 'a.b.c.d')).to.not.exist;\r
- done();\r
- });\r
-\r
- it('returns null on missing member', function (done) {\r
-\r
- expect(Hoek.reach(obj, 'a.b.c.d.x')).to.not.exist;\r
- done();\r
- });\r
-\r
- it('returns null on invalid member', function (done) {\r
-\r
- expect(Hoek.reach(obj, 'a.b.c.d-.x')).to.not.exist;\r
- done();\r
- });\r
-\r
- it('returns function member', function (done) {\r
-\r
- expect(typeof Hoek.reach(obj, 'i')).to.equal('function');\r
- done();\r
- });\r
- });\r
-\r
- describe('#inheritAsync', function () {\r
-\r
- it('should inherit selected methods and wrap in async call', function (done) {\r
-\r
- var proto = {\r
- a: function () {\r
- return 'a!';\r
- },\r
- b: function () {\r
- return 'b!';\r
- },\r
- c: function () {\r
- throw new Error('c!');\r
- }\r
- };\r
-\r
- var targetFunc = function () { };\r
- targetFunc.prototype.c = function () {\r
-\r
- return 'oops';\r
- };\r
-\r
- Hoek.inheritAsync(targetFunc, proto, ['a', 'c']);\r
- var target = new targetFunc();\r
-\r
- expect(typeof target.a).to.equal('function');\r
- expect(typeof target.c).to.equal('function');\r
- expect(target.b).to.not.exist;\r
-\r
- target.a(function (err, result) {\r
-\r
- expect(err).to.not.exist;\r
- expect(result).to.equal('a!');\r
-\r
- target.c(function (err, result) {\r
-\r
- expect(result).to.not.exist;\r
- expect(err.message).to.equal('c!');\r
- done();\r
- });\r
- });\r
- });\r
- });\r
-\r
- describe('#callStack', function () {\r
-\r
- it('should return the full call stack', function (done) {\r
-\r
- var stack = Hoek.callStack();\r
- expect(stack[0][0]).to.contain('index.js');\r
- expect(stack[0][2]).to.equal(30);\r
- done();\r
- });\r
- });\r
-\r
- describe('#displayStack ', function () {\r
-\r
- it('should return the full call stack for display', function (done) {\r
-\r
- var stack = Hoek.displayStack();\r
- expect(stack[0]).to.contain('test/index.js:');\r
- done();\r
- });\r
-\r
- it('should include constructor functions correctly', function (done) {\r
-\r
- var Something = function (next) {\r
-\r
- next();\r
- };\r
-\r
- var something = new Something(function () {\r
-\r
- var stack = Hoek.displayStack();\r
- expect(stack[1]).to.contain('new Something');\r
- done();\r
- });\r
- });\r
- });\r
-\r
- describe('#abort', function () {\r
-\r
- it('should exit process when not in test mode', function (done) {\r
-\r
- var env = process.env.NODE_ENV;\r
- var write = process.stdout.write;\r
- var exit = process.exit;\r
-\r
- process.env.NODE_ENV = 'nottatest';\r
- process.stdout.write = function () { };\r
- process.exit = function (state) {\r
-\r
- process.exit = exit;\r
- process.env.NODE_ENV = env;\r
- process.stdout.write = write;\r
-\r
- expect(state).to.equal(1);\r
- done();\r
- };\r
-\r
- Hoek.abort('Boom');\r
- });\r
-\r
- it('should throw when not in test mode and abortThrow is true', function (done) {\r
-\r
- var env = process.env.NODE_ENV;\r
- process.env.NODE_ENV = 'nottatest';\r
- Hoek.abortThrow = true;\r
-\r
- var fn = function () {\r
-\r
- Hoek.abort('my error message');\r
- };\r
-\r
- expect(fn).to.throw('my error message');\r
- Hoek.abortThrow = false;\r
- process.env.NODE_ENV = env;\r
-\r
- done();\r
- });\r
-\r
-\r
- it('should respect hideStack argument', function (done) {\r
-\r
- var env = process.env.NODE_ENV;\r
- var write = process.stdout.write;\r
- var exit = process.exit;\r
- var output = '';\r
-\r
- process.exit = function () { };\r
- process.env.NODE_ENV = '';\r
- process.stdout.write = function (message) {\r
-\r
- output = message;\r
- };\r
-\r
- Hoek.abort('my error message', true);\r
-\r
- process.env.NODE_ENV = env;\r
- process.stdout.write = write;\r
- process.exit = exit;\r
-\r
- expect(output).to.equal('ABORT: my error message\n\t\n');\r
-\r
- done();\r
- });\r
-\r
- it('should default to showing stack', function (done) {\r
-\r
- var env = process.env.NODE_ENV;\r
- var write = process.stdout.write;\r
- var exit = process.exit;\r
- var output = '';\r
-\r
- process.exit = function () { };\r
- process.env.NODE_ENV = '';\r
- process.stdout.write = function (message) {\r
-\r
- output = message;\r
- };\r
-\r
- Hoek.abort('my error message');\r
-\r
- process.env.NODE_ENV = env;\r
- process.stdout.write = write;\r
- process.exit = exit;\r
-\r
- expect(output).to.contain('index.js');\r
-\r
- done();\r
- });\r
- });\r
-\r
- describe('#assert', function () {\r
-\r
- it('should throw an Error when using assert in a test', function (done) {\r
-\r
- var fn = function () {\r
-\r
- Hoek.assert(false, 'my error message');\r
- };\r
-\r
- expect(fn).to.throw('my error message');\r
- done();\r
- });\r
-\r
- it('should throw an Error when using assert in a test with no message', function (done) {\r
-\r
- var fn = function () {\r
-\r
- Hoek.assert(false);\r
- };\r
-\r
- expect(fn).to.throw('Unknown error');\r
- done();\r
- });\r
-\r
- it('should throw an Error when using assert in a test with multipart message', function (done) {\r
-\r
- var fn = function () {\r
-\r
- Hoek.assert(false, 'This', 'is', 'my message');\r
- };\r
-\r
- expect(fn).to.throw('This is my message');\r
- done();\r
- });\r
-\r
- it('should throw an Error when using assert in a test with object message', function (done) {\r
-\r
- var fn = function () {\r
-\r
- Hoek.assert(false, 'This', 'is', { spinal: 'tap' });\r
- };\r
-\r
- expect(fn).to.throw('This is {"spinal":"tap"}');\r
- done();\r
- });\r
-\r
- it('should throw an Error when using assert in a test with error object message', function (done) {\r
-\r
- var fn = function () {\r
-\r
- Hoek.assert(false, new Error('This is spinal tap'));\r
- };\r
-\r
- expect(fn).to.throw('This is spinal tap');\r
- done();\r
- });\r
- });\r
-\r
- describe('#loadDirModules', function () {\r
-\r
- it('should load modules from directory', function (done) {\r
-\r
- var target = {};\r
- Hoek.loadDirModules(__dirname + '/modules', ['test2'], target);\r
- expect(target.Test1.x).to.equal(1);\r
- expect(target.Test2).to.not.exist;\r
- expect(target.Test3.z).to.equal(3);\r
- done();\r
- });\r
-\r
- it('should list modules from directory into function', function (done) {\r
-\r
- var target = {};\r
- Hoek.loadDirModules(__dirname + '/modules', ['test2'], function (path, name, capName) {\r
-\r
- target[name] = capName;\r
- });\r
-\r
- expect(target.test1).to.equal('Test1');\r
- expect(target.test2).to.not.exist;\r
- expect(target.test3).to.equal('Test3');\r
- done();\r
- });\r
- });\r
-\r
- describe('#rename', function () {\r
-\r
- it('should rename object key', function (done) {\r
-\r
- var a = { b: 'c' };\r
- Hoek.rename(a, 'b', 'x');\r
- expect(a.b).to.not.exist;\r
- expect(a.x).to.equal('c');\r
- done();\r
- });\r
- });\r
-\r
- describe('Timer', function () {\r
-\r
- it('should return time elapsed', function (done) {\r
-\r
- var timer = new Hoek.Timer();\r
- setTimeout(function () {\r
-\r
- expect(timer.elapsed()).to.be.above(9);\r
- done();\r
- }, 12);\r
- });\r
- });\r
-\r
- describe('#loadPackage', function () {\r
-\r
- it('should', function (done) {\r
-\r
- var pack = Hoek.loadPackage();\r
- expect(pack.name).to.equal('hoek');\r
- done();\r
- });\r
- });\r
-\r
- describe('#escapeRegex', function () {\r
-\r
- it('should escape all special regular expression characters', function (done) {\r
-\r
- var a = Hoek.escapeRegex('4^f$s.4*5+-_?%=#!:@|~\\/`"(>)[<]d{}s,');\r
- expect(a).to.equal('4\\^f\\$s\\.4\\*5\\+\\-_\\?%\\=#\\!\\:@\\|~\\\\\\/`"\\(>\\)\\[<\\]d\\{\\}s\\,');\r
- done();\r
- });\r
- });\r
-\r
- describe('#toss', function () {\r
-\r
- it('should call callback with new error', function (done) {\r
-\r
- var callback = function (err) {\r
-\r
- expect(err).to.exist;\r
- expect(err.message).to.equal('bug');\r
- done();\r
- };\r
-\r
- Hoek.toss(true, 'feature', callback);\r
- Hoek.toss(false, 'bug', callback);\r
- });\r
-\r
- it('should call callback with new error and no message', function (done) {\r
-\r
- Hoek.toss(false, function (err) {\r
-\r
- expect(err).to.exist;\r
- expect(err.message).to.equal('');\r
- done();\r
- });\r
- });\r
-\r
- it('should call callback with error condition', function (done) {\r
-\r
- Hoek.toss(new Error('boom'), function (err) {\r
-\r
- expect(err).to.exist;\r
- expect(err.message).to.equal('boom');\r
- done();\r
- });\r
- });\r
-\r
- it('should call callback with new error using message with error condition', function (done) {\r
-\r
- Hoek.toss(new Error('ka'), 'boom', function (err) {\r
-\r
- expect(err).to.exist;\r
- expect(err.message).to.equal('boom');\r
- done();\r
- });\r
- });\r
-\r
- it('should call callback with new error using passed error with error condition', function (done) {\r
-\r
- Hoek.toss(new Error('ka'), new Error('boom'), function (err) {\r
-\r
- expect(err).to.exist;\r
- expect(err.message).to.equal('boom');\r
- done();\r
- });\r
- });\r
- });\r
-\r
- describe('Base64Url', function () {\r
-\r
- var base64str = 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0-P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn-AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq-wsbKztLW2t7i5uru8vb6_wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t_g4eLj5OXm5-jp6uvs7e7v8PHy8_T19vf4-fr7_P3-_w';\r
- var str = unescape('%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20%21%22%23%24%25%26%27%28%29*+%2C-./0123456789%3A%3B%3C%3D%3E%3F@ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF');\r
-\r
- describe('#base64urlEncode', function () {\r
-\r
- it('should base64 URL-safe a string', function (done) {\r
-\r
- expect(Hoek.base64urlEncode(str)).to.equal(base64str);\r
- done();\r
- });\r
- });\r
-\r
- describe('#base64urlDecode', function () {\r
-\r
- it('should un-base64 URL-safe a string', function (done) {\r
-\r
- expect(Hoek.base64urlDecode(base64str)).to.equal(str);\r
- done();\r
- });\r
-\r
- it('should return error on undefined input', function (done) {\r
-\r
- expect(Hoek.base64urlDecode().message).to.exist;\r
- done();\r
- });\r
-\r
- it('should return error on invalid input', function (done) {\r
-\r
- expect(Hoek.base64urlDecode('*').message).to.exist;\r
- done();\r
- });\r
- });\r
- });\r
-\r
- describe('#escapeHeaderAttribute', function () {\r
-\r
- it('should not alter ascii values', function (done) {\r
-\r
- var a = Hoek.escapeHeaderAttribute('My Value');\r
- expect(a).to.equal('My Value');\r
- done();\r
- });\r
-\r
- it('should escape all special HTTP header attribute characters', function (done) {\r
-\r
- var a = Hoek.escapeHeaderAttribute('I said go!!!#"' + String.fromCharCode(92));\r
- expect(a).to.equal('I said go!!!#\\"\\\\');\r
- done();\r
- });\r
-\r
- it('should throw on large unicode characters', function (done) {\r
-\r
- var fn = function () {\r
-\r
- Hoek.escapeHeaderAttribute('this is a test' + String.fromCharCode(500) + String.fromCharCode(300));\r
- };\r
-\r
- expect(fn).to.throw(Error);\r
- done();\r
- });\r
-\r
- it('should throw on CRLF to prevent response splitting', function (done) {\r
-\r
- var fn = function () {\r
-\r
- Hoek.escapeHeaderAttribute('this is a test\r\n');\r
- };\r
-\r
- expect(fn).to.throw(Error);\r
- done();\r
- });\r
- });\r
-\r
- describe('#escapeHtml', function () {\r
-\r
- it('should escape all special HTML characters', function (done) {\r
-\r
- var a = Hoek.escapeHtml('&<>"\'`');\r
- expect(a).to.equal('&<>"'`');\r
- done();\r
- });\r
-\r
- it('should return empty string on falsy input', function (done) {\r
-\r
- var a = Hoek.escapeHtml('');\r
- expect(a).to.equal('');\r
- done();\r
- });\r
-\r
- it('should return unchanged string on no reserved input', function (done) {\r
-\r
- var a = Hoek.escapeHtml('abc');\r
- expect(a).to.equal('abc');\r
- done();\r
- });\r
- });\r
-\r
- describe('#printEvent', function () {\r
-\r
- it('outputs event as string', function (done) {\r
-\r
- var event = {\r
- timestamp: (new Date(2013, 1, 1, 6, 30, 45, 123)).getTime(),\r
- tags: ['a', 'b', 'c'],\r
- data: { some: 'data' }\r
- };\r
-\r
- Hoek.consoleFunc = function (string) {\r
-\r
- Hoek.consoleFunc = console.log;\r
- expect(string).to.equal('130201/063045.123, a, {"some":"data"}');\r
- done();\r
- };\r
-\r
- Hoek.printEvent(event);\r
- });\r
-\r
- it('outputs JSON error', function (done) {\r
-\r
- var event = {\r
- timestamp: (new Date(2013, 1, 1, 6, 30, 45, 123)).getTime(),\r
- tags: ['a', 'b', 'c'],\r
- data: { some: 'data' }\r
- };\r
-\r
- event.data.a = event.data;\r
-\r
- Hoek.consoleFunc = function (string) {\r
-\r
- Hoek.consoleFunc = console.log;\r
- expect(string).to.equal('130201/063045.123, a, JSON Error: Converting circular structure to JSON');\r
- done();\r
- };\r
-\r
- Hoek.printEvent(event);\r
- });\r
- });\r
-\r
- describe('#nextTick', function () {\r
-\r
- it('calls the provided callback on nextTick', function (done) {\r
-\r
- var a = 0;\r
-\r
- var inc = function (step, next) {\r
-\r
- a += step;\r
- next();\r
- };\r
-\r
- var ticked = Hoek.nextTick(inc);\r
-\r
- ticked(5, function () {\r
-\r
- expect(a).to.equal(6);\r
- done();\r
- });\r
-\r
- expect(a).to.equal(0);\r
- inc(1, function () {\r
-\r
- expect(a).to.equal(1);\r
- });\r
- });\r
- });\r
-});\r
-\r
+// Load modules
+
+var Fs = require('fs');
+var Path = require('path');
+var Code = require('code');
+var Hoek = require('../lib');
+var Lab = require('lab');
+
+
+// Declare internals
+
+var internals = {};
+
+
+// Test shortcuts
+
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
+
+
+var nestedObj = {
+ v: [7, 8, 9],
+ w: /^something$/igm,
+ x: {
+ a: [1, 2, 3],
+ b: 123456,
+ c: new Date(),
+ d: /hi/igm,
+ e: /hello/
+ },
+ y: 'y',
+ z: new Date(1378775452757)
+};
+
+var dupsArray = [nestedObj, { z: 'z' }, nestedObj];
+var reducedDupsArray = [nestedObj, { z: 'z' }];
+
+describe('clone()', function () {
+
+ it('clones a nested object', function (done) {
+
+ var a = nestedObj;
+ var b = Hoek.clone(a);
+
+ expect(a).to.deep.equal(b);
+ expect(a.z.getTime()).to.equal(b.z.getTime());
+ done();
+ });
+
+ it('clones a null object', function (done) {
+
+ var b = Hoek.clone(null);
+
+ expect(b).to.equal(null);
+ done();
+ });
+
+ it('should not convert undefined properties to null', function (done) {
+
+ var obj = { something: undefined };
+ var b = Hoek.clone(obj);
+
+ expect(typeof b.something).to.equal('undefined');
+ done();
+ });
+
+ it('should not throw on circular reference', function (done) {
+
+ var a = {};
+ a.x = a;
+
+ var test = function () {
+
+ var b = Hoek.clone(a);
+ };
+
+ expect(test).to.not.throw();
+ done();
+ });
+
+ it('clones circular reference', function (done) {
+
+ var x = {
+ 'z': new Date()
+ };
+ x.y = x;
+
+ var b = Hoek.clone(x);
+ expect(Object.keys(b.y)).to.deep.equal(Object.keys(x));
+ expect(b.z).to.not.equal(x.z);
+ expect(b.y).to.not.equal(x.y);
+ expect(b.y.z).to.not.equal(x.y.z);
+ expect(b.y).to.equal(b);
+ expect(b.y.y.y.y).to.equal(b);
+ done();
+ });
+
+ it('clones an object with a null prototype', function (done) {
+
+ var obj = Object.create(null);
+ var b = Hoek.clone(obj);
+
+ expect(b).to.deep.equal(obj);
+ done();
+ });
+
+ it('clones deeply nested object', function (done) {
+
+ var a = {
+ x: {
+ y: {
+ a: [1, 2, 3],
+ b: 123456,
+ c: new Date(),
+ d: /hi/igm,
+ e: /hello/
+ }
+ }
+ };
+
+ var b = Hoek.clone(a);
+
+ expect(a).to.deep.equal(b);
+ expect(a.x.y.c.getTime()).to.equal(b.x.y.c.getTime());
+ done();
+ });
+
+ it('clones arrays', function (done) {
+
+ var a = [1, 2, 3];
+
+ var b = Hoek.clone(a);
+
+ expect(a).to.deep.equal(b);
+ done();
+ });
+
+ it('performs actual copy for shallow keys (no pass by reference)', function (done) {
+
+ var x = Hoek.clone(nestedObj);
+ var y = Hoek.clone(nestedObj);
+
+ // Date
+ expect(x.z).to.not.equal(nestedObj.z);
+ expect(x.z).to.not.equal(y.z);
+
+ // Regex
+ expect(x.w).to.not.equal(nestedObj.w);
+ expect(x.w).to.not.equal(y.w);
+
+ // Array
+ expect(x.v).to.not.equal(nestedObj.v);
+ expect(x.v).to.not.equal(y.v);
+
+ // Immutable(s)
+ x.y = 5;
+ expect(x.y).to.not.equal(nestedObj.y);
+ expect(x.y).to.not.equal(y.y);
+
+ done();
+ });
+
+ it('performs actual copy for deep keys (no pass by reference)', function (done) {
+
+ var x = Hoek.clone(nestedObj);
+ var y = Hoek.clone(nestedObj);
+
+ expect(x.x.c).to.not.equal(nestedObj.x.c);
+ expect(x.x.c).to.not.equal(y.x.c);
+
+ expect(x.x.c.getTime()).to.equal(nestedObj.x.c.getTime());
+ expect(x.x.c.getTime()).to.equal(y.x.c.getTime());
+ done();
+ });
+
+ it('copies functions with properties', function (done) {
+
+ var a = {
+ x: function () { return 1; },
+ y: {}
+ };
+ a.x.z = 'string in function';
+ a.x.v = function () { return 2; };
+ a.y.u = a.x;
+
+ var b = Hoek.clone(a);
+ expect(b.x()).to.equal(1);
+ expect(b.x.v()).to.equal(2);
+ expect(b.y.u).to.equal(b.x);
+ expect(b.x.z).to.equal('string in function');
+ done();
+ });
+
+ it('should copy a buffer', function (done) {
+ var tls = {
+ key: new Buffer([1, 2, 3, 4, 5]),
+ cert: new Buffer([1, 2, 3, 4, 5, 6, 10])
+ };
+
+ var copiedTls = Hoek.clone(tls);
+ expect(Buffer.isBuffer(copiedTls.key)).to.equal(true);
+ expect(JSON.stringify(copiedTls.key)).to.equal(JSON.stringify(tls.key));
+ expect(Buffer.isBuffer(copiedTls.cert)).to.equal(true);
+ expect(JSON.stringify(copiedTls.cert)).to.equal(JSON.stringify(tls.cert));
+ done();
+ });
+
+ it('clones an object with a prototype', function (done) {
+
+ var Obj = function () {
+
+ this.a = 5;
+ };
+
+ Obj.prototype.b = function () { return 'c'; };
+
+ var a = new Obj();
+ var b = Hoek.clone(a);
+
+ expect(b.a).to.equal(5);
+ expect(b.b()).to.equal('c');
+ expect(a).to.deep.equal(b);
+ done();
+ });
+
+ it('reuses cloned Date object', function (done) {
+
+ var obj = {
+ a: new Date()
+ };
+
+ obj.b = obj.a;
+
+ var copy = Hoek.clone(obj);
+ expect(copy.a).to.equal(copy.b);
+ done();
+ });
+
+ it('shallow copies an object with a prototype and isImmutable flag', function (done) {
+
+ var Obj = function () {
+
+ this.value = 5;
+ };
+
+ Obj.prototype.b = function () { return 'c'; };
+ Obj.prototype.isImmutable = true;
+
+ var obj = {
+ a: new Obj()
+ };
+
+ var copy = Hoek.clone(obj);
+
+ expect(obj.a.value).to.equal(5);
+ expect(copy.a.value).to.equal(5);
+ expect(copy.a.b()).to.equal('c');
+ expect(obj.a).to.equal(copy.a);
+ done();
+ });
+
+ it('clones an object with property getter without executing it', function (done) {
+
+ var obj = {};
+ var value = 1;
+ var execCount = 0;
+
+ Object.defineProperty(obj, 'test', {
+ enumerable: true,
+ configurable: true,
+ get: function () {
+
+ ++execCount;
+ return value;
+ }
+ });
+
+ var copy = Hoek.clone(obj);
+ expect(execCount).to.equal(0);
+ expect(copy.test).to.equal(1);
+ expect(execCount).to.equal(1);
+ done();
+ });
+
+ it('clones an object with property getter and setter', function (done) {
+
+ var obj = {
+ _test: 0
+ };
+
+ Object.defineProperty(obj, 'test', {
+ enumerable: true,
+ configurable: true,
+ get: function () {
+
+ return this._test;
+ },
+ set: function (value) {
+
+ this._test = value - 1;
+ }
+ });
+
+ var copy = Hoek.clone(obj);
+ expect(copy.test).to.equal(0);
+ copy.test = 5;
+ expect(copy.test).to.equal(4);
+ done();
+ });
+
+ it('clones an object with only property setter', function (done) {
+
+ var obj = {
+ _test: 0
+ };
+
+ Object.defineProperty(obj, 'test', {
+ enumerable: true,
+ configurable: true,
+ set: function (value) {
+
+ this._test = value - 1;
+ }
+ });
+
+ var copy = Hoek.clone(obj);
+ expect(copy._test).to.equal(0);
+ copy.test = 5;
+ expect(copy._test).to.equal(4);
+ done();
+ });
+});
+
+describe('merge()', function () {
+
+ it('deep copies source items', function (done) {
+
+ var target = {
+ b: 3,
+ d: []
+ };
+
+ var source = {
+ c: {
+ d: 1
+ },
+ d: [{ e: 1 }]
+ };
+
+ Hoek.merge(target, source);
+ expect(target.c).to.not.equal(source.c);
+ expect(target.c).to.deep.equal(source.c);
+ expect(target.d).to.not.equal(source.d);
+ expect(target.d[0]).to.not.equal(source.d[0]);
+ expect(target.d).to.deep.equal(source.d);
+ done();
+ });
+
+ it('merges array over an object', function (done) {
+
+ var a = {
+ x: ['n', 'm']
+ };
+
+ var b = {
+ x: {
+ n: '1',
+ m: '2'
+ }
+ };
+
+ Hoek.merge(b, a);
+ expect(a.x[0]).to.equal('n');
+ expect(a.x.n).to.not.exist();
+ done();
+ });
+
+ it('merges object over an array', function (done) {
+
+ var a = {
+ x: ['n', 'm']
+ };
+
+ var b = {
+ x: {
+ n: '1',
+ m: '2'
+ }
+ };
+
+ Hoek.merge(a, b);
+ expect(a.x.n).to.equal('1');
+ expect(a.x[0]).to.not.exist();
+ done();
+ });
+
+ it('does not throw if source is null', function (done) {
+
+ var a = {};
+ var b = null;
+ var c = null;
+
+ expect(function () {
+
+ c = Hoek.merge(a, b);
+ }).to.not.throw();
+
+ expect(c).to.equal(a);
+ done();
+ });
+
+ it('does not throw if source is undefined', function (done) {
+
+ var a = {};
+ var b;
+ var c = null;
+
+ expect(function () {
+
+ c = Hoek.merge(a, b);
+ }).to.not.throw();
+
+ expect(c).to.equal(a);
+ done();
+ });
+
+ it('throws if source is not an object', function (done) {
+
+ expect(function () {
+
+ var a = {};
+ var b = 0;
+
+ Hoek.merge(a, b);
+ }).to.throw('Invalid source value: must be null, undefined, or an object');
+ done();
+ });
+
+ it('throws if target is not an object', function (done) {
+
+ expect(function () {
+
+ var a = 0;
+ var b = {};
+
+ Hoek.merge(a, b);
+ }).to.throw('Invalid target value: must be an object');
+ done();
+ });
+
+ it('throws if target is not an array and source is', function (done) {
+
+ expect(function () {
+
+ var a = {};
+ var b = [1, 2];
+
+ Hoek.merge(a, b);
+ }).to.throw('Cannot merge array onto an object');
+ done();
+ });
+
+ it('returns the same object when merging arrays', function (done) {
+
+ var a = [];
+ var b = [1, 2];
+
+ expect(Hoek.merge(a, b)).to.equal(a);
+ done();
+ });
+
+ it('combines an empty object with a non-empty object', function (done) {
+
+ var a = {};
+ var b = nestedObj;
+
+ var c = Hoek.merge(a, b);
+ expect(a).to.deep.equal(b);
+ expect(c).to.deep.equal(b);
+ done();
+ });
+
+ it('overrides values in target', function (done) {
+
+ var a = { x: 1, y: 2, z: 3, v: 5, t: 'test', m: 'abc' };
+ var b = { x: null, z: 4, v: 0, t: { u: 6 }, m: '123' };
+
+ var c = Hoek.merge(a, b);
+ expect(c.x).to.equal(null);
+ expect(c.y).to.equal(2);
+ expect(c.z).to.equal(4);
+ expect(c.v).to.equal(0);
+ expect(c.m).to.equal('123');
+ expect(c.t).to.deep.equal({ u: 6 });
+ done();
+ });
+
+ it('overrides values in target (flip)', function (done) {
+
+ var a = { x: 1, y: 2, z: 3, v: 5, t: 'test', m: 'abc' };
+ var b = { x: null, z: 4, v: 0, t: { u: 6 }, m: '123' };
+
+ var d = Hoek.merge(b, a);
+ expect(d.x).to.equal(1);
+ expect(d.y).to.equal(2);
+ expect(d.z).to.equal(3);
+ expect(d.v).to.equal(5);
+ expect(d.m).to.equal('abc');
+ expect(d.t).to.deep.equal('test');
+ done();
+ });
+
+ it('retains Date properties', function (done) {
+
+ var a = { x: new Date(1378776452757) };
+
+ var b = Hoek.merge({}, a);
+ expect(a.x.getTime()).to.equal(b.x.getTime());
+ done();
+ });
+
+ it('retains Date properties when merging keys', function (done) {
+
+ var a = { x: new Date(1378776452757) };
+
+ var b = Hoek.merge({ x: {} }, a);
+ expect(a.x.getTime()).to.equal(b.x.getTime());
+ done();
+ });
+
+ it('overrides Buffer', function (done) {
+
+ var a = { x: new Buffer('abc') };
+
+ var b = Hoek.merge({ x: {} }, a);
+ expect(a.x.toString()).to.equal('abc');
+ done();
+ });
+});
+
+describe('applyToDefaults()', function () {
+
+ var defaults = {
+ a: 1,
+ b: 2,
+ c: {
+ d: 3,
+ e: [5, 6]
+ },
+ f: 6,
+ g: 'test'
+ };
+
+ it('throws when target is null', function (done) {
+
+ expect(function () {
+
+ Hoek.applyToDefaults(null, {});
+ }).to.throw('Invalid defaults value: must be an object');
+ done();
+ });
+
+ it('returns null if options is false', function (done) {
+
+ var result = Hoek.applyToDefaults(defaults, false);
+ expect(result).to.equal(null);
+ done();
+ });
+
+ it('returns null if options is null', function (done) {
+
+ var result = Hoek.applyToDefaults(defaults, null);
+ expect(result).to.equal(null);
+ done();
+ });
+
+ it('returns null if options is undefined', function (done) {
+
+ var result = Hoek.applyToDefaults(defaults, undefined);
+ expect(result).to.equal(null);
+ done();
+ });
+
+ it('returns a copy of defaults if options is true', function (done) {
+
+ var result = Hoek.applyToDefaults(defaults, true);
+ expect(result).to.deep.equal(defaults);
+ done();
+ });
+
+ it('applies object to defaults', function (done) {
+
+ var obj = {
+ a: null,
+ c: {
+ e: [4]
+ },
+ f: 0,
+ g: {
+ h: 5
+ }
+ };
+
+ var result = Hoek.applyToDefaults(defaults, obj);
+ expect(result.c.e).to.deep.equal([4]);
+ expect(result.a).to.equal(1);
+ expect(result.b).to.equal(2);
+ expect(result.f).to.equal(0);
+ expect(result.g).to.deep.equal({ h: 5 });
+ done();
+ });
+});
+
+describe('cloneWithShallow()', function () {
+
+ it('deep clones except for listed keys', function (done) {
+
+ var source = {
+ a: {
+ b: 5
+ },
+ c: {
+ d: 6
+ }
+ };
+
+ var copy = Hoek.cloneWithShallow(source, ['c']);
+ expect(copy).to.deep.equal(source);
+ expect(copy).to.not.equal(source);
+ expect(copy.a).to.not.equal(source.a);
+ expect(copy.b).to.equal(source.b);
+ done();
+ });
+
+ it('returns immutable value', function (done) {
+
+ expect(Hoek.cloneWithShallow(5)).to.equal(5);
+ done();
+ });
+
+ it('returns null value', function (done) {
+
+ expect(Hoek.cloneWithShallow(null)).to.equal(null);
+ done();
+ });
+
+ it('returns undefined value', function (done) {
+
+ expect(Hoek.cloneWithShallow(undefined)).to.equal(undefined);
+ done();
+ });
+
+ it('deep clones except for listed keys (including missing keys)', function (done) {
+
+ var source = {
+ a: {
+ b: 5
+ },
+ c: {
+ d: 6
+ }
+ };
+
+ var copy = Hoek.cloneWithShallow(source, ['c', 'v']);
+ expect(copy).to.deep.equal(source);
+ expect(copy).to.not.equal(source);
+ expect(copy.a).to.not.equal(source.a);
+ expect(copy.b).to.equal(source.b);
+ done();
+ });
+});
+
+describe('applyToDefaultsWithShallow()', function () {
+
+ it('shallow copies the listed keys from options without merging', function (done) {
+
+ var defaults = {
+ a: {
+ b: 5,
+ e: 3
+ },
+ c: {
+ d: 7,
+ g: 1
+ }
+ };
+
+ var options = {
+ a: {
+ b: 4
+ },
+ c: {
+ d: 6,
+ f: 7
+ }
+ };
+
+ var merged = Hoek.applyToDefaultsWithShallow(defaults, options, ['a']);
+ expect(merged).to.deep.equal({ a: { b: 4 }, c: { d: 6, g: 1, f: 7 } });
+ expect(merged.a).to.equal(options.a);
+ expect(merged.a).to.not.equal(defaults.a);
+ expect(merged.c).to.not.equal(options.c);
+ expect(merged.c).to.not.equal(defaults.c);
+ done();
+ });
+
+ it('shallow copies the nested keys (override)', function (done) {
+
+ var defaults = {
+ a: {
+ b: 5
+ },
+ c: {
+ d: 7,
+ g: 1
+ }
+ };
+
+ var options = {
+ a: {
+ b: 4
+ },
+ c: {
+ d: 6,
+ g: {
+ h: 8
+ }
+ }
+ };
+
+ var merged = Hoek.applyToDefaultsWithShallow(defaults, options, ['c.g']);
+ expect(merged).to.deep.equal({ a: { b: 4 }, c: { d: 6, g: { h: 8 } } });
+ expect(merged.c.g).to.equal(options.c.g);
+ done();
+ });
+
+ it('shallow copies the nested keys (missing)', function (done) {
+
+ var defaults = {
+ a: {
+ b: 5
+ }
+ };
+
+ var options = {
+ a: {
+ b: 4
+ },
+ c: {
+ g: {
+ h: 8
+ }
+ }
+ };
+
+ var merged = Hoek.applyToDefaultsWithShallow(defaults, options, ['c.g']);
+ expect(merged).to.deep.equal({ a: { b: 4 }, c: { g: { h: 8 } } });
+ expect(merged.c.g).to.equal(options.c.g);
+ done();
+ });
+
+ it('shallow copies the nested keys (override)', function (done) {
+
+ var defaults = {
+ a: {
+ b: 5
+ },
+ c: {
+ g: {
+ d: 7
+ }
+ }
+ };
+
+ var options = {
+ a: {
+ b: 4
+ },
+ c: {
+ g: {
+ h: 8
+ }
+ }
+ };
+
+ var merged = Hoek.applyToDefaultsWithShallow(defaults, options, ['c.g']);
+ expect(merged).to.deep.equal({ a: { b: 4 }, c: { g: { h: 8 } } });
+ expect(merged.c.g).to.equal(options.c.g);
+ done();
+ });
+
+ it('shallow copies the nested keys (deeper)', function (done) {
+
+ var defaults = {
+ a: {
+ b: 5
+ }
+ };
+
+ var options = {
+ a: {
+ b: 4
+ },
+ c: {
+ g: {
+ r: {
+ h: 8
+ }
+ }
+ }
+ };
+
+ var merged = Hoek.applyToDefaultsWithShallow(defaults, options, ['c.g.r']);
+ expect(merged).to.deep.equal({ a: { b: 4 }, c: { g: { r: { h: 8 } } } });
+ expect(merged.c.g.r).to.equal(options.c.g.r);
+ done();
+ });
+
+ it('shallow copies the nested keys (not present)', function (done) {
+
+ var defaults = {
+ a: {
+ b: 5
+ }
+ };
+
+ var options = {
+ a: {
+ b: 4
+ },
+ c: {
+ g: {
+ r: {
+ h: 8
+ }
+ }
+ }
+ };
+
+ var merged = Hoek.applyToDefaultsWithShallow(defaults, options, ['x.y']);
+ expect(merged).to.deep.equal({ a: { b: 4 }, c: { g: { r: { h: 8 } } } });
+ done();
+ });
+
+ it('shallow copies the listed keys in the defaults', function (done) {
+
+ var defaults = {
+ a: {
+ b: 1
+ }
+ };
+
+ var merged = Hoek.applyToDefaultsWithShallow(defaults, {}, ['a']);
+ expect(merged.a).to.equal(defaults.a);
+ done();
+ });
+
+ it('shallow copies the listed keys in the defaults (true)', function (done) {
+
+ var defaults = {
+ a: {
+ b: 1
+ }
+ };
+
+ var merged = Hoek.applyToDefaultsWithShallow(defaults, true, ['a']);
+ expect(merged.a).to.equal(defaults.a);
+ done();
+ });
+
+ it('returns null on false', function (done) {
+
+ var defaults = {
+ a: {
+ b: 1
+ }
+ };
+
+ var merged = Hoek.applyToDefaultsWithShallow(defaults, false, ['a']);
+ expect(merged).to.equal(null);
+ done();
+ });
+
+ it('throws on missing defaults', function (done) {
+
+ expect(function () {
+
+ Hoek.applyToDefaultsWithShallow(null, {}, ['a']);
+ }).to.throw('Invalid defaults value: must be an object');
+ done();
+ });
+
+ it('throws on invalid defaults', function (done) {
+
+ expect(function () {
+
+ Hoek.applyToDefaultsWithShallow('abc', {}, ['a']);
+ }).to.throw('Invalid defaults value: must be an object');
+ done();
+ });
+
+ it('throws on invalid options', function (done) {
+
+ expect(function () {
+
+ Hoek.applyToDefaultsWithShallow({}, 'abc', ['a']);
+ }).to.throw('Invalid options value: must be true, falsy or an object');
+ done();
+ });
+
+ it('throws on missing keys', function (done) {
+
+ expect(function () {
+
+ Hoek.applyToDefaultsWithShallow({}, true);
+ }).to.throw('Invalid keys');
+ done();
+ });
+
+ it('throws on invalid keys', function (done) {
+
+ expect(function () {
+
+ Hoek.applyToDefaultsWithShallow({}, true, 'a');
+ }).to.throw('Invalid keys');
+ done();
+ });
+});
+
+describe('deepEqual()', function () {
+
+ it('compares simple values', function (done) {
+
+ expect(Hoek.deepEqual('x', 'x')).to.be.true();
+ expect(Hoek.deepEqual('x', 'y')).to.be.false();
+ expect(Hoek.deepEqual('x1', 'x')).to.be.false();
+ expect(Hoek.deepEqual(-0, +0)).to.be.false();
+ expect(Hoek.deepEqual(-0, -0)).to.be.true();
+ expect(Hoek.deepEqual(+0, +0)).to.be.true();
+ expect(Hoek.deepEqual(+0, -0)).to.be.false();
+ expect(Hoek.deepEqual(1, 1)).to.be.true();
+ expect(Hoek.deepEqual(0, 0)).to.be.true();
+ expect(Hoek.deepEqual(-1, 1)).to.be.false();
+ expect(Hoek.deepEqual(NaN, 0)).to.be.false();
+ expect(Hoek.deepEqual(NaN, NaN)).to.be.true();
+ done();
+ });
+
+ it('compares different types', function (done) {
+
+ expect(Hoek.deepEqual([], 5)).to.be.false();
+ expect(Hoek.deepEqual(5, [])).to.be.false();
+ expect(Hoek.deepEqual({}, null)).to.be.false();
+ expect(Hoek.deepEqual(null, {})).to.be.false();
+ expect(Hoek.deepEqual('abc', {})).to.be.false();
+ expect(Hoek.deepEqual({}, 'abc')).to.be.false();
+ done();
+ });
+
+ it('compares empty structures', function (done) {
+
+ expect(Hoek.deepEqual([], [])).to.be.true();
+ expect(Hoek.deepEqual({}, {})).to.be.true();
+ expect(Hoek.deepEqual([], {})).to.be.false();
+ done();
+ });
+
+ it('compares empty arguments object', function (done) {
+
+ var compare = function () {
+
+ expect(Hoek.deepEqual([], arguments)).to.be.false();
+ };
+
+ compare();
+ done();
+ });
+
+ it('compares empty arguments objects', function (done) {
+
+ var compare = function () {
+
+ var arg1 = arguments;
+
+ var inner = function () {
+
+ expect(Hoek.deepEqual(arg1, arguments)).to.be.true();
+ };
+
+ inner();
+ };
+
+ compare();
+ done();
+ });
+
+ it('compares dates', function (done) {
+
+ expect(Hoek.deepEqual(new Date(), new Date())).to.be.true();
+ expect(Hoek.deepEqual(new Date(100), new Date(101))).to.be.false();
+ expect(Hoek.deepEqual(new Date(), {})).to.be.false();
+ done();
+ });
+
+ it('compares regular expressions', function (done) {
+
+ expect(Hoek.deepEqual(/\s/, new RegExp('\\\s'))).to.be.true();
+ expect(Hoek.deepEqual(/\s/g, /\s/g)).to.be.true();
+ expect(Hoek.deepEqual(/a/, {})).to.be.false();
+ expect(Hoek.deepEqual(/\s/g, /\s/i)).to.be.false();
+ expect(Hoek.deepEqual(/a/g, /b/g)).to.be.false();
+ done();
+ });
+
+ it('compares arrays', function (done) {
+
+ expect(Hoek.deepEqual([[1]], [[1]])).to.be.true();
+ expect(Hoek.deepEqual([1, 2, 3], [1, 2, 3])).to.be.true();
+ expect(Hoek.deepEqual([1, 2, 3], [1, 3, 2])).to.be.false();
+ expect(Hoek.deepEqual([1, 2, 3], [1, 2])).to.be.false();
+ expect(Hoek.deepEqual([1], [1])).to.be.true();
+ done();
+ });
+
+ it('compares buffers', function (done) {
+
+ expect(Hoek.deepEqual(new Buffer([1, 2, 3]), new Buffer([1, 2, 3]))).to.be.true();
+ expect(Hoek.deepEqual(new Buffer([1, 2, 3]), new Buffer([1, 3, 2]))).to.be.false();
+ expect(Hoek.deepEqual(new Buffer([1, 2, 3]), new Buffer([1, 2]))).to.be.false();
+ expect(Hoek.deepEqual(new Buffer([1, 2, 3]), {})).to.be.false();
+ expect(Hoek.deepEqual(new Buffer([1, 2, 3]), [1, 2, 3])).to.be.false();
+ done();
+ });
+
+ it('compares objects', function (done) {
+
+ expect(Hoek.deepEqual({ a: 1, b: 2, c: 3 }, { a: 1, b: 2, c: 3 })).to.be.true();
+ expect(Hoek.deepEqual({ foo: 'bar' }, { foo: 'baz' })).to.be.false();
+ expect(Hoek.deepEqual({ foo: { bar: 'foo' } }, { foo: { bar: 'baz' } })).to.be.false();
+ done();
+ });
+
+ it('handles circular dependency', function (done) {
+
+ var a = {};
+ a.x = a;
+
+ var b = Hoek.clone(a);
+ expect(Hoek.deepEqual(a, b)).to.be.true();
+ done();
+ });
+
+ it('compares an object with property getter without executing it', function (done) {
+
+ var obj = {};
+ var value = 1;
+ var execCount = 0;
+
+ Object.defineProperty(obj, 'test', {
+ enumerable: true,
+ configurable: true,
+ get: function () {
+
+ ++execCount;
+ return value;
+ }
+ });
+
+ var copy = Hoek.clone(obj);
+ expect(Hoek.deepEqual(obj, copy)).to.be.true();
+ expect(execCount).to.equal(0);
+ expect(copy.test).to.equal(1);
+ expect(execCount).to.equal(1);
+ done();
+ });
+
+ it('compares objects with property getters', function (done) {
+
+ var obj = {};
+ Object.defineProperty(obj, 'test', {
+ enumerable: true,
+ configurable: true,
+ get: function () { return 1; }
+ });
+
+ var ref = {};
+ Object.defineProperty(ref, 'test', {
+ enumerable: true,
+ configurable: true,
+ get: function () { return 2; }
+ });
+
+ expect(Hoek.deepEqual(obj, ref)).to.be.false();
+ done();
+ });
+
+ it('compares object prototypes', function (done) {
+
+ var Obj = function () {
+
+ this.a = 5;
+ };
+
+ Obj.prototype.b = function () { return this.a; };
+
+ var Ref = function () {
+
+ this.a = 5;
+ };
+
+ Ref.prototype.b = function () { return this.a; };
+
+ expect(Hoek.deepEqual(new Obj(), new Ref())).to.be.false();
+ expect(Hoek.deepEqual(new Obj(), new Obj())).to.be.true();
+ expect(Hoek.deepEqual(new Ref(), new Ref())).to.be.true();
+ done();
+ });
+
+ it('compares plain objects', function (done) {
+
+ var a = Object.create(null);
+ var b = Object.create(null);
+
+ a.b = 'c';
+ b.b = 'c';
+
+ expect(Hoek.deepEqual(a, b)).to.be.true();
+ expect(Hoek.deepEqual(a, { b: 'c' })).to.be.false();
+ done();
+ });
+});
+
+describe('unique()', function () {
+
+ it('ensures uniqueness within array of objects based on subkey', function (done) {
+
+ var a = Hoek.unique(dupsArray, 'x');
+ expect(a).to.deep.equal(reducedDupsArray);
+ done();
+ });
+
+ it('removes duplicated without key', function (done) {
+
+ expect(Hoek.unique([1, 2, 3, 4, 2, 1, 5])).to.deep.equal([1, 2, 3, 4, 5]);
+ done();
+ });
+});
+
+describe('mapToObject()', function () {
+
+ it('returns null on null array', function (done) {
+
+ var a = Hoek.mapToObject(null);
+ expect(a).to.equal(null);
+ done();
+ });
+
+ it('converts basic array to existential object', function (done) {
+
+ var keys = [1, 2, 3, 4];
+ var a = Hoek.mapToObject(keys);
+ for (var i in keys) {
+ expect(a[keys[i]]).to.equal(true);
+ }
+ done();
+ });
+
+ it('converts array of objects to existential object', function (done) {
+
+ var keys = [{ x: 1 }, { x: 2 }, { x: 3 }, { y: 4 }];
+ var subkey = 'x';
+ var a = Hoek.mapToObject(keys, subkey);
+ expect(a).to.deep.equal({ 1: true, 2: true, 3: true });
+ done();
+ });
+});
+
+describe('intersect()', function () {
+
+ it('returns the common objects of two arrays', function (done) {
+
+ var array1 = [1, 2, 3, 4, 4, 5, 5];
+ var array2 = [5, 4, 5, 6, 7];
+ var common = Hoek.intersect(array1, array2);
+ expect(common.length).to.equal(2);
+ done();
+ });
+
+ it('returns just the first common object of two arrays', function (done) {
+
+ var array1 = [1, 2, 3, 4, 4, 5, 5];
+ var array2 = [5, 4, 5, 6, 7];
+ var common = Hoek.intersect(array1, array2, true);
+ expect(common).to.equal(5);
+ done();
+ });
+
+ it('returns null when no common and returning just the first common object of two arrays', function (done) {
+
+ var array1 = [1, 2, 3, 4, 4, 5, 5];
+ var array2 = [6, 7];
+ var common = Hoek.intersect(array1, array2, true);
+ expect(common).to.equal(null);
+ done();
+ });
+
+ it('returns an empty array if either input is null', function (done) {
+
+ expect(Hoek.intersect([1], null).length).to.equal(0);
+ expect(Hoek.intersect(null, [1]).length).to.equal(0);
+ done();
+ });
+
+ it('returns the common objects of object and array', function (done) {
+
+ var array1 = [1, 2, 3, 4, 4, 5, 5];
+ var array2 = [5, 4, 5, 6, 7];
+ var common = Hoek.intersect(Hoek.mapToObject(array1), array2);
+ expect(common.length).to.equal(2);
+ done();
+ });
+});
+
+describe('contain()', function () {
+
+ it('tests strings', function (done) {
+
+ expect(Hoek.contain('abc', 'ab')).to.be.true();
+ expect(Hoek.contain('abc', 'abc', { only: true })).to.be.true();
+ expect(Hoek.contain('aaa', 'a', { only: true })).to.be.true();
+ expect(Hoek.contain('abc', 'b', { once: true })).to.be.true();
+ expect(Hoek.contain('abc', ['a', 'c'])).to.be.true();
+ expect(Hoek.contain('abc', ['a', 'd'], { part: true })).to.be.true();
+
+ expect(Hoek.contain('abc', 'ac')).to.be.false();
+ expect(Hoek.contain('abcd', 'abc', { only: true })).to.be.false();
+ expect(Hoek.contain('aab', 'a', { only: true })).to.be.false();
+ expect(Hoek.contain('abb', 'b', { once: true })).to.be.false();
+ expect(Hoek.contain('abc', ['a', 'd'])).to.be.false();
+ expect(Hoek.contain('abc', ['ab', 'bc'])).to.be.false(); // Overlapping values not supported
+ done();
+ });
+
+ it('tests arrays', function (done) {
+
+ expect(Hoek.contain([1, 2, 3], 1)).to.be.true();
+ expect(Hoek.contain([{ a: 1 }], { a: 1 }, { deep: true })).to.be.true();
+ expect(Hoek.contain([1, 2, 3], [1, 2])).to.be.true();
+ expect(Hoek.contain([{ a: 1 }], [{ a: 1 }], { deep: true })).to.be.true();
+ expect(Hoek.contain([1, 1, 2], [1, 2], { only: true })).to.be.true();
+ expect(Hoek.contain([1, 2], [1, 2], { once: true })).to.be.true();
+ expect(Hoek.contain([1, 2, 3], [1, 4], { part: true })).to.be.true();
+ expect(Hoek.contain([[1], [2]], [[1]], { deep: true })).to.be.true();
+
+ expect(Hoek.contain([1, 2, 3], 4)).to.be.false();
+ expect(Hoek.contain([{ a: 1 }], { a: 2 }, { deep: true })).to.be.false();
+ expect(Hoek.contain([{ a: 1 }], { a: 1 })).to.be.false();
+ expect(Hoek.contain([1, 2, 3], [4, 5])).to.be.false();
+ expect(Hoek.contain([[3], [2]], [[1]])).to.be.false();
+ expect(Hoek.contain([[1], [2]], [[1]])).to.be.false();
+ expect(Hoek.contain([{ a: 1 }], [{ a: 2 }], { deep: true })).to.be.false();
+ expect(Hoek.contain([1, 3, 2], [1, 2], { only: true })).to.be.false();
+ expect(Hoek.contain([1, 2, 2], [1, 2], { once: true })).to.be.false();
+ expect(Hoek.contain([0, 2, 3], [1, 4], { part: true })).to.be.false();
+ done();
+ });
+
+ it('tests objects', function (done) {
+
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, 'a')).to.be.true();
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, ['a', 'c'])).to.be.true();
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, ['a', 'b', 'c'], { only: true })).to.be.true();
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, { a: 1 })).to.be.true();
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, { a: 1, c: 3 })).to.be.true();
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, { a: 1, d: 4 }, { part: true })).to.be.true();
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, { a: 1, b: 2, c: 3 }, { only: true })).to.be.true();
+ expect(Hoek.contain({ a: [1], b: [2], c: [3] }, { a: [1], c: [3] }, { deep: true })).to.be.true();
+
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, 'd')).to.be.false();
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, ['a', 'd'])).to.be.false();
+ expect(Hoek.contain({ a: 1, b: 2, c: 3, d: 4 }, ['a', 'b', 'c'], { only: true })).to.be.false();
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, { a: 2 })).to.be.false();
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, { a: 2, b: 2 }, { part: true })).to.be.false(); // part does not ignore bad value
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, { a: 1, d: 3 })).to.be.false();
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, { a: 1, d: 4 })).to.be.false();
+ expect(Hoek.contain({ a: 1, b: 2, c: 3 }, { a: 1, b: 2 }, { only: true })).to.be.false();
+ expect(Hoek.contain({ a: [1], b: [2], c: [3] }, { a: [1], c: [3] })).to.be.false();
+ done();
+ });
+});
+
+describe('flatten()', function () {
+
+ it('returns a flat array', function (done) {
+
+ var result = Hoek.flatten([1, 2, [3, 4, [5, 6], [7], 8], [9], [10, [11, 12]], 13]);
+ expect(result.length).to.equal(13);
+ expect(result).to.deep.equal([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);
+ done();
+ });
+});
+
+describe('reach()', function () {
+
+ var obj = {
+ a: {
+ b: {
+ c: {
+ d: 1,
+ e: 2
+ },
+ f: 'hello'
+ },
+ g: {
+ h: 3
+ }
+ },
+ i: function () { },
+ j: null,
+ k: [4, 8, 9, 1]
+ };
+
+ obj.i.x = 5;
+
+ it('returns first value of array', function (done) {
+
+ expect(Hoek.reach(obj, 'k.0')).to.equal(4);
+ done();
+ });
+
+ it('returns last value of array using negative index', function (done) {
+
+ expect(Hoek.reach(obj, 'k.-2')).to.equal(9);
+ done();
+ });
+
+ it('returns a valid member', function (done) {
+
+ expect(Hoek.reach(obj, 'a.b.c.d')).to.equal(1);
+ done();
+ });
+
+ it('returns a valid member with separator override', function (done) {
+
+ expect(Hoek.reach(obj, 'a/b/c/d', '/')).to.equal(1);
+ done();
+ });
+
+ it('returns undefined on null object', function (done) {
+
+ expect(Hoek.reach(null, 'a.b.c.d')).to.equal(undefined);
+ done();
+ });
+
+ it('returns undefined on missing object member', function (done) {
+
+ expect(Hoek.reach(obj, 'a.b.c.d.x')).to.equal(undefined);
+ done();
+ });
+
+ it('returns undefined on missing function member', function (done) {
+
+ expect(Hoek.reach(obj, 'i.y', { functions: true })).to.equal(undefined);
+ done();
+ });
+
+ it('throws on missing member in strict mode', function (done) {
+
+ expect(function () {
+
+ Hoek.reach(obj, 'a.b.c.o.x', { strict: true });
+ }).to.throw('Missing segment o in reach path a.b.c.o.x');
+
+ done();
+ });
+
+ it('returns undefined on invalid member', function (done) {
+
+ expect(Hoek.reach(obj, 'a.b.c.d-.x')).to.equal(undefined);
+ done();
+ });
+
+ it('returns function member', function (done) {
+
+ expect(typeof Hoek.reach(obj, 'i')).to.equal('function');
+ done();
+ });
+
+ it('returns function property', function (done) {
+
+ expect(Hoek.reach(obj, 'i.x')).to.equal(5);
+ done();
+ });
+
+ it('returns null', function (done) {
+
+ expect(Hoek.reach(obj, 'j')).to.equal(null);
+ done();
+ });
+
+ it('throws on function property when functions not allowed', function (done) {
+
+ expect(function () {
+
+ Hoek.reach(obj, 'i.x', { functions: false });
+ }).to.throw('Invalid segment x in reach path i.x');
+
+ done();
+ });
+
+ it('will return a default value if property is not found', function (done) {
+
+ expect(Hoek.reach(obj, 'a.b.q', { default: 'defaultValue' })).to.equal('defaultValue');
+ done();
+ });
+
+ it('will return a default value if path is not found', function (done) {
+
+ expect(Hoek.reach(obj, 'q', { default: 'defaultValue' })).to.equal('defaultValue');
+ done();
+ });
+
+ it('allows a falsey value to be used as the default value', function (done) {
+
+ expect(Hoek.reach(obj, 'q', { default: '' })).to.equal('');
+ done();
+ });
+});
+
+describe('callStack()', function () {
+
+ it('returns the full call stack', function (done) {
+
+ var stack = Hoek.callStack();
+ expect(stack[0][0]).to.contain('index.js');
+ expect(stack[0][2]).to.equal(26);
+ done();
+ });
+});
+
+describe('displayStack ()', function () {
+
+ it('returns the full call stack for display', function (done) {
+
+ var stack = Hoek.displayStack();
+ expect(stack[0]).to.contain(Path.normalize('/test/index.js') + ':');
+ done();
+ });
+
+ it('includes constructor functions correctly', function (done) {
+
+ var Something = function (next) {
+
+ next();
+ };
+
+ var something = new Something(function () {
+
+ var stack = Hoek.displayStack();
+ expect(stack[1]).to.contain('new Something');
+ done();
+ });
+ });
+});
+
+describe('abort()', function () {
+
+ it('exits process when not in test mode', function (done) {
+
+ var env = process.env.NODE_ENV;
+ var write = process.stdout.write;
+ var exit = process.exit;
+
+ process.env.NODE_ENV = 'nottatest';
+ process.stdout.write = function () { };
+ process.exit = function (state) {
+
+ process.exit = exit;
+ process.env.NODE_ENV = env;
+ process.stdout.write = write;
+
+ expect(state).to.equal(1);
+ done();
+ };
+
+ Hoek.abort('Boom');
+ });
+
+ it('throws when not in test mode and abortThrow is true', function (done) {
+
+ var env = process.env.NODE_ENV;
+ process.env.NODE_ENV = 'nottatest';
+ Hoek.abortThrow = true;
+
+ var fn = function () {
+
+ Hoek.abort('my error message');
+ };
+
+ expect(fn).to.throw('my error message');
+ Hoek.abortThrow = false;
+ process.env.NODE_ENV = env;
+
+ done();
+ });
+
+ it('respects hideStack argument', function (done) {
+
+ var env = process.env.NODE_ENV;
+ var write = process.stdout.write;
+ var exit = process.exit;
+ var output = '';
+
+ process.exit = function () { };
+ process.env.NODE_ENV = '';
+ process.stdout.write = function (message) {
+
+ output = message;
+ };
+
+ Hoek.abort('my error message', true);
+
+ process.env.NODE_ENV = env;
+ process.stdout.write = write;
+ process.exit = exit;
+
+ expect(output).to.equal('ABORT: my error message\n\t\n');
+
+ done();
+ });
+
+ it('throws in test mode', function (done) {
+
+ var env = process.env.NODE_ENV;
+ process.env.NODE_ENV = 'test';
+
+ expect(function () {
+
+ Hoek.abort('my error message', true);
+ }).to.throw('my error message');
+
+ process.env.NODE_ENV = env;
+ done();
+ });
+
+ it('throws in test mode with default message', function (done) {
+
+ var env = process.env.NODE_ENV;
+ process.env.NODE_ENV = 'test';
+
+ expect(function () {
+
+ Hoek.abort('', true);
+ }).to.throw('Unknown error');
+
+ process.env.NODE_ENV = env;
+ done();
+ });
+
+ it('defaults to showing stack', function (done) {
+
+ var env = process.env.NODE_ENV;
+ var write = process.stdout.write;
+ var exit = process.exit;
+ var output = '';
+
+ process.exit = function () { };
+ process.env.NODE_ENV = '';
+ process.stdout.write = function (message) {
+
+ output = message;
+ };
+
+ Hoek.abort('my error message');
+
+ process.env.NODE_ENV = env;
+ process.stdout.write = write;
+ process.exit = exit;
+
+ expect(output).to.contain('index.js');
+
+ done();
+ });
+});
+
+describe('assert()', function () {
+
+ it('throws an Error when using assert in a test', function (done) {
+
+ var fn = function () {
+
+ Hoek.assert(false, 'my error message');
+ };
+
+ expect(fn).to.throw('my error message');
+ done();
+ });
+
+ it('throws an Error when using assert in a test with no message', function (done) {
+
+ var fn = function () {
+
+ Hoek.assert(false);
+ };
+
+ expect(fn).to.throw('Unknown error');
+ done();
+ });
+
+ it('throws an Error when using assert in a test with multipart message', function (done) {
+
+ var fn = function () {
+
+ Hoek.assert(false, 'This', 'is', 'my message');
+ };
+
+ expect(fn).to.throw('This is my message');
+ done();
+ });
+
+ it('throws an Error when using assert in a test with multipart message (empty)', function (done) {
+
+ var fn = function () {
+
+ Hoek.assert(false, 'This', 'is', '', 'my message');
+ };
+
+ expect(fn).to.throw('This is my message');
+ done();
+ });
+
+ it('throws an Error when using assert in a test with object message', function (done) {
+
+ var fn = function () {
+
+ Hoek.assert(false, 'This', 'is', { spinal: 'tap' });
+ };
+
+ expect(fn).to.throw('This is {"spinal":"tap"}');
+ done();
+ });
+
+ it('throws an Error when using assert in a test with multipart string and error messages', function (done) {
+
+ var fn = function () {
+
+ Hoek.assert(false, 'This', 'is', new Error('spinal'), new Error('tap'));
+ };
+
+ expect(fn).to.throw('This is spinal tap');
+ done();
+ });
+
+ it('throws an Error when using assert in a test with error object message', function (done) {
+
+ var fn = function () {
+
+ Hoek.assert(false, new Error('This is spinal tap'));
+ };
+
+ expect(fn).to.throw('This is spinal tap');
+ done();
+ });
+
+ it('throws the same Error that is passed to it if there is only one error passed', function (done) {
+ var error = new Error('ruh roh');
+ var error2 = new Error('ruh roh');
+
+ var fn = function () {
+
+ Hoek.assert(false, error);
+ };
+
+ try {
+ fn();
+ } catch (err) {
+ expect(error).to.equal(error); // should be the same reference
+ expect(error).to.not.equal(error2); // error with the same message should not match
+ }
+
+ done();
+ });
+});
+
+describe('Timer', function () {
+
+ it('returns time elapsed', function (done) {
+
+ var timer = new Hoek.Timer();
+ setTimeout(function () {
+
+ expect(timer.elapsed()).to.be.above(9);
+ done();
+ }, 12);
+ });
+});
+
+describe('Bench', function () {
+
+ it('returns time elapsed', function (done) {
+
+ var timer = new Hoek.Bench();
+ setTimeout(function () {
+
+ expect(timer.elapsed()).to.be.above(9);
+ done();
+ }, 12);
+ });
+});
+
+describe('escapeRegex()', function () {
+
+ it('escapes all special regular expression characters', function (done) {
+
+ var a = Hoek.escapeRegex('4^f$s.4*5+-_?%=#!:@|~\\/`"(>)[<]d{}s,');
+ expect(a).to.equal('4\\^f\\$s\\.4\\*5\\+\\-_\\?%\\=#\\!\\:@\\|~\\\\\\/`"\\(>\\)\\[<\\]d\\{\\}s\\,');
+ done();
+ });
+});
+
+describe('Base64Url', function () {
+
+ var base64str = 'AAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxwdHh8gISIjJCUmJygpKissLS4vMDEyMzQ1Njc4OTo7PD0-P0BBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWltcXV5fYGFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6e3x9fn-AgYKDhIWGh4iJiouMjY6PkJGSk5SVlpeYmZqbnJ2en6ChoqOkpaanqKmqq6ytrq-wsbKztLW2t7i5uru8vb6_wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t_g4eLj5OXm5-jp6uvs7e7v8PHy8_T19vf4-fr7_P3-_w';
+ var str = unescape('%00%01%02%03%04%05%06%07%08%09%0A%0B%0C%0D%0E%0F%10%11%12%13%14%15%16%17%18%19%1A%1B%1C%1D%1E%1F%20%21%22%23%24%25%26%27%28%29*+%2C-./0123456789%3A%3B%3C%3D%3E%3F@ABCDEFGHIJKLMNOPQRSTUVWXYZ%5B%5C%5D%5E_%60abcdefghijklmnopqrstuvwxyz%7B%7C%7D%7E%7F%80%81%82%83%84%85%86%87%88%89%8A%8B%8C%8D%8E%8F%90%91%92%93%94%95%96%97%98%99%9A%9B%9C%9D%9E%9F%A0%A1%A2%A3%A4%A5%A6%A7%A8%A9%AA%AB%AC%AD%AE%AF%B0%B1%B2%B3%B4%B5%B6%B7%B8%B9%BA%BB%BC%BD%BE%BF%C0%C1%C2%C3%C4%C5%C6%C7%C8%C9%CA%CB%CC%CD%CE%CF%D0%D1%D2%D3%D4%D5%D6%D7%D8%D9%DA%DB%DC%DD%DE%DF%E0%E1%E2%E3%E4%E5%E6%E7%E8%E9%EA%EB%EC%ED%EE%EF%F0%F1%F2%F3%F4%F5%F6%F7%F8%F9%FA%FB%FC%FD%FE%FF');
+
+ describe('base64urlEncode()', function () {
+
+ it('should base64 URL-safe a string', function (done) {
+
+ expect(Hoek.base64urlEncode(str)).to.equal(base64str);
+ done();
+ });
+
+ it('encodes a buffer', function (done) {
+
+ expect(Hoek.base64urlEncode(new Buffer(str, 'binary'))).to.equal(base64str);
+ done();
+ });
+
+ it('should base64 URL-safe a hex string', function (done) {
+
+ var buffer = new Buffer(str, 'binary');
+ expect(Hoek.base64urlEncode(buffer.toString('hex'), 'hex')).to.equal(base64str);
+ done();
+ });
+
+ it('works on larger input strings', function (done) {
+
+ var input = Fs.readFileSync(Path.join(__dirname, 'index.js')).toString();
+ var encoded = Hoek.base64urlEncode(input);
+
+ expect(encoded).to.not.contain('+');
+ expect(encoded).to.not.contain('/');
+
+ var decoded = Hoek.base64urlDecode(encoded);
+
+ expect(decoded).to.equal(input);
+ done();
+ });
+ });
+
+ describe('base64urlDecode()', function () {
+
+ it('should un-base64 URL-safe a string', function (done) {
+
+ expect(Hoek.base64urlDecode(base64str)).to.equal(str);
+ done();
+ });
+
+ it('should un-base64 URL-safe a string into hex', function (done) {
+
+ expect(Hoek.base64urlDecode(base64str, 'hex')).to.equal(new Buffer(str, 'binary').toString('hex'));
+ done();
+ });
+
+ it('should un-base64 URL-safe a string and return a buffer', function (done) {
+
+ var buf = Hoek.base64urlDecode(base64str, 'buffer');
+ expect(buf instanceof Buffer).to.equal(true);
+ expect(buf.toString('binary')).to.equal(str);
+ done();
+ });
+
+ it('returns error on undefined input', function (done) {
+
+ expect(Hoek.base64urlDecode().message).to.exist();
+ done();
+ });
+
+ it('returns error on invalid input', function (done) {
+
+ expect(Hoek.base64urlDecode('*').message).to.exist();
+ done();
+ });
+ });
+});
+
+describe('escapeHeaderAttribute()', function () {
+
+ it('should not alter ascii values', function (done) {
+
+ var a = Hoek.escapeHeaderAttribute('My Value');
+ expect(a).to.equal('My Value');
+ done();
+ });
+
+ it('escapes all special HTTP header attribute characters', function (done) {
+
+ var a = Hoek.escapeHeaderAttribute('I said go!!!#"' + String.fromCharCode(92));
+ expect(a).to.equal('I said go!!!#\\"\\\\');
+ done();
+ });
+
+ it('throws on large unicode characters', function (done) {
+
+ var fn = function () {
+
+ Hoek.escapeHeaderAttribute('this is a test' + String.fromCharCode(500) + String.fromCharCode(300));
+ };
+
+ expect(fn).to.throw(Error);
+ done();
+ });
+
+ it('throws on CRLF to prevent response splitting', function (done) {
+
+ var fn = function () {
+
+ Hoek.escapeHeaderAttribute('this is a test\r\n');
+ };
+
+ expect(fn).to.throw(Error);
+ done();
+ });
+});
+
+describe('escapeHtml()', function () {
+
+ it('escapes all special HTML characters', function (done) {
+
+ var a = Hoek.escapeHtml('&<>"\'`');
+ expect(a).to.equal('&<>"'`');
+ done();
+ });
+
+ it('returns empty string on falsy input', function (done) {
+
+ var a = Hoek.escapeHtml('');
+ expect(a).to.equal('');
+ done();
+ });
+
+ it('returns unchanged string on no reserved input', function (done) {
+
+ var a = Hoek.escapeHtml('abc');
+ expect(a).to.equal('abc');
+ done();
+ });
+});
+
+describe('nextTick()', function () {
+
+ it('calls the provided callback on nextTick', function (done) {
+
+ var a = 0;
+
+ var inc = function (step, next) {
+
+ a += step;
+ next();
+ };
+
+ var ticked = Hoek.nextTick(inc);
+
+ ticked(5, function () {
+
+ expect(a).to.equal(6);
+ done();
+ });
+
+ expect(a).to.equal(0);
+ inc(1, function () {
+
+ expect(a).to.equal(1);
+ });
+ });
+});
+
+describe('once()', function () {
+
+ it('allows function to only execute once', function (done) {
+
+ var gen = 0;
+ var add = function (x) {
+
+ gen += x;
+ };
+
+ add(5);
+ expect(gen).to.equal(5);
+ add = Hoek.once(add);
+ add(5);
+ expect(gen).to.equal(10);
+ add(5);
+ expect(gen).to.equal(10);
+ done();
+ });
+
+ it('double once wraps one time', function (done) {
+
+ var method = function () { };
+ method = Hoek.once(method);
+ method.x = 1;
+ method = Hoek.once(method);
+ expect(method.x).to.equal(1);
+ done();
+ });
+});
+
+describe('isAbsoltePath()', function () {
+
+ it('identifies if path is absolute on Unix without node support', { parallel: false }, function (done) {
+
+ var orig = Path.isAbsolute;
+ Path.isAbsolute = undefined;
+
+ expect(Hoek.isAbsolutePath('')).to.equal(false);
+ expect(Hoek.isAbsolutePath('a')).to.equal(false);
+ expect(Hoek.isAbsolutePath('./a')).to.equal(false);
+ expect(Hoek.isAbsolutePath('/a')).to.equal(true);
+ expect(Hoek.isAbsolutePath('/')).to.equal(true);
+
+ Path.isAbsolute = orig;
+
+ done();
+ });
+
+ it('identifies if path is absolute with fake node support', { parallel: false }, function (done) {
+
+ var orig = Path.isAbsolute;
+ Path.isAbsolute = function (path) { return path[0] === '/'; };
+
+ expect(Hoek.isAbsolutePath('', 'linux')).to.equal(false);
+ expect(Hoek.isAbsolutePath('a', 'linux')).to.equal(false);
+ expect(Hoek.isAbsolutePath('./a', 'linux')).to.equal(false);
+ expect(Hoek.isAbsolutePath('/a', 'linux')).to.equal(true);
+ expect(Hoek.isAbsolutePath('/', 'linux')).to.equal(true);
+
+ Path.isAbsolute = orig;
+
+ done();
+ });
+
+ it('identifies if path is absolute on Windows without node support', { parallel: false }, function (done) {
+
+ var orig = Path.isAbsolute;
+ Path.isAbsolute = undefined;
+
+ expect(Hoek.isAbsolutePath('//server/file', 'win32')).to.equal(true);
+ expect(Hoek.isAbsolutePath('//server/file', 'win32')).to.equal(true);
+ expect(Hoek.isAbsolutePath('\\\\server\\file', 'win32')).to.equal(true);
+ expect(Hoek.isAbsolutePath('C:/Users/', 'win32')).to.equal(true);
+ expect(Hoek.isAbsolutePath('C:\\Users\\', 'win32')).to.equal(true);
+ expect(Hoek.isAbsolutePath('C:cwd/another', 'win32')).to.equal(false);
+ expect(Hoek.isAbsolutePath('C:cwd\\another', 'win32')).to.equal(false);
+ expect(Hoek.isAbsolutePath('directory/directory', 'win32')).to.equal(false);
+ expect(Hoek.isAbsolutePath('directory\\directory', 'win32')).to.equal(false);
+
+ Path.isAbsolute = orig;
+
+ done();
+ });
+});
+
+describe('isInteger()', function () {
+
+ it('validates integers', function (done) {
+
+ expect(Hoek.isInteger(0)).to.equal(true);
+ expect(Hoek.isInteger(1)).to.equal(true);
+ expect(Hoek.isInteger(1394035612500)).to.equal(true);
+ expect(Hoek.isInteger('0')).to.equal(false);
+ expect(Hoek.isInteger(1.0)).to.equal(true);
+ expect(Hoek.isInteger(1.1)).to.equal(false);
+ done();
+ });
+});
+
+describe('ignore()', function () {
+
+ it('exists', function (done) {
+
+ expect(Hoek.ignore).to.exist();
+ expect(typeof Hoek.ignore).to.equal('function');
+ done();
+ });
+});
+
+describe('inherits()', function () {
+
+ it('exists', function (done) {
+
+ expect(Hoek.inherits).to.exist();
+ expect(typeof Hoek.inherits).to.equal('function');
+ done();
+ });
+});
+
+describe('format()', function () {
+
+ it('exists', function (done) {
+
+ expect(Hoek.format).to.exist();
+ expect(typeof Hoek.format).to.equal('function');
+ done();
+ });
+
+ it('is a reference to Util.format', function (done) {
+
+ expect(Hoek.format('hello %s', 'world')).to.equal('hello world');
+ done();
+ });
+});
+
+describe('transform()', function () {
+
+ var source = {
+ address: {
+ one: '123 main street',
+ two: 'PO Box 1234'
+ },
+ zip: {
+ code: 3321232,
+ province: null
+ },
+ title: 'Warehouse',
+ state: 'CA'
+ };
+
+ it('transforms an object based on the input object', function (done) {
+
+ var result = Hoek.transform(source, {
+ 'person.address.lineOne': 'address.one',
+ 'person.address.lineTwo': 'address.two',
+ 'title': 'title',
+ 'person.address.region': 'state',
+ 'person.address.zip': 'zip.code',
+ 'person.address.location': 'zip.province'
+ });
+
+ expect(result).to.deep.equal({
+ person: {
+ address: {
+ lineOne: '123 main street',
+ lineTwo: 'PO Box 1234',
+ region: 'CA',
+ zip: 3321232,
+ location: null
+ }
+ },
+ title: 'Warehouse'
+ });
+
+ done();
+ });
+
+ it('uses the reach options passed into it', function (done) {
+
+ var schema = {
+ 'person.address.lineOne': 'address-one',
+ 'person.address.lineTwo': 'address-two',
+ 'title': 'title',
+ 'person.address.region': 'state',
+ 'person.prefix': 'person-title',
+ 'person.zip': 'zip-code'
+ };
+ var options = {
+ separator: '-',
+ default: 'unknown'
+ };
+ var result = Hoek.transform(source, schema, options);
+
+ expect(result).to.deep.equal({
+ person: {
+ address: {
+ lineOne: '123 main street',
+ lineTwo: 'PO Box 1234',
+ region: 'CA'
+ },
+ prefix: 'unknown',
+ zip: 3321232
+ },
+ title: 'Warehouse'
+ });
+
+ done();
+ });
+
+ it('works to create shallow objects', function (done) {
+
+ var result = Hoek.transform(source, {
+ lineOne: 'address.one',
+ lineTwo: 'address.two',
+ title: 'title',
+ region: 'state',
+ province: 'zip.province'
+ });
+
+ expect(result).to.deep.equal({
+ lineOne: '123 main street',
+ lineTwo: 'PO Box 1234',
+ title: 'Warehouse',
+ region: 'CA',
+ province: null
+ });
+
+ done();
+ });
+
+ it('only allows strings in the map', function (done) {
+
+ expect(function () {
+ var result = Hoek.transform(source, {
+ lineOne: {}
+ });
+ }).to.throw('All mappings must be "." delineated strings');
+
+ done();
+ });
+
+ it('throws an error on invalid arguments', function (done) {
+
+ expect(function () {
+
+ var result = Hoek.transform(NaN, {});
+ }).to.throw('Invalid source object: must be null, undefined, or an object');
+
+ done();
+ });
+
+ it('is safe to pass null', function (done) {
+
+ var result = Hoek.transform(null, {});
+ expect(result).to.deep.equal({});
+
+ done();
+ });
+
+ it('is safe to pass undefined', function (done) {
+
+ var result = Hoek.transform(undefined, {});
+ expect(result).to.deep.equal({});
+
+ done();
+ });
+});
+
+describe('uniqueFilename()', function () {
+
+ it('generates a random file path', function (done) {
+
+ var result = Hoek.uniqueFilename('./test/modules');
+
+ expect(result).to.exist();
+ expect(result).to.be.a.string();
+ expect(result).to.contain('test/modules');
+ done();
+ });
+
+ it('is random enough to use in fast loops', function (done) {
+
+ var results = [];
+
+ for (var i = 0; i < 10; ++i) {
+ results[i] = Hoek.uniqueFilename('./test/modules');
+ }
+
+ var filter = results.filter(function (item, index, array) {
+
+ return array.indexOf(item) === index;
+ });
+
+ expect(filter.length).to.equal(10);
+ expect(results.length).to.equal(10);
+ done();
+
+ });
+
+ it('combines the random elements with a supplied character', function (done) {
+
+ var result = Hoek.uniqueFilename('./test', 'txt');
+
+ expect(result).to.contain('test/');
+ expect(result).to.contain('.txt');
+
+ done();
+ });
+
+ it('accepts extensions with a "." in it', function (done) {
+
+ var result = Hoek.uniqueFilename('./test', '.mp3');
+
+ expect(result).to.contain('test/');
+ expect(result).to.contain('.mp3');
+
+ done();
+ });
+});
+
+describe('stringify()', function (done) {
+
+ it('converts object to string', function (done) {
+
+ var obj = { a: 1 };
+ expect(Hoek.stringify(obj)).to.equal('{"a":1}');
+ done();
+ });
+
+ it('returns error in result string', function (done) {
+
+ var obj = { a: 1 };
+ obj.b = obj;
+ expect(Hoek.stringify(obj)).to.equal('[Cannot display object: Converting circular structure to JSON]');
+ done();
+ });
+});
+
+describe('shallow()', function (done) {
+
+ it('shallow copies an object', function (done) {
+
+ var obj = {
+ a: 5,
+ b: {
+ c: 6
+ }
+ };
+
+ var shallow = Hoek.shallow(obj);
+ expect(shallow).to.not.equal(obj);
+ expect(shallow).to.deep.equal(obj);
+ expect(shallow.b).to.equal(obj.b);
+ done();
+ });
+});
-exports.x = 1;\r
+exports.x = 1;
-exports.y = 2;\r
+exports.y = 2;
-exports.z = 3;\r
+exports.z = 3;
-Copyright (c) 2012-2013, Eran Hammer.
+Copyright (c) 2012-2014, Eran Hammer and other contributors.
All rights reserved.
Redistribution and use in source and binary forms, with or without
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- * Neither the name of Eran Hammer nor the
- names of its contributors may be used to endorse or promote products
- derived from this software without specific prior written permission.
+ * The names of any contributors may not be used to endorse or promote
+ products derived from this software without specific prior written
+ permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL ERAN HAMMER BE LIABLE FOR ANY
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+ * * *
+
+The complete list of contributors can be found at: https://github.com/hueniverse/sntp/graphs/contributors
test:
- @./node_modules/.bin/lab
+ @node node_modules/lab/bin/lab
test-cov:
- @./node_modules/.bin/lab -r threshold -t 100
+ @node node_modules/lab/bin/lab -t 100 -m 3000
test-cov-html:
- @./node_modules/.bin/lab -r html -o coverage.html
-complexity:
- @./node_modules/.bin/cr -o complexity.md -f markdown lib
+ @node node_modules/lab/bin/lab -r html -o coverage.html
-.PHONY: test test-cov test-cov-html complexity
+.PHONY: test test-cov test-cov-html
// Ensure callback is only called once
- var isFinished = false;
var finish = function (err, result) {
if (timeoutId) {
timeoutId = 0;
}
- if (!isFinished) {
- isFinished = true;
- socket.removeAllListeners();
- socket.close();
- return callback(err, result);
- }
+ socket.removeAllListeners();
+ socket.once('error', internals.ignore);
+ socket.close();
+ return callback(err, result);
};
+ finish = Hoek.once(finish);
+
// Create UDP socket
var socket = Dgram.createSocket('udp4');
Dns.reverse(message.referenceId, function (err, domains) {
- if (!err) {
+ if (/* $lab:coverage:off$ */ !err /* $lab:coverage:on$ */) {
message.referenceHost = domains[0];
}
now < internals.last.expires) {
process.nextTick(function () {
-
+
callback(null, internals.last.offset);
});
if (internals.now.intervalId) {
process.nextTick(function () {
-
+
callback();
});
-
+
return;
}
return now + internals.last.offset;
};
+
+internals.ignore = function () {
+
+};
{
"name": "sntp",
"description": "SNTP Client",
- "version": "0.2.4",
+ "version": "1.0.9",
"author": {
"name": "Eran Hammer",
- "email": "eran@hueniverse.com",
+ "email": "eran@hammer.io",
"url": "http://hueniverse.com"
},
"contributors": [],
"node": ">=0.8.0"
},
"dependencies": {
- "hoek": "0.9.x"
+ "hoek": "2.x.x"
},
"devDependencies": {
- "lab": "0.1.x",
- "complexity-report": "0.x.x"
+ "lab": "4.x.x"
},
"scripts": {
"test": "make test-cov"
"url": "http://github.com/hueniverse/sntp/raw/master/LICENSE"
}
],
- "_id": "sntp@0.2.4",
- "dist": {
- "shasum": "fb885f18b0f3aad189f824862536bceeec750900",
- "tarball": "http://registry.npmjs.org/sntp/-/sntp-0.2.4.tgz"
+ "gitHead": "ee2e35284f684609990681734d39010cd356d7da",
+ "bugs": {
+ "url": "https://github.com/hueniverse/sntp/issues"
},
- "_from": "sntp@>=0.2.0 <0.3.0",
- "_npmVersion": "1.2.18",
+ "homepage": "https://github.com/hueniverse/sntp",
+ "_id": "sntp@1.0.9",
+ "_shasum": "6541184cc90aeea6c6e7b35e2659082443c66198",
+ "_from": "sntp@>=1.0.0 <2.0.0",
+ "_npmVersion": "1.4.23",
"_npmUser": {
"name": "hueniverse",
"email": "eran@hueniverse.com"
"email": "eran@hueniverse.com"
}
],
- "directories": {},
- "_shasum": "fb885f18b0f3aad189f824862536bceeec750900",
- "_resolved": "https://registry.npmjs.org/sntp/-/sntp-0.2.4.tgz",
- "bugs": {
- "url": "https://github.com/hueniverse/sntp/issues"
+ "dist": {
+ "shasum": "6541184cc90aeea6c6e7b35e2659082443c66198",
+ "tarball": "http://registry.npmjs.org/sntp/-/sntp-1.0.9.tgz"
},
- "readme": "ERROR: No README data found!",
- "homepage": "https://github.com/hueniverse/sntp"
+ "directories": {},
+ "_resolved": "https://registry.npmjs.org/sntp/-/sntp-1.0.9.tgz",
+ "readme": "ERROR: No README data found!"
}
// Load modules
+var Dns = require('dns');
var Dgram = require('dgram');
var Lab = require('lab');
var Sntp = require('../lib');
// Test shortcuts
+var lab = exports.lab = Lab.script();
+var before = lab.before;
+var after = lab.after;
+var describe = lab.experiment;
+var it = lab.test;
var expect = Lab.expect;
-var before = Lab.before;
-var after = Lab.after;
-var describe = Lab.experiment;
-var it = Lab.test;
describe('SNTP', function () {
});
});
- it('errors on error event', function (done) {
+ it('errors on error event', { parallel: false }, function (done) {
var orig = Dgram.createSocket;
Dgram.createSocket = function (type) {
Dgram.createSocket = orig;
var socket = Dgram.createSocket(type);
- process.nextTick(function () { socket.emit('error', new Error('Fake')) });
+ setImmediate(function () { socket.emit('error', new Error('Fake')) });
return socket;
};
});
});
+ it('errors on incorrect sent size', { parallel: false }, function (done) {
+
+ var orig = Dgram.Socket.prototype.send;
+ Dgram.Socket.prototype.send = function (buf, offset, length, port, address, callback) {
+
+ Dgram.Socket.prototype.send = orig;
+ return callback(null, 40);
+ };
+
+ Sntp.time(function (err, time) {
+
+ expect(err).to.exist;
+ expect(time).to.not.exist;
+ expect(err.message).to.equal('Could not send entire message');
+ done();
+ });
+ });
+
it('times out on invalid host', function (done) {
Sntp.time({ host: 'error', timeout: 10000 }, function (err, time) {
expect(err).to.exist;
expect(time).to.not.exist;
- expect(err.message).to.equal('getaddrinfo ENOTFOUND');
+ expect(err.message).to.contain('getaddrinfo');
done();
});
});
});
});
+ it('fails on bad originateTimestamp', function (done) {
+
+ messup([[24, 0x83], [25, 0xaa], [26, 0x7e], [27, 0x80], [28, 0], [29, 0], [30, 0], [31, 0]]);
+
+ Sntp.time({ host: 'localhost', port: 49123 }, function (err, time) {
+
+ expect(err).to.exist;
+ expect(err.message).to.equal('Invalid server response');
+ done();
+ });
+ });
+
+ it('fails on bad receiveTimestamp', function (done) {
+
+ messup([[32, 0x83], [33, 0xaa], [34, 0x7e], [35, 0x80], [36, 0], [37, 0], [38, 0], [39, 0]]);
+
+ Sntp.time({ host: 'localhost', port: 49123 }, function (err, time) {
+
+ expect(err).to.exist;
+ expect(err.message).to.equal('Invalid server response');
+ done();
+ });
+ });
+
it('fails on bad originate timestamp and alarm li', function (done) {
messup([[0, (3 << 6) + (4 << 3) + (4 << 0)]]);
});
});
+ it('gets the new offset on different server', function (done) {
+
+ Sntp.offset(function (err, offset) {
+
+ expect(err).to.not.exist;
+ expect(offset).to.not.equal(0);
+ var offset1 = offset;
+ Sntp.offset({ host: 'nist1-sj.ustiming.org' }, function (err, offset) {
+
+ expect(err).to.not.exist;
+ expect(offset).to.not.equal(offset1);
+ done();
+ });
+ });
+ });
+
+ it('gets the new offset on different server', function (done) {
+
+ Sntp.offset(function (err, offset) {
+
+ expect(err).to.not.exist;
+ expect(offset).to.not.equal(0);
+ var offset1 = offset;
+ Sntp.offset({ port: 123 }, function (err, offset) {
+
+ expect(err).to.not.exist;
+ expect(offset).to.not.equal(offset1);
+ done();
+ });
+ });
+ });
+
it('fails getting the current offset on invalid server', function (done) {
Sntp.offset({ host: 'error' }, function (err, offset) {
{
"name": "hawk",
"description": "HTTP Hawk Authentication Scheme",
- "version": "1.1.1",
+ "version": "2.3.1",
"author": {
"name": "Eran Hammer",
- "email": "eran@hueniverse.com",
+ "email": "eran@hammer.io",
"url": "http://hueniverse.com"
},
"contributors": [],
"engines": {
"node": ">=0.8.0"
},
+ "browser": "./lib/browser.js",
"dependencies": {
- "hoek": "0.9.x",
- "boom": "0.4.x",
- "cryptiles": "0.2.x",
- "sntp": "0.2.x"
+ "hoek": "2.x.x",
+ "boom": "2.x.x",
+ "cryptiles": "2.x.x",
+ "sntp": "1.x.x"
},
"devDependencies": {
- "lab": "0.1.x",
- "complexity-report": "0.x.x",
- "localStorage": "1.0.x"
+ "code": "1.x.x",
+ "lab": "5.x.x"
},
"scripts": {
"test": "make test-cov"
"url": "http://github.com/hueniverse/hawk/raw/master/LICENSE"
}
],
+ "gitHead": "492632da51ecedd5f59ce96f081860ad24ce6532",
"bugs": {
"url": "https://github.com/hueniverse/hawk/issues"
},
- "_id": "hawk@1.1.1",
- "dist": {
- "shasum": "87cd491f9b46e4e2aeaca335416766885d2d1ed9",
- "tarball": "http://registry.npmjs.org/hawk/-/hawk-1.1.1.tgz"
- },
- "_from": "hawk@1.1.1",
- "_npmVersion": "1.3.8",
+ "homepage": "https://github.com/hueniverse/hawk",
+ "_id": "hawk@2.3.1",
+ "_shasum": "1e731ce39447fa1d0f6d707f7bceebec0fd1ec1f",
+ "_from": "hawk@>=2.3.0 <2.4.0",
+ "_npmVersion": "1.4.28",
"_npmUser": {
"name": "hueniverse",
"email": "eran@hueniverse.com"
"email": "eran@hueniverse.com"
}
],
+ "dist": {
+ "shasum": "1e731ce39447fa1d0f6d707f7bceebec0fd1ec1f",
+ "tarball": "http://registry.npmjs.org/hawk/-/hawk-2.3.1.tgz"
+ },
"directories": {},
- "_shasum": "87cd491f9b46e4e2aeaca335416766885d2d1ed9",
- "_resolved": "https://registry.npmjs.org/hawk/-/hawk-1.1.1.tgz",
- "readme": "ERROR: No README data found!",
- "homepage": "https://github.com/hueniverse/hawk"
+ "_resolved": "https://registry.npmjs.org/hawk/-/hawk-2.3.1.tgz",
+ "readme": "ERROR: No README data found!"
}
// Load modules
-var Lab = require('lab');
-var Hoek = require('hoek');
+var Url = require('url');
+var Code = require('code');
var Hawk = require('../lib');
+var Hoek = require('hoek');
+var Lab = require('lab');
var Browser = require('../lib/browser');
-var LocalStorage = require('localStorage');
// Declare internals
// Test shortcuts
-var expect = Lab.expect;
-var before = Lab.before;
-var after = Lab.after;
-var describe = Lab.experiment;
-var it = Lab.test;
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
describe('Browser', function () {
return callback(null, credentials);
};
- it('should generate a header then successfully parse it (configuration)', function (done) {
+ it('should generate a bewit then successfully authenticate it', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?a=1&b=2',
+ host: 'example.com',
+ port: 80
+ };
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var bewit = Browser.client.bewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials, ttlSec: 60 * 60 * 24 * 365 * 100, ext: 'some-app-data' });
+ req.url += '&bewit=' + bewit;
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ expect(attributes.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+ });
+
+ it('should generate a bewit then successfully authenticate it (no ext)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?a=1&b=2',
+ host: 'example.com',
+ port: 80
+ };
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var bewit = Browser.client.bewit('http://example.com/resource/4?a=1&b=2', { credentials: credentials, ttlSec: 60 * 60 * 24 * 365 * 100 });
+ req.url += '&bewit=' + bewit;
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ done();
+ });
+ });
+ });
+
+ describe('#bewit', function () {
+
+ it('returns a valid bewit value', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdca3NjeHdOUjJ0SnBQMVQxekRMTlBiQjVVaUtJVTl0T1NKWFRVZEc3WDloOD1ceGFuZHlhbmR6');
+ done();
+ });
+
+ it('returns a valid bewit value (explicit HTTP port)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('http://example.com:8080/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcaFpiSjNQMmNLRW80a3kwQzhqa1pBa1J5Q1p1ZWc0V1NOYnhWN3ZxM3hIVT1ceGFuZHlhbmR6');
+ done();
+ });
+
+ it('returns a valid bewit value (explicit HTTPS port)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com:8043/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcL2t4UjhwK0xSaTdvQTRnUXc3cWlxa3BiVHRKYkR4OEtRMC9HRUwvVytTUT1ceGFuZHlhbmR6');
+ done();
+ });
+
+ it('returns a valid bewit value (null ext)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: null });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcSUdZbUxnSXFMckNlOEN4dktQczRKbFdJQStValdKSm91d2dBUmlWaENBZz1c');
+ done();
+ });
+
+ it('errors on invalid options', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', 4);
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on missing uri', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid uri', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit(5, { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid credentials (id)', function (done) {
+
+ var credentials = {
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on missing credentials', function (done) {
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { ttlSec: 3000, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid algorithm', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'hmac-sha-0'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on missing options', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'hmac-sha-0'
+ };
+
+ var bewit = Browser.client.bewit('https://example.com/somewhere/over/the/rainbow');
+ expect(bewit).to.equal('');
+ done();
+ });
+ });
+
+ it('generates a header then successfully parse it (configuration)', function (done) {
var req = {
method: 'GET',
credentialsFunc('123456', function (err, credentials) {
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }).field;
- expect(req.authorization).to.exist;
+ expect(req.authorization).to.exist();
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
done();
});
});
- it('should generate a header then successfully parse it (node request)', function (done) {
+ it('generates a header then successfully parse it (node request)', function (done) {
var req = {
method: 'POST',
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
};
res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
- expect(res.headers['server-authorization']).to.exist;
+ expect(res.headers['server-authorization']).to.exist();
expect(Browser.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(true);
done();
});
});
- it('should generate a header then successfully parse it (no server header options)', function (done) {
+ it('generates a header then successfully parse it (browserify)', function (done) {
var req = {
method: 'POST',
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain'
+ },
+ getHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(res.headers['server-authorization']).to.exist();
+
+ expect(Browser.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(true);
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (time offset)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', localtimeOffsetMsec: 100000 }).field;
+ expect(req.authorization).to.exist();
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 100000 }, function (err, credentials, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (no server header options)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: '/resource/4?filter=a',
+ headers: {
+ host: 'example.com:8080',
+ 'content-type': 'text/plain;x=y'
+ }
+ };
+
+ var payload = 'some not so random text';
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var reqHeader = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
+ req.headers.authorization = reqHeader.field;
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
+
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
};
res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts);
- expect(res.headers['server-authorization']).to.exist;
+ expect(res.headers['server-authorization']).to.exist();
expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true);
done();
});
});
- it('should generate a header then successfully parse it (no server header)', function (done) {
+ it('generates a header then successfully parse it (no server header)', function (done) {
var req = {
method: 'POST',
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
});
});
- it('should generate a header with stale ts and successfully authenticate on second call', function (done) {
+ it('generates a header with stale ts and successfully authenticate on second call', function (done) {
var req = {
method: 'GET',
Browser.utils.setNtpOffset(60 * 60 * 1000);
var header = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' });
req.authorization = header.field;
- expect(req.authorization).to.exist;
+ expect(req.authorization).to.exist();
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Stale timestamp');
var res = {
headers: {
- 'www-authenticate': err.response.headers['WWW-Authenticate']
+ 'www-authenticate': err.output.headers['WWW-Authenticate']
},
getResponseHeader: function (header) {
expect(Browser.utils.getNtpOffset()).to.equal(0);
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }).field;
- expect(req.authorization).to.exist;
+ expect(req.authorization).to.exist();
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
done();
});
});
- it('should generate a header with stale ts and successfully authenticate on second call (manual localStorage)', function (done) {
+ it('generates a header with stale ts and successfully authenticate on second call (manual localStorage)', function (done) {
var req = {
method: 'GET',
};
credentialsFunc('123456', function (err, credentials) {
- Browser.utils.setStorage(LocalStorage)
+
+ var localStorage = new Browser.internals.LocalStorage();
+
+ Browser.utils.setStorage(localStorage)
Browser.utils.setNtpOffset(60 * 60 * 1000);
var header = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' });
req.authorization = header.field;
- expect(req.authorization).to.exist;
+ expect(req.authorization).to.exist();
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Stale timestamp');
var res = {
headers: {
- 'www-authenticate': err.response.headers['WWW-Authenticate']
+ 'www-authenticate': err.output.headers['WWW-Authenticate']
},
getResponseHeader: function (header) {
}
};
- expect(parseInt(LocalStorage.getItem('hawk_ntp_offset'))).to.equal(60 * 60 * 1000);
+ expect(parseInt(localStorage.getItem('hawk_ntp_offset'))).to.equal(60 * 60 * 1000);
expect(Browser.utils.getNtpOffset()).to.equal(60 * 60 * 1000);
expect(Browser.client.authenticate(res, credentials, header.artifacts)).to.equal(true);
expect(Browser.utils.getNtpOffset()).to.equal(0);
- expect(parseInt(LocalStorage.getItem('hawk_ntp_offset'))).to.equal(0);
+ expect(parseInt(localStorage.getItem('hawk_ntp_offset'))).to.equal(0);
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data' }).field;
- expect(req.authorization).to.exist;
+ expect(req.authorization).to.exist();
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
done();
});
});
- it('should generate a header then fails to parse it (missing server header hash)', function (done) {
+ it('generates a header then fails to parse it (missing server header hash)', function (done) {
var req = {
method: 'POST',
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
};
res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts);
- expect(res.headers['server-authorization']).to.exist;
+ expect(res.headers['server-authorization']).to.exist();
expect(Browser.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(false);
done();
});
});
- it('should generate a header then successfully parse it (with hash)', function (done) {
+ it('generates a header then successfully parse it (with hash)', function (done) {
var req = {
method: 'GET',
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field;
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
done();
});
});
- it('should generate a header then successfully parse it then validate payload', function (done) {
+ it('generates a header then successfully parse it then validate payload', function (done) {
var req = {
method: 'GET',
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field;
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload('hola!', credentials, artifacts)).to.be.true;
- expect(Hawk.server.authenticatePayload('hello!', credentials, artifacts)).to.be.false;
+ expect(Hawk.server.authenticatePayload('hola!', credentials, artifacts)).to.be.true();
+ expect(Hawk.server.authenticatePayload('hello!', credentials, artifacts)).to.be.false();
done();
});
});
});
- it('should generate a header then successfully parse it (app)', function (done) {
+ it('generates a header then successfully parse it (app)', function (done) {
var req = {
method: 'GET',
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', app: 'asd23ased' }).field;
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(artifacts.app).to.equal('asd23ased');
});
});
- it('should generate a header then successfully parse it (app, dlg)', function (done) {
+ it('generates a header then successfully parse it (app, dlg)', function (done) {
var req = {
method: 'GET',
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', app: 'asd23ased', dlg: '23434szr3q4d' }).field;
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(artifacts.app).to.equal('asd23ased');
});
});
- it('should generate a header then fail authentication due to bad hash', function (done) {
+ it('generates a header then fail authentication due to bad hash', function (done) {
var req = {
method: 'GET',
req.authorization = Browser.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field;
Hawk.server.authenticate(req, credentialsFunc, { payload: 'byebye!' }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Bad payload hash');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad payload hash');
done();
});
});
});
- it('should generate a header for one resource then fail to authenticate another', function (done) {
+ it('generates a header for one resource then fail to authenticate another', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(credentials).to.exist;
+ expect(err).to.exist();
+ expect(credentials).to.exist();
done();
});
});
describe('#header', function () {
- it('should return a valid authorization header (sha1)', function (done) {
+ it('returns a valid authorization header (sha1)', function (done) {
var credentials = {
id: '123456',
done();
});
- it('should return a valid authorization header (sha256)', function (done) {
+ it('returns a valid authorization header (sha256)', function (done) {
var credentials = {
id: '123456',
done();
});
- it('should return a valid authorization header (no ext)', function (done) {
+ it('returns a valid authorization header (empty payload)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var header = Browser.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: '' }).field;
+ expect(header).to.equal('Hawk id=\"123456\", ts=\"1353809207\", nonce=\"Ygvqdz\", hash=\"404ghL7K+hfyhByKKejFBRGgTjU=\", ext=\"Bazinga!\", mac=\"Bh1sj1DOfFRWOdi3ww52nLCJdBE=\"');
+ done();
+ });
+
+ it('returns a valid authorization header (no ext)', function (done) {
var credentials = {
id: '123456',
done();
});
- it('should return an empty authorization header on missing options', function (done) {
+ it('returns a valid authorization header (null ext)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain', ext: null }).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
+ done();
+ });
+
+ it('returns a valid authorization header (uri object)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var uri = Browser.utils.parseUri('https://example.net/somewhere/over/the/rainbow');
+ var header = Browser.client.header(uri, 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' }).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
+ done();
+ });
+
+ it('errors on missing options', function (done) {
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST');
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on empty uri', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on invalid uri', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header(4, 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on missing method', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', '', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on invalid method', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 5, { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on missing credentials', function (done) {
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST').field;
- expect(header).to.equal('');
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid credentials object');
done();
});
- it('should return an empty authorization header on invalid credentials', function (done) {
+ it('errors on invalid credentials (id)', function (done) {
var credentials = {
key: '2983d45yun89q',
algorithm: 'sha256'
};
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 }).field;
- expect(header).to.equal('');
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid credentials object');
+ done();
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ algorithm: 'sha256'
+ };
+
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid credentials object');
done();
});
- it('should return an empty authorization header on invalid algorithm', function (done) {
+ it('errors on invalid algorithm', function (done) {
var credentials = {
id: '123456',
algorithm: 'hmac-sha-0'
};
- var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, payload: 'something, anything!', ext: 'Bazinga!', timestamp: 1353809207 }).field;
- expect(header).to.equal('');
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, payload: 'something, anything!', ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Unknown algorithm');
+ done();
+ });
+
+ it('uses a pre-calculated payload hash', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var options = { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' };
+ options.hash = Browser.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
+ var header = Browser.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', options).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="');
done();
});
});
describe('#authenticate', function () {
- it('should return false on invalid header', function (done) {
+ it('skips tsm validation when missing ts', function (done) {
+
+ var res = {
+ headers: {
+ 'www-authenticate': 'Hawk error="Stale timestamp"'
+ },
+ getResponseHeader: function (header) {
+
+ return res.headers[header.toLowerCase()];
+ }
+ };
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ ts: 1402135580,
+ nonce: 'iBRB6t',
+ method: 'GET',
+ resource: '/resource/4?filter=a',
+ host: 'example.com',
+ port: '8080',
+ ext: 'some-app-data'
+ };
+
+ expect(Browser.client.authenticate(res, credentials, artifacts)).to.equal(true);
+ done();
+ });
+
+ it('returns false on invalid header', function (done) {
var res = {
headers: {
done();
});
- it('should return false on invalid mac', function (done) {
+ it('returns false on invalid mac', function (done) {
var res = {
headers: {
done();
});
- it('should return true on ignoring hash', function (done) {
+ it('returns true on ignoring hash', function (done) {
var res = {
headers: {
done();
});
- it('should fail on invalid WWW-Authenticate header format', function (done) {
+ it('errors on invalid WWW-Authenticate header format', function (done) {
var res = {
headers: {
done();
});
- it('should fail on invalid WWW-Authenticate header format', function (done) {
+ it('errors on invalid WWW-Authenticate header format', function (done) {
var credentials = {
id: '123456',
});
describe('#message', function () {
- it('should generate an authorization then successfully parse it', function (done) {
+
+ it('generates an authorization then successfully parse it', function (done) {
credentialsFunc('123456', function (err, credentials) {
var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: credentials });
- expect(auth).to.exist;
+ expect(auth).to.exist();
Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
done();
});
});
});
- it('should fail on missing host', function (done) {
+ it('generates an authorization using custom nonce/timestamp', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: credentials, nonce: 'abc123', timestamp: 1398536270957 });
+ expect(auth).to.exist();
+ expect(auth.nonce).to.equal('abc123');
+ expect(auth.ts).to.equal(1398536270957);
+ done();
+ });
+ });
+
+ it('errors on missing host', function (done) {
credentialsFunc('123456', function (err, credentials) {
var auth = Browser.client.message(null, 8080, 'some message', { credentials: credentials });
- expect(auth).to.not.exist;
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on invalid host', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message(5, 8080, 'some message', { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on missing port', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message('example.com', 0, 'some message', { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on invalid port', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message('example.com', 'a', 'some message', { credentials: credentials });
+ expect(auth).to.not.exist();
done();
});
});
- it('should fail on missing credentials', function (done) {
+ it('errors on missing message', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message('example.com', 8080, undefined, { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on null message', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message('example.com', 8080, null, { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on invalid message', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Browser.client.message('example.com', 8080, 5, { credentials: credentials });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on missing credentials', function (done) {
var auth = Browser.client.message('example.com', 8080, 'some message', {});
- expect(auth).to.not.exist;
+ expect(auth).to.not.exist();
done();
});
- it('should fail on invalid algorithm', function (done) {
+ it('errors on missing options', function (done) {
+
+ var auth = Browser.client.message('example.com', 8080, 'some message');
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on invalid credentials (id)', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var creds = Hoek.clone(credentials);
+ delete creds.id;
+ var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var creds = Hoek.clone(credentials);
+ delete creds.key;
+ var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds });
+ expect(auth).to.not.exist();
+ done();
+ });
+ });
+
+ it('errors on invalid algorithm', function (done) {
credentialsFunc('123456', function (err, credentials) {
var creds = Hoek.clone(credentials);
creds.algorithm = 'blah';
var auth = Browser.client.message('example.com', 8080, 'some message', { credentials: creds });
- expect(auth).to.not.exist;
+ expect(auth).to.not.exist();
done();
});
});
describe('#authenticateTimestamp', function (done) {
- it('should validate a timestamp', function (done) {
+ it('validates a timestamp', function (done) {
credentialsFunc('123456', function (err, credentials) {
});
});
- it('should detect a bad timestamp', function (done) {
+ it('validates a timestamp without updating local time', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var offset = Browser.utils.getNtpOffset();
+ var tsm = Hawk.crypto.timestampMessage(credentials, 10000);
+ expect(Browser.client.authenticateTimestamp(tsm, credentials, false)).to.equal(true);
+ expect(offset).to.equal(Browser.utils.getNtpOffset());
+ done();
+ });
+ });
+
+ it('detects a bad timestamp', function (done) {
credentialsFunc('123456', function (err, credentials) {
});
});
- describe('#parseAuthorizationHeader', function (done) {
+ describe('internals', function () {
+
+ describe('LocalStorage', function () {
+
+ it('goes through the full lifecycle', function (done) {
+
+ var storage = new Browser.internals.LocalStorage();
+ expect(storage.length).to.equal(0);
+ expect(storage.getItem('a')).to.equal(null);
+ storage.setItem('a', 5);
+ expect(storage.length).to.equal(1);
+ expect(storage.key()).to.equal('a');
+ expect(storage.key(0)).to.equal('a');
+ expect(storage.getItem('a')).to.equal('5');
+ storage.setItem('b', 'test');
+ expect(storage.key()).to.equal('a');
+ expect(storage.key(0)).to.equal('a');
+ expect(storage.key(1)).to.equal('b');
+ expect(storage.length).to.equal(2);
+ expect(storage.getItem('b')).to.equal('test');
+ storage.removeItem('a');
+ expect(storage.length).to.equal(1);
+ expect(storage.getItem('a')).to.equal(null);
+ expect(storage.getItem('b')).to.equal('test');
+ storage.clear();
+ expect(storage.length).to.equal(0);
+ expect(storage.getItem('a')).to.equal(null);
+ expect(storage.getItem('b')).to.equal(null);
+ done();
+ });
+ });
+ });
- it('returns null on missing header', function (done) {
+ describe('utils', function () {
- expect(Browser.utils.parseAuthorizationHeader()).to.equal(null);
- done();
- });
+ describe('#setStorage', function () {
- it('returns null on bad header syntax (structure)', function (done) {
+ it('sets storage for the first time', function (done) {
- expect(Browser.utils.parseAuthorizationHeader('Hawk')).to.equal(null);
- done();
+ Browser.utils.storage = new Browser.internals.LocalStorage(); // Reset state
+
+ expect(Browser.utils.storage.getItem('hawk_ntp_offset')).to.not.exist();
+ Browser.utils.storage.setItem('test', '1');
+ Browser.utils.setStorage(new Browser.internals.LocalStorage());
+ expect(Browser.utils.storage.getItem('test')).to.not.exist();
+ Browser.utils.storage.setItem('test', '2');
+ expect(Browser.utils.storage.getItem('test')).to.equal('2');
+ done();
+ });
});
- it('returns null on bad header syntax (parts)', function (done) {
+ describe('#setNtpOffset', function (done) {
- expect(Browser.utils.parseAuthorizationHeader(' ')).to.equal(null);
- done();
- });
+ it('catches localStorage errors', function (done) {
- it('returns null on bad scheme name', function (done) {
+ var orig = Browser.utils.storage.setItem;
+ var error = console.error;
+ var count = 0;
+ console.error = function () { if (count++ === 2) { console.error = error; } };
+ Browser.utils.storage.setItem = function () {
- expect(Browser.utils.parseAuthorizationHeader('Basic asdasd')).to.equal(null);
- done();
- });
+ Browser.utils.storage.setItem = orig;
+ throw new Error()
+ };
- it('returns null on bad attribute value', function (done) {
+ expect(function () {
+ Browser.utils.setNtpOffset(100);
+ }).not.to.throw();
- expect(Browser.utils.parseAuthorizationHeader('Hawk test="\t"', ['test'])).to.equal(null);
- done();
+ done();
+ });
});
- it('returns null on duplicated attribute', function (done) {
+ describe('#parseAuthorizationHeader', function (done) {
- expect(Browser.utils.parseAuthorizationHeader('Hawk test="a", test="b"', ['test'])).to.equal(null);
- done();
+ it('returns null on missing header', function (done) {
+
+ expect(Browser.utils.parseAuthorizationHeader()).to.equal(null);
+ done();
+ });
+
+ it('returns null on bad header syntax (structure)', function (done) {
+
+ expect(Browser.utils.parseAuthorizationHeader('Hawk')).to.equal(null);
+ done();
+ });
+
+ it('returns null on bad header syntax (parts)', function (done) {
+
+ expect(Browser.utils.parseAuthorizationHeader(' ')).to.equal(null);
+ done();
+ });
+
+ it('returns null on bad scheme name', function (done) {
+
+ expect(Browser.utils.parseAuthorizationHeader('Basic asdasd')).to.equal(null);
+ done();
+ });
+
+ it('returns null on bad attribute value', function (done) {
+
+ expect(Browser.utils.parseAuthorizationHeader('Hawk test="\t"', ['test'])).to.equal(null);
+ done();
+ });
+
+ it('returns null on duplicated attribute', function (done) {
+
+ expect(Browser.utils.parseAuthorizationHeader('Hawk test="a", test="b"', ['test'])).to.equal(null);
+ done();
+ });
});
- });
- describe('#setNtpOffset', function (done) {
+ describe('#parseUri', function () {
+
+ it('returns empty port when unknown scheme', function (done) {
- it('catches localStorage errors', function (done) {
+ var uri = Browser.utils.parseUri('ftp://domain');
+ expect(uri.port).to.equal('');
+ done();
+ });
- var orig = Browser.utils.storage.setItem;
- var error = console.error;
- var count = 0;
- console.error = function () { if (count++ === 2) { console.error.error; } };
- Browser.utils.storage.setItem = function () {
+ it('returns default port when missing', function (done) {
- Browser.utils.storage.setItem = orig;
- throw new Error()
- };
+ var uri = Browser.utils.parseUri('http://');
+ expect(uri.port).to.equal('80');
+ done();
+ });
+ });
- expect(function () {
- Browser.utils.setNtpOffset(100);
- }).not.to.throw();
+ var str = "https://www.google.ca/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=url";
+ var base64str = "aHR0cHM6Ly93d3cuZ29vZ2xlLmNhL3dlYmhwP3NvdXJjZWlkPWNocm9tZS1pbnN0YW50Jmlvbj0xJmVzcHY9MiZpZT1VVEYtOCNxPXVybA";
+
+ describe('#base64urlEncode', function () {
+
+ it('should base64 URL-safe decode a string', function (done) {
+
+ expect(Browser.utils.base64urlEncode(str)).to.equal(base64str);
+ done();
+ });
- done();
});
+
});
});
// Load modules
var Url = require('url');
-var Lab = require('lab');
+var Code = require('code');
var Hawk = require('../lib');
+var Lab = require('lab');
// Declare internals
// Test shortcuts
-var expect = Lab.expect;
-var before = Lab.before;
-var after = Lab.after;
-var describe = Lab.experiment;
-var it = Lab.test;
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
describe('Hawk', function () {
describe('#header', function () {
- it('should return a valid authorization header (sha1)', function (done) {
+ it('returns a valid authorization header (sha1)', function (done) {
var credentials = {
id: '123456',
done();
});
- it('should return a valid authorization header (sha256)', function (done) {
+ it('returns a valid authorization header (sha256)', function (done) {
var credentials = {
id: '123456',
done();
});
- it('should return a valid authorization header (no ext)', function (done) {
+ it('returns a valid authorization header (no ext)', function (done) {
var credentials = {
id: '123456',
done();
});
- it('should return an empty authorization header on missing options', function (done) {
+ it('returns a valid authorization header (null ext)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain', ext: null }).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
+ done();
+ });
+
+ it('returns a valid authorization header (empty payload)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: '', contentType: 'text/plain' }).field;
+ expect(header).to.equal('Hawk id=\"123456\", ts=\"1353809207\", nonce=\"Ygvqdz\", hash=\"q/t+NNAkQZNlq/aAD6PlexImwQTxwgT2MahfTa9XRLA=\", mac=\"U5k16YEzn3UnBHKeBzsDXn067Gu3R4YaY6xOt9PYRZM=\"');
+ done();
+ });
+
+ it('returns a valid authorization header (pre hashed payload)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var options = { credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain' };
+ options.hash = Hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', options).field;
+ expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
+ done();
+ });
+
+ it('errors on missing uri', function (done) {
+
+ var header = Hawk.client.header('', 'POST');
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on invalid uri', function (done) {
+
+ var header = Hawk.client.header(4, 'POST');
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on missing method', function (done) {
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST').field;
- expect(header).to.equal('');
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', '');
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
done();
});
- it('should return an empty authorization header on invalid credentials', function (done) {
+ it('errors on invalid method', function (done) {
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 5);
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on missing options', function (done) {
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST');
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid argument type');
+ done();
+ });
+
+ it('errors on invalid credentials (id)', function (done) {
var credentials = {
key: '2983d45yun89q',
algorithm: 'sha256'
};
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 }).field;
- expect(header).to.equal('');
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid credential object');
+ done();
+ });
+
+ it('errors on missing credentials', function (done) {
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid credential object');
+ done();
+ });
+
+ it('errors on invalid credentials', function (done) {
+
+ var credentials = {
+ id: '123456',
+ algorithm: 'sha256'
+ };
+
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Invalid credential object');
done();
});
- it('should return an empty authorization header on invalid algorithm', function (done) {
+ it('errors on invalid algorithm', function (done) {
var credentials = {
id: '123456',
algorithm: 'hmac-sha-0'
};
- var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, payload: 'something, anything!', ext: 'Bazinga!', timestamp: 1353809207 }).field;
- expect(header).to.equal('');
+ var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', { credentials: credentials, payload: 'something, anything!', ext: 'Bazinga!', timestamp: 1353809207 });
+ expect(header.field).to.equal('');
+ expect(header.err).to.equal('Unknown algorithm');
done();
});
});
describe('#authenticate', function () {
- it('should return false on invalid header', function (done) {
+ it('returns false on invalid header', function (done) {
var res = {
headers: {
done();
});
- it('should return false on invalid mac', function (done) {
+ it('returns false on invalid mac', function (done) {
var res = {
headers: {
done();
});
- it('should return true on ignoring hash', function (done) {
+ it('returns true on ignoring hash', function (done) {
var res = {
headers: {
done();
});
- it('should fail on invalid WWW-Authenticate header format', function (done) {
+ it('fails on invalid WWW-Authenticate header format', function (done) {
var header = 'Hawk ts="1362346425875", tsm="PhwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", x="Stale timestamp"';
expect(Hawk.client.authenticate({ headers: { 'www-authenticate': header } }, {})).to.equal(false);
done();
});
- it('should fail on invalid WWW-Authenticate header format', function (done) {
+ it('fails on invalid WWW-Authenticate header format', function (done) {
var credentials = {
id: '123456',
expect(Hawk.client.authenticate({ headers: { 'www-authenticate': header } }, credentials)).to.equal(false);
done();
});
+
+ it('skips tsm validation when missing ts', function (done) {
+
+ var header = 'Hawk error="Stale timestamp"';
+ expect(Hawk.client.authenticate({ headers: { 'www-authenticate': header } }, {})).to.equal(true);
+ done();
+ });
+ });
+
+ describe('#message', function () {
+
+ it('generates authorization', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.exist();
+ expect(auth.ts).to.equal(1353809207);
+ expect(auth.nonce).to.equal('abc123');
+ done();
+ });
+
+ it('errors on invalid host', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message(5, 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on invalid port', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', '80', 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on missing host', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 0, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on null message', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, null, { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on missing message', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, undefined, { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on invalid message', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, 5, { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on missing options', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, 'I am the boodyman');
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on invalid credentials (id)', function (done) {
+
+ var credentials = {
+ key: '2983d45yun89q',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ algorithm: 'sha1'
+ };
+
+ var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', { credentials: credentials, timestamp: 1353809207, nonce: 'abc123' });
+ expect(auth).to.not.exist();
+ done();
+ });
});
});
});
// Load modules
-var Lab = require('lab');
+var Code = require('code');
var Hawk = require('../lib');
+var Lab = require('lab');
// Declare internals
// Test shortcuts
-var expect = Lab.expect;
-var before = Lab.before;
-var after = Lab.after;
-var describe = Lab.experiment;
-var it = Lab.test;
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
describe('Hawk', function () {
// Load modules
var Url = require('url');
-var Lab = require('lab');
+var Code = require('code');
var Hawk = require('../lib');
+var Lab = require('lab');
// Declare internals
// Test shortcuts
-var expect = Lab.expect;
-var before = Lab.before;
-var after = Lab.after;
-var describe = Lab.experiment;
-var it = Lab.test;
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
describe('Hawk', function () {
return callback(null, credentials);
};
- it('should generate a header then successfully parse it (configuration)', function (done) {
+ it('generates a header then successfully parse it (configuration)', function (done) {
var req = {
method: 'GET',
credentialsFunc('123456', function (err, credentials) {
req.authorization = Hawk.client.header(Url.parse('http://example.com:8080/resource/4?filter=a'), req.method, { credentials: credentials, ext: 'some-app-data' }).field;
- expect(req.authorization).to.exist;
+ expect(req.authorization).to.exist();
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
done();
});
});
- it('should generate a header then successfully parse it (node request)', function (done) {
+ it('generates a header then successfully parse it (node request)', function (done) {
var req = {
method: 'POST',
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
};
res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
- expect(res.headers['server-authorization']).to.exist;
+ expect(res.headers['server-authorization']).to.exist();
expect(Hawk.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(true);
done();
});
});
- it('should generate a header then successfully parse it (no server header options)', function (done) {
+ it('generates a header then successfully parse it (absolute request uri)', function (done) {
+
+ var req = {
+ method: 'POST',
+ url: 'http://example.com:8080/resource/4?filter=a',
+ headers: {
+ host: 'example.com:8080',
+ 'content-type': 'text/plain;x=y'
+ }
+ };
+
+ var payload = 'some not so random text';
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var reqHeader = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', payload: payload, contentType: req.headers['content-type'] });
+ req.headers.authorization = reqHeader.field;
+
+ Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
+
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
+
+ var res = {
+ headers: {
+ 'content-type': 'text/plain'
+ }
+ };
+
+ res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(res.headers['server-authorization']).to.exist();
+
+ expect(Hawk.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(true);
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parse it (no server header options)', function (done) {
var req = {
method: 'POST',
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
};
res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts);
- expect(res.headers['server-authorization']).to.exist;
+ expect(res.headers['server-authorization']).to.exist();
expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(true);
done();
});
});
- it('should generate a header then fails to parse it (missing server header hash)', function (done) {
+ it('generates a header then fails to parse it (missing server header hash)', function (done) {
var req = {
method: 'POST',
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(Hawk.server.authenticatePayload(payload, credentials, artifacts, req.headers['content-type'])).to.equal(true);
};
res.headers['server-authorization'] = Hawk.server.header(credentials, artifacts);
- expect(res.headers['server-authorization']).to.exist;
+ expect(res.headers['server-authorization']).to.exist();
expect(Hawk.client.authenticate(res, credentials, artifacts, { payload: 'some reply' })).to.equal(false);
done();
});
});
- it('should generate a header then successfully parse it (with hash)', function (done) {
+ it('generates a header then successfully parse it (with hash)', function (done) {
var req = {
method: 'GET',
req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field;
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
done();
});
});
- it('should generate a header then successfully parse it then validate payload', function (done) {
+ it('generates a header then successfully parse it then validate payload', function (done) {
var req = {
method: 'GET',
req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field;
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
+ expect(credentials.user).to.equal('steve');
+ expect(artifacts.ext).to.equal('some-app-data');
+ expect(Hawk.server.authenticatePayload('hola!', credentials, artifacts)).to.be.true();
+ expect(Hawk.server.authenticatePayload('hello!', credentials, artifacts)).to.be.false();
+ done();
+ });
+ });
+ });
+
+ it('generates a header then successfully parses and validates payload', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080
+ };
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field;
+ Hawk.server.authenticate(req, credentialsFunc, { payload: 'hola!' }, function (err, credentials, artifacts) {
+
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
- expect(Hawk.server.authenticatePayload('hola!', credentials, artifacts)).to.be.true;
- expect(Hawk.server.authenticatePayload('hello!', credentials, artifacts)).to.be.false;
done();
});
});
});
- it('should generate a header then successfully parse it (app)', function (done) {
+ it('generates a header then successfully parse it (app)', function (done) {
var req = {
method: 'GET',
req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', app: 'asd23ased' }).field;
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(artifacts.app).to.equal('asd23ased');
});
});
- it('should generate a header then successfully parse it (app, dlg)', function (done) {
+ it('generates a header then successfully parse it (app, dlg)', function (done) {
var req = {
method: 'GET',
req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, ext: 'some-app-data', app: 'asd23ased', dlg: '23434szr3q4d' }).field;
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(artifacts.ext).to.equal('some-app-data');
expect(artifacts.app).to.equal('asd23ased');
});
});
- it('should generate a header then fail authentication due to bad hash', function (done) {
+ it('generates a header then fail authentication due to bad hash', function (done) {
var req = {
method: 'GET',
req.authorization = Hawk.client.header('http://example.com:8080/resource/4?filter=a', req.method, { credentials: credentials, payload: 'hola!', ext: 'some-app-data' }).field;
Hawk.server.authenticate(req, credentialsFunc, { payload: 'byebye!' }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Bad payload hash');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad payload hash');
done();
});
});
});
- it('should generate a header for one resource then fail to authenticate another', function (done) {
+ it('generates a header for one resource then fail to authenticate another', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(credentials).to.exist;
+ expect(err).to.exist();
+ expect(credentials).to.exist();
done();
});
});
// Load modules
var Url = require('url');
-var Lab = require('lab');
-var Hoek = require('hoek');
+var Code = require('code');
var Hawk = require('../lib');
+var Hoek = require('hoek');
+var Lab = require('lab');
// Declare internals
// Test shortcuts
-var expect = Lab.expect;
-var before = Lab.before;
-var after = Lab.after;
-var describe = Lab.experiment;
-var it = Lab.test;
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
describe('Hawk', function () {
credentialsFunc('123456', function (err, credentials) {
var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
- expect(auth).to.exist;
+ expect(auth).to.exist();
Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
done();
});
credentialsFunc('123456', function (err, credentials) {
var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
- expect(auth).to.exist;
+ expect(auth).to.exist();
Hawk.server.authenticateMessage('example1.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Bad mac');
done();
});
credentialsFunc('123456', function (err, credentials) {
var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
- expect(auth).to.exist;
+ expect(auth).to.exist();
Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { localtimeOffsetMsec: 100000 }, function (err, credentials) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Stale timestamp');
done();
});
});
});
+ it('overrides timestampSkewSec', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials, localtimeOffsetMsec: 100000 });
+ expect(auth).to.exist();
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { timestampSkewSec: 500 }, function (err, credentials) {
+
+ expect(err).to.not.exist();
+ done();
+ });
+ });
+ });
+
it('should fail authorization on invalid authorization', function (done) {
credentialsFunc('123456', function (err, credentials) {
var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
- expect(auth).to.exist;
+ expect(auth).to.exist();
delete auth.id;
Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Invalid authorization');
done();
});
credentialsFunc('123456', function (err, credentials) {
var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
- expect(auth).to.exist;
+ expect(auth).to.exist();
Hawk.server.authenticateMessage('example.com', 8080, 'some message1', auth, credentialsFunc, {}, function (err, credentials) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Bad message hash');
done();
});
credentialsFunc('123456', function (err, credentials) {
var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
- expect(auth).to.exist;
+ expect(auth).to.exist();
Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, { nonceFunc: function (nonce, ts, callback) { callback (new Error('kaboom')); } }, function (err, credentials) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Invalid nonce');
done();
});
credentialsFunc('123456', function (err, credentials) {
var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
- expect(auth).to.exist;
+ expect(auth).to.exist();
var errFunc = function (id, callback) {
Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('kablooey');
done();
});
credentialsFunc('123456', function (err, credentials) {
var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
- expect(auth).to.exist;
+ expect(auth).to.exist();
var errFunc = function (id, callback) {
Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Unknown credentials');
done();
});
credentialsFunc('123456', function (err, credentials) {
var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
- expect(auth).to.exist;
+ expect(auth).to.exist();
var errFunc = function (id, callback) {
Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Invalid credentials');
done();
});
credentialsFunc('123456', function (err, credentials) {
var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
- expect(auth).to.exist;
+ expect(auth).to.exist();
var errFunc = function (id, callback) {
Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, errFunc, {}, function (err, credentials) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Unknown algorithm');
done();
});
credentialsFunc('123456', function (err, credentials) {
var auth = Hawk.client.message(null, 8080, 'some message', { credentials: credentials });
- expect(auth).to.not.exist;
+ expect(auth).to.not.exist();
done();
});
});
it('should fail on missing credentials', function (done) {
var auth = Hawk.client.message('example.com', 8080, 'some message', {});
- expect(auth).to.not.exist;
+ expect(auth).to.not.exist();
done();
});
var creds = Hoek.clone(credentials);
creds.algorithm = 'blah';
var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: creds });
- expect(auth).to.not.exist;
+ expect(auth).to.not.exist();
done();
});
});
// Load modules
-var Lab = require('lab');
-var Hoek = require('hoek');
+var Code = require('code');
var Hawk = require('../lib');
+var Hoek = require('hoek');
+var Lab = require('lab');
// Declare internals
// Test shortcuts
-var expect = Lab.expect;
-var before = Lab.before;
-var after = Lab.after;
-var describe = Lab.experiment;
-var it = Lab.test;
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
describe('Hawk', function () {
// Load modules
var Url = require('url');
-var Lab = require('lab');
+var Code = require('code');
var Hawk = require('../lib');
+var Lab = require('lab');
// Declare internals
// Test shortcuts
-var expect = Lab.expect;
-var before = Lab.before;
-var after = Lab.after;
-var describe = Lab.experiment;
-var it = Lab.test;
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
describe('Hawk', function () {
describe('#authenticate', function () {
- it('should parse a valid authentication header (sha1)', function (done) {
+ it('parses a valid authentication header (sha1)', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
done();
});
});
- it('should parse a valid authentication header (sha256)', function (done) {
+ it('parses a valid authentication header (sha256)', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353832234000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
done();
});
});
- it('should parse a valid authentication header (host override)', function (done) {
+ it('parses a valid authentication header (host override)', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { host: 'example.com', localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
done();
});
});
- it('should parse a valid authentication header (host port override)', function (done) {
+ it('parses a valid authentication header (host port override)', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { host: 'example.com', port: 8080, localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
done();
});
});
- it('should parse a valid authentication header (POST with payload)', function (done) {
+ it('parses a valid authentication header (POST with payload)', function (done) {
var req = {
method: 'POST',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1357926341000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
done();
});
});
- it('should fail on missing hash', function (done) {
+ it('errors on missing hash', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { payload: 'body', localtimeOffsetMsec: 1353832234000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Missing required payload hash');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing required payload hash');
done();
});
});
- it('should fail on a stale timestamp', function (done) {
+ it('errors on a stale timestamp', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Stale timestamp');
- var header = err.response.headers['WWW-Authenticate'];
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Stale timestamp');
+ var header = err.output.headers['WWW-Authenticate'];
var ts = header.match(/^Hawk ts\=\"(\d+)\"\, tsm\=\"([^\"]+)\"\, error=\"Stale timestamp\"$/);
var now = Hawk.utils.now();
expect(parseInt(ts[1], 10) * 1000).to.be.within(now - 1000, now + 1000);
});
});
- it('should fail on a replay', function (done) {
+ it('errors on a replay', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, options, function (err, credentials, artifacts) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
Hawk.server.authenticate(req, credentialsFunc, options, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Invalid nonce');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid nonce');
done();
});
});
});
- it('should fail on an invalid authentication header: wrong scheme', function (done) {
+ it('errors on an invalid authentication header: wrong scheme', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.not.exist;
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.not.exist();
done();
});
});
- it('should fail on an invalid authentication header: no scheme', function (done) {
+ it('errors on an invalid authentication header: no scheme', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Invalid header syntax');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid header syntax');
done();
});
});
- it('should fail on an missing authorization header', function (done) {
+ it('errors on an missing authorization header', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, {}, function (err, credentials, artifacts) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.isMissing).to.equal(true);
done();
});
});
- it('should fail on an missing host header', function (done) {
+ it('errors on an missing host header', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Invalid Host header');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid Host header');
done();
});
});
- it('should fail on an missing authorization attribute (id)', function (done) {
+ it('errors on an missing authorization attribute (id)', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Missing attributes');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing attributes');
done();
});
});
- it('should fail on an missing authorization attribute (ts)', function (done) {
+ it('errors on an missing authorization attribute (ts)', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Missing attributes');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing attributes');
done();
});
});
- it('should fail on an missing authorization attribute (nonce)', function (done) {
+ it('errors on an missing authorization attribute (nonce)', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Missing attributes');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing attributes');
done();
});
});
- it('should fail on an missing authorization attribute (mac)', function (done) {
+ it('errors on an missing authorization attribute (mac)', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Missing attributes');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing attributes');
done();
});
});
- it('should fail on an unknown authorization attribute', function (done) {
+ it('errors on an unknown authorization attribute', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Unknown attribute: x');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Unknown attribute: x');
done();
});
});
- it('should fail on an bad authorization header format', function (done) {
+ it('errors on an bad authorization header format', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Bad header format');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad header format');
done();
});
});
- it('should fail on an bad authorization attribute value', function (done) {
+ it('errors on an bad authorization attribute value', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Bad attribute value: id');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad attribute value: id');
done();
});
});
- it('should fail on an empty authorization attribute value', function (done) {
+ it('errors on an empty authorization attribute value', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Bad attribute value: id');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad attribute value: id');
done();
});
});
- it('should fail on duplicated authorization attribute key', function (done) {
+ it('errors on duplicated authorization attribute key', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Duplicate attribute: id');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Duplicate attribute: id');
done();
});
});
- it('should fail on an invalid authorization header format', function (done) {
+ it('errors on an invalid authorization header format', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Invalid header syntax');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid header syntax');
done();
});
});
- it('should fail on an bad host header (missing host)', function (done) {
+ it('errors on an bad host header (missing host)', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Invalid Host header');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid Host header');
done();
});
});
- it('should fail on an bad host header (pad port)', function (done) {
+ it('errors on an bad host header (pad port)', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Invalid Host header');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid Host header');
done();
});
});
- it('should fail on credentialsFunc error', function (done) {
+ it('errors on credentialsFunc error', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
+ expect(err).to.exist();
+ expect(err.message).to.equal('Unknown user');
+ done();
+ });
+ });
+
+ it('errors on credentialsFunc error (with credentials)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ var credentialsFunc = function (id, callback) {
+
+ return callback(new Error('Unknown user'), { some: 'value' });
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
expect(err.message).to.equal('Unknown user');
+ expect(credentials.some).to.equal('value');
done();
});
});
- it('should fail on missing credentials', function (done) {
+ it('errors on missing credentials', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Unknown credentials');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Unknown credentials');
done();
});
});
- it('should fail on invalid credentials', function (done) {
+ it('errors on invalid credentials (id)', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Invalid credentials');
- expect(err.response.payload.message).to.equal('An internal server error occurred');
+ expect(err.output.payload.message).to.equal('An internal server error occurred');
done();
});
});
- it('should fail on unknown credentials algorithm', function (done) {
+ it('errors on invalid credentials (key)', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?filter=a',
+ host: 'example.com',
+ port: 8080,
+ authorization: 'Hawk id="123", ts="1353788437", nonce="k3j4h2", mac="/qwS4UjfVWMcUyW6EEgUH4jlr7T/wuKe3dKijvTvSos=", ext="hello"'
+ };
+
+ var credentialsFunc = function (id, callback) {
+
+ var credentials = {
+ id: '23434d3q4d5345d',
+ user: 'steve'
+ };
+
+ return callback(null, credentials);
+ };
+
+ Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid credentials');
+ expect(err.output.payload.message).to.equal('An internal server error occurred');
+ done();
+ });
+ });
+
+ it('errors on unknown credentials algorithm', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Unknown algorithm');
- expect(err.response.payload.message).to.equal('An internal server error occurred');
+ expect(err.output.payload.message).to.equal('An internal server error occurred');
done();
});
});
- it('should fail on unknown bad mac', function (done) {
+ it('errors on unknown bad mac', function (done) {
var req = {
method: 'GET',
Hawk.server.authenticate(req, credentialsFunc, { localtimeOffsetMsec: 1353788437000 - Hawk.utils.now() }, function (err, credentials, artifacts) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Bad mac');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad mac');
done();
});
});
describe('#header', function () {
- it('should return an empty authorization header on missing options', function (done) {
+ it('generates header', function (done) {
- var header = Hawk.server.header();
- expect(header).to.equal('');
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(header).to.equal('Hawk mac=\"n14wVJK4cOxAytPUMc5bPezQzuJGl5n7MYXhFQgEKsE=\", hash=\"f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=\", ext=\"response-specific\"');
+ done();
+ });
+
+ it('generates header (empty payload)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var header = Hawk.server.header(credentials, artifacts, { payload: '', contentType: 'text/plain', ext: 'response-specific' });
+ expect(header).to.equal('Hawk mac=\"i8/kUBDx0QF+PpCtW860kkV/fa9dbwEoe/FpGUXowf0=\", hash=\"q/t+NNAkQZNlq/aAD6PlexImwQTxwgT2MahfTa9XRLA=\", ext=\"response-specific\"');
+ done();
+ });
+
+ it('generates header (pre calculated hash)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var options = { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' };
+ options.hash = Hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
+ var header = Hawk.server.header(credentials, artifacts, options);
+ expect(header).to.equal('Hawk mac=\"n14wVJK4cOxAytPUMc5bPezQzuJGl5n7MYXhFQgEKsE=\", hash=\"f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=\", ext=\"response-specific\"');
+ done();
+ });
+
+ it('generates header (null ext)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: null });
+ expect(header).to.equal('Hawk mac=\"6PrybJTJs20jsgBw5eilXpcytD8kUbaIKNYXL+6g0ns=\", hash=\"f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=\"');
done();
});
- it('should return an empty authorization header on missing credentials', function (done) {
+ it('errors on missing artifacts', function (done) {
- var header = Hawk.server.header(null, {});
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
+ };
+
+ var header = Hawk.server.header(credentials, null, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
expect(header).to.equal('');
done();
});
- it('should return an empty authorization header on invalid credentials', function (done) {
+ it('errors on invalid artifacts', function (done) {
var credentials = {
- key: '2983d45yun89q'
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'sha256',
+ user: 'steve'
};
- var header = Hawk.server.header(credentials);
+ var header = Hawk.server.header(credentials, 5, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
expect(header).to.equal('');
done();
});
- it('should return an empty authorization header on invalid algorithm', function (done) {
+ it('errors on missing credentials', function (done) {
var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
id: '123456'
};
+ var header = Hawk.server.header(null, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(header).to.equal('');
+ done();
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
var credentials = {
- key: '2983d45yun89q',
- algorithm: 'hmac-sha-0'
+ id: '123456',
+ algorithm: 'sha256',
+ user: 'steve'
};
- var header = Hawk.server.header(credentials, artifacts);
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
expect(header).to.equal('');
done();
});
+
+ it('errors on invalid algorithm', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
+ algorithm: 'x',
+ user: 'steve'
+ };
+
+ var artifacts = {
+ method: 'POST',
+ host: 'example.com',
+ port: '8080',
+ resource: '/resource/4?filter=a',
+ ts: '1398546787',
+ nonce: 'xUwusx',
+ hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
+ ext: 'some-app-data',
+ mac: 'dvIvMThwi28J61Jc3P0ryAhuKpanU63GXdx6hkmQkJA=',
+ id: '123456'
+ };
+
+ var header = Hawk.server.header(credentials, artifacts, { payload: 'some reply', contentType: 'text/plain', ext: 'response-specific' });
+ expect(header).to.equal('');
+ done();
+ });
+ });
+
+ describe('#authenticateMessage', function () {
+
+ it('errors on invalid authorization (ts)', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
+ delete auth.ts;
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid authorization');
+ done();
+ });
+ });
+ });
+
+ it('errors on invalid authorization (nonce)', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
+ delete auth.nonce;
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid authorization');
+ done();
+ });
+ });
+ });
+
+ it('errors on invalid authorization (hash)', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
+ delete auth.hash;
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, credentialsFunc, {}, function (err, credentials) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('Invalid authorization');
+ done();
+ });
+ });
+ });
+
+ it('errors with credentials', function (done) {
+
+ credentialsFunc('123456', function (err, credentials) {
+
+ var auth = Hawk.client.message('example.com', 8080, 'some message', { credentials: credentials });
+
+ Hawk.server.authenticateMessage('example.com', 8080, 'some message', auth, function (id, callback) { callback(new Error('something'), { some: 'value' }); }, {}, function (err, credentials) {
+
+ expect(err).to.exist();
+ expect(err.message).to.equal('something');
+ expect(credentials.some).to.equal('value');
+ done();
+ });
+ });
+ });
+ });
+
+ describe('#authenticatePayloadHash', function () {
+
+ it('checks payload hash', function (done) {
+
+ expect(Hawk.server.authenticatePayloadHash('abcdefg', { hash: 'abcdefg' })).to.equal(true);
+ expect(Hawk.server.authenticatePayloadHash('1234567', { hash: 'abcdefg' })).to.equal(false);
+ done();
+ });
});
});
});
// Load modules
var Http = require('http');
-var Lab = require('lab');
+var Url = require('url');
+var Code = require('code');
var Hawk = require('../lib');
+var Hoek = require('hoek');
+var Lab = require('lab');
// Declare internals
// Test shortcuts
-var expect = Lab.expect;
-var before = Lab.before;
-var after = Lab.after;
-var describe = Lab.experiment;
-var it = Lab.test;
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
describe('Hawk', function () {
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(attributes.ext).to.equal('some-app-data');
done();
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
done();
});
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(attributes.ext).to.equal('some-app-data');
done();
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(attributes.ext).to.equal('some-app-data');
done();
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.not.exist;
+ expect(err).to.not.exist();
expect(credentials.user).to.equal('steve');
expect(attributes.ext).to.equal('some-app-data');
done();
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Multiple authentications');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Multiple authentications');
done();
});
});
var bewit = credentials.id + '\\' + exp + '\\' + mac + '\\' + ext;
- req.url += '&bewit=' + Hawk.utils.base64urlEncode(bewit);
+ req.url += '&bewit=' + Hoek.base64urlEncode(bewit);
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Invalid method');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid method');
done();
});
});
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Invalid Host header');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid Host header');
done();
});
});
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Empty bewit');
- expect(err.isMissing).to.not.exist;
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Empty bewit');
+ expect(err.isMissing).to.not.exist();
done();
});
});
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Invalid bewit encoding');
- expect(err.isMissing).to.not.exist;
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid bewit encoding');
+ expect(err.isMissing).to.not.exist();
done();
});
});
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.not.exist;
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.not.exist();
expect(err.isMissing).to.equal(true);
done();
});
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Invalid bewit structure');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Invalid bewit structure');
done();
});
});
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Missing bewit attributes');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing bewit attributes');
+ done();
+ });
+ });
+
+ it('should fail on missing bewit id attribute', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=XDQ1NTIxNDc2MjJcK0JFbFhQMXhuWjcvd1Nrbm1ldGhlZm5vUTNHVjZNSlFVRHk4NWpTZVJ4VT1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Missing bewit attributes');
done();
});
});
Hawk.uri.authenticate(req, credentialsFunc, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Access expired');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Access expired');
done();
});
});
Hawk.uri.authenticate(req, function (id, callback) { callback(Hawk.error.badRequest('Boom')); }, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Boom');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Boom');
+ done();
+ });
+ });
+
+ it('should fail on credentials function error with credentials', function (done) {
+
+ var req = {
+ method: 'GET',
+ url: '/resource/4?bewit=MTIzNDU2XDQ1MDk5OTE3MTlcTUE2eWkwRWRwR0pEcWRwb0JkYVdvVDJrL0hDSzA1T0Y3MkhuZlVmVy96Zz1cc29tZS1hcHAtZGF0YQ',
+ host: 'example.com',
+ port: 8080
+ };
+
+ Hawk.uri.authenticate(req, function (id, callback) { callback(Hawk.error.badRequest('Boom'), { some: 'value' }); }, {}, function (err, credentials, attributes) {
+
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Boom');
+ expect(credentials.some).to.equal('value');
done();
});
});
Hawk.uri.authenticate(req, function (id, callback) { callback(null, null); }, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Unknown credentials');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Unknown credentials');
done();
});
});
Hawk.uri.authenticate(req, function (id, callback) { callback(null, {}); }, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Invalid credentials');
done();
});
Hawk.uri.authenticate(req, function (id, callback) { callback(null, { key: 'xxx', algorithm: 'xxx' }); }, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
+ expect(err).to.exist();
expect(err.message).to.equal('Unknown algorithm');
done();
});
Hawk.uri.authenticate(req, function (id, callback) { callback(null, { key: 'xxx', algorithm: 'sha256' }); }, {}, function (err, credentials, attributes) {
- expect(err).to.exist;
- expect(err.response.payload.message).to.equal('Bad mac');
+ expect(err).to.exist();
+ expect(err.output.payload.message).to.equal('Bad mac');
done();
});
});
describe('#getBewit', function () {
- it('should return a valid bewit value', function (done) {
+ it('returns a valid bewit value', function (done) {
var credentials = {
id: '123456',
done();
});
- it('should return an empty bewit on invalid credentials', function (done) {
+ it('returns a valid bewit value (explicit port)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit('https://example.com:8080/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcaFpiSjNQMmNLRW80a3kwQzhqa1pBa1J5Q1p1ZWc0V1NOYnhWN3ZxM3hIVT1ceGFuZHlhbmR6');
+ done();
+ });
+
+ it('returns a valid bewit value (null ext)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: null });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdcSUdZbUxnSXFMckNlOEN4dktQczRKbFdJQStValdKSm91d2dBUmlWaENBZz1c');
+ done();
+ });
+
+ it('returns a valid bewit value (parsed uri)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit(Url.parse('https://example.com/somewhere/over/the/rainbow'), { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('MTIzNDU2XDEzNTY0MjA3MDdca3NjeHdOUjJ0SnBQMVQxekRMTlBiQjVVaUtJVTl0T1NKWFRVZEc3WDloOD1ceGFuZHlhbmR6');
+ done();
+ });
+
+ it('errors on invalid options', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', 4);
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on missing uri', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit('', { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid uri', function (done) {
+
+ var credentials = {
+ id: '123456',
+ key: '2983d45yun89q',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit(5, { credentials: credentials, ttlSec: 300, localtimeOffsetMsec: 1356420407232 - Hawk.utils.now(), ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid credentials (id)', function (done) {
var credentials = {
key: '2983d45yun89q',
done();
});
- it('should return an empty bewit on invalid algorithm', function (done) {
+ it('errors on missing credentials', function (done) {
+
+ var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { ttlSec: 3000, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid credentials (key)', function (done) {
+
+ var credentials = {
+ id: '123456',
+ algorithm: 'sha256'
+ };
+
+ var bewit = Hawk.uri.getBewit('https://example.com/somewhere/over/the/rainbow', { credentials: credentials, ttlSec: 3000, ext: 'xandyandz' });
+ expect(bewit).to.equal('');
+ done();
+ });
+
+ it('errors on invalid algorithm', function (done) {
var credentials = {
id: '123456',
done();
});
- it('should return an empty bewit on missing options', function (done) {
+ it('errors on missing options', function (done) {
var credentials = {
id: '123456',
// Load modules
-var Lab = require('lab');
+var Code = require('code');
var Hawk = require('../lib');
+var Lab = require('lab');
var Package = require('../package.json');
// Test shortcuts
-var expect = Lab.expect;
-var before = Lab.before;
-var after = Lab.after;
-var describe = Lab.experiment;
-var it = Lab.test;
+var lab = exports.lab = Lab.script();
+var describe = lab.experiment;
+var it = lab.test;
+var expect = Code.expect;
describe('Hawk', function () {
it('returns a hawk 401', function (done) {
- expect(Hawk.utils.unauthorized('kaboom').response.headers['WWW-Authenticate']).to.equal('Hawk error="kaboom"');
+ expect(Hawk.utils.unauthorized('kaboom').output.headers['WWW-Authenticate']).to.equal('Hawk error="kaboom"');
done();
});
});
## Usage
Note the example below signs a request with the same key/cert used to start an
-HTTP server. This is almost certainly not what you actaully want, but is just
+HTTP server. This is almost certainly not what you actually want, but is just
used to illustrate the API calls; you will need to provide your own key
management in addition to this library.
### Client
- var fs = require('fs');
- var https = require('https');
- var httpSignature = require('http-signature');
+```js
+var fs = require('fs');
+var https = require('https');
+var httpSignature = require('http-signature');
- var key = fs.readFileSync('./key.pem', 'ascii');
+var key = fs.readFileSync('./key.pem', 'ascii');
- var options = {
- host: 'localhost',
- port: 8443,
- path: '/',
- method: 'GET',
- headers: {}
- };
+var options = {
+ host: 'localhost',
+ port: 8443,
+ path: '/',
+ method: 'GET',
+ headers: {}
+};
- // Adds a 'Date' header in, signs it, and adds the
- // 'Authorization' header in.
- var req = https.request(options, function(res) {
- console.log(res.statusCode);
- });
+// Adds a 'Date' header in, signs it, and adds the
+// 'Authorization' header in.
+var req = https.request(options, function(res) {
+ console.log(res.statusCode);
+});
- httpSignature.sign(req, {
- key: key,
- keyId: './cert.pem'
- });
+httpSignature.sign(req, {
+ key: key,
+ keyId: './cert.pem'
+});
- req.end();
+req.end();
+```
### Server
- var fs = require('fs');
- var https = require('https');
- var httpSignature = require('http-signature');
-
- var options = {
- key: fs.readFileSync('./key.pem'),
- cert: fs.readFileSync('./cert.pem')
- };
-
- https.createServer(options, function (req, res) {
- var rc = 200;
- var parsed = httpSignature.parseRequest(req);
- var pub = fs.readFileSync(parsed.keyId, 'ascii');
- if (!httpSignature.verifySignature(parsed, pub))
- rc = 401;
-
- res.writeHead(rc);
- res.end();
- }).listen(8443);
+```js
+var fs = require('fs');
+var https = require('https');
+var httpSignature = require('http-signature');
+
+var options = {
+ key: fs.readFileSync('./key.pem'),
+ cert: fs.readFileSync('./cert.pem')
+};
+
+https.createServer(options, function (req, res) {
+ var rc = 200;
+ var parsed = httpSignature.parseRequest(req);
+ var pub = fs.readFileSync(parsed.keyId, 'ascii');
+ if (!httpSignature.verifySignature(parsed, pub))
+ rc = 401;
+
+ res.writeHead(rc);
+ res.end();
+}).listen(8443);
+```
## Installation
requests. RFC2617 (HTTP Authentication) defines Basic and Digest authentication
mechanisms, and RFC5246 (TLS 1.2) defines client-auth, both of which are widely
employed on the Internet today. However, it is common place that the burdens of
-PKI prevent web service operators from deploying that methodoloy, and so many
+PKI prevent web service operators from deploying that methodology, and so many
fall back to Basic authentication, which has poor security characteristics.
Additionally, OAuth provides a fully-specified alternative for authorization
1. If the header name is not `request-line` then append the lowercased header
name followed with an ASCII colon `:` and an ASCII space ` `.
-2. If the header name is `request-line` then appened the HTTP request line,
+2. If the header name is `request-line` then append the HTTP request line,
otherwise append the header value.
3. If value is not the last value then append an ASCII newline `\n`. The string
MUST NOT include a trailing ASCII newline.
# Example Requests
-All requests refer to the following request (body ommitted):
+All requests refer to the following request (body omitted):
POST /foo HTTP/1.1
Host: example.org
Note the default parameterization of the `Signature` scheme is only safe if all
requests are carried over a secure transport (i.e., TLS). Sending the default
scheme over a non-secure transport will leave the request vulnerable to
-spoofing, tampering, replay/repudiaton, and integrity violations (if using the
+spoofing, tampering, replay/repudiation, and integrity violations (if using the
STRIDE threat-modeling methodology).
## Insecure Transports
## Nonces
Nonces are out of scope for this document simply because many service providers
-fail to implement them correctly, or do not adopt security specfiications
+fail to implement them correctly, or do not adopt security specifications
because of the infrastructure complexity. Given the `header` parameterization,
a service provider is fully enabled to add nonce semantics into this scheme by
using something like an `x-request-nonce` header, and ensuring it is signed
The following test data uses the RSA (2048b) keys, which we will refer
to as `keyId=Test` in the following samples:
- -----BEGIN PUBLIC KEY-----
- MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCFENGw33yGihy92pDjZQhl0C3
- 6rPJj+CvfSC8+q28hxA161QFNUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6
- Z4UMR7EOcpfdUE9Hf3m/hs+FUR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJw
- oYi+1hqp1fIekaxsyQIDAQAB
- -----END PUBLIC KEY-----
+ -----BEGIN PUBLIC KEY-----
+ MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDCFENGw33yGihy92pDjZQhl0C3
+ 6rPJj+CvfSC8+q28hxA161QFNUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6
+ Z4UMR7EOcpfdUE9Hf3m/hs+FUR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJw
+ oYi+1hqp1fIekaxsyQIDAQAB
+ -----END PUBLIC KEY-----
-----BEGIN RSA PRIVATE KEY-----
MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF
The Authorization header would be:
- Authorization: Signature keyId="Test",algorithm="rsa-sha256",signature="JldXnt8W9t643M2Sce10gqCh/+E7QIYLiI+bSjnFBGCti7s+mPPvOjVb72sbd1FjeOUwPTDpKbrQQORrm+xBYfAwCxF3LBSSzORvyJ5nRFCFxfJ3nlQD6Kdxhw8wrVZX5nSem4A/W3C8qH5uhFTRwF4ruRjh+ENHWuovPgO/HGQ="
+ Authorization: Signature keyId="Test",algorithm="rsa-sha256",signature="ATp0r26dbMIxOopqw0OfABDT7CKMIoENumuruOtarj8n/97Q3htHFYpH8yOSQk3Z5zh8UxUym6FYTb5+A0Nz3NRsXJibnYi7brE/4tx5But9kkFGzG+xpUmimN4c3TMN7OFH//+r8hBf7BT9/GmHDUVZT2JzWGLZES2xDOUuMtA="
### All Headers
The Authorization header would be:
- Authorization: Signature keyId="Test",algorithm="rsa-sha256",headers="request-line host date content-type content-md5 content-length",signature="Gm7W/r+e90REDpWytALMrft4MqZxCmslOTOvwJX17ViEBA5E65QqvWI0vIH3l/vSsGiaMVmuUgzYsJLYMLcm5dGrv1+a+0fCoUdVKPZWHyImQEqpLkopVwqEH67LVECFBqFTAKlQgBn676zrfXQbb+b/VebAsNUtvQMe6cTjnDY="
+ Authorization: Signature keyId="Test",algorithm="rsa-sha256",headers="request-line host date content-type content-md5 content-length",signature="H/AaTDkJvLELy4i1RujnKlS6dm8QWiJvEpn9cKRMi49kKF+mohZ15z1r+mF+XiKS5kOOscyS83olfBtsVhYjPg2Ei3/D9D4Mvb7bFm9IaLJgYTFFuQCghrKQQFPiqJN320emjHxFowpIm1BkstnEU7lktH/XdXVBo8a6Uteiztw="
sshKeyToPEM: util.sshKeyToPEM,
sshKeyFingerprint: util.fingerprint,
+ pemToRsaSSHKey: util.pemToRsaSSHKey,
verify: verify.verifySignature,
verifySignature: verify.verifySignature
}
stringToSign += h + ': ' + value;
} else {
- value =
stringToSign +=
request.method + ' ' + request.path + ' HTTP/' + options.httpVersion;
}
}
return fp;
- }
-
+ },
+ /**
+ * Converts a PKGCS#8 PEM file to an OpenSSH public key (rsa)
+ *
+ * The reverse of the above function.
+ */
+ pemToRsaSSHKey: function pemToRsaSSHKey(pem, comment) {
+ assert.equal('string', typeof pem, 'typeof pem');
+
+ // chop off the BEGIN PUBLIC KEY and END PUBLIC KEY portion
+ var cleaned = pem.split('\n').slice(1, -2).join('');
+
+ var buf = new Buffer(cleaned, 'base64');
+
+ var der = new asn1.BerReader(buf);
+
+ der.readSequence();
+ der.readSequence();
+
+ var oid = der.readOID();
+ assert.equal(oid, '1.2.840.113549.1.1.1', 'pem not in RSA format');
+
+ // Null -- XXX this probably isn't good practice
+ der.readByte();
+ der.readByte();
+
+ // bit string sequence
+ der.readSequence(0x03);
+ der.readByte();
+ der.readSequence();
+
+ // modulus
+ assert.equal(der.peek(), asn1.Ber.Integer, 'modulus not an integer');
+ der._offset = der.readLength(der.offset + 1);
+ var modulus = der._buf.slice(der.offset, der.offset + der.length);
+ der._offset += der.length;
+
+ // exponent
+ assert.equal(der.peek(), asn1.Ber.Integer, 'exponent not an integer');
+ der._offset = der.readLength(der.offset + 1);
+ var exponent = der._buf.slice(der.offset, der.offset + der.length);
+ der._offset += der.length;
+
+ // now, make the key
+ var type = new Buffer('ssh-rsa');
+ var buffer = new Buffer(4 + type.length + 4 + modulus.length + 4 + exponent.length);
+ var i = 0;
+ buffer.writeUInt32BE(type.length, i); i += 4;
+ type.copy(buffer, i); i += type.length;
+ buffer.writeUInt32BE(exponent.length, i); i += 4;
+ exponent.copy(buffer, i); i += exponent.length;
+ buffer.writeUInt32BE(modulus.length, i); i += 4;
+ modulus.copy(buffer, i); i += modulus.length;
+
+ var s = type.toString() + ' ' + buffer.toString('base64') + ' ' + (comment || '');
+ return s;
+ }
};
"pretest": "which gjslint; if [[ \"$?\" = 0 ]] ; then gjslint --nojsdoc -r lib -r tst; else echo \"Missing gjslint. Skipping lint\"; fi",
"test": "tap ./tst"
},
- "readme": "node-asn1 is a library for encoding and decoding ASN.1 datatypes in pure JS.\nCurrently BER encoding is supported; at some point I'll likely have to do DER.\n\n## Usage\n\nMostly, if you're *actually* needing to read and write ASN.1, you probably don't\nneed this readme to explain what and why. If you have no idea what ASN.1 is,\nsee this: ftp://ftp.rsa.com/pub/pkcs/ascii/layman.asc\n\nThe source is pretty much self-explanatory, and has read/write methods for the\ncommon types out there.\n\n### Decoding\n\nThe following reads an ASN.1 sequence with a boolean.\n\n var Ber = require('asn1').Ber;\n\n var reader = new Ber.Reader(new Buffer([0x30, 0x03, 0x01, 0x01, 0xff]));\n\n reader.readSequence();\n console.log('Sequence len: ' + reader.length);\n if (reader.peek() === Ber.Boolean)\n console.log(reader.readBoolean());\n\n### Encoding\n\nThe following generates the same payload as above.\n\n var Ber = require('asn1').Ber;\n\n var writer = new Ber.Writer();\n\n writer.startSequence();\n writer.writeBoolean(true);\n writer.endSequence();\n\n console.log(writer.buffer);\n\n## Installation\n\n npm install asn1\n\n## License\n\nMIT.\n\n## Bugs\n\nSee <https://github.com/mcavage/node-asn1/issues>.\n",
- "readmeFilename": "README.md",
- "bugs": {
- "url": "https://github.com/mcavage/node-asn1/issues"
+ "_npmUser": {
+ "name": "mcavage",
+ "email": "mcavage@gmail.com"
},
- "homepage": "https://github.com/mcavage/node-asn1",
"_id": "asn1@0.1.11",
+ "_engineSupported": true,
+ "_npmVersion": "1.1.0-beta-4",
+ "_nodeVersion": "v0.6.6",
+ "_defaultsLoaded": true,
+ "dist": {
+ "shasum": "559be18376d08a4ec4dbe80877d27818639b2df7",
+ "tarball": "http://registry.npmjs.org/asn1/-/asn1-0.1.11.tgz"
+ },
+ "maintainers": [
+ {
+ "name": "mcavage",
+ "email": "mcavage@gmail.com"
+ }
+ ],
+ "directories": {},
"_shasum": "559be18376d08a4ec4dbe80877d27818639b2df7",
"_resolved": "https://registry.npmjs.org/asn1/-/asn1-0.1.11.tgz",
- "_from": "asn1@0.1.11"
+ "_from": "asn1@0.1.11",
+ "bugs": {
+ "url": "https://github.com/mcavage/node-asn1/issues"
+ },
+ "readme": "ERROR: No README data found!",
+ "homepage": "https://github.com/mcavage/node-asn1"
}
///--- Globals
var NDEBUG = process.env.NODE_NDEBUG || false;
+var UUID_REGEXP = /^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$/;
}
+function _instanceof(arg, type, name, stackFunc) {
+ if (!NDEBUG) {
+ name = name || type;
+ stackFunc = stackFunc || _instanceof.caller;
+
+ if (!(arg instanceof type)) {
+ throw new assert.AssertionError({
+ message: _(TYPE_REQUIRED, name, type.name),
+ actual: _getClass(arg),
+ expected: type.name,
+ operator: 'instanceof',
+ stackStartFunction: stackFunc
+ });
+ }
+ }
+}
+
+function _getClass(object) {
+ return (Object.prototype.toString.call(object).slice(8, -1));
+};
+
+
///--- API
function buffer(arg, name) {
if (!Buffer.isBuffer(arg)) {
throw new assert.AssertionError({
- message: _(TYPE_REQUIRED, name, type),
+ message: _(TYPE_REQUIRED, name || '', 'Buffer'),
actual: typeof (arg),
expected: 'buffer',
operator: 'Buffer.isBuffer',
function number(arg, name) {
_assert(arg, 'number', name);
+ if (!NDEBUG && (isNaN(arg) || !isFinite(arg))) {
+ throw new assert.AssertionError({
+ message: _(TYPE_REQUIRED, name, 'number'),
+ actual: arg,
+ expected: 'number',
+ operator: 'isNaN',
+ stackStartFunction: number
+ });
+ }
}
function stream(arg, name) {
- if (!(arg instanceof Stream)) {
- throw new assert.AssertionError({
- message: _(TYPE_REQUIRED, name, type),
- actual: typeof (arg),
- expected: 'Stream',
- operator: 'instanceof',
- stackStartFunction: buffer
- });
- }
+ _instanceof(arg, Stream, name);
+}
+
+
+function date(arg, name) {
+ _instanceof(arg, Date, name);
+}
+
+function regexp(arg, name) {
+ _instanceof(arg, RegExp, name);
}
}
+function uuid(arg, name) {
+ string(arg, name);
+ if (!NDEBUG && !UUID_REGEXP.test(arg)) {
+ throw new assert.AssertionError({
+ message: _(TYPE_REQUIRED, name, 'uuid'),
+ actual: 'string',
+ expected: 'uuid',
+ operator: 'test',
+ stackStartFunction: uuid
+ });
+ }
+}
+
///--- Exports
module.exports = {
bool: bool,
buffer: buffer,
+ date: date,
func: func,
number: number,
object: object,
+ regexp: regexp,
stream: stream,
- string: string
+ string: string,
+ uuid: uuid
};
},
"name": "assert-plus",
"description": "Extra assertions on top of node's assert module",
- "version": "0.1.2",
+ "version": "0.1.5",
"main": "./assert.js",
- "dependencies": {},
"devDependencies": {},
"optionalDependencies": {},
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/mcavage/node-assert-plus.git"
+ },
"engines": {
- "node": ">=0.6"
+ "node": ">=0.8"
+ },
+ "bugs": {
+ "url": "https://github.com/mcavage/node-assert-plus/issues"
+ },
+ "dependencies": {},
+ "_id": "assert-plus@0.1.5",
+ "dist": {
+ "shasum": "ee74009413002d84cec7219c6ac811812e723160",
+ "tarball": "http://registry.npmjs.org/assert-plus/-/assert-plus-0.1.5.tgz"
+ },
+ "_from": "assert-plus@>=0.1.5 <0.2.0",
+ "_npmVersion": "1.3.11",
+ "_npmUser": {
+ "name": "mcavage",
+ "email": "mcavage@gmail.com"
},
- "readme": "# node-assert-plus\n\nThis library is a super small wrapper over node's assert module that has two\nthings: (1) the ability to disable assertions with the environment variable\nNODE_NDEBUG, and (2) some API wrappers for argument testing. Like\n`assert.string(myArg, 'myArg')`. As a simple example, most of my code looks\nlike this:\n\n var assert = require('assert-plus');\n\n function fooAccount(options, callback) {\n\t assert.object(options, 'options');\n\t\tassert.number(options.id, 'options.id);\n\t\tassert.bool(options.isManager, 'options.isManager');\n\t\tassert.string(options.name, 'options.name');\n\t\tassert.arrayOfString(options.email, 'options.email');\n\t\tassert.func(callback, 'callback');\n\n // Do stuff\n\t\tcallback(null, {});\n }\n\n# API\n\nAll methods that *aren't* part of node's core assert API are simply assumed to\ntake an argument, and then a string 'name' that's not a message; `AssertionError`\nwill be thrown if the assertion fails with a message like:\n\n AssertionError: foo (string) is required\n\tat test (/home/mark/work/foo/foo.js:3:9)\n\tat Object.<anonymous> (/home/mark/work/foo/foo.js:15:1)\n\tat Module._compile (module.js:446:26)\n\tat Object..js (module.js:464:10)\n\tat Module.load (module.js:353:31)\n\tat Function._load (module.js:311:12)\n\tat Array.0 (module.js:484:10)\n\tat EventEmitter._tickCallback (node.js:190:38)\n\nfrom:\n\n function test(foo) {\n\t assert.string(foo, 'foo');\n }\n\nThere you go. You can check that arrays are of a homogenous type with `Arrayof$Type`:\n\n function test(foo) {\n\t assert.arrayOfString(foo, 'foo');\n }\n\nYou can assert IFF an argument is not `undefined` (i.e., an optional arg):\n\n assert.optionalString(foo, 'foo');\n\nLastly, you can opt-out of assertion checking altogether by setting the\nenvironment variable `NODE_NDEBUG=1`. This is pseudo-useful if you have\nlots of assertions, and don't want to pay `typeof ()` taxes to v8 in\nproduction.\n\nThe complete list of APIs is:\n\n* assert.bool\n* assert.buffer\n* assert.func\n* assert.number\n* assert.object\n* assert.string\n* assert.arrayOfBool\n* assert.arrayOfFunc\n* assert.arrayOfNumber\n* assert.arrayOfObject\n* assert.arrayOfString\n* assert.optionalBool\n* assert.optionalBuffer\n* assert.optionalFunc\n* assert.optionalNumber\n* assert.optionalObject\n* assert.optionalString\n* assert.optionalArrayOfBool\n* assert.optionalArrayOfFunc\n* assert.optionalArrayOfNumber\n* assert.optionalArrayOfObject\n* assert.optionalArrayOfString\n* assert.AssertionError\n* assert.fail\n* assert.ok\n* assert.equal\n* assert.notEqual\n* assert.deepEqual\n* assert.notDeepEqual\n* assert.strictEqual\n* assert.notStrictEqual\n* assert.throws\n* assert.doesNotThrow\n* assert.ifError\n\n# Installation\n\n npm install assert-plus\n\n## License\n\nThe MIT License (MIT)\nCopyright (c) 2012 Mark Cavage\n\nPermission is hereby granted, free of charge, to any person obtaining a copy of\nthis software and associated documentation files (the \"Software\"), to deal in\nthe Software without restriction, including without limitation the rights to\nuse, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of\nthe Software, and to permit persons to whom the Software is furnished to do so,\nsubject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n\n## Bugs\n\nSee <https://github.com/mcavage/node-assert-plus/issues>.\n",
- "readmeFilename": "README.md",
- "_id": "assert-plus@0.1.2",
- "_shasum": "d93ffdbb67ac5507779be316a7d65146417beef8",
- "_resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-0.1.2.tgz",
- "_from": "assert-plus@0.1.2",
+ "maintainers": [
+ {
+ "name": "mcavage",
+ "email": "mcavage@gmail.com"
+ }
+ ],
+ "directories": {},
+ "_shasum": "ee74009413002d84cec7219c6ac811812e723160",
+ "_resolved": "https://registry.npmjs.org/assert-plus/-/assert-plus-0.1.5.tgz",
+ "readme": "ERROR: No README data found!",
+ "homepage": "https://github.com/mcavage/node-assert-plus",
"scripts": {}
}
would be issue 42. Each issue can be found at:
https://github.com/rmustacc/node-ctype/issues/%d.
-CTYPE v0.5.2
+v0.5.3
+CTYPE-50 Release 0.5.3
+Contributed by Nick Schonning:
+CTYPE-49 Add repository section to package.json
+Contributed by Jonathan Ong:
+CTYPE-48 Create .npmignore
+
+v0.5.2
CTYPE-46 Release 0.5.2
CTYPE-45 error in setEndian logic
{
"name": "ctype",
- "version": "0.5.2",
+ "version": "0.5.3",
"description": "read and write binary structures and data types",
"homepage": "https://github.com/rmustacc/node-ctype",
"author": {
"node": ">= 0.4"
},
"main": "ctype.js",
- "_id": "ctype@0.5.2",
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/rmustacc/node-ctype.git"
+ },
+ "_id": "ctype@0.5.3",
"dist": {
- "shasum": "fe8091d468a373a0b0c9ff8bbfb3425c00973a1d",
- "tarball": "http://registry.npmjs.org/ctype/-/ctype-0.5.2.tgz"
+ "shasum": "82c18c2461f74114ef16c135224ad0b9144ca12f",
+ "tarball": "http://registry.npmjs.org/ctype/-/ctype-0.5.3.tgz"
},
"_npmVersion": "1.1.59",
"_npmUser": {
}
],
"directories": {},
- "_shasum": "fe8091d468a373a0b0c9ff8bbfb3425c00973a1d",
- "_resolved": "https://registry.npmjs.org/ctype/-/ctype-0.5.2.tgz",
- "_from": "ctype@0.5.2",
+ "_shasum": "82c18c2461f74114ef16c135224ad0b9144ca12f",
+ "_resolved": "https://registry.npmjs.org/ctype/-/ctype-0.5.3.tgz",
+ "_from": "ctype@0.5.3",
+ "bugs": {
+ "url": "https://github.com/rmustacc/node-ctype/issues"
+ },
"readme": "ERROR: No README data found!",
"scripts": {}
}
+++ /dev/null
-{ "metadata":
- {
- "ctf2json_version": "1.0",
- "created_at": 1316563626,
- "derived_from": "/lib/libc.so",
- "ctf_version": 2,
- "requested_types": [ "float" ]
- },
-"data":
- [
- { "name": "float", "float": { "length": 4 } }
- ]
-}
+++ /dev/null
-{ "metadata":
- {
- "ctf2json_version": "1.0",
- "created_at": 1316563631,
- "derived_from": "/lib/libc.so",
- "ctf_version": 2,
- "requested_types": [ "int" ]
- },
-"data":
- [
- { "name": "int", "integer": { "length": 4, "signed": true } }
- ]
-}
+++ /dev/null
-{ "metadata":
- {
- "ctf2json_version": "1.0",
- "created_at": 1316563573,
- "derived_from": "/lib/libc.so",
- "ctf_version": 2,
- "requested_types": [ "psinfo_t" ]
- },
-"data":
- [
- { "name": "int", "integer": { "length": 4, "signed": true } },
- { "name": "char", "integer": { "length": 1, "signed": true } },
- { "name": "unsigned short", "integer": { "length": 2, "signed": false } },
- { "name": "long", "integer": { "length": 4, "signed": true } },
- { "name": "unsigned", "integer": { "length": 4, "signed": false } },
- { "name": "size_t", "typedef": "unsigned" },
- { "name": "unsigned long", "integer": { "length": 4, "signed": false } },
- { "name": "time_t", "typedef": "long" },
- { "name": "struct timespec", "struct": [
- { "name": "tv_sec", "type": "time_t" },
- { "name": "tv_nsec", "type": "long" }
- ] },
- { "name": "zoneid_t", "typedef": "long" },
- { "name": "taskid_t", "typedef": "long" },
- { "name": "dev_t", "typedef": "unsigned long" },
- { "name": "uid_t", "typedef": "unsigned" },
- { "name": "gid_t", "typedef": "unsigned" },
- { "name": "timestruc_t", "typedef": "struct timespec" },
- { "name": "short", "integer": { "length": 2, "signed": true } },
- { "name": "projid_t", "typedef": "long" },
- { "name": "ushort_t", "typedef": "unsigned short" },
- { "name": "poolid_t", "typedef": "long" },
- { "name": "uintptr_t", "typedef": "unsigned" },
- { "name": "id_t", "typedef": "long" },
- { "name": "pid_t", "typedef": "long" },
- { "name": "processorid_t", "typedef": "int" },
- { "name": "psetid_t", "typedef": "int" },
- { "name": "struct lwpsinfo", "struct": [
- { "name": "pr_flag", "type": "int" },
- { "name": "pr_lwpid", "type": "id_t" },
- { "name": "pr_addr", "type": "uintptr_t" },
- { "name": "pr_wchan", "type": "uintptr_t" },
- { "name": "pr_stype", "type": "char" },
- { "name": "pr_state", "type": "char" },
- { "name": "pr_sname", "type": "char" },
- { "name": "pr_nice", "type": "char" },
- { "name": "pr_syscall", "type": "short" },
- { "name": "pr_oldpri", "type": "char" },
- { "name": "pr_cpu", "type": "char" },
- { "name": "pr_pri", "type": "int" },
- { "name": "pr_pctcpu", "type": "ushort_t" },
- { "name": "pr_pad", "type": "ushort_t" },
- { "name": "pr_start", "type": "timestruc_t" },
- { "name": "pr_time", "type": "timestruc_t" },
- { "name": "pr_clname", "type": "char [8]" },
- { "name": "pr_name", "type": "char [16]" },
- { "name": "pr_onpro", "type": "processorid_t" },
- { "name": "pr_bindpro", "type": "processorid_t" },
- { "name": "pr_bindpset", "type": "psetid_t" },
- { "name": "pr_lgrp", "type": "int" },
- { "name": "pr_filler", "type": "int [4]" }
- ] },
- { "name": "lwpsinfo_t", "typedef": "struct lwpsinfo" },
- { "name": "struct psinfo", "struct": [
- { "name": "pr_flag", "type": "int" },
- { "name": "pr_nlwp", "type": "int" },
- { "name": "pr_pid", "type": "pid_t" },
- { "name": "pr_ppid", "type": "pid_t" },
- { "name": "pr_pgid", "type": "pid_t" },
- { "name": "pr_sid", "type": "pid_t" },
- { "name": "pr_uid", "type": "uid_t" },
- { "name": "pr_euid", "type": "uid_t" },
- { "name": "pr_gid", "type": "gid_t" },
- { "name": "pr_egid", "type": "gid_t" },
- { "name": "pr_addr", "type": "uintptr_t" },
- { "name": "pr_size", "type": "size_t" },
- { "name": "pr_rssize", "type": "size_t" },
- { "name": "pr_pad1", "type": "size_t" },
- { "name": "pr_ttydev", "type": "dev_t" },
- { "name": "pr_pctcpu", "type": "ushort_t" },
- { "name": "pr_pctmem", "type": "ushort_t" },
- { "name": "pr_start", "type": "timestruc_t" },
- { "name": "pr_time", "type": "timestruc_t" },
- { "name": "pr_ctime", "type": "timestruc_t" },
- { "name": "pr_fname", "type": "char [16]" },
- { "name": "pr_psargs", "type": "char [80]" },
- { "name": "pr_wstat", "type": "int" },
- { "name": "pr_argc", "type": "int" },
- { "name": "pr_argv", "type": "uintptr_t" },
- { "name": "pr_envp", "type": "uintptr_t" },
- { "name": "pr_dmodel", "type": "char" },
- { "name": "pr_pad2", "type": "char [3]" },
- { "name": "pr_taskid", "type": "taskid_t" },
- { "name": "pr_projid", "type": "projid_t" },
- { "name": "pr_nzomb", "type": "int" },
- { "name": "pr_poolid", "type": "poolid_t" },
- { "name": "pr_zoneid", "type": "zoneid_t" },
- { "name": "pr_contract", "type": "id_t" },
- { "name": "pr_filler", "type": "int [1]" },
- { "name": "pr_lwp", "type": "lwpsinfo_t" }
- ] },
- { "name": "psinfo_t", "typedef": "struct psinfo" }
- ]
-}
+++ /dev/null
-{ "metadata":
- {
- "ctf2json_version": "1.0",
- "created_at": 1316563648,
- "derived_from": "/lib/libc.so",
- "ctf_version": 2,
- "requested_types": [ "timestruc_t" ]
- },
-"data":
- [
- { "name": "long", "integer": { "length": 4, "signed": true } },
- { "name": "time_t", "typedef": "long" },
- { "name": "struct timespec", "struct": [
- { "name": "tv_sec", "type": "time_t" },
- { "name": "tv_nsec", "type": "long" }
- ] },
- { "name": "timestruc_t", "typedef": "struct timespec" }
- ]
-}
+++ /dev/null
-/*
- * Test several conditions that should always cause us to throw.
- */
-var mod_assert = require('assert');
-var mod_ctype = require('../../ctype.js');
-
-var cases = [
-{ json: { }, msg: 'bad JSON - no metadata or data' },
-{ json: { metadata: {} }, msg: 'bad JSON - bad metadata section' },
-{ json: { metadata: { 'JSON version': [] } },
- msg: 'bad JSON - bad JSON version' },
-{ json: { metadata: { 'JSON version': 2 } },
- msg: 'bad JSON - bad JSON version' },
-{ json: { metadata: { 'JSON version': '100.20' } },
- msg: 'bad JSON - bad JSON version' },
-{ json: { metadata: { 'JSON version': '1.0' } },
- msg: 'missing data section' },
-{ json: { metadata: { 'JSON version': '1.0' }, data: 1 },
- msg: 'invalid data section' },
-{ json: { metadata: { 'JSON version': '1.0' }, data: 1.1 },
- msg: 'invalid data section' },
-{ json: { metadata: { 'JSON version': '1.0' }, data: '1.1' },
- msg: 'invalid data section' },
-{ json: { metadata: { 'JSON version': '1.0' }, data: {} },
- msg: 'invalid data section' }
-];
-
-function test()
-{
- var ii;
-
- for (ii = 0; ii < cases.length; ii++) {
- mod_assert.throws(function () {
- mod_ctype.parseCTF(cases[ii].json);
- }, Error, cases[ii].msg);
- }
-}
-
-test();
+++ /dev/null
-var mod_fs = require('fs');
-var mod_ctype = require('../../ctype.js');
-var mod_assert = require('assert');
-
-function test()
-{
- var data, parser;
-
- data = JSON.parse(mod_fs.readFileSync('./float.json').toString());
- parser = mod_ctype.parseCTF(data, { endian: 'big' });
- mod_assert.deepEqual(parser.lstypes(), {});
-}
-
-test();
+++ /dev/null
-var mod_fs = require('fs');
-var mod_ctype = require('../../ctype.js');
-var mod_assert = require('assert');
-
-function test()
-{
- var data, parser;
-
- data = JSON.parse(mod_fs.readFileSync('./int.json').toString());
- parser = mod_ctype.parseCTF(data, { endian: 'big' });
- mod_assert.deepEqual(parser.lstypes(), { 'int': 'int32_t' });
-}
-
-test();
+++ /dev/null
-var mod_fs = require('fs');
-var mod_ctype = require('../../ctype.js');
-var mod_assert = require('assert');
-
-/*
- * This is too unwieldly to actually write out. Just make sure we can parse it
- * without errrors.
- */
-function test()
-{
- var data;
-
- data = JSON.parse(mod_fs.readFileSync('./psinfo.json').toString());
- mod_ctype.parseCTF(data, { endian: 'big' });
-}
-
-test();
+++ /dev/null
-var mod_fs = require('fs');
-var mod_ctype = require('../../ctype.js');
-var mod_assert = require('assert');
-
-function test()
-{
- var data, parser;
-
- data = JSON.parse(mod_fs.readFileSync('./struct.json').toString());
- parser = mod_ctype.parseCTF(data, { endian: 'big' });
- mod_assert.deepEqual(parser.lstypes(), { 'long': 'int32_t',
- 'time_t': 'long',
- 'timestruc_t': 'struct timespec',
- 'struct timespec': [ { 'tv_sec': { 'type': 'time_t' } },
- { 'tv_nsec': { 'type': 'long' } } ] });
-}
-
-test();
+++ /dev/null
-var mod_fs = require('fs');
-var mod_ctype = require('../../ctype.js');
-var mod_assert = require('assert');
-
-function test()
-{
- var data, parser;
-
- data = JSON.parse(mod_fs.readFileSync('./typedef.json').toString());
- parser = mod_ctype.parseCTF(data, { endian: 'big' });
- mod_assert.deepEqual(parser.lstypes(), { 'bar_t': 'int',
- 'int': 'int32_t' });
-}
-
-test();
+++ /dev/null
-{ "metadata":
- {
- "ctf2json_version": "1.0",
- "created_at": 1316302348,
- "derived_from": "/lib/libc.so",
- "ctf_version": 2,
- "requested_types": [ "bar_t" ]
- },
-"data":
- [
- { "name": "int", "integer": { "length": 4, "signed": true } },
- { "name": "bar_t", "typedef": "int" }
- ]
-}
+++ /dev/null
-/*
- * Battery of tests to break our floating point implementation. Oh ho ho.
- *
- * There are a few useful ways to generate the expected output. The first is
- * just write a C program and write raw bytes out and inspect with xxd. Remember
- * to consider whether or not you're on a big endian or little endian machine.
- * Another useful site I found to help with some of this was:
- *
- * http://babbage.cs.qc.edu/IEEE-754/
- */
-
-var mod_ctype = require('../../../ctio.js');
-var ASSERT = require('assert');
-
-function testfloat()
-{
- var buffer = new Buffer(4);
- /* Start off with some of the easy ones: +zero */
- buffer[0] = 0;
- buffer[1] = 0;
- buffer[2] = 0;
- buffer[3] = 0;
-
- ASSERT.equal(0, mod_ctype.rfloat(buffer, 'big', 0));
- ASSERT.equal(0, mod_ctype.rfloat(buffer, 'little', 0));
-
- /* Test -0 */
- buffer[0] = 0x80;
- ASSERT.equal(0, mod_ctype.rfloat(buffer, 'big', 0));
- buffer[3] = buffer[0];
- buffer[0] = 0;
- ASSERT.equal(0, mod_ctype.rfloat(buffer, 'little', 0));
-
- /* Catch +infin */
- buffer[0] = 0x7f;
- buffer[1] = 0x80;
- buffer[2] = 0x00;
- buffer[3] = 0x00;
- ASSERT.equal(Number.POSITIVE_INFINITY,
- mod_ctype.rfloat(buffer, 'big', 0));
- buffer[3] = 0x7f;
- buffer[2] = 0x80;
- buffer[1] = 0x00;
- buffer[0] = 0x00;
- ASSERT.equal(Number.POSITIVE_INFINITY,
- mod_ctype.rfloat(buffer, 'litle', 0));
-
- /* Catch -infin */
- buffer[0] = 0xff;
- buffer[1] = 0x80;
- buffer[2] = 0x00;
- buffer[3] = 0x00;
- ASSERT.equal(Number.NEGATIVE_INFINITY,
- mod_ctype.rfloat(buffer, 'big', 0));
- buffer[3] = 0xff;
- buffer[2] = 0x80;
- buffer[1] = 0x00;
- buffer[0] = 0x00;
- ASSERT.equal(Number.NEGATIVE_INFINITY,
- mod_ctype.rfloat(buffer, 'litle', 0));
-
- /* Catch NaN */
-
- buffer[0] = 0x7f;
- buffer[1] = 0x80;
- buffer[2] = 0x00;
- buffer[3] = 0x23;
- ASSERT.ok(isNaN(mod_ctype.rfloat(buffer, 'big', 0)));
- buffer[3] = 0x7f;
- buffer[2] = 0x80;
- buffer[1] = 0x00;
- buffer[0] = 0x23;
- ASSERT.ok(isNaN(mod_ctype.rfloat(buffer, 'little', 0)));
-
- /* Catch -infin */
- buffer[0] = 0xff;
- buffer[1] = 0x80;
- buffer[2] = 0x00;
- buffer[3] = 0x23;
- ASSERT.ok(isNaN(mod_ctype.rfloat(buffer, 'big', 0)));
- buffer[3] = 0xff;
- buffer[2] = 0x80;
- buffer[1] = 0x00;
- buffer[0] = 0x23;
- ASSERT.ok(isNaN(mod_ctype.rfloat(buffer, 'little', 0)));
-
- /* On to some basic tests */
- /* 1.125 */
- buffer[0] = 0x3f;
- buffer[1] = 0x90;
- buffer[2] = 0x00;
- buffer[3] = 0x00;
- ASSERT.equal(1.125, mod_ctype.rfloat(buffer, 'big', 0));
-
- buffer[3] = 0x3f;
- buffer[2] = 0x90;
- buffer[1] = 0x00;
- buffer[0] = 0x00;
- ASSERT.equal(1.125, mod_ctype.rfloat(buffer, 'little', 0));
-
- /* ff34a2b0 -2.4010576103645774e+38 */
- buffer[0] = 0xff;
- buffer[1] = 0x34;
- buffer[2] = 0xa2;
- buffer[3] = 0xb0;
- ASSERT.equal(-2.4010576103645774e+38,
- mod_ctype.rfloat(buffer, 'big', 0));
-
- buffer[3] = 0xff;
- buffer[2] = 0x34;
- buffer[1] = 0xa2;
- buffer[0] = 0xb0;
- ASSERT.equal(-2.4010576103645774e+38,
- mod_ctype.rfloat(buffer, 'little', 0));
-
- /* Denormalized tests */
-
- /* 0003f89a +/- 3.6468792534053364e-40 */
- buffer[0] = 0x00;
- buffer[1] = 0x03;
- buffer[2] = 0xf8;
- buffer[3] = 0x9a;
- ASSERT.equal(3.6468792534053364e-40,
- mod_ctype.rfloat(buffer, 'big', 0));
-
- buffer[3] = 0x00;
- buffer[2] = 0x03;
- buffer[1] = 0xf8;
- buffer[0] = 0x9a;
- ASSERT.equal(3.6468792534053364e-40,
- mod_ctype.rfloat(buffer, 'little', 0));
-
- buffer[0] = 0x80;
- buffer[1] = 0x03;
- buffer[2] = 0xf8;
- buffer[3] = 0x9a;
- ASSERT.equal(-3.6468792534053364e-40,
- mod_ctype.rfloat(buffer, 'big', 0));
-
- buffer[3] = 0x80;
- buffer[2] = 0x03;
- buffer[1] = 0xf8;
- buffer[0] = 0x9a;
- ASSERT.equal(-3.6468792534053364e-40,
- mod_ctype.rfloat(buffer, 'little', 0));
-
-
- /* Maximum and minimum normalized and denormalized values */
-
- /* Largest normalized number +/- 3.4028234663852886e+38 */
-
- buffer[0] = 0x7f;
- buffer[1] = 0x7f;
- buffer[2] = 0xff;
- buffer[3] = 0xff;
- ASSERT.equal(3.4028234663852886e+38,
- mod_ctype.rfloat(buffer, 'big', 0));
-
- buffer[3] = 0x7f;
- buffer[2] = 0x7f;
- buffer[1] = 0xff;
- buffer[0] = 0xff;
- ASSERT.equal(3.4028234663852886e+38,
- mod_ctype.rfloat(buffer, 'little', 0));
-
- buffer[0] = 0xff;
- buffer[1] = 0x7f;
- buffer[2] = 0xff;
- buffer[3] = 0xff;
- ASSERT.equal(-3.4028234663852886e+38,
- mod_ctype.rfloat(buffer, 'big', 0));
-
- buffer[3] = 0xff;
- buffer[2] = 0x7f;
- buffer[1] = 0xff;
- buffer[0] = 0xff;
- ASSERT.equal(-3.4028234663852886e+38,
- mod_ctype.rfloat(buffer, 'little', 0));
-
- /* Smallest normalied number +/- 1.1754943508222875e-38 */
- buffer[0] = 0x00;
- buffer[1] = 0x80;
- buffer[2] = 0x00;
- buffer[3] = 0x00;
- ASSERT.equal(1.1754943508222875e-38,
- mod_ctype.rfloat(buffer, 'big', 0));
-
- buffer[3] = 0x00;
- buffer[2] = 0x80;
- buffer[1] = 0x00;
- buffer[0] = 0x00;
- ASSERT.equal(1.1754943508222875e-38,
- mod_ctype.rfloat(buffer, 'little', 0));
-
- buffer[0] = 0x80;
- buffer[1] = 0x80;
- buffer[2] = 0x00;
- buffer[3] = 0x00;
- ASSERT.equal(-1.1754943508222875e-38,
- mod_ctype.rfloat(buffer, 'big', 0));
-
- buffer[3] = 0x80;
- buffer[2] = 0x80;
- buffer[1] = 0x00;
- buffer[0] = 0x00;
- ASSERT.equal(-1.1754943508222875e-38,
- mod_ctype.rfloat(buffer, 'little', 0));
-
-
- /* Smallest denormalized number 1.401298464324817e-45 */
- buffer[0] = 0x00;
- buffer[1] = 0x00;
- buffer[2] = 0x00;
- buffer[3] = 0x01;
- ASSERT.equal(1.401298464324817e-45,
- mod_ctype.rfloat(buffer, 'big', 0));
-
- buffer[3] = 0x00;
- buffer[2] = 0x00;
- buffer[1] = 0x00;
- buffer[0] = 0x01;
- ASSERT.equal(1.401298464324817e-45,
- mod_ctype.rfloat(buffer, 'little', 0));
-
- buffer[0] = 0x80;
- buffer[1] = 0x00;
- buffer[2] = 0x00;
- buffer[3] = 0x01;
- ASSERT.equal(-1.401298464324817e-45,
- mod_ctype.rfloat(buffer, 'big', 0));
-
- buffer[3] = 0x80;
- buffer[2] = 0x00;
- buffer[1] = 0x00;
- buffer[0] = 0x01;
- ASSERT.equal(-1.401298464324817e-45,
- mod_ctype.rfloat(buffer, 'little', 0));
-
- /* Largest denormalized value +/- 1.1754942106924411e-38 */
- buffer[0] = 0x00;
- buffer[1] = 0x7f;
- buffer[2] = 0xff;
- buffer[3] = 0xff;
- ASSERT.equal(1.1754942106924411e-38,
- mod_ctype.rfloat(buffer, 'big', 0));
-
- buffer[3] = 0x00;
- buffer[2] = 0x7f;
- buffer[1] = 0xff;
- buffer[0] = 0xff;
- ASSERT.equal(1.1754942106924411e-38,
- mod_ctype.rfloat(buffer, 'little', 0));
-
- buffer[0] = 0x80;
- buffer[1] = 0x7f;
- buffer[2] = 0xff;
- buffer[3] = 0xff;
- ASSERT.equal(-1.1754942106924411e-38,
- mod_ctype.rfloat(buffer, 'big', 0));
-
- buffer[3] = 0x80;
- buffer[2] = 0x7f;
- buffer[1] = 0xff;
- buffer[0] = 0xff;
- ASSERT.equal(-1.1754942106924411e-38,
- mod_ctype.rfloat(buffer, 'little', 0));
-
- /* Do some quick offset testing */
- buffer = new Buffer(6);
- buffer[0] = 0x7f;
- buffer[1] = 0x4e;
- buffer[2] = 0x8a;
- buffer[3] = 0x79;
- buffer[4] = 0xcd;
- buffer[5] = 0x3f;
-
- ASSERT.equal(2.745399582697325e+38,
- mod_ctype.rfloat(buffer, 'big', 0));
- ASSERT.equal(1161619072,
- mod_ctype.rfloat(buffer, 'big', 1));
- ASSERT.equal(-1.2027516403607578e-32,
- mod_ctype.rfloat(buffer, 'big', 2));
-
- ASSERT.equal(8.97661320504413e+34,
- mod_ctype.rfloat(buffer, 'little', 0));
- ASSERT.equal(-261661920,
- mod_ctype.rfloat(buffer, 'little', 1));
- ASSERT.equal(1.605271577835083,
- mod_ctype.rfloat(buffer, 'little', 2));
-
-}
-
-function testdouble()
-{
- var buffer = new Buffer(10);
-
- /* Check 0 */
- buffer[0] = 0;
- buffer[1] = 0;
- buffer[2] = 0;
- buffer[3] = 0;
- buffer[4] = 0;
- buffer[5] = 0;
- buffer[6] = 0;
- buffer[7] = 0;
- ASSERT.equal(0,
- mod_ctype.rdouble(buffer, 'big', 0));
- ASSERT.equal(0,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- buffer[0] = 0x80;
- buffer[1] = 0;
- buffer[2] = 0;
- buffer[3] = 0;
- buffer[4] = 0;
- buffer[5] = 0;
- buffer[6] = 0;
- buffer[7] = 0;
- ASSERT.equal(0,
- mod_ctype.rdouble(buffer, 'big', 0));
- buffer[7] = 0x80;
- buffer[6] = 0;
- buffer[5] = 0;
- buffer[4] = 0;
- buffer[3] = 0;
- buffer[2] = 0;
- buffer[1] = 0;
- buffer[0] = 0;
- ASSERT.equal(0,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- /* Check NaN */
- buffer[0] = 0x7f;
- buffer[1] = 0xf0;
- buffer[2] = 0;
- buffer[3] = 0;
- buffer[4] = 0;
- buffer[5] = 0;
- buffer[6] = 0;
- buffer[7] = 23;
- ASSERT.ok(isNaN(mod_ctype.rdouble(buffer, 'big', 0)));
-
- buffer[7] = 0x7f;
- buffer[6] = 0xf0;
- buffer[5] = 0;
- buffer[4] = 0;
- buffer[3] = 0;
- buffer[2] = 0;
- buffer[1] = 0;
- buffer[0] = 23;
- ASSERT.ok(isNaN(mod_ctype.rdouble(buffer, 'little', 0)));
-
- buffer[0] = 0xff;
- buffer[1] = 0xf0;
- buffer[2] = 0;
- buffer[3] = 0;
- buffer[4] = 0;
- buffer[5] = 0;
- buffer[6] = 0;
- buffer[7] = 23;
- ASSERT.ok(isNaN(mod_ctype.rdouble(buffer, 'big', 0)));
-
- buffer[7] = 0xff;
- buffer[6] = 0xf0;
- buffer[5] = 0;
- buffer[4] = 0;
- buffer[3] = 0;
- buffer[2] = 0;
- buffer[1] = 0;
- buffer[0] = 23;
- ASSERT.ok(isNaN(mod_ctype.rdouble(buffer, 'little', 0)));
-
- /* pos inf */
- buffer[0] = 0x7f;
- buffer[1] = 0xf0;
- buffer[2] = 0;
- buffer[3] = 0;
- buffer[4] = 0;
- buffer[5] = 0;
- buffer[6] = 0;
- buffer[7] = 0;
- ASSERT.equal(Number.POSITIVE_INFINITY,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0x7f;
- buffer[6] = 0xf0;
- buffer[5] = 0;
- buffer[4] = 0;
- buffer[3] = 0;
- buffer[2] = 0;
- buffer[1] = 0;
- buffer[0] = 0;
- ASSERT.equal(Number.POSITIVE_INFINITY,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- /* neg inf */
- buffer[0] = 0xff;
- buffer[1] = 0xf0;
- buffer[2] = 0;
- buffer[3] = 0;
- buffer[4] = 0;
- buffer[5] = 0;
- buffer[6] = 0;
- buffer[7] = 0;
- ASSERT.equal(Number.NEGATIVE_INFINITY,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0xff;
- buffer[6] = 0xf0;
- buffer[5] = 0;
- buffer[4] = 0;
- buffer[3] = 0;
- buffer[2] = 0;
- buffer[1] = 0;
- buffer[0] = 0;
- ASSERT.equal(Number.NEGATIVE_INFINITY,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- /* Simple normalized values */
-
- /* +/- 1.125 */
- buffer[0] = 0x3f;
- buffer[1] = 0xf2;
- buffer[2] = 0;
- buffer[3] = 0;
- buffer[4] = 0;
- buffer[5] = 0;
- buffer[6] = 0;
- buffer[7] = 0;
- ASSERT.equal(1.125,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0x3f;
- buffer[6] = 0xf2;
- buffer[5] = 0;
- buffer[4] = 0;
- buffer[3] = 0;
- buffer[2] = 0;
- buffer[1] = 0;
- buffer[0] = 0;
- ASSERT.equal(1.125,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- buffer[0] = 0xbf;
- buffer[1] = 0xf2;
- buffer[2] = 0;
- buffer[3] = 0;
- buffer[4] = 0;
- buffer[5] = 0;
- buffer[6] = 0;
- buffer[7] = 0;
- ASSERT.equal(-1.125,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0xbf;
- buffer[6] = 0xf2;
- buffer[5] = 0;
- buffer[4] = 0;
- buffer[3] = 0;
- buffer[2] = 0;
- buffer[1] = 0;
- buffer[0] = 0;
- ASSERT.equal(-1.125,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- /* +/- 1.4397318913736026e+283 */
- buffer[0] = 0x7a;
- buffer[1] = 0xb8;
- buffer[2] = 0xc9;
- buffer[3] = 0x34;
- buffer[4] = 0x72;
- buffer[5] = 0x16;
- buffer[6] = 0xf9;
- buffer[7] = 0x0e;
- ASSERT.equal(1.4397318913736026e+283,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0x7a;
- buffer[6] = 0xb8;
- buffer[5] = 0xc9;
- buffer[4] = 0x34;
- buffer[3] = 0x72;
- buffer[2] = 0x16;
- buffer[1] = 0xf9;
- buffer[0] = 0x0e;
- ASSERT.equal(1.4397318913736026e+283,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- buffer[0] = 0xfa;
- buffer[1] = 0xb8;
- buffer[2] = 0xc9;
- buffer[3] = 0x34;
- buffer[4] = 0x72;
- buffer[5] = 0x16;
- buffer[6] = 0xf9;
- buffer[7] = 0x0e;
- ASSERT.equal(-1.4397318913736026e+283,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0xfa;
- buffer[6] = 0xb8;
- buffer[5] = 0xc9;
- buffer[4] = 0x34;
- buffer[3] = 0x72;
- buffer[2] = 0x16;
- buffer[1] = 0xf9;
- buffer[0] = 0x0e;
- ASSERT.equal(-1.4397318913736026e+283,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- /* Denormalized values */
- /* +/- 8.82521232268344e-309 */
- buffer[0] = 0x00;
- buffer[1] = 0x06;
- buffer[2] = 0x58;
- buffer[3] = 0x94;
- buffer[4] = 0x13;
- buffer[5] = 0x27;
- buffer[6] = 0x8a;
- buffer[7] = 0xcd;
- ASSERT.equal(8.82521232268344e-309,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0x00;
- buffer[6] = 0x06;
- buffer[5] = 0x58;
- buffer[4] = 0x94;
- buffer[3] = 0x13;
- buffer[2] = 0x27;
- buffer[1] = 0x8a;
- buffer[0] = 0xcd;
- ASSERT.equal(8.82521232268344e-309,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- buffer[0] = 0x80;
- buffer[1] = 0x06;
- buffer[2] = 0x58;
- buffer[3] = 0x94;
- buffer[4] = 0x13;
- buffer[5] = 0x27;
- buffer[6] = 0x8a;
- buffer[7] = 0xcd;
- ASSERT.equal(-8.82521232268344e-309,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0x80;
- buffer[6] = 0x06;
- buffer[5] = 0x58;
- buffer[4] = 0x94;
- buffer[3] = 0x13;
- buffer[2] = 0x27;
- buffer[1] = 0x8a;
- buffer[0] = 0xcd;
- ASSERT.equal(-8.82521232268344e-309,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- /* Edge cases, maximum and minimum values */
-
- /* Smallest denormalized value 5e-324 */
- buffer[0] = 0x00;
- buffer[1] = 0x00;
- buffer[2] = 0x00;
- buffer[3] = 0x00;
- buffer[4] = 0x00;
- buffer[5] = 0x00;
- buffer[6] = 0x00;
- buffer[7] = 0x01;
- ASSERT.equal(5e-324,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0x00;
- buffer[6] = 0x00;
- buffer[5] = 0x00;
- buffer[4] = 0x00;
- buffer[3] = 0x00;
- buffer[2] = 0x00;
- buffer[1] = 0x00;
- buffer[0] = 0x01;
- ASSERT.equal(5e-324,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- buffer[0] = 0x80;
- buffer[1] = 0x00;
- buffer[2] = 0x00;
- buffer[3] = 0x00;
- buffer[4] = 0x00;
- buffer[5] = 0x00;
- buffer[6] = 0x00;
- buffer[7] = 0x01;
- ASSERT.equal(-5e-324,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0x80;
- buffer[6] = 0x00;
- buffer[5] = 0x00;
- buffer[4] = 0x00;
- buffer[3] = 0x00;
- buffer[2] = 0x00;
- buffer[1] = 0x00;
- buffer[0] = 0x01;
- ASSERT.equal(-5e-324,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- /* Largest denormalized value 2.225073858507201e-308 */
- buffer[0] = 0x00;
- buffer[1] = 0x0f;
- buffer[2] = 0xff;
- buffer[3] = 0xff;
- buffer[4] = 0xff;
- buffer[5] = 0xff;
- buffer[6] = 0xff;
- buffer[7] = 0xff;
- ASSERT.equal(2.225073858507201e-308,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0x00;
- buffer[6] = 0x0f;
- buffer[5] = 0xff;
- buffer[4] = 0xff;
- buffer[3] = 0xff;
- buffer[2] = 0xff;
- buffer[1] = 0xff;
- buffer[0] = 0xff;
- ASSERT.equal(2.225073858507201e-308,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- buffer[0] = 0x80;
- buffer[1] = 0x0f;
- buffer[2] = 0xff;
- buffer[3] = 0xff;
- buffer[4] = 0xff;
- buffer[5] = 0xff;
- buffer[6] = 0xff;
- buffer[7] = 0xff;
- ASSERT.equal(-2.225073858507201e-308,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0x80;
- buffer[6] = 0x0f;
- buffer[5] = 0xff;
- buffer[4] = 0xff;
- buffer[3] = 0xff;
- buffer[2] = 0xff;
- buffer[1] = 0xff;
- buffer[0] = 0xff;
- ASSERT.equal(-2.225073858507201e-308,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- /* Smallest normalized value 2.2250738585072014e-308 */
- buffer[0] = 0x00;
- buffer[1] = 0x10;
- buffer[2] = 0x00;
- buffer[3] = 0x00;
- buffer[4] = 0x00;
- buffer[5] = 0x00;
- buffer[6] = 0x00;
- buffer[7] = 0x00;
- ASSERT.equal(2.2250738585072014e-308,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0x00;
- buffer[6] = 0x10;
- buffer[5] = 0x00;
- buffer[4] = 0x00;
- buffer[3] = 0x00;
- buffer[2] = 0x00;
- buffer[1] = 0x00;
- buffer[0] = 0x00;
- ASSERT.equal(2.2250738585072014e-308,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- buffer[0] = 0x80;
- buffer[1] = 0x10;
- buffer[2] = 0x00;
- buffer[3] = 0x00;
- buffer[4] = 0x00;
- buffer[5] = 0x00;
- buffer[6] = 0x00;
- buffer[7] = 0x00;
- ASSERT.equal(-2.2250738585072014e-308,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0x80;
- buffer[6] = 0x10;
- buffer[5] = 0x00;
- buffer[4] = 0x00;
- buffer[3] = 0x00;
- buffer[2] = 0x00;
- buffer[1] = 0x00;
- buffer[0] = 0x00;
- ASSERT.equal(-2.2250738585072014e-308,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- /* Largest normalized value 1.7976931348623157e+308 */
- buffer[0] = 0x7f;
- buffer[1] = 0xef;
- buffer[2] = 0xff;
- buffer[3] = 0xff;
- buffer[4] = 0xff;
- buffer[5] = 0xff;
- buffer[6] = 0xff;
- buffer[7] = 0xff;
- ASSERT.equal(1.7976931348623157e+308,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0x7f;
- buffer[6] = 0xef;
- buffer[5] = 0xff;
- buffer[4] = 0xff;
- buffer[3] = 0xff;
- buffer[2] = 0xff;
- buffer[1] = 0xff;
- buffer[0] = 0xff;
- ASSERT.equal(1.7976931348623157e+308,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- buffer[0] = 0xff;
- buffer[1] = 0xef;
- buffer[2] = 0xff;
- buffer[3] = 0xff;
- buffer[4] = 0xff;
- buffer[5] = 0xff;
- buffer[6] = 0xff;
- buffer[7] = 0xff;
- ASSERT.equal(-1.7976931348623157e+308,
- mod_ctype.rdouble(buffer, 'big', 0));
-
- buffer[7] = 0xff;
- buffer[6] = 0xef;
- buffer[5] = 0xff;
- buffer[4] = 0xff;
- buffer[3] = 0xff;
- buffer[2] = 0xff;
- buffer[1] = 0xff;
- buffer[0] = 0xff;
- ASSERT.equal(-1.7976931348623157e+308,
- mod_ctype.rdouble(buffer, 'little', 0));
-
- /* Try offsets */
- buffer[0] = 0xde;
- buffer[1] = 0xad;
- buffer[2] = 0xbe;
- buffer[3] = 0xef;
- buffer[4] = 0xba;
- buffer[5] = 0xdd;
- buffer[6] = 0xca;
- buffer[7] = 0xfe;
- buffer[8] = 0x16;
- buffer[9] = 0x79;
-
- ASSERT.equal(-1.1885958404126936e+148,
- mod_ctype.rdouble(buffer, 'big', 0));
- ASSERT.equal(-2.4299184080448593e-88,
- mod_ctype.rdouble(buffer, 'big', 1));
- ASSERT.equal(-0.000015130017658081283,
- mod_ctype.rdouble(buffer, 'big', 2));
-
- ASSERT.equal(-5.757458694845505e+302,
- mod_ctype.rdouble(buffer, 'little', 0));
- ASSERT.equal(6.436459604192476e-198,
- mod_ctype.rdouble(buffer, 'little', 1));
- ASSERT.equal(1.9903745632417286e+275,
- mod_ctype.rdouble(buffer, 'little', 2));
-}
-
-testfloat();
-testdouble();
+++ /dev/null
-/*
- * Another place to find bugs that may yet plague us. This time with writing out
- * floats to arrays. We are lazy and did basically just take the opposite of our
- * test code to read in values.
- */
-
-var mod_ctype = require('../../../ctio.js');
-var ASSERT = require('assert');
-
-
-/*
- * A useful thing to keep around for debugging
- * console.log('buffer[0]: ' + buffer[0].toString(16));
- * console.log('buffer[1]: ' + buffer[1].toString(16));
- * console.log('buffer[2]: ' + buffer[2].toString(16));
- * console.log('buffer[3]: ' + buffer[3].toString(16));
- * console.log('buffer[4]: ' + buffer[4].toString(16));
- * console.log('buffer[5]: ' + buffer[5].toString(16));
- * console.log('buffer[6]: ' + buffer[6].toString(16));
- * console.log('buffer[7]: ' + buffer[7].toString(16));
- */
-
-function testfloat()
-{
- var buffer = new Buffer(4);
- mod_ctype.wfloat(0, 'big', buffer, 0);
- /* Start off with some of the easy ones: +zero */
- ASSERT.equal(0, buffer[0]);
- ASSERT.equal(0, buffer[1]);
- ASSERT.equal(0, buffer[2]);
- ASSERT.equal(0, buffer[3]);
- mod_ctype.wfloat(0, 'little', buffer, 0);
- ASSERT.equal(0, buffer[0]);
- ASSERT.equal(0, buffer[1]);
- ASSERT.equal(0, buffer[2]);
- ASSERT.equal(0, buffer[3]);
-
- /* Catch +infin */
- mod_ctype.wfloat(Number.POSITIVE_INFINITY, 'big', buffer, 0);
- ASSERT.equal(0x7f, buffer[0]);
- ASSERT.equal(0x80, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- mod_ctype.wfloat(Number.POSITIVE_INFINITY, 'little', buffer, 0);
- ASSERT.equal(0x7f, buffer[3]);
- ASSERT.equal(0x80, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[0]);
-
- /* Catch -infin */
- mod_ctype.wfloat(Number.NEGATIVE_INFINITY, 'big', buffer, 0);
- ASSERT.equal(0xff, buffer[0]);
- ASSERT.equal(0x80, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- mod_ctype.wfloat(Number.NEGATIVE_INFINITY, 'little', buffer, 0);
- ASSERT.equal(0xff, buffer[3]);
- ASSERT.equal(0x80, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[0]);
-
- /* Catch NaN */
-
- /*
- * NaN Is a litle weird in its requirements, so we're going to encode a
- * bit of how we actually implement it into this test. Probably not the
- * best, since technically the sign is a don't care and the mantissa
- * needs to just be non-zero.
- */
- mod_ctype.wfloat(NaN, 'big', buffer, 0);
- ASSERT.equal(0x7f, buffer[0]);
- ASSERT.equal(0x80, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x17, buffer[3]);
- mod_ctype.wfloat(NaN, 'little', buffer, 0);
- ASSERT.equal(0x7f, buffer[3]);
- ASSERT.equal(0x80, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x17, buffer[0]);
-
- /* On to some basic tests */
- /* 1.125 */
- mod_ctype.wfloat(1.125, 'big', buffer, 0);
- ASSERT.equal(0x3f, buffer[0]);
- ASSERT.equal(0x90, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- mod_ctype.wfloat(1.125, 'little', buffer, 0);
- ASSERT.equal(0x3f, buffer[3]);
- ASSERT.equal(0x90, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[0]);
-
- mod_ctype.wfloat(1.0000001192092896, 'big', buffer, 0);
- ASSERT.equal(0x3f, buffer[0]);
- ASSERT.equal(0x80, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x01, buffer[3]);
- mod_ctype.wfloat(1.0000001192092896, 'little', buffer, 0);
- ASSERT.equal(0x3f, buffer[3]);
- ASSERT.equal(0x80, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x01, buffer[0]);
-
- mod_ctype.wfloat(1.0000001192092896, 'big', buffer, 0);
- ASSERT.equal(0x3f, buffer[0]);
- ASSERT.equal(0x80, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x01, buffer[3]);
- mod_ctype.wfloat(1.0000001192092896, 'little', buffer, 0);
- ASSERT.equal(0x3f, buffer[3]);
- ASSERT.equal(0x80, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x01, buffer[0]);
-
- mod_ctype.wfloat(2.3283067140944524e-10, 'big', buffer, 0);
- ASSERT.equal(0x2f, buffer[0]);
- ASSERT.equal(0x80, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x01, buffer[3]);
- mod_ctype.wfloat(2.3283067140944524e-10, 'little', buffer, 0);
- ASSERT.equal(0x2f, buffer[3]);
- ASSERT.equal(0x80, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x01, buffer[0]);
-
- /* ff34a2b0 -2.4010576103645774e+38 */
- mod_ctype.wfloat(-2.4010576103645774e+38,
- 'big', buffer, 0);
- ASSERT.equal(0xff, buffer[0]);
- ASSERT.equal(0x34, buffer[1]);
- ASSERT.equal(0xa2, buffer[2]);
- ASSERT.equal(0xb0, buffer[3]);
- mod_ctype.wfloat(-2.4010576103645774e+38,
- 'little', buffer, 0);
- ASSERT.equal(0xff, buffer[3]);
- ASSERT.equal(0x34, buffer[2]);
- ASSERT.equal(0xa2, buffer[1]);
- ASSERT.equal(0xb0, buffer[0]);
-
- /* Denormalized tests */
-
- /* 0003f89a +/- 3.6468792534053364e-40 */
- mod_ctype.wfloat(3.6468792534053364e-40,
- 'big', buffer, 0);
- ASSERT.equal(0x00, buffer[0]);
- ASSERT.equal(0x03, buffer[1]);
- ASSERT.equal(0xf8, buffer[2]);
- ASSERT.equal(0x9a, buffer[3]);
- mod_ctype.wfloat(3.6468792534053364e-40,
- 'little', buffer, 0);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x03, buffer[2]);
- ASSERT.equal(0xf8, buffer[1]);
- ASSERT.equal(0x9a, buffer[0]);
-
- mod_ctype.wfloat(-3.6468792534053364e-40,
- 'big', buffer, 0);
- ASSERT.equal(0x80, buffer[0]);
- ASSERT.equal(0x03, buffer[1]);
- ASSERT.equal(0xf8, buffer[2]);
- ASSERT.equal(0x9a, buffer[3]);
- mod_ctype.wfloat(-3.6468792534053364e-40,
- 'little', buffer, 0);
- ASSERT.equal(0x80, buffer[3]);
- ASSERT.equal(0x03, buffer[2]);
- ASSERT.equal(0xf8, buffer[1]);
- ASSERT.equal(0x9a, buffer[0]);
-
- /* Maximum and minimum normalized and denormalized values */
-
- /* Largest normalized number +/- 3.4028234663852886e+38 */
-
- mod_ctype.wfloat(3.4028234663852886e+38,
- 'big', buffer, 0);
- ASSERT.equal(0x7f, buffer[0]);
- ASSERT.equal(0x7f, buffer[1]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xff, buffer[3]);
- mod_ctype.wfloat(3.4028234663852886e+38,
- 'little', buffer, 0);
- ASSERT.equal(0x7f, buffer[3]);
- ASSERT.equal(0x7f, buffer[2]);
- ASSERT.equal(0xff, buffer[1]);
- ASSERT.equal(0xff, buffer[0]);
-
- mod_ctype.wfloat(-3.4028234663852886e+38,
- 'big', buffer, 0);
- ASSERT.equal(0xff, buffer[0]);
- ASSERT.equal(0x7f, buffer[1]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xff, buffer[3]);
- mod_ctype.wfloat(-3.4028234663852886e+38,
- 'little', buffer, 0);
- ASSERT.equal(0xff, buffer[3]);
- ASSERT.equal(0x7f, buffer[2]);
- ASSERT.equal(0xff, buffer[1]);
- ASSERT.equal(0xff, buffer[0]);
-
- /* Smallest normalied number +/- 1.1754943508222875e-38 */
-
- mod_ctype.wfloat(1.1754943508222875e-38,
- 'big', buffer, 0);
- ASSERT.equal(0x00, buffer[0]);
- ASSERT.equal(0x80, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- mod_ctype.wfloat(1.1754943508222875e-38,
- 'little', buffer, 0);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x80, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[0]);
-
- mod_ctype.wfloat(-1.1754943508222875e-38,
- 'big', buffer, 0);
- ASSERT.equal(0x80, buffer[0]);
- ASSERT.equal(0x80, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- mod_ctype.wfloat(-1.1754943508222875e-38,
- 'little', buffer, 0);
- ASSERT.equal(0x80, buffer[3]);
- ASSERT.equal(0x80, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[0]);
-
- /* Smallest denormalized number 1.401298464324817e-45 */
- mod_ctype.wfloat(1.401298464324817e-45,
- 'big', buffer, 0);
- ASSERT.equal(0x00, buffer[0]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x01, buffer[3]);
- mod_ctype.wfloat(1.401298464324817e-45,
- 'little', buffer, 0);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x01, buffer[0]);
-
- mod_ctype.wfloat(-1.401298464324817e-45,
- 'big', buffer, 0);
- ASSERT.equal(0x80, buffer[0]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x01, buffer[3]);
- mod_ctype.wfloat(-1.401298464324817e-45,
- 'little', buffer, 0);
- ASSERT.equal(0x80, buffer[3]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x01, buffer[0]);
-
- /* Largest denormalized value +/- 1.1754942106924411e-38 */
-
- mod_ctype.wfloat(1.1754942106924411e-38,
- 'big', buffer, 0);
- ASSERT.equal(0x00, buffer[0]);
- ASSERT.equal(0x7f, buffer[1]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xff, buffer[3]);
- mod_ctype.wfloat(1.1754942106924411e-38,
- 'little', buffer, 0);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x7f, buffer[2]);
- ASSERT.equal(0xff, buffer[1]);
- ASSERT.equal(0xff, buffer[0]);
-
- mod_ctype.wfloat(-1.1754942106924411e-38,
- 'big', buffer, 0);
- ASSERT.equal(0x80, buffer[0]);
- ASSERT.equal(0x7f, buffer[1]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xff, buffer[3]);
- mod_ctype.wfloat(-1.1754942106924411e-38,
- 'little', buffer, 0);
- ASSERT.equal(0x80, buffer[3]);
- ASSERT.equal(0x7f, buffer[2]);
- ASSERT.equal(0xff, buffer[1]);
- ASSERT.equal(0xff, buffer[0]);
-
- /* Do some quick offset testing */
- buffer = new Buffer(6);
- mod_ctype.wfloat(-1.2027516403607578e-32,
- 'big', buffer, 2);
- ASSERT.equal(0x8a, buffer[2]);
- ASSERT.equal(0x79, buffer[3]);
- ASSERT.equal(0xcd, buffer[4]);
- ASSERT.equal(0x3f, buffer[5]);
-
- mod_ctype.wfloat(-1.2027516403607578e-32,
- 'little', buffer, 2);
- ASSERT.equal(0x8a, buffer[5]);
- ASSERT.equal(0x79, buffer[4]);
- ASSERT.equal(0xcd, buffer[3]);
- ASSERT.equal(0x3f, buffer[2]);
-
-}
-
-function testdouble()
-{
- var buffer = new Buffer(10);
-
- /* Check 0 */
- mod_ctype.wdouble(0, 'big', buffer, 0);
- ASSERT.equal(0x00, buffer[0]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x00, buffer[7]);
- mod_ctype.wdouble(0, 'little', buffer, 0);
- ASSERT.equal(0x00, buffer[7]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[0]);
-
- /* Check NaN */
- /* Similar to floats we are only generating a subset of values */
- mod_ctype.wdouble(NaN, 'big', buffer, 0);
- ASSERT.equal(0x7f, buffer[0]);
- ASSERT.equal(0xf0, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x17, buffer[7]);
- mod_ctype.wdouble(NaN, 'little', buffer, 0);
- ASSERT.equal(0x7f, buffer[7]);
- ASSERT.equal(0xf0, buffer[6]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x17, buffer[0]);
-
- /* pos inf */
- mod_ctype.wdouble(Number.POSITIVE_INFINITY,
- 'big', buffer, 0);
- ASSERT.equal(0x7f, buffer[0]);
- ASSERT.equal(0xf0, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x00, buffer[7]);
- mod_ctype.wdouble(Number.POSITIVE_INFINITY,
- 'little', buffer, 0);
- ASSERT.equal(0x7f, buffer[7]);
- ASSERT.equal(0xf0, buffer[6]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[0]);
-
- /* neg inf */
- mod_ctype.wdouble(Number.NEGATIVE_INFINITY,
- 'big', buffer, 0);
- ASSERT.equal(0xff, buffer[0]);
- ASSERT.equal(0xf0, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x00, buffer[7]);
- mod_ctype.wdouble(Number.NEGATIVE_INFINITY,
- 'little', buffer, 0);
- ASSERT.equal(0xff, buffer[7]);
- ASSERT.equal(0xf0, buffer[6]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[0]);
-
- /* Simple normalized values */
-
- /* +/- 1.125 */
- mod_ctype.wdouble(1.125,
- 'big', buffer, 0);
- ASSERT.equal(0x3f, buffer[0]);
- ASSERT.equal(0xf2, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x00, buffer[7]);
-
- mod_ctype.wdouble(1.125,
- 'little', buffer, 0);
- ASSERT.equal(0x3f, buffer[7]);
- ASSERT.equal(0xf2, buffer[6]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[0]);
-
- mod_ctype.wdouble(-1.125,
- 'big', buffer, 0);
- ASSERT.equal(0xbf, buffer[0]);
- ASSERT.equal(0xf2, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x00, buffer[7]);
-
- mod_ctype.wdouble(-1.125,
- 'little', buffer, 0);
- ASSERT.equal(0xbf, buffer[7]);
- ASSERT.equal(0xf2, buffer[6]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[0]);
-
-
- /* +/- 1.4397318913736026e+283 */
- mod_ctype.wdouble(1.4397318913736026e+283,
- 'big', buffer, 0);
- ASSERT.equal(0x7a, buffer[0]);
- ASSERT.equal(0xb8, buffer[1]);
- ASSERT.equal(0xc9, buffer[2]);
- ASSERT.equal(0x34, buffer[3]);
- ASSERT.equal(0x72, buffer[4]);
- ASSERT.equal(0x16, buffer[5]);
- ASSERT.equal(0xf9, buffer[6]);
- ASSERT.equal(0x0e, buffer[7]);
-
- mod_ctype.wdouble(1.4397318913736026e+283,
- 'little', buffer, 0);
- ASSERT.equal(0x7a, buffer[7]);
- ASSERT.equal(0xb8, buffer[6]);
- ASSERT.equal(0xc9, buffer[5]);
- ASSERT.equal(0x34, buffer[4]);
- ASSERT.equal(0x72, buffer[3]);
- ASSERT.equal(0x16, buffer[2]);
- ASSERT.equal(0xf9, buffer[1]);
- ASSERT.equal(0x0e, buffer[0]);
-
- mod_ctype.wdouble(-1.4397318913736026e+283,
- 'big', buffer, 0);
- ASSERT.equal(0xfa, buffer[0]);
- ASSERT.equal(0xb8, buffer[1]);
- ASSERT.equal(0xc9, buffer[2]);
- ASSERT.equal(0x34, buffer[3]);
- ASSERT.equal(0x72, buffer[4]);
- ASSERT.equal(0x16, buffer[5]);
- ASSERT.equal(0xf9, buffer[6]);
- ASSERT.equal(0x0e, buffer[7]);
-
- mod_ctype.wdouble(-1.4397318913736026e+283,
- 'little', buffer, 0);
- ASSERT.equal(0xfa, buffer[7]);
- ASSERT.equal(0xb8, buffer[6]);
- ASSERT.equal(0xc9, buffer[5]);
- ASSERT.equal(0x34, buffer[4]);
- ASSERT.equal(0x72, buffer[3]);
- ASSERT.equal(0x16, buffer[2]);
- ASSERT.equal(0xf9, buffer[1]);
- ASSERT.equal(0x0e, buffer[0]);
-
- /* Denormalized values */
- /* +/- 8.82521232268344e-309 */
- mod_ctype.wdouble(8.82521232268344e-309,
- 'big', buffer, 0);
- ASSERT.equal(0x00, buffer[0]);
- ASSERT.equal(0x06, buffer[1]);
- ASSERT.equal(0x58, buffer[2]);
- ASSERT.equal(0x94, buffer[3]);
- ASSERT.equal(0x13, buffer[4]);
- ASSERT.equal(0x27, buffer[5]);
- ASSERT.equal(0x8a, buffer[6]);
- ASSERT.equal(0xcd, buffer[7]);
-
- mod_ctype.wdouble(8.82521232268344e-309,
- 'little', buffer, 0);
- ASSERT.equal(0x00, buffer[7]);
- ASSERT.equal(0x06, buffer[6]);
- ASSERT.equal(0x58, buffer[5]);
- ASSERT.equal(0x94, buffer[4]);
- ASSERT.equal(0x13, buffer[3]);
- ASSERT.equal(0x27, buffer[2]);
- ASSERT.equal(0x8a, buffer[1]);
- ASSERT.equal(0xcd, buffer[0]);
-
- mod_ctype.wdouble(-8.82521232268344e-309,
- 'big', buffer, 0);
- ASSERT.equal(0x80, buffer[0]);
- ASSERT.equal(0x06, buffer[1]);
- ASSERT.equal(0x58, buffer[2]);
- ASSERT.equal(0x94, buffer[3]);
- ASSERT.equal(0x13, buffer[4]);
- ASSERT.equal(0x27, buffer[5]);
- ASSERT.equal(0x8a, buffer[6]);
- ASSERT.equal(0xcd, buffer[7]);
-
- mod_ctype.wdouble(-8.82521232268344e-309,
- 'little', buffer, 0);
- ASSERT.equal(0x80, buffer[7]);
- ASSERT.equal(0x06, buffer[6]);
- ASSERT.equal(0x58, buffer[5]);
- ASSERT.equal(0x94, buffer[4]);
- ASSERT.equal(0x13, buffer[3]);
- ASSERT.equal(0x27, buffer[2]);
- ASSERT.equal(0x8a, buffer[1]);
- ASSERT.equal(0xcd, buffer[0]);
-
-
- /* Edge cases, maximum and minimum values */
-
- /* Smallest denormalized value 5e-324 */
- mod_ctype.wdouble(5e-324,
- 'big', buffer, 0);
- ASSERT.equal(0x00, buffer[0]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x01, buffer[7]);
-
- mod_ctype.wdouble(5e-324,
- 'little', buffer, 0);
- ASSERT.equal(0x00, buffer[7]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x01, buffer[0]);
-
- mod_ctype.wdouble(-5e-324,
- 'big', buffer, 0);
- ASSERT.equal(0x80, buffer[0]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x01, buffer[7]);
-
- mod_ctype.wdouble(-5e-324,
- 'little', buffer, 0);
- ASSERT.equal(0x80, buffer[7]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x01, buffer[0]);
-
-
-
- /* Largest denormalized value 2.225073858507201e-308 */
- mod_ctype.wdouble(2.225073858507201e-308,
- 'big', buffer, 0);
- ASSERT.equal(0x00, buffer[0]);
- ASSERT.equal(0x0f, buffer[1]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xff, buffer[3]);
- ASSERT.equal(0xff, buffer[4]);
- ASSERT.equal(0xff, buffer[5]);
- ASSERT.equal(0xff, buffer[6]);
- ASSERT.equal(0xff, buffer[7]);
-
- mod_ctype.wdouble(2.225073858507201e-308,
- 'little', buffer, 0);
- ASSERT.equal(0x00, buffer[7]);
- ASSERT.equal(0x0f, buffer[6]);
- ASSERT.equal(0xff, buffer[5]);
- ASSERT.equal(0xff, buffer[4]);
- ASSERT.equal(0xff, buffer[3]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xff, buffer[1]);
- ASSERT.equal(0xff, buffer[0]);
-
- mod_ctype.wdouble(-2.225073858507201e-308,
- 'big', buffer, 0);
- ASSERT.equal(0x80, buffer[0]);
- ASSERT.equal(0x0f, buffer[1]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xff, buffer[3]);
- ASSERT.equal(0xff, buffer[4]);
- ASSERT.equal(0xff, buffer[5]);
- ASSERT.equal(0xff, buffer[6]);
- ASSERT.equal(0xff, buffer[7]);
-
- mod_ctype.wdouble(-2.225073858507201e-308,
- 'little', buffer, 0);
- ASSERT.equal(0x80, buffer[7]);
- ASSERT.equal(0x0f, buffer[6]);
- ASSERT.equal(0xff, buffer[5]);
- ASSERT.equal(0xff, buffer[4]);
- ASSERT.equal(0xff, buffer[3]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xff, buffer[1]);
- ASSERT.equal(0xff, buffer[0]);
-
-
- /* Smallest normalized value 2.2250738585072014e-308 */
- mod_ctype.wdouble(2.2250738585072014e-308,
- 'big', buffer, 0);
- ASSERT.equal(0x00, buffer[0]);
- ASSERT.equal(0x10, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x00, buffer[7]);
-
- mod_ctype.wdouble(2.2250738585072014e-308,
- 'little', buffer, 0);
- ASSERT.equal(0x00, buffer[7]);
- ASSERT.equal(0x10, buffer[6]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[0]);
-
- mod_ctype.wdouble(-2.2250738585072014e-308,
- 'big', buffer, 0);
- ASSERT.equal(0x80, buffer[0]);
- ASSERT.equal(0x10, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x00, buffer[7]);
-
- mod_ctype.wdouble(-2.2250738585072014e-308,
- 'little', buffer, 0);
- ASSERT.equal(0x80, buffer[7]);
- ASSERT.equal(0x10, buffer[6]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[4]);
- ASSERT.equal(0x00, buffer[3]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[0]);
-
-
- /* Largest normalized value 1.7976931348623157e+308 */
- mod_ctype.wdouble(1.7976931348623157e+308,
- 'big', buffer, 0);
- ASSERT.equal(0x7f, buffer[0]);
- ASSERT.equal(0xef, buffer[1]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xff, buffer[3]);
- ASSERT.equal(0xff, buffer[4]);
- ASSERT.equal(0xff, buffer[5]);
- ASSERT.equal(0xff, buffer[6]);
- ASSERT.equal(0xff, buffer[7]);
-
- mod_ctype.wdouble(1.7976931348623157e+308,
- 'little', buffer, 0);
- ASSERT.equal(0x7f, buffer[7]);
- ASSERT.equal(0xef, buffer[6]);
- ASSERT.equal(0xff, buffer[5]);
- ASSERT.equal(0xff, buffer[4]);
- ASSERT.equal(0xff, buffer[3]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xff, buffer[1]);
- ASSERT.equal(0xff, buffer[0]);
-
- mod_ctype.wdouble(-1.7976931348623157e+308,
- 'big', buffer, 0);
- ASSERT.equal(0xff, buffer[0]);
- ASSERT.equal(0xef, buffer[1]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xff, buffer[3]);
- ASSERT.equal(0xff, buffer[4]);
- ASSERT.equal(0xff, buffer[5]);
- ASSERT.equal(0xff, buffer[6]);
- ASSERT.equal(0xff, buffer[7]);
-
- mod_ctype.wdouble(-1.7976931348623157e+308,
- 'little', buffer, 0);
- ASSERT.equal(0xff, buffer[7]);
- ASSERT.equal(0xef, buffer[6]);
- ASSERT.equal(0xff, buffer[5]);
- ASSERT.equal(0xff, buffer[4]);
- ASSERT.equal(0xff, buffer[3]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xff, buffer[1]);
- ASSERT.equal(0xff, buffer[0]);
-
-
- /* Try offsets */
- buffer[0] = 0xde;
- buffer[1] = 0xad;
- buffer[2] = 0xbe;
- buffer[3] = 0xef;
- buffer[4] = 0xba;
- buffer[5] = 0xdd;
- buffer[6] = 0xca;
- buffer[7] = 0xfe;
- buffer[8] = 0x16;
- buffer[9] = 0x79;
-
- mod_ctype.wdouble(-0.000015130017658081283,
- 'big', buffer, 2);
- ASSERT.equal(0xbe, buffer[2]);
- ASSERT.equal(0xef, buffer[3]);
- ASSERT.equal(0xba, buffer[4]);
- ASSERT.equal(0xdd, buffer[5]);
- ASSERT.equal(0xca, buffer[6]);
- ASSERT.equal(0xfe, buffer[7]);
- ASSERT.equal(0x16, buffer[8]);
- ASSERT.equal(0x79, buffer[9]);
-
- mod_ctype.wdouble(-0.000015130017658081283,
- 'little', buffer, 2);
- ASSERT.equal(0xbe, buffer[9]);
- ASSERT.equal(0xef, buffer[8]);
- ASSERT.equal(0xba, buffer[7]);
- ASSERT.equal(0xdd, buffer[6]);
- ASSERT.equal(0xca, buffer[5]);
- ASSERT.equal(0xfe, buffer[4]);
- ASSERT.equal(0x16, buffer[3]);
- ASSERT.equal(0x79, buffer[2]);
-}
-
-testfloat();
-testdouble();
+++ /dev/null
-/*
- * Test our ability to read and write signed 64-bit integers.
- */
-
-var mod_ctype = require('../../../ctio.js');
-var ASSERT = require('assert');
-
-function testRead()
-{
- var res, data;
- data = new Buffer(10);
-
- data[0] = 0x32;
- data[1] = 0x65;
- data[2] = 0x42;
- data[3] = 0x56;
- data[4] = 0x23;
- data[5] = 0xff;
- data[6] = 0xff;
- data[7] = 0xff;
- data[8] = 0x89;
- data[9] = 0x11;
- res = mod_ctype.rsint64(data, 'big', 0);
- ASSERT.equal(0x32654256, res[0]);
- ASSERT.equal(0x23ffffff, res[1]);
- res = mod_ctype.rsint64(data, 'big', 1);
- ASSERT.equal(0x65425623, res[0]);
- ASSERT.equal(0xffffff89, res[1]);
- res = mod_ctype.rsint64(data, 'big', 2);
- ASSERT.equal(0x425623ff, res[0]);
- ASSERT.equal(0xffff8911, res[1]);
- res = mod_ctype.rsint64(data, 'little', 0);
- ASSERT.equal(-0x000000dc, res[0]);
- ASSERT.equal(-0xa9bd9ace, res[1]);
- res = mod_ctype.rsint64(data, 'little', 1);
- ASSERT.equal(-0x76000000, res[0]);
- ASSERT.equal(-0xdca9bd9b, res[1]);
- res = mod_ctype.rsint64(data, 'little', 2);
- ASSERT.equal(0x1189ffff, res[0]);
- ASSERT.equal(0xff235642, res[1]);
-
- data.fill(0x00);
- res = mod_ctype.rsint64(data, 'big', 0);
- ASSERT.equal(0x00000000, res[0]);
- ASSERT.equal(0x00000000, res[1]);
- res = mod_ctype.rsint64(data, 'big', 1);
- ASSERT.equal(0x00000000, res[0]);
- ASSERT.equal(0x00000000, res[1]);
- res = mod_ctype.rsint64(data, 'big', 2);
- ASSERT.equal(0x00000000, res[0]);
- ASSERT.equal(0x00000000, res[1]);
- res = mod_ctype.rsint64(data, 'little', 0);
- ASSERT.equal(0x00000000, res[0]);
- ASSERT.equal(0x00000000, res[1]);
- res = mod_ctype.rsint64(data, 'little', 1);
- ASSERT.equal(0x00000000, res[0]);
- ASSERT.equal(0x00000000, res[1]);
- res = mod_ctype.rsint64(data, 'little', 2);
- ASSERT.equal(0x00000000, res[0]);
- ASSERT.equal(0x00000000, res[1]);
-
- data.fill(0xff);
- res = mod_ctype.rsint64(data, 'big', 0);
- ASSERT.equal(0x00000000, res[0]);
- ASSERT.equal(-1, res[1]);
- res = mod_ctype.rsint64(data, 'big', 1);
- ASSERT.equal(0x00000000, res[0]);
- ASSERT.equal(-1, res[1]);
- res = mod_ctype.rsint64(data, 'big', 2);
- ASSERT.equal(0x00000000, res[0]);
- ASSERT.equal(-1, res[1]);
- res = mod_ctype.rsint64(data, 'little', 0);
- ASSERT.equal(0x00000000, res[0]);
- ASSERT.equal(-1, res[1]);
- res = mod_ctype.rsint64(data, 'little', 1);
- ASSERT.equal(0x00000000, res[0]);
- ASSERT.equal(-1, res[1]);
- res = mod_ctype.rsint64(data, 'little', 2);
- ASSERT.equal(0x00000000, res[0]);
- ASSERT.equal(-1, res[1]);
-
- data[0] = 0x80;
- data[1] = 0x00;
- data[2] = 0x00;
- data[3] = 0x00;
- data[4] = 0x00;
- data[5] = 0x00;
- data[6] = 0x00;
- data[7] = 0x00;
- res = mod_ctype.rsint64(data, 'big', 0);
- ASSERT.equal(-0x80000000, res[0]);
- ASSERT.equal(0, res[1]);
-
-
- data[7] = 0x80;
- data[6] = 0x00;
- data[5] = 0x00;
- data[4] = 0x00;
- data[3] = 0x00;
- data[2] = 0x00;
- data[1] = 0x00;
- data[0] = 0x00;
- res = mod_ctype.rsint64(data, 'little', 0);
- ASSERT.equal(-0x80000000, res[0]);
- ASSERT.equal(0, res[1]);
-
- data[0] = 0x80;
- data[1] = 0x00;
- data[2] = 0x00;
- data[3] = 0x00;
- data[4] = 0x00;
- data[5] = 0x00;
- data[6] = 0x00;
- data[7] = 0x01;
- res = mod_ctype.rsint64(data, 'big', 0);
- ASSERT.equal(-0x7fffffff, res[0]);
- ASSERT.equal(-0xffffffff, res[1]);
-
-
-}
-
-function testWriteZero()
-{
- var data, buf;
- buf = new Buffer(10);
-
- buf.fill(0x66);
- data = [0, 0];
- mod_ctype.wsint64(data, 'big', buf, 0);
- ASSERT.equal(0, buf[0]);
- ASSERT.equal(0, buf[1]);
- ASSERT.equal(0, buf[2]);
- ASSERT.equal(0, buf[3]);
- ASSERT.equal(0, buf[4]);
- ASSERT.equal(0, buf[5]);
- ASSERT.equal(0, buf[6]);
- ASSERT.equal(0, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- data = [0, 0];
- mod_ctype.wsint64(data, 'big', buf, 1);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0, buf[1]);
- ASSERT.equal(0, buf[2]);
- ASSERT.equal(0, buf[3]);
- ASSERT.equal(0, buf[4]);
- ASSERT.equal(0, buf[5]);
- ASSERT.equal(0, buf[6]);
- ASSERT.equal(0, buf[7]);
- ASSERT.equal(0, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- data = [0, 0];
- mod_ctype.wsint64(data, 'big', buf, 2);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x66, buf[1]);
- ASSERT.equal(0, buf[2]);
- ASSERT.equal(0, buf[3]);
- ASSERT.equal(0, buf[4]);
- ASSERT.equal(0, buf[5]);
- ASSERT.equal(0, buf[6]);
- ASSERT.equal(0, buf[7]);
- ASSERT.equal(0, buf[8]);
- ASSERT.equal(0, buf[9]);
-
-
- buf.fill(0x66);
- data = [0, 0];
- mod_ctype.wsint64(data, 'little', buf, 0);
- ASSERT.equal(0, buf[0]);
- ASSERT.equal(0, buf[1]);
- ASSERT.equal(0, buf[2]);
- ASSERT.equal(0, buf[3]);
- ASSERT.equal(0, buf[4]);
- ASSERT.equal(0, buf[5]);
- ASSERT.equal(0, buf[6]);
- ASSERT.equal(0, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- data = [0, 0];
- mod_ctype.wsint64(data, 'little', buf, 1);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0, buf[1]);
- ASSERT.equal(0, buf[2]);
- ASSERT.equal(0, buf[3]);
- ASSERT.equal(0, buf[4]);
- ASSERT.equal(0, buf[5]);
- ASSERT.equal(0, buf[6]);
- ASSERT.equal(0, buf[7]);
- ASSERT.equal(0, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- data = [0, 0];
- mod_ctype.wsint64(data, 'little', buf, 2);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x66, buf[1]);
- ASSERT.equal(0, buf[2]);
- ASSERT.equal(0, buf[3]);
- ASSERT.equal(0, buf[4]);
- ASSERT.equal(0, buf[5]);
- ASSERT.equal(0, buf[6]);
- ASSERT.equal(0, buf[7]);
- ASSERT.equal(0, buf[8]);
- ASSERT.equal(0, buf[9]);
-}
-
-/*
- * Also include tests that are going to force us to go into a negative value and
- * insure that it's written correctly.
- */
-function testWrite()
-{
- var data, buf;
-
- buf = new Buffer(10);
- data = [ 0x234456, 0x87 ];
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'big', buf, 0);
- ASSERT.equal(0x00, buf[0]);
- ASSERT.equal(0x23, buf[1]);
- ASSERT.equal(0x44, buf[2]);
- ASSERT.equal(0x56, buf[3]);
- ASSERT.equal(0x00, buf[4]);
- ASSERT.equal(0x00, buf[5]);
- ASSERT.equal(0x00, buf[6]);
- ASSERT.equal(0x87, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'big', buf, 1);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x00, buf[1]);
- ASSERT.equal(0x23, buf[2]);
- ASSERT.equal(0x44, buf[3]);
- ASSERT.equal(0x56, buf[4]);
- ASSERT.equal(0x00, buf[5]);
- ASSERT.equal(0x00, buf[6]);
- ASSERT.equal(0x00, buf[7]);
- ASSERT.equal(0x87, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'big', buf, 2);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x66, buf[1]);
- ASSERT.equal(0x00, buf[2]);
- ASSERT.equal(0x23, buf[3]);
- ASSERT.equal(0x44, buf[4]);
- ASSERT.equal(0x56, buf[5]);
- ASSERT.equal(0x00, buf[6]);
- ASSERT.equal(0x00, buf[7]);
- ASSERT.equal(0x00, buf[8]);
- ASSERT.equal(0x87, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'little', buf, 0);
- ASSERT.equal(0x87, buf[0]);
- ASSERT.equal(0x00, buf[1]);
- ASSERT.equal(0x00, buf[2]);
- ASSERT.equal(0x00, buf[3]);
- ASSERT.equal(0x56, buf[4]);
- ASSERT.equal(0x44, buf[5]);
- ASSERT.equal(0x23, buf[6]);
- ASSERT.equal(0x00, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'little', buf, 1);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x87, buf[1]);
- ASSERT.equal(0x00, buf[2]);
- ASSERT.equal(0x00, buf[3]);
- ASSERT.equal(0x00, buf[4]);
- ASSERT.equal(0x56, buf[5]);
- ASSERT.equal(0x44, buf[6]);
- ASSERT.equal(0x23, buf[7]);
- ASSERT.equal(0x00, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'little', buf, 2);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x66, buf[1]);
- ASSERT.equal(0x87, buf[2]);
- ASSERT.equal(0x00, buf[3]);
- ASSERT.equal(0x00, buf[4]);
- ASSERT.equal(0x00, buf[5]);
- ASSERT.equal(0x56, buf[6]);
- ASSERT.equal(0x44, buf[7]);
- ASSERT.equal(0x23, buf[8]);
- ASSERT.equal(0x00, buf[9]);
-
- data = [0x3421, 0x34abcdba];
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'big', buf, 0);
- ASSERT.equal(0x00, buf[0]);
- ASSERT.equal(0x00, buf[1]);
- ASSERT.equal(0x34, buf[2]);
- ASSERT.equal(0x21, buf[3]);
- ASSERT.equal(0x34, buf[4]);
- ASSERT.equal(0xab, buf[5]);
- ASSERT.equal(0xcd, buf[6]);
- ASSERT.equal(0xba, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'big', buf, 1);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x00, buf[1]);
- ASSERT.equal(0x00, buf[2]);
- ASSERT.equal(0x34, buf[3]);
- ASSERT.equal(0x21, buf[4]);
- ASSERT.equal(0x34, buf[5]);
- ASSERT.equal(0xab, buf[6]);
- ASSERT.equal(0xcd, buf[7]);
- ASSERT.equal(0xba, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'big', buf, 2);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x66, buf[1]);
- ASSERT.equal(0x00, buf[2]);
- ASSERT.equal(0x00, buf[3]);
- ASSERT.equal(0x34, buf[4]);
- ASSERT.equal(0x21, buf[5]);
- ASSERT.equal(0x34, buf[6]);
- ASSERT.equal(0xab, buf[7]);
- ASSERT.equal(0xcd, buf[8]);
- ASSERT.equal(0xba, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'little', buf, 0);
- ASSERT.equal(0xba, buf[0]);
- ASSERT.equal(0xcd, buf[1]);
- ASSERT.equal(0xab, buf[2]);
- ASSERT.equal(0x34, buf[3]);
- ASSERT.equal(0x21, buf[4]);
- ASSERT.equal(0x34, buf[5]);
- ASSERT.equal(0x00, buf[6]);
- ASSERT.equal(0x00, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'little', buf, 1);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0xba, buf[1]);
- ASSERT.equal(0xcd, buf[2]);
- ASSERT.equal(0xab, buf[3]);
- ASSERT.equal(0x34, buf[4]);
- ASSERT.equal(0x21, buf[5]);
- ASSERT.equal(0x34, buf[6]);
- ASSERT.equal(0x00, buf[7]);
- ASSERT.equal(0x00, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'little', buf, 2);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x66, buf[1]);
- ASSERT.equal(0xba, buf[2]);
- ASSERT.equal(0xcd, buf[3]);
- ASSERT.equal(0xab, buf[4]);
- ASSERT.equal(0x34, buf[5]);
- ASSERT.equal(0x21, buf[6]);
- ASSERT.equal(0x34, buf[7]);
- ASSERT.equal(0x00, buf[8]);
- ASSERT.equal(0x00, buf[9]);
-
-
- data = [ -0x80000000, 0 ];
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'big', buf, 0);
- ASSERT.equal(0x80, buf[0]);
- ASSERT.equal(0x00, buf[1]);
- ASSERT.equal(0x00, buf[2]);
- ASSERT.equal(0x00, buf[3]);
- ASSERT.equal(0x00, buf[4]);
- ASSERT.equal(0x00, buf[5]);
- ASSERT.equal(0x00, buf[6]);
- ASSERT.equal(0x00, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'little', buf, 0);
- ASSERT.equal(0x00, buf[0]);
- ASSERT.equal(0x00, buf[1]);
- ASSERT.equal(0x00, buf[2]);
- ASSERT.equal(0x00, buf[3]);
- ASSERT.equal(0x00, buf[4]);
- ASSERT.equal(0x00, buf[5]);
- ASSERT.equal(0x00, buf[6]);
- ASSERT.equal(0x80, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- data = [ -0x7fffffff, -0xffffffff ];
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'big', buf, 0);
- ASSERT.equal(0x80, buf[0]);
- ASSERT.equal(0x00, buf[1]);
- ASSERT.equal(0x00, buf[2]);
- ASSERT.equal(0x00, buf[3]);
- ASSERT.equal(0x00, buf[4]);
- ASSERT.equal(0x00, buf[5]);
- ASSERT.equal(0x00, buf[6]);
- ASSERT.equal(0x01, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'little', buf, 0);
- ASSERT.equal(0x01, buf[0]);
- ASSERT.equal(0x00, buf[1]);
- ASSERT.equal(0x00, buf[2]);
- ASSERT.equal(0x00, buf[3]);
- ASSERT.equal(0x00, buf[4]);
- ASSERT.equal(0x00, buf[5]);
- ASSERT.equal(0x00, buf[6]);
- ASSERT.equal(0x80, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- data = [ 0x0, -0x1];
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'big', buf, 0);
- ASSERT.equal(0xff, buf[0]);
- ASSERT.equal(0xff, buf[1]);
- ASSERT.equal(0xff, buf[2]);
- ASSERT.equal(0xff, buf[3]);
- ASSERT.equal(0xff, buf[4]);
- ASSERT.equal(0xff, buf[5]);
- ASSERT.equal(0xff, buf[6]);
- ASSERT.equal(0xff, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wsint64(data, 'little', buf, 0);
- ASSERT.equal(0xff, buf[0]);
- ASSERT.equal(0xff, buf[1]);
- ASSERT.equal(0xff, buf[2]);
- ASSERT.equal(0xff, buf[3]);
- ASSERT.equal(0xff, buf[4]);
- ASSERT.equal(0xff, buf[5]);
- ASSERT.equal(0xff, buf[6]);
- ASSERT.equal(0xff, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-}
-
-/*
- * Make sure we catch invalid writes.
- */
-function testWriteInvalid()
-{
- var data, buf;
-
- /* Buffer too small */
- buf = new Buffer(4);
- data = [ 0, 0];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 0);
- }, Error, 'buffer too small');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 0);
- }, Error, 'buffer too small');
-
- /* Beyond the end of the buffer */
- buf = new Buffer(12);
- data = [ 0, 0];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 11);
- }, Error, 'write beyond end of buffer');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 11);
- }, Error, 'write beyond end of buffer');
-
- /* Write fractional values */
- buf = new Buffer(12);
- data = [ 3.33, 0 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write fractions');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write fractions');
-
- data = [ 0, 3.3 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write fractions');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write fractions');
-
- data = [ -3.33, 0 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write fractions');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write fractions');
-
- data = [ 0, -3.3 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write fractions');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write fractions');
-
- data = [ 3.33, 2.42 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write fractions');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write fractions');
-
- data = [ 3.33, -2.42 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write fractions');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write fractions');
-
- data = [ -3.33, -2.42 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write fractions');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write fractions');
-
- data = [ -3.33, 2.42 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write fractions');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write fractions');
-
- /* Signs don't match */
- buf = new Buffer(12);
- data = [ 0x800000, -0x32 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write too large');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write too large');
-
- data = [ -0x800000, 0x32 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write too large');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write too large');
-
- /* Write values that are too large */
- buf = new Buffer(12);
- data = [ 0x80000000, 0 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write too large');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write too large');
-
- data = [ 0x7fffffff, 0x100000000 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write too large');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write too large');
-
- data = [ 0x00, 0x800000000 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write too large');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write too large');
-
- data = [ 0xffffffffff, 0xffffff238 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write too large');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write too large');
-
- data = [ 0x23, 0xffffff238 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write too large');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write too large');
-
- data = [ -0x80000000, -0xfff238 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write too large');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write too large');
-
- data = [ -0x80000004, -0xfff238 ];
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'big', buf, 1);
- }, Error, 'write too large');
- ASSERT.throws(function () {
- mod_ctype.wsint64(data, 'little', buf, 1);
- }, Error, 'write too large');
-}
-
-
-testRead();
-testWrite();
-testWriteZero();
-testWriteInvalid();
+++ /dev/null
-/*
- * Tests to verify we're reading in signed integers correctly
- */
-var mod_ctype = require('../../../ctio.js');
-var ASSERT = require('assert');
-
-/*
- * Test 8 bit signed integers
- */
-function test8()
-{
- var data = new Buffer(4);
-
- data[0] = 0x23;
- ASSERT.equal(0x23, mod_ctype.rsint8(data, 'big', 0));
- ASSERT.equal(0x23, mod_ctype.rsint8(data, 'little', 0));
-
- data[0] = 0xff;
- ASSERT.equal(-1, mod_ctype.rsint8(data, 'big', 0));
- ASSERT.equal(-1, mod_ctype.rsint8(data, 'little', 0));
-
- data[0] = 0x87;
- data[1] = 0xab;
- data[2] = 0x7c;
- data[3] = 0xef;
- ASSERT.equal(-121, mod_ctype.rsint8(data, 'big', 0));
- ASSERT.equal(-85, mod_ctype.rsint8(data, 'big', 1));
- ASSERT.equal(124, mod_ctype.rsint8(data, 'big', 2));
- ASSERT.equal(-17, mod_ctype.rsint8(data, 'big', 3));
- ASSERT.equal(-121, mod_ctype.rsint8(data, 'little', 0));
- ASSERT.equal(-85, mod_ctype.rsint8(data, 'little', 1));
- ASSERT.equal(124, mod_ctype.rsint8(data, 'little', 2));
- ASSERT.equal(-17, mod_ctype.rsint8(data, 'little', 3));
-}
-
-function test16()
-{
- var buffer = new Buffer(6);
- buffer[0] = 0x16;
- buffer[1] = 0x79;
- ASSERT.equal(0x1679, mod_ctype.rsint16(buffer, 'big', 0));
- ASSERT.equal(0x7916, mod_ctype.rsint16(buffer, 'little', 0));
-
- buffer[0] = 0xff;
- buffer[1] = 0x80;
- ASSERT.equal(-128, mod_ctype.rsint16(buffer, 'big', 0));
- ASSERT.equal(-32513, mod_ctype.rsint16(buffer, 'little', 0));
-
- /* test offset with weenix */
- buffer[0] = 0x77;
- buffer[1] = 0x65;
- buffer[2] = 0x65;
- buffer[3] = 0x6e;
- buffer[4] = 0x69;
- buffer[5] = 0x78;
- ASSERT.equal(0x7765, mod_ctype.rsint16(buffer, 'big', 0));
- ASSERT.equal(0x6565, mod_ctype.rsint16(buffer, 'big', 1));
- ASSERT.equal(0x656e, mod_ctype.rsint16(buffer, 'big', 2));
- ASSERT.equal(0x6e69, mod_ctype.rsint16(buffer, 'big', 3));
- ASSERT.equal(0x6978, mod_ctype.rsint16(buffer, 'big', 4));
- ASSERT.equal(0x6577, mod_ctype.rsint16(buffer, 'little', 0));
- ASSERT.equal(0x6565, mod_ctype.rsint16(buffer, 'little', 1));
- ASSERT.equal(0x6e65, mod_ctype.rsint16(buffer, 'little', 2));
- ASSERT.equal(0x696e, mod_ctype.rsint16(buffer, 'little', 3));
- ASSERT.equal(0x7869, mod_ctype.rsint16(buffer, 'little', 4));
-}
-
-function test32()
-{
- var buffer = new Buffer(6);
- buffer[0] = 0x43;
- buffer[1] = 0x53;
- buffer[2] = 0x16;
- buffer[3] = 0x79;
- ASSERT.equal(0x43531679, mod_ctype.rsint32(buffer, 'big', 0));
- ASSERT.equal(0x79165343, mod_ctype.rsint32(buffer, 'little', 0));
-
- buffer[0] = 0xff;
- buffer[1] = 0xfe;
- buffer[2] = 0xef;
- buffer[3] = 0xfa;
- ASSERT.equal(-69638, mod_ctype.rsint32(buffer, 'big', 0));
- ASSERT.equal(-84934913, mod_ctype.rsint32(buffer, 'little', 0));
-
- buffer[0] = 0x42;
- buffer[1] = 0xc3;
- buffer[2] = 0x95;
- buffer[3] = 0xa9;
- buffer[4] = 0x36;
- buffer[5] = 0x17;
- ASSERT.equal(0x42c395a9, mod_ctype.rsint32(buffer, 'big', 0));
- ASSERT.equal(-1013601994, mod_ctype.rsint32(buffer, 'big', 1));
- ASSERT.equal(-1784072681, mod_ctype.rsint32(buffer, 'big', 2));
- ASSERT.equal(-1449802942, mod_ctype.rsint32(buffer, 'little', 0));
- ASSERT.equal(917083587, mod_ctype.rsint32(buffer, 'little', 1));
- ASSERT.equal(389458325, mod_ctype.rsint32(buffer, 'little', 2));
-}
-
-test8();
-test16();
-test32();
+++ /dev/null
-/*
- * Test to make sure that we properly are erroring whenever we try to write
- * beyond the size of the integer.
- */
-
-var mod_ctio = require('../../../ctio.js');
-var mod_assert = require('assert');
-var tb = new Buffer(16); /* Largest buffer we'll need */
-
-var cases = [
- { func:
- function () {
- mod_ctio.wsint8(0x80, 'big', tb, 0);
- }, test: '+int8_t' },
- { func:
- function () {
- mod_ctio.wsint8(-0x81, 'big', tb, 0);
- }, test: '-int8_t' },
-
- { func:
- function () {
- mod_ctio.wsint16(0x8000, 'big', tb, 0);
- }, test: '+int16_t' },
- { func:
- function () {
- mod_ctio.wsint16(-0x8001, 'big', tb, 0);
- }, test: '-int16_t' },
- { func:
- function () {
- mod_ctio.wsint32(0x80000000, 'big', tb, 0);
- }, test: '+int32_t' },
- { func:
- function () {
- mod_ctio.wsint32(-0x80000001, 'big', tb, 0);
- }, test: '-int32_t' },
- { func:
- function () {
- mod_ctio.wsint64([ 0x80000000, 0 ], 'big', tb, 0);
- }, test: '+int64_t' },
- { func:
- function () {
- mod_ctio.wsint64([ -0x80000000, -1 ], 'big', tb, 0);
- }, test: '-int64_t' }
-];
-
-function test()
-{
- var ii;
- for (ii = 0; ii < cases.length; ii++)
- mod_assert.throws(cases[ii]['func'], Error, cases[ii]['test']);
-}
-
-test();
+++ /dev/null
-/*
- * Tests to verify we're writing signed integers correctly
- */
-var mod_ctype = require('../../../ctio.js');
-var ASSERT = require('assert');
-
-function test8()
-{
- var buffer = new Buffer(4);
- mod_ctype.wsint8(0x23, 'big', buffer, 0);
- mod_ctype.wsint8(0x23, 'little', buffer, 1);
- mod_ctype.wsint8(-5, 'big', buffer, 2);
- mod_ctype.wsint8(-5, 'little', buffer, 3);
-
- ASSERT.equal(0x23, buffer[0]);
- ASSERT.equal(0x23, buffer[1]);
- ASSERT.equal(0xfb, buffer[2]);
- ASSERT.equal(0xfb, buffer[3]);
-
- /* Make sure we handle truncation correctly */
- ASSERT.throws(function () {
- mod_ctype.wsint8(0xabc, 'big', buffer, 0);
- });
- ASSERT.throws(function () {
- mod_ctype.wsint8(0xabc, 'little', buffer, 0);
- });
-}
-
-function test16()
-{
- var buffer = new Buffer(6);
- mod_ctype.wsint16(0x0023, 'big', buffer, 0);
- mod_ctype.wsint16(0x0023, 'little', buffer, 2);
- ASSERT.equal(0x00, buffer[0]);
- ASSERT.equal(0x23, buffer[1]);
- ASSERT.equal(0x23, buffer[2]);
- ASSERT.equal(0x00, buffer[3]);
- mod_ctype.wsint16(-5, 'big', buffer, 0);
- mod_ctype.wsint16(-5, 'little', buffer, 2);
- ASSERT.equal(0xff, buffer[0]);
- ASSERT.equal(0xfb, buffer[1]);
- ASSERT.equal(0xfb, buffer[2]);
- ASSERT.equal(0xff, buffer[3]);
-
- mod_ctype.wsint16(-1679, 'big', buffer, 1);
- mod_ctype.wsint16(-1679, 'little', buffer, 3);
- ASSERT.equal(0xf9, buffer[1]);
- ASSERT.equal(0x71, buffer[2]);
- ASSERT.equal(0x71, buffer[3]);
- ASSERT.equal(0xf9, buffer[4]);
-}
-
-function test32()
-{
- var buffer = new Buffer(8);
- mod_ctype.wsint32(0x23, 'big', buffer, 0);
- mod_ctype.wsint32(0x23, 'little', buffer, 4);
- ASSERT.equal(0x00, buffer[0]);
- ASSERT.equal(0x00, buffer[1]);
- ASSERT.equal(0x00, buffer[2]);
- ASSERT.equal(0x23, buffer[3]);
- ASSERT.equal(0x23, buffer[4]);
- ASSERT.equal(0x00, buffer[5]);
- ASSERT.equal(0x00, buffer[6]);
- ASSERT.equal(0x00, buffer[7]);
-
- mod_ctype.wsint32(-5, 'big', buffer, 0);
- mod_ctype.wsint32(-5, 'little', buffer, 4);
- ASSERT.equal(0xff, buffer[0]);
- ASSERT.equal(0xff, buffer[1]);
- ASSERT.equal(0xff, buffer[2]);
- ASSERT.equal(0xfb, buffer[3]);
- ASSERT.equal(0xfb, buffer[4]);
- ASSERT.equal(0xff, buffer[5]);
- ASSERT.equal(0xff, buffer[6]);
- ASSERT.equal(0xff, buffer[7]);
-
- mod_ctype.wsint32(-805306713, 'big', buffer, 0);
- mod_ctype.wsint32(-805306713, 'litle', buffer, 4);
- ASSERT.equal(0xcf, buffer[0]);
- ASSERT.equal(0xff, buffer[1]);
- ASSERT.equal(0xfe, buffer[2]);
- ASSERT.equal(0xa7, buffer[3]);
- ASSERT.equal(0xa7, buffer[4]);
- ASSERT.equal(0xfe, buffer[5]);
- ASSERT.equal(0xff, buffer[6]);
- ASSERT.equal(0xcf, buffer[7]);
-}
-
-test8();
-test16();
-test32();
+++ /dev/null
-/*
- * Test our ability to read and write unsigned 64-bit integers.
- */
-
-var mod_ctype = require('../../../ctio.js');
-var ASSERT = require('assert');
-
-function testRead()
-{
- var res, data;
- data = new Buffer(10);
-
- data[0] = 0x32;
- data[1] = 0x65;
- data[2] = 0x42;
- data[3] = 0x56;
- data[4] = 0x23;
- data[5] = 0xff;
- data[6] = 0xff;
- data[7] = 0xff;
- data[8] = 0x89;
- data[9] = 0x11;
- res = mod_ctype.ruint64(data, 'big', 0);
- ASSERT.equal(0x32654256, res[0]);
- ASSERT.equal(0x23ffffff, res[1]);
- res = mod_ctype.ruint64(data, 'big', 1);
- ASSERT.equal(0x65425623, res[0]);
- ASSERT.equal(0xffffff89, res[1]);
- res = mod_ctype.ruint64(data, 'big', 2);
- ASSERT.equal(0x425623ff, res[0]);
- ASSERT.equal(0xffff8911, res[1]);
- res = mod_ctype.ruint64(data, 'little', 0);
- ASSERT.equal(0xffffff23, res[0]);
- ASSERT.equal(0x56426532, res[1]);
- res = mod_ctype.ruint64(data, 'little', 1);
- ASSERT.equal(0x89ffffff, res[0]);
- ASSERT.equal(0x23564265, res[1]);
- res = mod_ctype.ruint64(data, 'little', 2);
- ASSERT.equal(0x1189ffff, res[0]);
- ASSERT.equal(0xff235642, res[1]);
-
-}
-
-function testReadOver()
-{
- var res, data;
- data = new Buffer(10);
-
- data[0] = 0x80;
- data[1] = 0xff;
- data[2] = 0x80;
- data[3] = 0xff;
- data[4] = 0x80;
- data[5] = 0xff;
- data[6] = 0x80;
- data[7] = 0xff;
- data[8] = 0x80;
- data[9] = 0xff;
- res = mod_ctype.ruint64(data, 'big', 0);
- ASSERT.equal(0x80ff80ff, res[0]);
- ASSERT.equal(0x80ff80ff, res[1]);
- res = mod_ctype.ruint64(data, 'big', 1);
- ASSERT.equal(0xff80ff80, res[0]);
- ASSERT.equal(0xff80ff80, res[1]);
- res = mod_ctype.ruint64(data, 'big', 2);
- ASSERT.equal(0x80ff80ff, res[0]);
- ASSERT.equal(0x80ff80ff, res[1]);
- res = mod_ctype.ruint64(data, 'little', 0);
- ASSERT.equal(0xff80ff80, res[0]);
- ASSERT.equal(0xff80ff80, res[1]);
- res = mod_ctype.ruint64(data, 'little', 1);
- ASSERT.equal(0x80ff80ff, res[0]);
- ASSERT.equal(0x80ff80ff, res[1]);
- res = mod_ctype.ruint64(data, 'little', 2);
- ASSERT.equal(0xff80ff80, res[0]);
- ASSERT.equal(0xff80ff80, res[1]);
-}
-
-function testWriteZero()
-{
- var data, buf;
- buf = new Buffer(10);
-
- buf.fill(0x66);
- data = [0, 0];
- mod_ctype.wuint64(data, 'big', buf, 0);
- ASSERT.equal(0, buf[0]);
- ASSERT.equal(0, buf[1]);
- ASSERT.equal(0, buf[2]);
- ASSERT.equal(0, buf[3]);
- ASSERT.equal(0, buf[4]);
- ASSERT.equal(0, buf[5]);
- ASSERT.equal(0, buf[6]);
- ASSERT.equal(0, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- data = [0, 0];
- mod_ctype.wuint64(data, 'big', buf, 1);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0, buf[1]);
- ASSERT.equal(0, buf[2]);
- ASSERT.equal(0, buf[3]);
- ASSERT.equal(0, buf[4]);
- ASSERT.equal(0, buf[5]);
- ASSERT.equal(0, buf[6]);
- ASSERT.equal(0, buf[7]);
- ASSERT.equal(0, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- data = [0, 0];
- mod_ctype.wuint64(data, 'big', buf, 2);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x66, buf[1]);
- ASSERT.equal(0, buf[2]);
- ASSERT.equal(0, buf[3]);
- ASSERT.equal(0, buf[4]);
- ASSERT.equal(0, buf[5]);
- ASSERT.equal(0, buf[6]);
- ASSERT.equal(0, buf[7]);
- ASSERT.equal(0, buf[8]);
- ASSERT.equal(0, buf[9]);
-
-
- buf.fill(0x66);
- data = [0, 0];
- mod_ctype.wuint64(data, 'little', buf, 0);
- ASSERT.equal(0, buf[0]);
- ASSERT.equal(0, buf[1]);
- ASSERT.equal(0, buf[2]);
- ASSERT.equal(0, buf[3]);
- ASSERT.equal(0, buf[4]);
- ASSERT.equal(0, buf[5]);
- ASSERT.equal(0, buf[6]);
- ASSERT.equal(0, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- data = [0, 0];
- mod_ctype.wuint64(data, 'little', buf, 1);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0, buf[1]);
- ASSERT.equal(0, buf[2]);
- ASSERT.equal(0, buf[3]);
- ASSERT.equal(0, buf[4]);
- ASSERT.equal(0, buf[5]);
- ASSERT.equal(0, buf[6]);
- ASSERT.equal(0, buf[7]);
- ASSERT.equal(0, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- data = [0, 0];
- mod_ctype.wuint64(data, 'little', buf, 2);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x66, buf[1]);
- ASSERT.equal(0, buf[2]);
- ASSERT.equal(0, buf[3]);
- ASSERT.equal(0, buf[4]);
- ASSERT.equal(0, buf[5]);
- ASSERT.equal(0, buf[6]);
- ASSERT.equal(0, buf[7]);
- ASSERT.equal(0, buf[8]);
- ASSERT.equal(0, buf[9]);
-}
-
-/*
- * Also include tests that are going to force us to go into a negative value and
- * insure that it's written correctly.
- */
-function testWrite()
-{
- var data, buf;
-
- buf = new Buffer(10);
- data = [ 0x234456, 0x87 ];
- buf.fill(0x66);
- mod_ctype.wuint64(data, 'big', buf, 0);
- ASSERT.equal(0x00, buf[0]);
- ASSERT.equal(0x23, buf[1]);
- ASSERT.equal(0x44, buf[2]);
- ASSERT.equal(0x56, buf[3]);
- ASSERT.equal(0x00, buf[4]);
- ASSERT.equal(0x00, buf[5]);
- ASSERT.equal(0x00, buf[6]);
- ASSERT.equal(0x87, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wuint64(data, 'big', buf, 1);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x00, buf[1]);
- ASSERT.equal(0x23, buf[2]);
- ASSERT.equal(0x44, buf[3]);
- ASSERT.equal(0x56, buf[4]);
- ASSERT.equal(0x00, buf[5]);
- ASSERT.equal(0x00, buf[6]);
- ASSERT.equal(0x00, buf[7]);
- ASSERT.equal(0x87, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wuint64(data, 'big', buf, 2);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x66, buf[1]);
- ASSERT.equal(0x00, buf[2]);
- ASSERT.equal(0x23, buf[3]);
- ASSERT.equal(0x44, buf[4]);
- ASSERT.equal(0x56, buf[5]);
- ASSERT.equal(0x00, buf[6]);
- ASSERT.equal(0x00, buf[7]);
- ASSERT.equal(0x00, buf[8]);
- ASSERT.equal(0x87, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wuint64(data, 'little', buf, 0);
- ASSERT.equal(0x87, buf[0]);
- ASSERT.equal(0x00, buf[1]);
- ASSERT.equal(0x00, buf[2]);
- ASSERT.equal(0x00, buf[3]);
- ASSERT.equal(0x56, buf[4]);
- ASSERT.equal(0x44, buf[5]);
- ASSERT.equal(0x23, buf[6]);
- ASSERT.equal(0x00, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wuint64(data, 'little', buf, 1);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x87, buf[1]);
- ASSERT.equal(0x00, buf[2]);
- ASSERT.equal(0x00, buf[3]);
- ASSERT.equal(0x00, buf[4]);
- ASSERT.equal(0x56, buf[5]);
- ASSERT.equal(0x44, buf[6]);
- ASSERT.equal(0x23, buf[7]);
- ASSERT.equal(0x00, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
-
- buf.fill(0x66);
- mod_ctype.wuint64(data, 'little', buf, 2);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x66, buf[1]);
- ASSERT.equal(0x87, buf[2]);
- ASSERT.equal(0x00, buf[3]);
- ASSERT.equal(0x00, buf[4]);
- ASSERT.equal(0x00, buf[5]);
- ASSERT.equal(0x56, buf[6]);
- ASSERT.equal(0x44, buf[7]);
- ASSERT.equal(0x23, buf[8]);
- ASSERT.equal(0x00, buf[9]);
-
- data = [0xffff3421, 0x34abcdba];
- buf.fill(0x66);
- mod_ctype.wuint64(data, 'big', buf, 0);
- ASSERT.equal(0xff, buf[0]);
- ASSERT.equal(0xff, buf[1]);
- ASSERT.equal(0x34, buf[2]);
- ASSERT.equal(0x21, buf[3]);
- ASSERT.equal(0x34, buf[4]);
- ASSERT.equal(0xab, buf[5]);
- ASSERT.equal(0xcd, buf[6]);
- ASSERT.equal(0xba, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wuint64(data, 'big', buf, 1);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0xff, buf[1]);
- ASSERT.equal(0xff, buf[2]);
- ASSERT.equal(0x34, buf[3]);
- ASSERT.equal(0x21, buf[4]);
- ASSERT.equal(0x34, buf[5]);
- ASSERT.equal(0xab, buf[6]);
- ASSERT.equal(0xcd, buf[7]);
- ASSERT.equal(0xba, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wuint64(data, 'big', buf, 2);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x66, buf[1]);
- ASSERT.equal(0xff, buf[2]);
- ASSERT.equal(0xff, buf[3]);
- ASSERT.equal(0x34, buf[4]);
- ASSERT.equal(0x21, buf[5]);
- ASSERT.equal(0x34, buf[6]);
- ASSERT.equal(0xab, buf[7]);
- ASSERT.equal(0xcd, buf[8]);
- ASSERT.equal(0xba, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wuint64(data, 'little', buf, 0);
- ASSERT.equal(0xba, buf[0]);
- ASSERT.equal(0xcd, buf[1]);
- ASSERT.equal(0xab, buf[2]);
- ASSERT.equal(0x34, buf[3]);
- ASSERT.equal(0x21, buf[4]);
- ASSERT.equal(0x34, buf[5]);
- ASSERT.equal(0xff, buf[6]);
- ASSERT.equal(0xff, buf[7]);
- ASSERT.equal(0x66, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wuint64(data, 'little', buf, 1);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0xba, buf[1]);
- ASSERT.equal(0xcd, buf[2]);
- ASSERT.equal(0xab, buf[3]);
- ASSERT.equal(0x34, buf[4]);
- ASSERT.equal(0x21, buf[5]);
- ASSERT.equal(0x34, buf[6]);
- ASSERT.equal(0xff, buf[7]);
- ASSERT.equal(0xff, buf[8]);
- ASSERT.equal(0x66, buf[9]);
-
- buf.fill(0x66);
- mod_ctype.wuint64(data, 'little', buf, 2);
- ASSERT.equal(0x66, buf[0]);
- ASSERT.equal(0x66, buf[1]);
- ASSERT.equal(0xba, buf[2]);
- ASSERT.equal(0xcd, buf[3]);
- ASSERT.equal(0xab, buf[4]);
- ASSERT.equal(0x34, buf[5]);
- ASSERT.equal(0x21, buf[6]);
- ASSERT.equal(0x34, buf[7]);
- ASSERT.equal(0xff, buf[8]);
- ASSERT.equal(0xff, buf[9]);
-}
-
-/*
- * Make sure we catch invalid writes.
- */
-function testWriteInvalid()
-{
- var data, buf;
-
- /* Buffer too small */
- buf = new Buffer(4);
- data = [ 0, 0];
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'big', buf, 0);
- }, Error, 'buffer too small');
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'little', buf, 0);
- }, Error, 'buffer too small');
-
- /* Beyond the end of the buffer */
- buf = new Buffer(12);
- data = [ 0, 0];
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'little', buf, 11);
- }, Error, 'write beyond end of buffer');
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'big', buf, 11);
- }, Error, 'write beyond end of buffer');
-
- /* Write negative values */
- buf = new Buffer(12);
- data = [ -3, 0 ];
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'big', buf, 1);
- }, Error, 'write negative number');
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'little', buf, 1);
- }, Error, 'write negative number');
-
- data = [ 0, -3 ];
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'big', buf, 1);
- }, Error, 'write negative number');
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'little', buf, 1);
- }, Error, 'write negative number');
-
- data = [ -3, -3 ];
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'big', buf, 1);
- }, Error, 'write negative number');
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'little', buf, 1);
- }, Error, 'write negative number');
-
-
- /* Write fractional values */
- buf = new Buffer(12);
- data = [ 3.33, 0 ];
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'big', buf, 1);
- }, Error, 'write fractions');
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'little', buf, 1);
- }, Error, 'write fractions');
-
- data = [ 0, 3.3 ];
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'big', buf, 1);
- }, Error, 'write fractions');
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'little', buf, 1);
- }, Error, 'write fractions');
-
- data = [ 3.33, 2.42 ];
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'big', buf, 1);
- }, Error, 'write fractions');
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'little', buf, 1);
- }, Error, 'write fractions');
-
- /* Write values that are too large */
- buf = new Buffer(12);
- data = [ 0xffffffffff, 23 ];
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'big', buf, 1);
- }, Error, 'write too large');
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'little', buf, 1);
- }, Error, 'write too large');
-
- data = [ 0xffffffffff, 0xffffff238 ];
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'big', buf, 1);
- }, Error, 'write too large');
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'little', buf, 1);
- }, Error, 'write too large');
-
- data = [ 0x23, 0xffffff238 ];
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'big', buf, 1);
- }, Error, 'write too large');
- ASSERT.throws(function () {
- mod_ctype.wuint64(data, 'little', buf, 1);
- }, Error, 'write too large');
-}
-
-
-testRead();
-testReadOver();
-testWriteZero();
-testWrite();
-testWriteInvalid();
+++ /dev/null
-/*
- * A battery of tests for sucessful round-trip between writes and reads
- */
-
-var mod_ctype = require('../../../ctio.js');
-var ASSERT = require('assert');
-
-
-/*
- * What the heck, let's just test every value for 8-bits.
- */
-
-function test8() {
- var data = new Buffer(1);
- var i;
- for (i = 0; i < 256; i++) {
- mod_ctype.wuint8(i, 'big', data, 0);
- ASSERT.equal(i, mod_ctype.ruint8(data, 'big', 0));
- mod_ctype.wuint8(i, 'little', data, 0);
- ASSERT.equal(i, mod_ctype.ruint8(data, 'little', 0));
- }
- ASSERT.ok(true);
-}
-
-/*
- * Test a random sample of 256 values in the 16-bit unsigned range
- */
-
-function test16() {
- var data = new Buffer(2);
- var i = 0;
- for (i = 0; i < 256; i++) {
- var value = Math.round(Math.random() * Math.pow(2, 16));
- mod_ctype.wuint16(value, 'big', data, 0);
- ASSERT.equal(value, mod_ctype.ruint16(data, 'big', 0));
- mod_ctype.wuint16(value, 'little', data, 0);
- ASSERT.equal(value, mod_ctype.ruint16(data, 'little', 0));
- }
-}
-
-/*
- * Test a random sample of 256 values in the 32-bit unsigned range
- */
-
-function test32() {
- var data = new Buffer(4);
- var i = 0;
- for (i = 0; i < 256; i++) {
- var value = Math.round(Math.random() * Math.pow(2, 32));
- mod_ctype.wuint32(value, 'big', data, 0);
- ASSERT.equal(value, mod_ctype.ruint32(data, 'big', 0));
- mod_ctype.wuint32(value, 'little', data, 0);
- ASSERT.equal(value, mod_ctype.ruint32(data, 'little', 0));
- }
-}
-
-/*
- * Test a random sample of 256 values in the 64-bit unsigned range
- */
-
-function test64() {
- var data = new Buffer(8);
- var i = 0;
- for (i = 0; i < 256; i++) {
- var low = Math.round(Math.random() * Math.pow(2, 32));
- var high = Math.round(Math.random() * Math.pow(2, 32));
- mod_ctype.wuint64([high, low], 'big', data, 0);
- var result = mod_ctype.ruint64(data, 'big', 0);
- ASSERT.equal(high, result[0]);
- ASSERT.equal(low, result[1]);
- mod_ctype.wuint64([high, low], 'little', data, 0);
- result = mod_ctype.ruint64(data, 'little', 0);
- ASSERT.equal(high, result[0]);
- ASSERT.equal(low, result[1]);
- }
-}
-
-exports.test8 = test8;
-exports.test16 = test16;
-exports.test32 = test32;
-exports.test64 = test64;
+++ /dev/null
-/*
- * A battery of tests to help us read a series of uints
- */
-
-var mod_ctype = require('../../../ctio.js');
-var ASSERT = require('assert');
-
-/*
- * We need to check the following things:
- * - We are correctly resolving big endian (doesn't mean anything for 8 bit)
- * - Correctly resolving little endian (doesn't mean anything for 8 bit)
- * - Correctly using the offsets
- * - Correctly interpreting values that are beyond the signed range as unsigned
- */
-function test8()
-{
- var data = new Buffer(4);
- data[0] = 23;
- data[1] = 23;
- data[2] = 23;
- data[3] = 23;
- ASSERT.equal(23, mod_ctype.ruint8(data, 'big', 0));
- ASSERT.equal(23, mod_ctype.ruint8(data, 'little', 0));
- ASSERT.equal(23, mod_ctype.ruint8(data, 'big', 1));
- ASSERT.equal(23, mod_ctype.ruint8(data, 'little', 1));
- ASSERT.equal(23, mod_ctype.ruint8(data, 'big', 2));
- ASSERT.equal(23, mod_ctype.ruint8(data, 'little', 2));
- ASSERT.equal(23, mod_ctype.ruint8(data, 'big', 3));
- ASSERT.equal(23, mod_ctype.ruint8(data, 'little', 3));
- data[0] = 255; /* If it became a signed int, would be -1 */
- ASSERT.equal(255, mod_ctype.ruint8(data, 'big', 0));
- ASSERT.equal(255, mod_ctype.ruint8(data, 'little', 0));
-}
-
-/*
- * Test 16 bit unsigned integers. We need to verify the same set as 8 bit, only
- * now some of the issues actually matter:
- * - We are correctly resolving big endian
- * - Correctly resolving little endian
- * - Correctly using the offsets
- * - Correctly interpreting values that are beyond the signed range as unsigned
- */
-function test16()
-{
- var data = new Buffer(4);
- /* Test signed values first */
- data[0] = 0;
- data[1] = 0x23;
- data[2] = 0x42;
- data[3] = 0x3f;
-
- ASSERT.equal(0x23, mod_ctype.ruint16(data, 'big', 0));
- ASSERT.equal(0x2342, mod_ctype.ruint16(data, 'big', 1));
- ASSERT.equal(0x423f, mod_ctype.ruint16(data, 'big', 2));
-
- ASSERT.equal(0x2300, mod_ctype.ruint16(data, 'little', 0));
- ASSERT.equal(0x4223, mod_ctype.ruint16(data, 'little', 1));
- ASSERT.equal(0x3f42, mod_ctype.ruint16(data, 'little', 2));
-
- data[0] = 0xfe;
- data[1] = 0xfe;
-
- ASSERT.equal(0xfefe, mod_ctype.ruint16(data, 'big', 0));
- ASSERT.equal(0xfefe, mod_ctype.ruint16(data, 'little', 0));
-}
-
-/*
- * Test 32 bit unsigned integers. We need to verify the same set as 8 bit, only
- * now some of the issues actually matter:
- * - We are correctly resolving big endian
- * - Correctly using the offsets
- * - Correctly interpreting values that are beyond the signed range as unsigned
- */
-function test32()
-{
- var data = new Buffer(8);
- data[0] = 0x32;
- data[1] = 0x65;
- data[2] = 0x42;
- data[3] = 0x56;
- data[4] = 0x23;
- data[5] = 0xff;
-
- ASSERT.equal(0x32654256, mod_ctype.ruint32(data, 'big', 0));
- ASSERT.equal(0x65425623, mod_ctype.ruint32(data, 'big', 1));
- ASSERT.equal(0x425623ff, mod_ctype.ruint32(data, 'big', 2));
-
- ASSERT.equal(0x56426532, mod_ctype.ruint32(data, 'little', 0));
- ASSERT.equal(0x23564265, mod_ctype.ruint32(data, 'little', 1));
- ASSERT.equal(0xff235642, mod_ctype.ruint32(data, 'little', 2));
-}
-
-test8();
-test16();
-test32();
+++ /dev/null
-/*
- * A battery of tests to help us read a series of uints
- */
-
-var mod_ctype = require('../../../ctio.js');
-var ASSERT = require('assert');
-
-/*
- * We need to check the following things:
- * - We are correctly resolving big endian (doesn't mean anything for 8 bit)
- * - Correctly resolving little endian (doesn't mean anything for 8 bit)
- * - Correctly using the offsets
- * - Correctly interpreting values that are beyond the signed range as unsigned
- */
-function test8()
-{
- var data = new Buffer(4);
- mod_ctype.wuint8(23, 'big', data, 0);
- mod_ctype.wuint8(23, 'big', data, 1);
- mod_ctype.wuint8(23, 'big', data, 2);
- mod_ctype.wuint8(23, 'big', data, 3);
- ASSERT.equal(23, data[0]);
- ASSERT.equal(23, data[1]);
- ASSERT.equal(23, data[2]);
- ASSERT.equal(23, data[3]);
- mod_ctype.wuint8(23, 'little', data, 0);
- mod_ctype.wuint8(23, 'little', data, 1);
- mod_ctype.wuint8(23, 'little', data, 2);
- mod_ctype.wuint8(23, 'little', data, 3);
- ASSERT.equal(23, data[0]);
- ASSERT.equal(23, data[1]);
- ASSERT.equal(23, data[2]);
- ASSERT.equal(23, data[3]);
- mod_ctype.wuint8(255, 'big', data, 0);
- ASSERT.equal(255, data[0]);
- mod_ctype.wuint8(255, 'little', data, 0);
- ASSERT.equal(255, data[0]);
-}
-
-function test16()
-{
- var value = 0x2343;
- var data = new Buffer(4);
- mod_ctype.wuint16(value, 'big', data, 0);
- ASSERT.equal(0x23, data[0]);
- ASSERT.equal(0x43, data[1]);
- mod_ctype.wuint16(value, 'big', data, 1);
- ASSERT.equal(0x23, data[1]);
- ASSERT.equal(0x43, data[2]);
- mod_ctype.wuint16(value, 'big', data, 2);
- ASSERT.equal(0x23, data[2]);
- ASSERT.equal(0x43, data[3]);
-
- mod_ctype.wuint16(value, 'little', data, 0);
- ASSERT.equal(0x23, data[1]);
- ASSERT.equal(0x43, data[0]);
-
- mod_ctype.wuint16(value, 'little', data, 1);
- ASSERT.equal(0x23, data[2]);
- ASSERT.equal(0x43, data[1]);
-
- mod_ctype.wuint16(value, 'little', data, 2);
- ASSERT.equal(0x23, data[3]);
- ASSERT.equal(0x43, data[2]);
-
- value = 0xff80;
- mod_ctype.wuint16(value, 'little', data, 0);
- ASSERT.equal(0xff, data[1]);
- ASSERT.equal(0x80, data[0]);
-
- mod_ctype.wuint16(value, 'big', data, 0);
- ASSERT.equal(0xff, data[0]);
- ASSERT.equal(0x80, data[1]);
-}
-
-function test32()
-{
- var data = new Buffer(6);
- var value = 0xe7f90a6d;
-
- mod_ctype.wuint32(value, 'big', data, 0);
- ASSERT.equal(0xe7, data[0]);
- ASSERT.equal(0xf9, data[1]);
- ASSERT.equal(0x0a, data[2]);
- ASSERT.equal(0x6d, data[3]);
-
- mod_ctype.wuint32(value, 'big', data, 1);
- ASSERT.equal(0xe7, data[1]);
- ASSERT.equal(0xf9, data[2]);
- ASSERT.equal(0x0a, data[3]);
- ASSERT.equal(0x6d, data[4]);
-
- mod_ctype.wuint32(value, 'big', data, 2);
- ASSERT.equal(0xe7, data[2]);
- ASSERT.equal(0xf9, data[3]);
- ASSERT.equal(0x0a, data[4]);
- ASSERT.equal(0x6d, data[5]);
-
- mod_ctype.wuint32(value, 'little', data, 0);
- ASSERT.equal(0xe7, data[3]);
- ASSERT.equal(0xf9, data[2]);
- ASSERT.equal(0x0a, data[1]);
- ASSERT.equal(0x6d, data[0]);
-
- mod_ctype.wuint32(value, 'little', data, 1);
- ASSERT.equal(0xe7, data[4]);
- ASSERT.equal(0xf9, data[3]);
- ASSERT.equal(0x0a, data[2]);
- ASSERT.equal(0x6d, data[1]);
-
- mod_ctype.wuint32(value, 'little', data, 2);
- ASSERT.equal(0xe7, data[5]);
- ASSERT.equal(0xf9, data[4]);
- ASSERT.equal(0x0a, data[3]);
- ASSERT.equal(0x6d, data[2]);
-}
-
-function test64()
-{
- var data = new Buffer(10);
- var value = 0x0007cda8e7f90a6d;
- var high = Math.floor(value / Math.pow(2, 32));
- var low = value - (high * Math.pow(2, 32));
- ASSERT.equal(0x0007cda8, high);
- ASSERT.equal(0xe7f90a6d, low);
-
- mod_ctype.wuint64([high, low], 'big', data, 0);
- ASSERT.equal(0x00, data[0]);
- ASSERT.equal(0x07, data[1]);
- ASSERT.equal(0xcd, data[2]);
- ASSERT.equal(0xa8, data[3]);
- ASSERT.equal(0xe7, data[4]);
- ASSERT.equal(0xf9, data[5]);
- ASSERT.equal(0x0a, data[6]);
- ASSERT.equal(0x6d, data[7]);
-
- mod_ctype.wuint64([high, low], 'little', data, 0);
- ASSERT.equal(0x6d, data[0]);
- ASSERT.equal(0x0a, data[1]);
- ASSERT.equal(0xf9, data[2]);
- ASSERT.equal(0xe7, data[3]);
- ASSERT.equal(0xa8, data[4]);
- ASSERT.equal(0xcd, data[5]);
- ASSERT.equal(0x07, data[6]);
- ASSERT.equal(0x00, data[7]);
-}
-
-test8();
-test16();
-test32();
-test64();
-
-exports.test8 = test8;
-exports.test16 = test16;
-exports.test32 = test32;
-exports.test64 = test64;
+++ /dev/null
-/*
- * Simple does to see if it works at all
- */
-var mod_ctype = require('../../ctype');
-var ASSERT = require('assert');
-var mod_sys = require('sys');
-
-function test()
-{
- var ii, p, result, buffer;
-
- p = new mod_ctype.Parser({ endian: 'little' });
- buffer = new Buffer(4);
- buffer[0] = 23;
- buffer[3] = 42;
- result = p.readData([ { x: { type: 'uint8_t' }},
- { y: { type: 'uint8_t', offset: 3 }}
- ], buffer, 0);
- ASSERT.equal(23, result['x']);
- ASSERT.equal(42, result['y']);
-
- buffer = new Buffer(23);
- for (ii = 0; ii < 23; ii++)
- buffer[ii] = 0;
-
- buffer.write('Hello, world!');
- result = p.readData([ { x: { type: 'char[20]' }} ], buffer, 0);
-
- /*
- * This is currently broken behvaior, need to redesign check
- * ASSERT.equal('Hello, world!', result['x'].toString('utf-8', 0,
- * result['x'].length));
- */
-
- buffer = new Buffer(4);
- buffer[0] = 0x03;
- buffer[1] = 0x24;
- buffer[2] = 0x25;
- buffer[3] = 0x26;
- result = p.readData([ { y: { type: 'uint8_t' }},
- { x: { type: 'uint8_t[y]' }}], buffer, 0);
- console.log(mod_sys.inspect(result, true));
-
- p.typedef('ssize_t', 'int32_t');
- ASSERT.deepEqual({ 'ssize_t': 'int32_t' }, p.lstypes());
- result = p.readData([ { x: { type: 'ssize_t' } } ], buffer, 0);
- ASSERT.equal(0x26252403, result['x']);
-}
-
-test();
+++ /dev/null
-/*
- * Simple does it fucking work at all test
- */
-
-var mod_ctype = require('../../ctype');
-var ASSERT = require('assert');
-var mod_sys = require('sys');
-
-function test()
-{
- var ii, p, buffer, buf2;
-
- p = new mod_ctype.Parser({ endian: 'big' });
- buffer = new Buffer(4);
- p.writeData([ { x: { type: 'uint8_t', value: 23 }},
- { y: { type: 'uint8_t', offset: 3, value: 42 }}
- ], buffer, 0);
- ASSERT.equal(23, buffer[0]);
- ASSERT.equal(42, buffer[3]);
-
- buffer = new Buffer(20);
- for (ii = 0; ii < 20; ii++)
- buffer[ii] = 0;
-
- buffer.write('Hello, world!');
- buf2 = new Buffer(22);
- p.writeData([ { x: { type: 'char[20]', value: buffer }} ], buf2, 0);
- for (ii = 0; ii < 20; ii++)
- ASSERT.equal(buffer[ii], buf2[ii]);
- /*
- * This is currently broken behvaior, need to redesign check
- * ASSERT.equal('Hello, world!', result['x'].toString('utf-8', 0,
- * result['x'].length));
- */
-
- buffer = new Buffer(4);
- p.writeData([ { y: { type: 'uint8_t', value: 3 }},
- { x: { type: 'uint8_t[y]', value: [ 0x24, 0x25, 0x26] }}],
- buffer, 0);
- console.log(mod_sys.inspect(buffer));
-
- p.typedef('ssize_t', 'int32_t');
- ASSERT.deepEqual({ 'ssize_t': 'int32_t' }, p.lstypes());
-}
+++ /dev/null
-/*
- * Test the different forms of reading characters:
- *
- * - the default, a single element buffer
- * - uint8, values are uint8_ts
- * - int8, values are int8_ts
- */
-var mod_ctype = require('../../ctype');
-var mod_assert = require('assert');
-
-function test()
-{
- var p, buf, res;
-
- buf = new Buffer(1);
- buf[0] = 255;
-
- p = new mod_ctype.Parser({ endian: 'little'});
- res = p.readData([ { c: { type: 'char' }} ], buf, 0);
- res = res['c'];
- mod_assert.ok(res instanceof Buffer);
- mod_assert.equal(255, res[0]);
-
- p = new mod_ctype.Parser({ endian: 'little',
- 'char-type': 'int8' });
- res = p.readData([ { c: { type: 'char' }} ], buf, 0);
- res = res['c'];
- mod_assert.ok(typeof (res) == 'number', 'got typeof (res): ' +
- typeof (res));
- mod_assert.equal(-1, res);
-
- p = new mod_ctype.Parser({ endian: 'little',
- 'char-type': 'uint8' });
- res = p.readData([ { c: { type: 'char' }} ], buf, 0);
- res = res['c'];
- mod_assert.ok(typeof (res) == 'number', 'got typeof (res): ' +
- typeof (res));
- mod_assert.equal(255, res);
-
-}
-
-test();
+++ /dev/null
-/*
- * Simple test to make sure that the endian setting works.
- */
-
-var mod_ctype = require('../../ctype.js');
-var mod_assert = require('assert');
-
-function test()
-{
- var parser, buf;
-
- parser = new mod_ctype.Parser({
- endian: 'little'
- });
-
- buf = new Buffer(2);
- parser.writeData([ { key: { type: 'uint16_t' } } ], buf, 0, [ 0x1234 ]);
- mod_assert.equal(buf[0], 0x34);
- mod_assert.equal(buf[1], 0x12);
- parser.setEndian('big');
-
- parser.writeData([ { key: { type: 'uint16_t' } } ], buf, 0, [ 0x1234 ]);
- mod_assert.equal(buf[0], 0x12);
- mod_assert.equal(buf[1], 0x34);
-
- parser.setEndian('little');
- parser.writeData([ { key: { type: 'uint16_t' } } ], buf, 0, [ 0x1234 ]);
- mod_assert.equal(buf[0], 0x34);
- mod_assert.equal(buf[1], 0x12);
-}
-
-function fail()
-{
- var parser;
-
- parser = new mod_ctype.Parser({
- endian: 'little'
- });
- mod_assert.throws(function () {
- parser.setEndian('littlebigwrong');
- });
-}
-
-test();
-fail();
+++ /dev/null
-/*
- * A long overdue test to go through and verify that we can read and write
- * structures as well as nested structures.
- */
-
-var mod_ctype = require('../../ctype.js');
-var mod_assert = require('assert');
-
-function test()
-{
- var parser, buf, data;
- parser = new mod_ctype.Parser({
- endian: 'little'
- });
- parser.typedef('point_t', [
- { x: { type: 'uint8_t' } },
- { y: { type: 'uint8_t' } }
- ]);
- buf = new Buffer(2);
- data = [
- { point: { type: 'point_t', value: [ 23, 42 ] } }
- ];
- parser.writeData(data, buf, 0);
- mod_assert.ok(buf[0] == 23);
- mod_assert.ok(buf[1] == 42);
-}
-
-test();
+++ /dev/null
-/*
- * Testing to ensure we're reading the expected number bytes
- */
-var mod_ctype = require('../../ctype');
-var ASSERT = require('assert');
-
-function testUint8()
-{
- var parser, result, buffer;
- parser = new mod_ctype.Parser({ endian: 'little' });
- buffer = new Buffer('80', 'hex');
- result = parser.readStruct([ { item: { type: 'uint8_t' } } ], buffer,
- 0);
- ASSERT.equal(result['size'], 1);
-}
-
-function testSint8()
-{
- var parser, result, buffer;
- parser = new mod_ctype.Parser({ endian: 'little' });
- buffer = new Buffer('80', 'hex');
- result = parser.readStruct([ { item: { type: 'int8_t' } } ], buffer, 0);
- ASSERT.equal(result['size'], 1);
-}
-
-function testUint16()
-{
- var parser, result, buffer;
- parser = new mod_ctype.Parser({ endian: 'little' });
- buffer = new Buffer('8000', 'hex');
- result = parser.readStruct([ { item: { type: 'uint16_t' } } ], buffer,
- 0);
- ASSERT.equal(result['size'], 2);
-}
-
-function testSint16()
-{
- var parser, result, buffer;
- parser = new mod_ctype.Parser({ endian: 'little' });
- buffer = new Buffer('8000', 'hex');
- result = parser.readStruct([ { item: { type: 'int16_t' } } ], buffer,
- 0);
- ASSERT.equal(result['size'], 2);
-}
-
-function testUint32()
-{
- var parser, result, buffer;
- parser = new mod_ctype.Parser({ endian: 'little' });
- buffer = new Buffer('80000000', 'hex');
- result = parser.readStruct([ { item: { type: 'uint32_t' } } ], buffer,
- 0);
- ASSERT.equal(result['size'], 4);
-}
-
-function testSint32()
-{
- var parser, result, buffer;
- parser = new mod_ctype.Parser({ endian: 'little' });
- buffer = new Buffer('80000000', 'hex');
- result = parser.readStruct([ { item: { type: 'int32_t' } } ], buffer,
- 0);
- ASSERT.equal(result['size'], 4);
-}
-
-function testUint64()
-{
- var parser, result, buffer;
- parser = new mod_ctype.Parser({ endian: 'little' });
- buffer = new Buffer('8000000000000000', 'hex');
- result = parser.readStruct([ { item: { type: 'uint64_t' } } ], buffer,
- 0);
- ASSERT.equal(result['size'], 8);
-}
-
-function testSint64()
-{
- var parser, result, buffer;
- parser = new mod_ctype.Parser({ endian: 'little' });
- buffer = new Buffer('8000000000000000', 'hex');
- result = parser.readStruct([ { item: { type: 'int64_t' } } ], buffer,
- 0);
- ASSERT.equal(result['size'], 8);
-}
-
-function testFloat()
-{
- var parser, result, buffer;
- parser = new mod_ctype.Parser({ endian: 'little' });
- buffer = new Buffer('ABAAAA3E', 'hex');
- result = parser.readStruct([ { item: { type: 'float' } } ], buffer, 0);
- ASSERT.equal(result['size'], 4);
-}
-
-function testDouble()
-{
- var parser, result, buffer;
- parser = new mod_ctype.Parser({ endian: 'little' });
- buffer = new Buffer('000000000000F03F', 'hex');
- result = parser.readStruct([ { item: { type: 'double' } } ], buffer, 0);
- ASSERT.equal(result['size'], 8);
-}
-
-function testChar()
-{
- var parser, result, buffer;
- parser = new mod_ctype.Parser({ endian: 'little' });
- buffer = new Buffer('t');
- result = parser.readStruct([ { item: { type: 'char' } } ], buffer, 0);
- ASSERT.equal(result['size'], 1);
-}
-
-function test()
-{
- testSint8();
- testUint8();
- testSint16();
- testUint16();
- testSint32();
- testUint32();
- testSint64();
- testUint64();
- testFloat();
- testDouble();
- testChar();
-}
-
-test();
+++ /dev/null
-/*
- * A long overdue test to go through and verify that we can read and write
- * structures as well as nested structures.
- */
-
-var mod_ctype = require('../../ctype.js');
-var mod_assert = require('assert');
-
-function test()
-{
- var parser, buf, data;
- parser = new mod_ctype.Parser({
- endian: 'little'
- });
- parser.typedef('point_t', [
- { x: { type: 'uint8_t' } },
- { y: { type: 'uint8_t' } }
- ]);
- buf = new Buffer(2);
- data = [
- { point: { type: 'point_t' } }
- ];
- parser.writeData(data, buf, 0, [ [ 23, 42 ] ]);
- mod_assert.ok(buf[0] == 23);
- mod_assert.ok(buf[1] == 42);
-}
-
-test();
+++ /dev/null
-/*
- * Test to verify that the offset is incremented when structures are written to.
- * Hopefully we will not regress issue #41
- */
-
-var mod_ctype = require('../../ctype.js');
-var mod_assert = require('assert');
-
-function test()
-{
- var parser, buf, data;
- parser = new mod_ctype.Parser({
- endian: 'little'
- });
- parser.typedef('point_t', [
- { x: { type: 'uint8_t' } },
- { y: { type: 'uint8_t' } }
- ]);
- buf = new Buffer(4);
- data = [
- { point1: { type: 'point_t' } },
- { point2: { type: 'point_t' } }
- ];
- parser.writeData(data, buf, 0, [ [ 23, 42 ], [ 91, 18 ] ]);
- mod_assert.ok(buf[0] == 23);
- mod_assert.ok(buf[1] == 42);
- mod_assert.ok(buf[2] == 91);
- mod_assert.ok(buf[3] == 18);
-}
-
-test();
{
+ "name": "http-signature",
+ "description": "Reference implementation of Joyent's HTTP Signature scheme.",
+ "version": "0.10.1",
+ "license": "MIT",
"author": {
"name": "Joyent, Inc"
},
- "name": "http-signature",
- "description": "Reference implementation of Joyent's HTTP Signature Scheme",
- "version": "0.10.0",
+ "contributors": [
+ {
+ "name": "Mark Cavage",
+ "email": "mcavage@gmail.com"
+ },
+ {
+ "name": "David I. Lehn",
+ "email": "dil@lehn.org"
+ }
+ ],
"repository": {
"type": "git",
"url": "git://github.com/joyent/node-http-signature.git"
},
+ "homepage": "https://github.com/joyent/node-http-signature/",
+ "bugs": {
+ "url": "https://github.com/joyent/node-http-signature/issues"
+ },
+ "keywords": [
+ "https",
+ "request"
+ ],
"engines": {
"node": ">=0.8"
},
"main": "lib/index.js",
"scripts": {
- "test": "tap tst/*.js"
+ "test": "tap test/*.js"
},
"dependencies": {
- "assert-plus": "0.1.2",
+ "assert-plus": "^0.1.5",
"asn1": "0.1.11",
- "ctype": "0.5.2"
+ "ctype": "0.5.3"
},
"devDependencies": {
- "node-uuid": "1.4.0",
+ "node-uuid": "^1.4.1",
"tap": "0.4.2"
},
- "readme": "# node-http-signature\n\nnode-http-signature is a node.js library that has client and server components\nfor Joyent's [HTTP Signature Scheme](http_signing.md).\n\n## Usage\n\nNote the example below signs a request with the same key/cert used to start an\nHTTP server. This is almost certainly not what you actaully want, but is just\nused to illustrate the API calls; you will need to provide your own key\nmanagement in addition to this library.\n\n### Client\n\n var fs = require('fs');\n var https = require('https');\n var httpSignature = require('http-signature');\n\n var key = fs.readFileSync('./key.pem', 'ascii');\n\n var options = {\n host: 'localhost',\n port: 8443,\n path: '/',\n method: 'GET',\n headers: {}\n };\n\n // Adds a 'Date' header in, signs it, and adds the\n // 'Authorization' header in.\n var req = https.request(options, function(res) {\n console.log(res.statusCode);\n });\n\n\n httpSignature.sign(req, {\n key: key,\n keyId: './cert.pem'\n });\n\n req.end();\n\n### Server\n\n var fs = require('fs');\n var https = require('https');\n var httpSignature = require('http-signature');\n\n var options = {\n key: fs.readFileSync('./key.pem'),\n cert: fs.readFileSync('./cert.pem')\n };\n\n https.createServer(options, function (req, res) {\n var rc = 200;\n var parsed = httpSignature.parseRequest(req);\n var pub = fs.readFileSync(parsed.keyId, 'ascii');\n if (!httpSignature.verifySignature(parsed, pub))\n rc = 401;\n\n res.writeHead(rc);\n res.end();\n }).listen(8443);\n\n## Installation\n\n npm install http-signature\n\n## License\n\nMIT.\n\n## Bugs\n\nSee <https://github.com/joyent/node-http-signature/issues>.\n",
- "readmeFilename": "README.md",
- "_id": "http-signature@0.10.0",
- "dist": {
- "shasum": "1494e4f5000a83c0f11bcc12d6007c530cb99582",
- "tarball": "http://registry.npmjs.org/http-signature/-/http-signature-0.10.0.tgz"
- },
+ "_id": "http-signature@0.10.1",
+ "_shasum": "4fbdac132559aa8323121e540779c0a012b27e66",
+ "_resolved": "https://registry.npmjs.org/http-signature/-/http-signature-0.10.1.tgz",
"_from": "http-signature@>=0.10.0 <0.11.0",
- "_npmVersion": "1.2.18",
+ "_npmVersion": "1.4.28",
"_npmUser": {
- "name": "mcavage",
- "email": "mcavage@gmail.com"
+ "name": "pfmooney",
+ "email": "patrick.f.mooney@gmail.com"
},
"maintainers": [
{
"name": "mcavage",
"email": "mcavage@gmail.com"
+ },
+ {
+ "name": "pfmooney",
+ "email": "patrick.f.mooney@gmail.com"
}
],
- "directories": {},
- "_shasum": "1494e4f5000a83c0f11bcc12d6007c530cb99582",
- "_resolved": "https://registry.npmjs.org/http-signature/-/http-signature-0.10.0.tgz",
- "bugs": {
- "url": "https://github.com/joyent/node-http-signature/issues"
+ "dist": {
+ "shasum": "4fbdac132559aa8323121e540779c0a012b27e66",
+ "tarball": "http://registry.npmjs.org/http-signature/-/http-signature-0.10.1.tgz"
},
- "homepage": "https://github.com/joyent/node-http-signature"
+ "directories": {},
+ "readme": "ERROR: No README data found!"
}
--- /dev/null
+{
+ "predef": [ ]
+ , "bitwise": false
+ , "camelcase": false
+ , "curly": false
+ , "eqeqeq": false
+ , "forin": false
+ , "immed": false
+ , "latedef": false
+ , "noarg": true
+ , "noempty": true
+ , "nonew": true
+ , "plusplus": false
+ , "quotmark": true
+ , "regexp": false
+ , "undef": true
+ , "unused": true
+ , "strict": false
+ , "trailing": true
+ , "maxlen": 120
+ , "asi": true
+ , "boss": true
+ , "debug": true
+ , "eqnull": true
+ , "esnext": true
+ , "evil": true
+ , "expr": true
+ , "funcscope": false
+ , "globalstrict": false
+ , "iterator": false
+ , "lastsemic": true
+ , "laxbreak": true
+ , "laxcomma": true
+ , "loopfunc": true
+ , "multistr": false
+ , "onecase": false
+ , "proto": false
+ , "regexdash": false
+ , "scripturl": true
+ , "smarttabs": false
+ , "shadow": false
+ , "sub": true
+ , "supernew": false
+ , "validthis": true
+ , "browser": true
+ , "couch": false
+ , "devel": false
+ , "dojo": false
+ , "mootools": false
+ , "node": true
+ , "nonstandard": true
+ , "prototypejs": false
+ , "rhino": false
+ , "worker": true
+ , "wsh": false
+ , "nomen": false
+ , "onevar": false
+ , "passfail": false
+}
\ No newline at end of file
--- /dev/null
+language: node_js
+node_js:
+ - "0.8"
+ - "0.10"
+ - "0.11"
+branches:
+ only:
+ - master
+notifications:
+ email:
+ - rod@vagg.org
+script: npm test
--- /dev/null
+Copyright 2014, Rod Vagg (the "Original Author")
+All rights reserved.
+
+MIT +no-false-attribs License
+
+Permission is hereby granted, free of charge, to any person
+obtaining a copy of this software and associated documentation
+files (the "Software"), to deal in the Software without
+restriction, including without limitation the rights to use,
+copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the
+Software is furnished to do so, subject to the following
+conditions:
+
+The above copyright notice and this permission notice shall be
+included in all copies or substantial portions of the Software.
+
+Distributions of all or part of the Software intended to be used
+by the recipients as they would use the unmodified Software,
+containing modifications that substantially alter, remove, or
+disable functionality of the Software, outside of the documented
+configuration mechanisms provided by the Software, shall be
+modified such that the Original Author's bug reporting email
+addresses and urls are either replaced with the contact information
+of the parties responsible for the changes, or removed entirely.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
+OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
+NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
+HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
+WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
+OTHER DEALINGS IN THE SOFTWARE.
+
+
+Except where noted, this license applies to any and all software
+programs and associated documentation files created by the
+Original Author, when distributed with the Software.
--- /dev/null
+# isStream
+
+[![Build Status](https://secure.travis-ci.org/rvagg/isstream.png)](http://travis-ci.org/rvagg/isstream)
+
+**Test if an object is a `Stream`**
+
+[![NPM](https://nodei.co/npm/isstream.svg)](https://nodei.co/npm/isstream/)
+
+The missing `Stream.isStream(obj)`: determine if an object is standard Node.js `Stream`. Works for Node-core `Stream` objects (for 0.8, 0.10, 0.11, and in theory, older and newer versions) and all versions of **[readable-stream](https://github.com/isaacs/readable-stream)**.
+
+## Usage:
+
+```js
+var isStream = require('isstream')
+var Stream = require('stream')
+
+isStream(new Stream()) // true
+
+isStream({}) // false
+
+isStream(new Stream.Readable()) // true
+isStream(new Stream.Writable()) // true
+isStream(new Stream.Duplex()) // true
+isStream(new Stream.Transform()) // true
+isStream(new Stream.PassThrough()) // true
+```
+
+## But wait! There's more!
+
+You can also test for `isReadable(obj)`, `isWritable(obj)` and `isDuplex(obj)` to test for implementations of Streams2 (and Streams3) base classes.
+
+```js
+var isReadable = require('isstream').isReadable
+var isWritable = require('isstream').isWritable
+var isDuplex = require('isstream').isDuplex
+var Stream = require('stream')
+
+isReadable(new Stream()) // false
+isWritable(new Stream()) // false
+isDuplex(new Stream()) // false
+
+isReadable(new Stream.Readable()) // true
+isReadable(new Stream.Writable()) // false
+isReadable(new Stream.Duplex()) // true
+isReadable(new Stream.Transform()) // true
+isReadable(new Stream.PassThrough()) // true
+
+isWritable(new Stream.Readable()) // false
+isWritable(new Stream.Writable()) // true
+isWritable(new Stream.Duplex()) // true
+isWritable(new Stream.Transform()) // true
+isWritable(new Stream.PassThrough()) // true
+
+isDuplex(new Stream.Readable()) // false
+isDuplex(new Stream.Writable()) // false
+isDuplex(new Stream.Duplex()) // true
+isDuplex(new Stream.Transform()) // true
+isDuplex(new Stream.PassThrough()) // true
+```
+
+*Reminder: when implementing your own streams, please [use **readable-stream** rather than core streams](http://r.va.gg/2014/06/why-i-dont-use-nodes-core-stream-module.html).*
+
+
+## License
+
+**isStream** is Copyright (c) 2014 Rod Vagg [@rvagg](https://twitter.com/rvagg) and licenced under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details.
--- /dev/null
+var stream = require('stream')
+
+
+function isStream (obj) {
+ return obj instanceof stream.Stream
+}
+
+
+function isReadable (obj) {
+ return isStream(obj) && typeof obj._read == 'function' && typeof obj._readableState == 'object'
+}
+
+
+function isWritable (obj) {
+ return isStream(obj) && typeof obj._write == 'function' && typeof obj._writableState == 'object'
+}
+
+
+function isDuplex (obj) {
+ return isReadable(obj) && isWritable(obj)
+}
+
+
+module.exports = isStream
+module.exports.isReadable = isReadable
+module.exports.isWritable = isWritable
+module.exports.isDuplex = isDuplex
--- /dev/null
+{
+ "name": "isstream",
+ "version": "0.1.1",
+ "description": "Determine if an object is a Stream",
+ "main": "isstream.js",
+ "scripts": {
+ "test": "tar --xform 's/^package/readable-stream-1.0/' -zxf readable-stream-1.0.*.tgz && tar --xform 's/^package/readable-stream-1.1/' -zxf readable-stream-1.1.*.tgz && node test.js; rm -rf readable-stream-1.?/"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/rvagg/isstream.git"
+ },
+ "keywords": [
+ "stream",
+ "type",
+ "streams",
+ "readable-stream",
+ "hippo"
+ ],
+ "devDependencies": {
+ "tape": "~2.12.3",
+ "core-util-is": "~1.0.0",
+ "isarray": "0.0.1",
+ "string_decoder": "~0.10.x",
+ "inherits": "~2.0.1"
+ },
+ "author": {
+ "name": "Rod Vagg",
+ "email": "rod@vagg.org"
+ },
+ "license": "MIT",
+ "bugs": {
+ "url": "https://github.com/rvagg/isstream/issues"
+ },
+ "homepage": "https://github.com/rvagg/isstream",
+ "gitHead": "0406cfe2677231b7b23a229a61b15999bf60ce67",
+ "_id": "isstream@0.1.1",
+ "_shasum": "48332c5999893996ba253c81c7bd6e7ae0905c4f",
+ "_from": "isstream@>=0.1.1 <0.2.0",
+ "_npmVersion": "1.4.28",
+ "_npmUser": {
+ "name": "rvagg",
+ "email": "rod@vagg.org"
+ },
+ "maintainers": [
+ {
+ "name": "rvagg",
+ "email": "rod@vagg.org"
+ }
+ ],
+ "dist": {
+ "shasum": "48332c5999893996ba253c81c7bd6e7ae0905c4f",
+ "tarball": "http://registry.npmjs.org/isstream/-/isstream-0.1.1.tgz"
+ },
+ "directories": {},
+ "_resolved": "https://registry.npmjs.org/isstream/-/isstream-0.1.1.tgz",
+ "readme": "ERROR: No README data found!"
+}
--- /dev/null
+var tape = require('tape')
+ , EE = require('events').EventEmitter
+ , util = require('util')
+
+
+ , isStream = require('./')
+ , isReadable = require('./').isReadable
+ , isWritable = require('./').isWritable
+ , isDuplex = require('./').isDuplex
+
+ , CoreStreams = require('stream')
+ , ReadableStream10 = require('./readable-stream-1.0/')
+ , ReadableStream11 = require('./readable-stream-1.1/')
+
+
+function test (pass, type, stream) {
+ tape('isStream(' + type + ')', function (t) {
+ t.plan(1)
+ t.ok(pass === isStream(stream), type)
+ })
+}
+
+
+function testReadable (pass, type, stream) {
+ tape('isReadable(' + type + ')', function (t) {
+ t.plan(1)
+ t.ok(pass === isReadable(stream), type)
+ })
+}
+
+
+function testWritable (pass, type, stream) {
+ tape('isWritable(' + type + ')', function (t) {
+ t.plan(1)
+ t.ok(pass === isWritable(stream), type)
+ })
+}
+
+
+function testDuplex (pass, type, stream) {
+ tape('isDuplex(' + type + ')', function (t) {
+ t.plan(1)
+ t.ok(pass === isDuplex(stream), type)
+ })
+}
+
+
+[ undefined, null, '', true, false, 0, 1, 1.0, 'string', {}, function foo () {} ].forEach(function (o) {
+ test(false, 'non-stream / primitive: ' + (JSON.stringify(o) || (o && o.toString()) || o), o)
+})
+
+
+test(false, 'fake stream obj', { pipe: function () {} })
+
+
+;(function () {
+
+ // looks like a stream!
+
+ function Stream () {
+ EE.call(this)
+ }
+ util.inherits(Stream, EE)
+ Stream.prototype.pipe = function () {}
+ Stream.Stream = Stream
+
+ test(false, 'fake stream "new Stream()"', new Stream())
+
+}())
+
+
+test(true, 'CoreStreams.Stream', new (CoreStreams.Stream)())
+test(true, 'CoreStreams.Readable', new (CoreStreams.Readable)())
+test(true, 'CoreStreams.Writable', new (CoreStreams.Writable)())
+test(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)())
+test(true, 'CoreStreams.Transform', new (CoreStreams.Transform)())
+test(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)())
+
+test(true, 'ReadableStream10.Readable', new (ReadableStream10.Readable)())
+test(true, 'ReadableStream10.Writable', new (ReadableStream10.Writable)())
+test(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)())
+test(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)())
+test(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)())
+
+test(true, 'ReadableStream11.Readable', new (ReadableStream11.Readable)())
+test(true, 'ReadableStream11.Writable', new (ReadableStream11.Writable)())
+test(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)())
+test(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)())
+test(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)())
+
+
+testReadable(false, 'CoreStreams.Stream', new (CoreStreams.Stream)())
+testReadable(true, 'CoreStreams.Readable', new (CoreStreams.Readable)())
+testReadable(false, 'CoreStreams.Writable', new (CoreStreams.Writable)())
+testReadable(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)())
+testReadable(true, 'CoreStreams.Transform', new (CoreStreams.Transform)())
+testReadable(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)())
+
+testReadable(true, 'ReadableStream10.Readable', new (ReadableStream10.Readable)())
+testReadable(false, 'ReadableStream10.Writable', new (ReadableStream10.Writable)())
+testReadable(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)())
+testReadable(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)())
+testReadable(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)())
+
+testReadable(true, 'ReadableStream11.Readable', new (ReadableStream11.Readable)())
+testReadable(false, 'ReadableStream11.Writable', new (ReadableStream11.Writable)())
+testReadable(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)())
+testReadable(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)())
+testReadable(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)())
+
+
+testWritable(false, 'CoreStreams.Stream', new (CoreStreams.Stream)())
+testWritable(false, 'CoreStreams.Readable', new (CoreStreams.Readable)())
+testWritable(true, 'CoreStreams.Writable', new (CoreStreams.Writable)())
+testWritable(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)())
+testWritable(true, 'CoreStreams.Transform', new (CoreStreams.Transform)())
+testWritable(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)())
+
+testWritable(false, 'ReadableStream10.Readable', new (ReadableStream10.Readable)())
+testWritable(true, 'ReadableStream10.Writable', new (ReadableStream10.Writable)())
+testWritable(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)())
+testWritable(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)())
+testWritable(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)())
+
+testWritable(false, 'ReadableStream11.Readable', new (ReadableStream11.Readable)())
+testWritable(true, 'ReadableStream11.Writable', new (ReadableStream11.Writable)())
+testWritable(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)())
+testWritable(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)())
+testWritable(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)())
+
+
+testDuplex(false, 'CoreStreams.Stream', new (CoreStreams.Stream)())
+testDuplex(false, 'CoreStreams.Readable', new (CoreStreams.Readable)())
+testDuplex(false, 'CoreStreams.Writable', new (CoreStreams.Writable)())
+testDuplex(true, 'CoreStreams.Duplex', new (CoreStreams.Duplex)())
+testDuplex(true, 'CoreStreams.Transform', new (CoreStreams.Transform)())
+testDuplex(true, 'CoreStreams.PassThrough', new (CoreStreams.PassThrough)())
+
+testDuplex(false, 'ReadableStream10.Readable', new (ReadableStream10.Readable)())
+testDuplex(false, 'ReadableStream10.Writable', new (ReadableStream10.Writable)())
+testDuplex(true, 'ReadableStream10.Duplex', new (ReadableStream10.Duplex)())
+testDuplex(true, 'ReadableStream10.Transform', new (ReadableStream10.Transform)())
+testDuplex(true, 'ReadableStream10.PassThrough', new (ReadableStream10.PassThrough)())
+
+testDuplex(false, 'ReadableStream11.Readable', new (ReadableStream11.Readable)())
+testDuplex(false, 'ReadableStream11.Writable', new (ReadableStream11.Writable)())
+testDuplex(true, 'ReadableStream11.Duplex', new (ReadableStream11.Duplex)())
+testDuplex(true, 'ReadableStream11.Transform', new (ReadableStream11.Transform)())
+testDuplex(true, 'ReadableStream11.PassThrough', new (ReadableStream11.PassThrough)())
+
+
+;[ CoreStreams, ReadableStream10, ReadableStream11 ].forEach(function (p) {
+ [ 'Stream', 'Readable', 'Writable', 'Duplex', 'Transform', 'PassThrough' ].forEach(function (k) {
+ if (!p[k])
+ return
+
+ function SubStream () {
+ p[k].call(this)
+ }
+ util.inherits(SubStream, p[k])
+
+ test(true, 'Stream subclass: ' + p.name + '.' + k, new SubStream())
+
+ })
+})
+++ /dev/null
-test
-build.js
-
-# OS generated files #
-######################
-.DS_Store*
-# Icon?
-ehthumbs.db
-Thumbs.db
-
-# Node.js #
-###########
-node_modules
-npm-debug.log
+++ /dev/null
-language: node_js
-node_js:
- - "0.8"
- - "0.10"
- - "0.11"
-matrix:
- allow_failures:
- - node_js: "0.11"
- fast_finish: true
-before_install:
- # remove build script deps before install
- - node -pe 'f="./package.json";p=require(f);d=p.devDependencies;for(k in d){if("co"===k.substr(0,2))delete d[k]}require("fs").writeFileSync(f,JSON.stringify(p,null,2))'
+2.0.8 / 2015-01-29
+==================
+
+ * deps: mime-db@~1.6.0
+ - Add new mime types
+
+2.0.7 / 2014-12-30
+==================
+
+ * deps: mime-db@~1.5.0
+ - Add new mime types
+ - Fix various invalid MIME type entries
+
+2.0.6 / 2014-12-30
+==================
+
+ * deps: mime-db@~1.4.0
+ - Add new mime types
+ - Fix various invalid MIME type entries
+ - Remove example template MIME types
+
+2.0.5 / 2014-12-29
+==================
+
+ * deps: mime-db@~1.3.1
+ - Fix missing extensions
+
2.0.4 / 2014-12-10
==================
+++ /dev/null
-
-build:
- node --harmony-generators build.js
-
-test:
- node test/mime.js
- mocha --require should --reporter spec test/test.js
-
-.PHONY: build test
# mime-types
-[![NPM version](https://badge.fury.io/js/mime-types.svg)](https://badge.fury.io/js/mime-types) [![Build Status](https://travis-ci.org/expressjs/mime-types.svg?branch=master)](https://travis-ci.org/expressjs/mime-types)
-The ultimate javascript content-type utility.
-
-### Install
+[![NPM Version][npm-image]][npm-url]
+[![NPM Downloads][downloads-image]][downloads-url]
+[![Node.js Version][node-version-image]][node-version-url]
+[![Build Status][travis-image]][travis-url]
+[![Test Coverage][coveralls-image]][coveralls-url]
-```sh
-$ npm install mime-types
-```
+The ultimate javascript content-type utility.
-#### Similar to [node-mime](https://github.com/broofa/node-mime), except:
+Similar to [node-mime](https://github.com/broofa/node-mime), except:
-- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`, so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`.
+- __No fallbacks.__ Instead of naively returning the first available type, `mime-types` simply returns `false`,
+ so do `var type = mime.lookup('unrecognized') || 'application/octet-stream'`.
- No `new Mime()` business, so you could do `var lookup = require('mime-types').lookup`.
-- Additional mime types are added such as jade and stylus. Feel free to add more!
-- Browser support via Browserify and Component by converting lists to JSON files.
+- Additional mime types are added such as jade and stylus via [mime-db](https://github.com/jshttp/mime-db)
+- No `.define()` functionality
Otherwise, the API is compatible.
-### Adding Types
+## Install
-If you'd like to add additional types,
-simply create a PR adding the type to `custom.json` and
-a reference link to the [sources](SOURCES.md).
+```sh
+$ npm install mime-types
+```
-Do __NOT__ edit `mime.json` or `node.json`.
-Those are pulled using `build.js`.
-You should only touch `custom.json`.
+## Adding Types
+
+All mime types are based on [mime-db](https://github.com/jshttp/mime-db),
+so open a PR there if you'd like to add mime types.
## API
mime.charset('text/x-markdown') // 'UTF-8'
```
-### mime.types[extension] = type
+### var type = mime.types[extension]
A map of content-types by extension.
-### mime.extensions[type] = [extensions]
+### [extensions...] = mime.extensions[type]
A map of extensions by content-type.
-### mime.define(types)
-
-Globally add definitions.
-`types` must be an object of the form:
-
-```js
-{
- "<content-type>": [extensions...],
- "<content-type>": [extensions...]
-}
-```
-
-See the `.json` files in `lib/` for examples.
-
## License
[MIT](LICENSE)
+
+[npm-image]: https://img.shields.io/npm/v/mime-types.svg?style=flat
+[npm-url]: https://npmjs.org/package/mime-types
+[node-version-image]: https://img.shields.io/badge/node.js-%3E%3D_0.6-brightgreen.svg?style=flat
+[node-version-url]: http://nodejs.org/download/
+[travis-image]: https://img.shields.io/travis/jshttp/mime-types.svg?style=flat
+[travis-url]: https://travis-ci.org/jshttp/mime-types
+[coveralls-image]: https://img.shields.io/coveralls/jshttp/mime-types.svg?style=flat
+[coveralls-url]: https://coveralls.io/r/jshttp/mime-types
+[downloads-image]: https://img.shields.io/npm/dm/mime-types.svg?style=flat
+[downloads-url]: https://npmjs.org/package/mime-types
+++ /dev/null
-
-### Sources for custom types
-
-This is a list of sources for any custom mime types.
-When adding custom mime types, please link to where you found the mime type,
-even if it's from an unofficial source.
-
-- `text/coffeescript` - http://coffeescript.org/#scripts
-- `text/x-handlebars-template` - https://handlebarsjs.com/#getting-started
-- `text/x-sass` & `text/x-scss` - https://github.com/janlelis/rubybuntu-mime/blob/master/sass.xml
-- `text.jsx` - http://facebook.github.io/react/docs/getting-started.html [[2]](https://github.com/facebook/react/blob/f230e0a03154e6f8a616e0da1fb3d97ffa1a6472/vendor/browser-transforms.js#L210)
-
-[Sources for node.json types](https://github.com/broofa/node-mime/blob/master/types/node.types)
-
-### Notes on weird types
-
-- `font/opentype` - This type is technically invalid according to the spec. No valid types begin with `font/`. No-one uses the official type of `application/vnd.ms-opentype` as the community standardized `application/x-font-otf`. However, chrome logs nonsense warnings unless opentype fonts are served with `font/opentype`. [[1]](http://stackoverflow.com/questions/2871655/proper-mime-type-for-fonts)
+++ /dev/null
-{
- "name": "mime-types",
- "description": "The ultimate javascript content-type utility.",
- "version": "0.1.0",
- "author": {
- "name": "Jonathan Ong",
- "email": "me@jongleberry.com",
- "url": "http://jongleberry.com",
- "twitter": "https://twitter.com/jongleberry"
- },
- "repository": "expressjs/mime-types",
- "license": "MIT",
- "main": "lib/index.js",
- "scripts": ["lib/index.js"],
- "json": ["mime.json", "node.json", "custom.json"]
-}
+++ /dev/null
-{
- "text/jade": [
- "jade"
- ],
- "text/stylus": [
- "stylus",
- "styl"
- ],
- "text/less": [
- "less"
- ],
- "text/x-sass": [
- "sass"
- ],
- "text/x-scss": [
- "scss"
- ],
- "text/coffeescript": [
- "coffee"
- ],
- "text/x-handlebars-template": [
- "hbs"
- ],
- "text/jsx": [
- "jsx"
- ]
-}
+++ /dev/null
-
-// types[extension] = type
-exports.types = Object.create(null)
-// extensions[type] = [extensions]
-exports.extensions = Object.create(null)
-// define more mime types
-exports.define = define
-
-// store the json files
-exports.json = {
- mime: require('./mime.json'),
- node: require('./node.json'),
- custom: require('./custom.json'),
-}
-
-exports.lookup = function (string) {
- if (!string || typeof string !== "string") return false
- string = string.replace(/.*[\.\/\\]/, '').toLowerCase()
- if (!string) return false
- return exports.types[string] || false
-}
-
-exports.extension = function (type) {
- if (!type || typeof type !== "string") return false
- type = type.match(/^\s*([^;\s]*)(?:;|\s|$)/)
- if (!type) return false
- var exts = exports.extensions[type[1].toLowerCase()]
- if (!exts || !exts.length) return false
- return exts[0]
-}
-
-// type has to be an exact mime type
-exports.charset = function (type) {
- // special cases
- switch (type) {
- case 'application/json': return 'UTF-8'
- case 'application/javascript': return 'UTF-8'
- }
-
- // default text/* to utf-8
- if (/^text\//.test(type)) return 'UTF-8'
-
- return false
-}
-
-// backwards compatibility
-exports.charsets = {
- lookup: exports.charset
-}
-
-exports.contentType = function (type) {
- if (!type || typeof type !== "string") return false
- if (!~type.indexOf('/')) type = exports.lookup(type)
- if (!type) return false
- if (!~type.indexOf('charset')) {
- var charset = exports.charset(type)
- if (charset) type += '; charset=' + charset.toLowerCase()
- }
- return type
-}
-
-define(exports.json.mime)
-define(exports.json.node)
-define(exports.json.custom)
-
-function define(json) {
- Object.keys(json).forEach(function (type) {
- var exts = json[type] || []
- exports.extensions[type] = exports.extensions[type] || []
- exts.forEach(function (ext) {
- if (!~exports.extensions[type].indexOf(ext)) exports.extensions[type].push(ext)
- exports.types[ext] = type
- })
- })
-}
+++ /dev/null
-{
- "application/1d-interleaved-parityfec": [],
- "application/3gpp-ims+xml": [],
- "application/activemessage": [],
- "application/andrew-inset": [
- "ez"
- ],
- "application/applefile": [],
- "application/applixware": [
- "aw"
- ],
- "application/atom+xml": [
- "atom"
- ],
- "application/atomcat+xml": [
- "atomcat"
- ],
- "application/atomicmail": [],
- "application/atomsvc+xml": [
- "atomsvc"
- ],
- "application/auth-policy+xml": [],
- "application/batch-smtp": [],
- "application/beep+xml": [],
- "application/calendar+xml": [],
- "application/cals-1840": [],
- "application/ccmp+xml": [],
- "application/ccxml+xml": [
- "ccxml"
- ],
- "application/cdmi-capability": [
- "cdmia"
- ],
- "application/cdmi-container": [
- "cdmic"
- ],
- "application/cdmi-domain": [
- "cdmid"
- ],
- "application/cdmi-object": [
- "cdmio"
- ],
- "application/cdmi-queue": [
- "cdmiq"
- ],
- "application/cea-2018+xml": [],
- "application/cellml+xml": [],
- "application/cfw": [],
- "application/cnrp+xml": [],
- "application/commonground": [],
- "application/conference-info+xml": [],
- "application/cpl+xml": [],
- "application/csta+xml": [],
- "application/cstadata+xml": [],
- "application/cu-seeme": [
- "cu"
- ],
- "application/cybercash": [],
- "application/davmount+xml": [
- "davmount"
- ],
- "application/dca-rft": [],
- "application/dec-dx": [],
- "application/dialog-info+xml": [],
- "application/dicom": [],
- "application/dns": [],
- "application/docbook+xml": [
- "dbk"
- ],
- "application/dskpp+xml": [],
- "application/dssc+der": [
- "dssc"
- ],
- "application/dssc+xml": [
- "xdssc"
- ],
- "application/dvcs": [],
- "application/ecmascript": [
- "ecma"
- ],
- "application/edi-consent": [],
- "application/edi-x12": [],
- "application/edifact": [],
- "application/emma+xml": [
- "emma"
- ],
- "application/epp+xml": [],
- "application/epub+zip": [
- "epub"
- ],
- "application/eshop": [],
- "application/example": [],
- "application/exi": [
- "exi"
- ],
- "application/fastinfoset": [],
- "application/fastsoap": [],
- "application/fits": [],
- "application/font-tdpfr": [
- "pfr"
- ],
- "application/framework-attributes+xml": [],
- "application/gml+xml": [
- "gml"
- ],
- "application/gpx+xml": [
- "gpx"
- ],
- "application/gxf": [
- "gxf"
- ],
- "application/h224": [],
- "application/held+xml": [],
- "application/http": [],
- "application/hyperstudio": [
- "stk"
- ],
- "application/ibe-key-request+xml": [],
- "application/ibe-pkg-reply+xml": [],
- "application/ibe-pp-data": [],
- "application/iges": [],
- "application/im-iscomposing+xml": [],
- "application/index": [],
- "application/index.cmd": [],
- "application/index.obj": [],
- "application/index.response": [],
- "application/index.vnd": [],
- "application/inkml+xml": [
- "ink",
- "inkml"
- ],
- "application/iotp": [],
- "application/ipfix": [
- "ipfix"
- ],
- "application/ipp": [],
- "application/isup": [],
- "application/java-archive": [
- "jar"
- ],
- "application/java-serialized-object": [
- "ser"
- ],
- "application/java-vm": [
- "class"
- ],
- "application/javascript": [
- "js"
- ],
- "application/json": [
- "json"
- ],
- "application/jsonml+json": [
- "jsonml"
- ],
- "application/kpml-request+xml": [],
- "application/kpml-response+xml": [],
- "application/lost+xml": [
- "lostxml"
- ],
- "application/mac-binhex40": [
- "hqx"
- ],
- "application/mac-compactpro": [
- "cpt"
- ],
- "application/macwriteii": [],
- "application/mads+xml": [
- "mads"
- ],
- "application/marc": [
- "mrc"
- ],
- "application/marcxml+xml": [
- "mrcx"
- ],
- "application/mathematica": [
- "ma",
- "nb",
- "mb"
- ],
- "application/mathml-content+xml": [],
- "application/mathml-presentation+xml": [],
- "application/mathml+xml": [
- "mathml"
- ],
- "application/mbms-associated-procedure-description+xml": [],
- "application/mbms-deregister+xml": [],
- "application/mbms-envelope+xml": [],
- "application/mbms-msk+xml": [],
- "application/mbms-msk-response+xml": [],
- "application/mbms-protection-description+xml": [],
- "application/mbms-reception-report+xml": [],
- "application/mbms-register+xml": [],
- "application/mbms-register-response+xml": [],
- "application/mbms-user-service-description+xml": [],
- "application/mbox": [
- "mbox"
- ],
- "application/media_control+xml": [],
- "application/mediaservercontrol+xml": [
- "mscml"
- ],
- "application/metalink+xml": [
- "metalink"
- ],
- "application/metalink4+xml": [
- "meta4"
- ],
- "application/mets+xml": [
- "mets"
- ],
- "application/mikey": [],
- "application/mods+xml": [
- "mods"
- ],
- "application/moss-keys": [],
- "application/moss-signature": [],
- "application/mosskey-data": [],
- "application/mosskey-request": [],
- "application/mp21": [
- "m21",
- "mp21"
- ],
- "application/mp4": [
- "mp4s"
- ],
- "application/mpeg4-generic": [],
- "application/mpeg4-iod": [],
- "application/mpeg4-iod-xmt": [],
- "application/msc-ivr+xml": [],
- "application/msc-mixer+xml": [],
- "application/msword": [
- "doc",
- "dot"
- ],
- "application/mxf": [
- "mxf"
- ],
- "application/nasdata": [],
- "application/news-checkgroups": [],
- "application/news-groupinfo": [],
- "application/news-transmission": [],
- "application/nss": [],
- "application/ocsp-request": [],
- "application/ocsp-response": [],
- "application/octet-stream": [
- "bin",
- "dms",
- "lrf",
- "mar",
- "so",
- "dist",
- "distz",
- "pkg",
- "bpk",
- "dump",
- "elc",
- "deploy"
- ],
- "application/oda": [
- "oda"
- ],
- "application/oebps-package+xml": [
- "opf"
- ],
- "application/ogg": [
- "ogx"
- ],
- "application/omdoc+xml": [
- "omdoc"
- ],
- "application/onenote": [
- "onetoc",
- "onetoc2",
- "onetmp",
- "onepkg"
- ],
- "application/oxps": [
- "oxps"
- ],
- "application/parityfec": [],
- "application/patch-ops-error+xml": [
- "xer"
- ],
- "application/pdf": [
- "pdf"
- ],
- "application/pgp-encrypted": [
- "pgp"
- ],
- "application/pgp-keys": [],
- "application/pgp-signature": [
- "asc",
- "sig"
- ],
- "application/pics-rules": [
- "prf"
- ],
- "application/pidf+xml": [],
- "application/pidf-diff+xml": [],
- "application/pkcs10": [
- "p10"
- ],
- "application/pkcs7-mime": [
- "p7m",
- "p7c"
- ],
- "application/pkcs7-signature": [
- "p7s"
- ],
- "application/pkcs8": [
- "p8"
- ],
- "application/pkix-attr-cert": [
- "ac"
- ],
- "application/pkix-cert": [
- "cer"
- ],
- "application/pkix-crl": [
- "crl"
- ],
- "application/pkix-pkipath": [
- "pkipath"
- ],
- "application/pkixcmp": [
- "pki"
- ],
- "application/pls+xml": [
- "pls"
- ],
- "application/poc-settings+xml": [],
- "application/postscript": [
- "ai",
- "eps",
- "ps"
- ],
- "application/prs.alvestrand.titrax-sheet": [],
- "application/prs.cww": [
- "cww"
- ],
- "application/prs.nprend": [],
- "application/prs.plucker": [],
- "application/prs.rdf-xml-crypt": [],
- "application/prs.xsf+xml": [],
- "application/pskc+xml": [
- "pskcxml"
- ],
- "application/qsig": [],
- "application/rdf+xml": [
- "rdf"
- ],
- "application/reginfo+xml": [
- "rif"
- ],
- "application/relax-ng-compact-syntax": [
- "rnc"
- ],
- "application/remote-printing": [],
- "application/resource-lists+xml": [
- "rl"
- ],
- "application/resource-lists-diff+xml": [
- "rld"
- ],
- "application/riscos": [],
- "application/rlmi+xml": [],
- "application/rls-services+xml": [
- "rs"
- ],
- "application/rpki-ghostbusters": [
- "gbr"
- ],
- "application/rpki-manifest": [
- "mft"
- ],
- "application/rpki-roa": [
- "roa"
- ],
- "application/rpki-updown": [],
- "application/rsd+xml": [
- "rsd"
- ],
- "application/rss+xml": [
- "rss"
- ],
- "application/rtf": [
- "rtf"
- ],
- "application/rtx": [],
- "application/samlassertion+xml": [],
- "application/samlmetadata+xml": [],
- "application/sbml+xml": [
- "sbml"
- ],
- "application/scvp-cv-request": [
- "scq"
- ],
- "application/scvp-cv-response": [
- "scs"
- ],
- "application/scvp-vp-request": [
- "spq"
- ],
- "application/scvp-vp-response": [
- "spp"
- ],
- "application/sdp": [
- "sdp"
- ],
- "application/set-payment": [],
- "application/set-payment-initiation": [
- "setpay"
- ],
- "application/set-registration": [],
- "application/set-registration-initiation": [
- "setreg"
- ],
- "application/sgml": [],
- "application/sgml-open-catalog": [],
- "application/shf+xml": [
- "shf"
- ],
- "application/sieve": [],
- "application/simple-filter+xml": [],
- "application/simple-message-summary": [],
- "application/simplesymbolcontainer": [],
- "application/slate": [],
- "application/smil": [],
- "application/smil+xml": [
- "smi",
- "smil"
- ],
- "application/soap+fastinfoset": [],
- "application/soap+xml": [],
- "application/sparql-query": [
- "rq"
- ],
- "application/sparql-results+xml": [
- "srx"
- ],
- "application/spirits-event+xml": [],
- "application/srgs": [
- "gram"
- ],
- "application/srgs+xml": [
- "grxml"
- ],
- "application/sru+xml": [
- "sru"
- ],
- "application/ssdl+xml": [
- "ssdl"
- ],
- "application/ssml+xml": [
- "ssml"
- ],
- "application/tamp-apex-update": [],
- "application/tamp-apex-update-confirm": [],
- "application/tamp-community-update": [],
- "application/tamp-community-update-confirm": [],
- "application/tamp-error": [],
- "application/tamp-sequence-adjust": [],
- "application/tamp-sequence-adjust-confirm": [],
- "application/tamp-status-query": [],
- "application/tamp-status-response": [],
- "application/tamp-update": [],
- "application/tamp-update-confirm": [],
- "application/tei+xml": [
- "tei",
- "teicorpus"
- ],
- "application/thraud+xml": [
- "tfi"
- ],
- "application/timestamp-query": [],
- "application/timestamp-reply": [],
- "application/timestamped-data": [
- "tsd"
- ],
- "application/tve-trigger": [],
- "application/ulpfec": [],
- "application/vcard+xml": [],
- "application/vemmi": [],
- "application/vividence.scriptfile": [],
- "application/vnd.3gpp.bsf+xml": [],
- "application/vnd.3gpp.pic-bw-large": [
- "plb"
- ],
- "application/vnd.3gpp.pic-bw-small": [
- "psb"
- ],
- "application/vnd.3gpp.pic-bw-var": [
- "pvb"
- ],
- "application/vnd.3gpp.sms": [],
- "application/vnd.3gpp2.bcmcsinfo+xml": [],
- "application/vnd.3gpp2.sms": [],
- "application/vnd.3gpp2.tcap": [
- "tcap"
- ],
- "application/vnd.3m.post-it-notes": [
- "pwn"
- ],
- "application/vnd.accpac.simply.aso": [
- "aso"
- ],
- "application/vnd.accpac.simply.imp": [
- "imp"
- ],
- "application/vnd.acucobol": [
- "acu"
- ],
- "application/vnd.acucorp": [
- "atc",
- "acutc"
- ],
- "application/vnd.adobe.air-application-installer-package+zip": [
- "air"
- ],
- "application/vnd.adobe.formscentral.fcdt": [
- "fcdt"
- ],
- "application/vnd.adobe.fxp": [
- "fxp",
- "fxpl"
- ],
- "application/vnd.adobe.partial-upload": [],
- "application/vnd.adobe.xdp+xml": [
- "xdp"
- ],
- "application/vnd.adobe.xfdf": [
- "xfdf"
- ],
- "application/vnd.aether.imp": [],
- "application/vnd.ah-barcode": [],
- "application/vnd.ahead.space": [
- "ahead"
- ],
- "application/vnd.airzip.filesecure.azf": [
- "azf"
- ],
- "application/vnd.airzip.filesecure.azs": [
- "azs"
- ],
- "application/vnd.amazon.ebook": [
- "azw"
- ],
- "application/vnd.americandynamics.acc": [
- "acc"
- ],
- "application/vnd.amiga.ami": [
- "ami"
- ],
- "application/vnd.amundsen.maze+xml": [],
- "application/vnd.android.package-archive": [
- "apk"
- ],
- "application/vnd.anser-web-certificate-issue-initiation": [
- "cii"
- ],
- "application/vnd.anser-web-funds-transfer-initiation": [
- "fti"
- ],
- "application/vnd.antix.game-component": [
- "atx"
- ],
- "application/vnd.apple.installer+xml": [
- "mpkg"
- ],
- "application/vnd.apple.mpegurl": [
- "m3u8"
- ],
- "application/vnd.arastra.swi": [],
- "application/vnd.aristanetworks.swi": [
- "swi"
- ],
- "application/vnd.astraea-software.iota": [
- "iota"
- ],
- "application/vnd.audiograph": [
- "aep"
- ],
- "application/vnd.autopackage": [],
- "application/vnd.avistar+xml": [],
- "application/vnd.blueice.multipass": [
- "mpm"
- ],
- "application/vnd.bluetooth.ep.oob": [],
- "application/vnd.bmi": [
- "bmi"
- ],
- "application/vnd.businessobjects": [
- "rep"
- ],
- "application/vnd.cab-jscript": [],
- "application/vnd.canon-cpdl": [],
- "application/vnd.canon-lips": [],
- "application/vnd.cendio.thinlinc.clientconf": [],
- "application/vnd.chemdraw+xml": [
- "cdxml"
- ],
- "application/vnd.chipnuts.karaoke-mmd": [
- "mmd"
- ],
- "application/vnd.cinderella": [
- "cdy"
- ],
- "application/vnd.cirpack.isdn-ext": [],
- "application/vnd.claymore": [
- "cla"
- ],
- "application/vnd.cloanto.rp9": [
- "rp9"
- ],
- "application/vnd.clonk.c4group": [
- "c4g",
- "c4d",
- "c4f",
- "c4p",
- "c4u"
- ],
- "application/vnd.cluetrust.cartomobile-config": [
- "c11amc"
- ],
- "application/vnd.cluetrust.cartomobile-config-pkg": [
- "c11amz"
- ],
- "application/vnd.collection+json": [],
- "application/vnd.commerce-battelle": [],
- "application/vnd.commonspace": [
- "csp"
- ],
- "application/vnd.contact.cmsg": [
- "cdbcmsg"
- ],
- "application/vnd.cosmocaller": [
- "cmc"
- ],
- "application/vnd.crick.clicker": [
- "clkx"
- ],
- "application/vnd.crick.clicker.keyboard": [
- "clkk"
- ],
- "application/vnd.crick.clicker.palette": [
- "clkp"
- ],
- "application/vnd.crick.clicker.template": [
- "clkt"
- ],
- "application/vnd.crick.clicker.wordbank": [
- "clkw"
- ],
- "application/vnd.criticaltools.wbs+xml": [
- "wbs"
- ],
- "application/vnd.ctc-posml": [
- "pml"
- ],
- "application/vnd.ctct.ws+xml": [],
- "application/vnd.cups-pdf": [],
- "application/vnd.cups-postscript": [],
- "application/vnd.cups-ppd": [
- "ppd"
- ],
- "application/vnd.cups-raster": [],
- "application/vnd.cups-raw": [],
- "application/vnd.curl": [],
- "application/vnd.curl.car": [
- "car"
- ],
- "application/vnd.curl.pcurl": [
- "pcurl"
- ],
- "application/vnd.cybank": [],
- "application/vnd.dart": [
- "dart"
- ],
- "application/vnd.data-vision.rdz": [
- "rdz"
- ],
- "application/vnd.dece.data": [
- "uvf",
- "uvvf",
- "uvd",
- "uvvd"
- ],
- "application/vnd.dece.ttml+xml": [
- "uvt",
- "uvvt"
- ],
- "application/vnd.dece.unspecified": [
- "uvx",
- "uvvx"
- ],
- "application/vnd.dece.zip": [
- "uvz",
- "uvvz"
- ],
- "application/vnd.denovo.fcselayout-link": [
- "fe_launch"
- ],
- "application/vnd.dir-bi.plate-dl-nosuffix": [],
- "application/vnd.dna": [
- "dna"
- ],
- "application/vnd.dolby.mlp": [
- "mlp"
- ],
- "application/vnd.dolby.mobile.1": [],
- "application/vnd.dolby.mobile.2": [],
- "application/vnd.dpgraph": [
- "dpg"
- ],
- "application/vnd.dreamfactory": [
- "dfac"
- ],
- "application/vnd.ds-keypoint": [
- "kpxx"
- ],
- "application/vnd.dvb.ait": [
- "ait"
- ],
- "application/vnd.dvb.dvbj": [],
- "application/vnd.dvb.esgcontainer": [],
- "application/vnd.dvb.ipdcdftnotifaccess": [],
- "application/vnd.dvb.ipdcesgaccess": [],
- "application/vnd.dvb.ipdcesgaccess2": [],
- "application/vnd.dvb.ipdcesgpdd": [],
- "application/vnd.dvb.ipdcroaming": [],
- "application/vnd.dvb.iptv.alfec-base": [],
- "application/vnd.dvb.iptv.alfec-enhancement": [],
- "application/vnd.dvb.notif-aggregate-root+xml": [],
- "application/vnd.dvb.notif-container+xml": [],
- "application/vnd.dvb.notif-generic+xml": [],
- "application/vnd.dvb.notif-ia-msglist+xml": [],
- "application/vnd.dvb.notif-ia-registration-request+xml": [],
- "application/vnd.dvb.notif-ia-registration-response+xml": [],
- "application/vnd.dvb.notif-init+xml": [],
- "application/vnd.dvb.pfr": [],
- "application/vnd.dvb.service": [
- "svc"
- ],
- "application/vnd.dxr": [],
- "application/vnd.dynageo": [
- "geo"
- ],
- "application/vnd.easykaraoke.cdgdownload": [],
- "application/vnd.ecdis-update": [],
- "application/vnd.ecowin.chart": [
- "mag"
- ],
- "application/vnd.ecowin.filerequest": [],
- "application/vnd.ecowin.fileupdate": [],
- "application/vnd.ecowin.series": [],
- "application/vnd.ecowin.seriesrequest": [],
- "application/vnd.ecowin.seriesupdate": [],
- "application/vnd.emclient.accessrequest+xml": [],
- "application/vnd.enliven": [
- "nml"
- ],
- "application/vnd.eprints.data+xml": [],
- "application/vnd.epson.esf": [
- "esf"
- ],
- "application/vnd.epson.msf": [
- "msf"
- ],
- "application/vnd.epson.quickanime": [
- "qam"
- ],
- "application/vnd.epson.salt": [
- "slt"
- ],
- "application/vnd.epson.ssf": [
- "ssf"
- ],
- "application/vnd.ericsson.quickcall": [],
- "application/vnd.eszigno3+xml": [
- "es3",
- "et3"
- ],
- "application/vnd.etsi.aoc+xml": [],
- "application/vnd.etsi.cug+xml": [],
- "application/vnd.etsi.iptvcommand+xml": [],
- "application/vnd.etsi.iptvdiscovery+xml": [],
- "application/vnd.etsi.iptvprofile+xml": [],
- "application/vnd.etsi.iptvsad-bc+xml": [],
- "application/vnd.etsi.iptvsad-cod+xml": [],
- "application/vnd.etsi.iptvsad-npvr+xml": [],
- "application/vnd.etsi.iptvservice+xml": [],
- "application/vnd.etsi.iptvsync+xml": [],
- "application/vnd.etsi.iptvueprofile+xml": [],
- "application/vnd.etsi.mcid+xml": [],
- "application/vnd.etsi.overload-control-policy-dataset+xml": [],
- "application/vnd.etsi.sci+xml": [],
- "application/vnd.etsi.simservs+xml": [],
- "application/vnd.etsi.tsl+xml": [],
- "application/vnd.etsi.tsl.der": [],
- "application/vnd.eudora.data": [],
- "application/vnd.ezpix-album": [
- "ez2"
- ],
- "application/vnd.ezpix-package": [
- "ez3"
- ],
- "application/vnd.f-secure.mobile": [],
- "application/vnd.fdf": [
- "fdf"
- ],
- "application/vnd.fdsn.mseed": [
- "mseed"
- ],
- "application/vnd.fdsn.seed": [
- "seed",
- "dataless"
- ],
- "application/vnd.ffsns": [],
- "application/vnd.fints": [],
- "application/vnd.flographit": [
- "gph"
- ],
- "application/vnd.fluxtime.clip": [
- "ftc"
- ],
- "application/vnd.font-fontforge-sfd": [],
- "application/vnd.framemaker": [
- "fm",
- "frame",
- "maker",
- "book"
- ],
- "application/vnd.frogans.fnc": [
- "fnc"
- ],
- "application/vnd.frogans.ltf": [
- "ltf"
- ],
- "application/vnd.fsc.weblaunch": [
- "fsc"
- ],
- "application/vnd.fujitsu.oasys": [
- "oas"
- ],
- "application/vnd.fujitsu.oasys2": [
- "oa2"
- ],
- "application/vnd.fujitsu.oasys3": [
- "oa3"
- ],
- "application/vnd.fujitsu.oasysgp": [
- "fg5"
- ],
- "application/vnd.fujitsu.oasysprs": [
- "bh2"
- ],
- "application/vnd.fujixerox.art-ex": [],
- "application/vnd.fujixerox.art4": [],
- "application/vnd.fujixerox.hbpl": [],
- "application/vnd.fujixerox.ddd": [
- "ddd"
- ],
- "application/vnd.fujixerox.docuworks": [
- "xdw"
- ],
- "application/vnd.fujixerox.docuworks.binder": [
- "xbd"
- ],
- "application/vnd.fut-misnet": [],
- "application/vnd.fuzzysheet": [
- "fzs"
- ],
- "application/vnd.genomatix.tuxedo": [
- "txd"
- ],
- "application/vnd.geocube+xml": [],
- "application/vnd.geogebra.file": [
- "ggb"
- ],
- "application/vnd.geogebra.tool": [
- "ggt"
- ],
- "application/vnd.geometry-explorer": [
- "gex",
- "gre"
- ],
- "application/vnd.geonext": [
- "gxt"
- ],
- "application/vnd.geoplan": [
- "g2w"
- ],
- "application/vnd.geospace": [
- "g3w"
- ],
- "application/vnd.globalplatform.card-content-mgt": [],
- "application/vnd.globalplatform.card-content-mgt-response": [],
- "application/vnd.gmx": [
- "gmx"
- ],
- "application/vnd.google-earth.kml+xml": [
- "kml"
- ],
- "application/vnd.google-earth.kmz": [
- "kmz"
- ],
- "application/vnd.grafeq": [
- "gqf",
- "gqs"
- ],
- "application/vnd.gridmp": [],
- "application/vnd.groove-account": [
- "gac"
- ],
- "application/vnd.groove-help": [
- "ghf"
- ],
- "application/vnd.groove-identity-message": [
- "gim"
- ],
- "application/vnd.groove-injector": [
- "grv"
- ],
- "application/vnd.groove-tool-message": [
- "gtm"
- ],
- "application/vnd.groove-tool-template": [
- "tpl"
- ],
- "application/vnd.groove-vcard": [
- "vcg"
- ],
- "application/vnd.hal+json": [],
- "application/vnd.hal+xml": [
- "hal"
- ],
- "application/vnd.handheld-entertainment+xml": [
- "zmm"
- ],
- "application/vnd.hbci": [
- "hbci"
- ],
- "application/vnd.hcl-bireports": [],
- "application/vnd.hhe.lesson-player": [
- "les"
- ],
- "application/vnd.hp-hpgl": [
- "hpgl"
- ],
- "application/vnd.hp-hpid": [
- "hpid"
- ],
- "application/vnd.hp-hps": [
- "hps"
- ],
- "application/vnd.hp-jlyt": [
- "jlt"
- ],
- "application/vnd.hp-pcl": [
- "pcl"
- ],
- "application/vnd.hp-pclxl": [
- "pclxl"
- ],
- "application/vnd.httphone": [],
- "application/vnd.hzn-3d-crossword": [],
- "application/vnd.ibm.afplinedata": [],
- "application/vnd.ibm.electronic-media": [],
- "application/vnd.ibm.minipay": [
- "mpy"
- ],
- "application/vnd.ibm.modcap": [
- "afp",
- "listafp",
- "list3820"
- ],
- "application/vnd.ibm.rights-management": [
- "irm"
- ],
- "application/vnd.ibm.secure-container": [
- "sc"
- ],
- "application/vnd.iccprofile": [
- "icc",
- "icm"
- ],
- "application/vnd.igloader": [
- "igl"
- ],
- "application/vnd.immervision-ivp": [
- "ivp"
- ],
- "application/vnd.immervision-ivu": [
- "ivu"
- ],
- "application/vnd.informedcontrol.rms+xml": [],
- "application/vnd.informix-visionary": [],
- "application/vnd.infotech.project": [],
- "application/vnd.infotech.project+xml": [],
- "application/vnd.innopath.wamp.notification": [],
- "application/vnd.insors.igm": [
- "igm"
- ],
- "application/vnd.intercon.formnet": [
- "xpw",
- "xpx"
- ],
- "application/vnd.intergeo": [
- "i2g"
- ],
- "application/vnd.intertrust.digibox": [],
- "application/vnd.intertrust.nncp": [],
- "application/vnd.intu.qbo": [
- "qbo"
- ],
- "application/vnd.intu.qfx": [
- "qfx"
- ],
- "application/vnd.iptc.g2.conceptitem+xml": [],
- "application/vnd.iptc.g2.knowledgeitem+xml": [],
- "application/vnd.iptc.g2.newsitem+xml": [],
- "application/vnd.iptc.g2.newsmessage+xml": [],
- "application/vnd.iptc.g2.packageitem+xml": [],
- "application/vnd.iptc.g2.planningitem+xml": [],
- "application/vnd.ipunplugged.rcprofile": [
- "rcprofile"
- ],
- "application/vnd.irepository.package+xml": [
- "irp"
- ],
- "application/vnd.is-xpr": [
- "xpr"
- ],
- "application/vnd.isac.fcs": [
- "fcs"
- ],
- "application/vnd.jam": [
- "jam"
- ],
- "application/vnd.japannet-directory-service": [],
- "application/vnd.japannet-jpnstore-wakeup": [],
- "application/vnd.japannet-payment-wakeup": [],
- "application/vnd.japannet-registration": [],
- "application/vnd.japannet-registration-wakeup": [],
- "application/vnd.japannet-setstore-wakeup": [],
- "application/vnd.japannet-verification": [],
- "application/vnd.japannet-verification-wakeup": [],
- "application/vnd.jcp.javame.midlet-rms": [
- "rms"
- ],
- "application/vnd.jisp": [
- "jisp"
- ],
- "application/vnd.joost.joda-archive": [
- "joda"
- ],
- "application/vnd.kahootz": [
- "ktz",
- "ktr"
- ],
- "application/vnd.kde.karbon": [
- "karbon"
- ],
- "application/vnd.kde.kchart": [
- "chrt"
- ],
- "application/vnd.kde.kformula": [
- "kfo"
- ],
- "application/vnd.kde.kivio": [
- "flw"
- ],
- "application/vnd.kde.kontour": [
- "kon"
- ],
- "application/vnd.kde.kpresenter": [
- "kpr",
- "kpt"
- ],
- "application/vnd.kde.kspread": [
- "ksp"
- ],
- "application/vnd.kde.kword": [
- "kwd",
- "kwt"
- ],
- "application/vnd.kenameaapp": [
- "htke"
- ],
- "application/vnd.kidspiration": [
- "kia"
- ],
- "application/vnd.kinar": [
- "kne",
- "knp"
- ],
- "application/vnd.koan": [
- "skp",
- "skd",
- "skt",
- "skm"
- ],
- "application/vnd.kodak-descriptor": [
- "sse"
- ],
- "application/vnd.las.las+xml": [
- "lasxml"
- ],
- "application/vnd.liberty-request+xml": [],
- "application/vnd.llamagraphics.life-balance.desktop": [
- "lbd"
- ],
- "application/vnd.llamagraphics.life-balance.exchange+xml": [
- "lbe"
- ],
- "application/vnd.lotus-1-2-3": [
- "123"
- ],
- "application/vnd.lotus-approach": [
- "apr"
- ],
- "application/vnd.lotus-freelance": [
- "pre"
- ],
- "application/vnd.lotus-notes": [
- "nsf"
- ],
- "application/vnd.lotus-organizer": [
- "org"
- ],
- "application/vnd.lotus-screencam": [
- "scm"
- ],
- "application/vnd.lotus-wordpro": [
- "lwp"
- ],
- "application/vnd.macports.portpkg": [
- "portpkg"
- ],
- "application/vnd.marlin.drm.actiontoken+xml": [],
- "application/vnd.marlin.drm.conftoken+xml": [],
- "application/vnd.marlin.drm.license+xml": [],
- "application/vnd.marlin.drm.mdcf": [],
- "application/vnd.mcd": [
- "mcd"
- ],
- "application/vnd.medcalcdata": [
- "mc1"
- ],
- "application/vnd.mediastation.cdkey": [
- "cdkey"
- ],
- "application/vnd.meridian-slingshot": [],
- "application/vnd.mfer": [
- "mwf"
- ],
- "application/vnd.mfmp": [
- "mfm"
- ],
- "application/vnd.micrografx.flo": [
- "flo"
- ],
- "application/vnd.micrografx.igx": [
- "igx"
- ],
- "application/vnd.mif": [
- "mif"
- ],
- "application/vnd.minisoft-hp3000-save": [],
- "application/vnd.mitsubishi.misty-guard.trustweb": [],
- "application/vnd.mobius.daf": [
- "daf"
- ],
- "application/vnd.mobius.dis": [
- "dis"
- ],
- "application/vnd.mobius.mbk": [
- "mbk"
- ],
- "application/vnd.mobius.mqy": [
- "mqy"
- ],
- "application/vnd.mobius.msl": [
- "msl"
- ],
- "application/vnd.mobius.plc": [
- "plc"
- ],
- "application/vnd.mobius.txf": [
- "txf"
- ],
- "application/vnd.mophun.application": [
- "mpn"
- ],
- "application/vnd.mophun.certificate": [
- "mpc"
- ],
- "application/vnd.motorola.flexsuite": [],
- "application/vnd.motorola.flexsuite.adsi": [],
- "application/vnd.motorola.flexsuite.fis": [],
- "application/vnd.motorola.flexsuite.gotap": [],
- "application/vnd.motorola.flexsuite.kmr": [],
- "application/vnd.motorola.flexsuite.ttc": [],
- "application/vnd.motorola.flexsuite.wem": [],
- "application/vnd.motorola.iprm": [],
- "application/vnd.mozilla.xul+xml": [
- "xul"
- ],
- "application/vnd.ms-artgalry": [
- "cil"
- ],
- "application/vnd.ms-asf": [],
- "application/vnd.ms-cab-compressed": [
- "cab"
- ],
- "application/vnd.ms-color.iccprofile": [],
- "application/vnd.ms-excel": [
- "xls",
- "xlm",
- "xla",
- "xlc",
- "xlt",
- "xlw"
- ],
- "application/vnd.ms-excel.addin.macroenabled.12": [
- "xlam"
- ],
- "application/vnd.ms-excel.sheet.binary.macroenabled.12": [
- "xlsb"
- ],
- "application/vnd.ms-excel.sheet.macroenabled.12": [
- "xlsm"
- ],
- "application/vnd.ms-excel.template.macroenabled.12": [
- "xltm"
- ],
- "application/vnd.ms-fontobject": [
- "eot"
- ],
- "application/vnd.ms-htmlhelp": [
- "chm"
- ],
- "application/vnd.ms-ims": [
- "ims"
- ],
- "application/vnd.ms-lrm": [
- "lrm"
- ],
- "application/vnd.ms-office.activex+xml": [],
- "application/vnd.ms-officetheme": [
- "thmx"
- ],
- "application/vnd.ms-opentype": [],
- "application/vnd.ms-package.obfuscated-opentype": [],
- "application/vnd.ms-pki.seccat": [
- "cat"
- ],
- "application/vnd.ms-pki.stl": [
- "stl"
- ],
- "application/vnd.ms-playready.initiator+xml": [],
- "application/vnd.ms-powerpoint": [
- "ppt",
- "pps",
- "pot"
- ],
- "application/vnd.ms-powerpoint.addin.macroenabled.12": [
- "ppam"
- ],
- "application/vnd.ms-powerpoint.presentation.macroenabled.12": [
- "pptm"
- ],
- "application/vnd.ms-powerpoint.slide.macroenabled.12": [
- "sldm"
- ],
- "application/vnd.ms-powerpoint.slideshow.macroenabled.12": [
- "ppsm"
- ],
- "application/vnd.ms-powerpoint.template.macroenabled.12": [
- "potm"
- ],
- "application/vnd.ms-printing.printticket+xml": [],
- "application/vnd.ms-project": [
- "mpp",
- "mpt"
- ],
- "application/vnd.ms-tnef": [],
- "application/vnd.ms-wmdrm.lic-chlg-req": [],
- "application/vnd.ms-wmdrm.lic-resp": [],
- "application/vnd.ms-wmdrm.meter-chlg-req": [],
- "application/vnd.ms-wmdrm.meter-resp": [],
- "application/vnd.ms-word.document.macroenabled.12": [
- "docm"
- ],
- "application/vnd.ms-word.template.macroenabled.12": [
- "dotm"
- ],
- "application/vnd.ms-works": [
- "wps",
- "wks",
- "wcm",
- "wdb"
- ],
- "application/vnd.ms-wpl": [
- "wpl"
- ],
- "application/vnd.ms-xpsdocument": [
- "xps"
- ],
- "application/vnd.mseq": [
- "mseq"
- ],
- "application/vnd.msign": [],
- "application/vnd.multiad.creator": [],
- "application/vnd.multiad.creator.cif": [],
- "application/vnd.music-niff": [],
- "application/vnd.musician": [
- "mus"
- ],
- "application/vnd.muvee.style": [
- "msty"
- ],
- "application/vnd.mynfc": [
- "taglet"
- ],
- "application/vnd.ncd.control": [],
- "application/vnd.ncd.reference": [],
- "application/vnd.nervana": [],
- "application/vnd.netfpx": [],
- "application/vnd.neurolanguage.nlu": [
- "nlu"
- ],
- "application/vnd.nitf": [
- "ntf",
- "nitf"
- ],
- "application/vnd.noblenet-directory": [
- "nnd"
- ],
- "application/vnd.noblenet-sealer": [
- "nns"
- ],
- "application/vnd.noblenet-web": [
- "nnw"
- ],
- "application/vnd.nokia.catalogs": [],
- "application/vnd.nokia.conml+wbxml": [],
- "application/vnd.nokia.conml+xml": [],
- "application/vnd.nokia.isds-radio-presets": [],
- "application/vnd.nokia.iptv.config+xml": [],
- "application/vnd.nokia.landmark+wbxml": [],
- "application/vnd.nokia.landmark+xml": [],
- "application/vnd.nokia.landmarkcollection+xml": [],
- "application/vnd.nokia.n-gage.ac+xml": [],
- "application/vnd.nokia.n-gage.data": [
- "ngdat"
- ],
- "application/vnd.nokia.ncd": [],
- "application/vnd.nokia.pcd+wbxml": [],
- "application/vnd.nokia.pcd+xml": [],
- "application/vnd.nokia.radio-preset": [
- "rpst"
- ],
- "application/vnd.nokia.radio-presets": [
- "rpss"
- ],
- "application/vnd.novadigm.edm": [
- "edm"
- ],
- "application/vnd.novadigm.edx": [
- "edx"
- ],
- "application/vnd.novadigm.ext": [
- "ext"
- ],
- "application/vnd.ntt-local.file-transfer": [],
- "application/vnd.ntt-local.sip-ta_remote": [],
- "application/vnd.ntt-local.sip-ta_tcp_stream": [],
- "application/vnd.oasis.opendocument.chart": [
- "odc"
- ],
- "application/vnd.oasis.opendocument.chart-template": [
- "otc"
- ],
- "application/vnd.oasis.opendocument.database": [
- "odb"
- ],
- "application/vnd.oasis.opendocument.formula": [
- "odf"
- ],
- "application/vnd.oasis.opendocument.formula-template": [
- "odft"
- ],
- "application/vnd.oasis.opendocument.graphics": [
- "odg"
- ],
- "application/vnd.oasis.opendocument.graphics-template": [
- "otg"
- ],
- "application/vnd.oasis.opendocument.image": [
- "odi"
- ],
- "application/vnd.oasis.opendocument.image-template": [
- "oti"
- ],
- "application/vnd.oasis.opendocument.presentation": [
- "odp"
- ],
- "application/vnd.oasis.opendocument.presentation-template": [
- "otp"
- ],
- "application/vnd.oasis.opendocument.spreadsheet": [
- "ods"
- ],
- "application/vnd.oasis.opendocument.spreadsheet-template": [
- "ots"
- ],
- "application/vnd.oasis.opendocument.text": [
- "odt"
- ],
- "application/vnd.oasis.opendocument.text-master": [
- "odm"
- ],
- "application/vnd.oasis.opendocument.text-template": [
- "ott"
- ],
- "application/vnd.oasis.opendocument.text-web": [
- "oth"
- ],
- "application/vnd.obn": [],
- "application/vnd.oftn.l10n+json": [],
- "application/vnd.oipf.contentaccessdownload+xml": [],
- "application/vnd.oipf.contentaccessstreaming+xml": [],
- "application/vnd.oipf.cspg-hexbinary": [],
- "application/vnd.oipf.dae.svg+xml": [],
- "application/vnd.oipf.dae.xhtml+xml": [],
- "application/vnd.oipf.mippvcontrolmessage+xml": [],
- "application/vnd.oipf.pae.gem": [],
- "application/vnd.oipf.spdiscovery+xml": [],
- "application/vnd.oipf.spdlist+xml": [],
- "application/vnd.oipf.ueprofile+xml": [],
- "application/vnd.oipf.userprofile+xml": [],
- "application/vnd.olpc-sugar": [
- "xo"
- ],
- "application/vnd.oma-scws-config": [],
- "application/vnd.oma-scws-http-request": [],
- "application/vnd.oma-scws-http-response": [],
- "application/vnd.oma.bcast.associated-procedure-parameter+xml": [],
- "application/vnd.oma.bcast.drm-trigger+xml": [],
- "application/vnd.oma.bcast.imd+xml": [],
- "application/vnd.oma.bcast.ltkm": [],
- "application/vnd.oma.bcast.notification+xml": [],
- "application/vnd.oma.bcast.provisioningtrigger": [],
- "application/vnd.oma.bcast.sgboot": [],
- "application/vnd.oma.bcast.sgdd+xml": [],
- "application/vnd.oma.bcast.sgdu": [],
- "application/vnd.oma.bcast.simple-symbol-container": [],
- "application/vnd.oma.bcast.smartcard-trigger+xml": [],
- "application/vnd.oma.bcast.sprov+xml": [],
- "application/vnd.oma.bcast.stkm": [],
- "application/vnd.oma.cab-address-book+xml": [],
- "application/vnd.oma.cab-feature-handler+xml": [],
- "application/vnd.oma.cab-pcc+xml": [],
- "application/vnd.oma.cab-user-prefs+xml": [],
- "application/vnd.oma.dcd": [],
- "application/vnd.oma.dcdc": [],
- "application/vnd.oma.dd2+xml": [
- "dd2"
- ],
- "application/vnd.oma.drm.risd+xml": [],
- "application/vnd.oma.group-usage-list+xml": [],
- "application/vnd.oma.pal+xml": [],
- "application/vnd.oma.poc.detailed-progress-report+xml": [],
- "application/vnd.oma.poc.final-report+xml": [],
- "application/vnd.oma.poc.groups+xml": [],
- "application/vnd.oma.poc.invocation-descriptor+xml": [],
- "application/vnd.oma.poc.optimized-progress-report+xml": [],
- "application/vnd.oma.push": [],
- "application/vnd.oma.scidm.messages+xml": [],
- "application/vnd.oma.xcap-directory+xml": [],
- "application/vnd.omads-email+xml": [],
- "application/vnd.omads-file+xml": [],
- "application/vnd.omads-folder+xml": [],
- "application/vnd.omaloc-supl-init": [],
- "application/vnd.openofficeorg.extension": [
- "oxt"
- ],
- "application/vnd.openxmlformats-officedocument.custom-properties+xml": [],
- "application/vnd.openxmlformats-officedocument.customxmlproperties+xml": [],
- "application/vnd.openxmlformats-officedocument.drawing+xml": [],
- "application/vnd.openxmlformats-officedocument.drawingml.chart+xml": [],
- "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml": [],
- "application/vnd.openxmlformats-officedocument.drawingml.diagramcolors+xml": [],
- "application/vnd.openxmlformats-officedocument.drawingml.diagramdata+xml": [],
- "application/vnd.openxmlformats-officedocument.drawingml.diagramlayout+xml": [],
- "application/vnd.openxmlformats-officedocument.drawingml.diagramstyle+xml": [],
- "application/vnd.openxmlformats-officedocument.extended-properties+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.commentauthors+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.comments+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.handoutmaster+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.notesmaster+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.notesslide+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.presentation": [
- "pptx"
- ],
- "application/vnd.openxmlformats-officedocument.presentationml.presentation.main+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.presprops+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.slide": [
- "sldx"
- ],
- "application/vnd.openxmlformats-officedocument.presentationml.slide+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.slidelayout+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.slidemaster+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.slideshow": [
- "ppsx"
- ],
- "application/vnd.openxmlformats-officedocument.presentationml.slideshow.main+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.slideupdateinfo+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.tablestyles+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.tags+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.template": [
- "potx"
- ],
- "application/vnd.openxmlformats-officedocument.presentationml.template.main+xml": [],
- "application/vnd.openxmlformats-officedocument.presentationml.viewprops+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.calcchain+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.chartsheet+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.connections+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.dialogsheet+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.externallink+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcachedefinition+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.pivotcacherecords+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.pivottable+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.querytable+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionheaders+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.revisionlog+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sharedstrings+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": [
- "xlsx"
- ],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.sheetmetadata+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.tablesinglecells+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.template": [
- "xltx"
- ],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.template.main+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.usernames+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.volatiledependencies+xml": [],
- "application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml": [],
- "application/vnd.openxmlformats-officedocument.theme+xml": [],
- "application/vnd.openxmlformats-officedocument.themeoverride+xml": [],
- "application/vnd.openxmlformats-officedocument.vmldrawing": [],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.comments+xml": [],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document": [
- "docx"
- ],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document.glossary+xml": [],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml": [],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.endnotes+xml": [],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.fonttable+xml": [],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.footer+xml": [],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.footnotes+xml": [],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.numbering+xml": [],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.settings+xml": [],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml": [],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.template": [
- "dotx"
- ],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml": [],
- "application/vnd.openxmlformats-officedocument.wordprocessingml.websettings+xml": [],
- "application/vnd.openxmlformats-package.core-properties+xml": [],
- "application/vnd.openxmlformats-package.digital-signature-xmlsignature+xml": [],
- "application/vnd.openxmlformats-package.relationships+xml": [],
- "application/vnd.quobject-quoxdocument": [],
- "application/vnd.osa.netdeploy": [],
- "application/vnd.osgeo.mapguide.package": [
- "mgp"
- ],
- "application/vnd.osgi.bundle": [],
- "application/vnd.osgi.dp": [
- "dp"
- ],
- "application/vnd.osgi.subsystem": [
- "esa"
- ],
- "application/vnd.otps.ct-kip+xml": [],
- "application/vnd.palm": [
- "pdb",
- "pqa",
- "oprc"
- ],
- "application/vnd.paos.xml": [],
- "application/vnd.pawaafile": [
- "paw"
- ],
- "application/vnd.pg.format": [
- "str"
- ],
- "application/vnd.pg.osasli": [
- "ei6"
- ],
- "application/vnd.piaccess.application-licence": [],
- "application/vnd.picsel": [
- "efif"
- ],
- "application/vnd.pmi.widget": [
- "wg"
- ],
- "application/vnd.poc.group-advertisement+xml": [],
- "application/vnd.pocketlearn": [
- "plf"
- ],
- "application/vnd.powerbuilder6": [
- "pbd"
- ],
- "application/vnd.powerbuilder6-s": [],
- "application/vnd.powerbuilder7": [],
- "application/vnd.powerbuilder7-s": [],
- "application/vnd.powerbuilder75": [],
- "application/vnd.powerbuilder75-s": [],
- "application/vnd.preminet": [],
- "application/vnd.previewsystems.box": [
- "box"
- ],
- "application/vnd.proteus.magazine": [
- "mgz"
- ],
- "application/vnd.publishare-delta-tree": [
- "qps"
- ],
- "application/vnd.pvi.ptid1": [
- "ptid"
- ],
- "application/vnd.pwg-multiplexed": [],
- "application/vnd.pwg-xhtml-print+xml": [],
- "application/vnd.qualcomm.brew-app-res": [],
- "application/vnd.quark.quarkxpress": [
- "qxd",
- "qxt",
- "qwd",
- "qwt",
- "qxl",
- "qxb"
- ],
- "application/vnd.radisys.moml+xml": [],
- "application/vnd.radisys.msml+xml": [],
- "application/vnd.radisys.msml-audit+xml": [],
- "application/vnd.radisys.msml-audit-conf+xml": [],
- "application/vnd.radisys.msml-audit-conn+xml": [],
- "application/vnd.radisys.msml-audit-dialog+xml": [],
- "application/vnd.radisys.msml-audit-stream+xml": [],
- "application/vnd.radisys.msml-conf+xml": [],
- "application/vnd.radisys.msml-dialog+xml": [],
- "application/vnd.radisys.msml-dialog-base+xml": [],
- "application/vnd.radisys.msml-dialog-fax-detect+xml": [],
- "application/vnd.radisys.msml-dialog-fax-sendrecv+xml": [],
- "application/vnd.radisys.msml-dialog-group+xml": [],
- "application/vnd.radisys.msml-dialog-speech+xml": [],
- "application/vnd.radisys.msml-dialog-transform+xml": [],
- "application/vnd.rainstor.data": [],
- "application/vnd.rapid": [],
- "application/vnd.realvnc.bed": [
- "bed"
- ],
- "application/vnd.recordare.musicxml": [
- "mxl"
- ],
- "application/vnd.recordare.musicxml+xml": [
- "musicxml"
- ],
- "application/vnd.renlearn.rlprint": [],
- "application/vnd.rig.cryptonote": [
- "cryptonote"
- ],
- "application/vnd.rim.cod": [
- "cod"
- ],
- "application/vnd.rn-realmedia": [
- "rm"
- ],
- "application/vnd.rn-realmedia-vbr": [
- "rmvb"
- ],
- "application/vnd.route66.link66+xml": [
- "link66"
- ],
- "application/vnd.rs-274x": [],
- "application/vnd.ruckus.download": [],
- "application/vnd.s3sms": [],
- "application/vnd.sailingtracker.track": [
- "st"
- ],
- "application/vnd.sbm.cid": [],
- "application/vnd.sbm.mid2": [],
- "application/vnd.scribus": [],
- "application/vnd.sealed.3df": [],
- "application/vnd.sealed.csf": [],
- "application/vnd.sealed.doc": [],
- "application/vnd.sealed.eml": [],
- "application/vnd.sealed.mht": [],
- "application/vnd.sealed.net": [],
- "application/vnd.sealed.ppt": [],
- "application/vnd.sealed.tiff": [],
- "application/vnd.sealed.xls": [],
- "application/vnd.sealedmedia.softseal.html": [],
- "application/vnd.sealedmedia.softseal.pdf": [],
- "application/vnd.seemail": [
- "see"
- ],
- "application/vnd.sema": [
- "sema"
- ],
- "application/vnd.semd": [
- "semd"
- ],
- "application/vnd.semf": [
- "semf"
- ],
- "application/vnd.shana.informed.formdata": [
- "ifm"
- ],
- "application/vnd.shana.informed.formtemplate": [
- "itp"
- ],
- "application/vnd.shana.informed.interchange": [
- "iif"
- ],
- "application/vnd.shana.informed.package": [
- "ipk"
- ],
- "application/vnd.simtech-mindmapper": [
- "twd",
- "twds"
- ],
- "application/vnd.smaf": [
- "mmf"
- ],
- "application/vnd.smart.notebook": [],
- "application/vnd.smart.teacher": [
- "teacher"
- ],
- "application/vnd.software602.filler.form+xml": [],
- "application/vnd.software602.filler.form-xml-zip": [],
- "application/vnd.solent.sdkm+xml": [
- "sdkm",
- "sdkd"
- ],
- "application/vnd.spotfire.dxp": [
- "dxp"
- ],
- "application/vnd.spotfire.sfs": [
- "sfs"
- ],
- "application/vnd.sss-cod": [],
- "application/vnd.sss-dtf": [],
- "application/vnd.sss-ntf": [],
- "application/vnd.stardivision.calc": [
- "sdc"
- ],
- "application/vnd.stardivision.draw": [
- "sda"
- ],
- "application/vnd.stardivision.impress": [
- "sdd"
- ],
- "application/vnd.stardivision.math": [
- "smf"
- ],
- "application/vnd.stardivision.writer": [
- "sdw",
- "vor"
- ],
- "application/vnd.stardivision.writer-global": [
- "sgl"
- ],
- "application/vnd.stepmania.package": [
- "smzip"
- ],
- "application/vnd.stepmania.stepchart": [
- "sm"
- ],
- "application/vnd.street-stream": [],
- "application/vnd.sun.xml.calc": [
- "sxc"
- ],
- "application/vnd.sun.xml.calc.template": [
- "stc"
- ],
- "application/vnd.sun.xml.draw": [
- "sxd"
- ],
- "application/vnd.sun.xml.draw.template": [
- "std"
- ],
- "application/vnd.sun.xml.impress": [
- "sxi"
- ],
- "application/vnd.sun.xml.impress.template": [
- "sti"
- ],
- "application/vnd.sun.xml.math": [
- "sxm"
- ],
- "application/vnd.sun.xml.writer": [
- "sxw"
- ],
- "application/vnd.sun.xml.writer.global": [
- "sxg"
- ],
- "application/vnd.sun.xml.writer.template": [
- "stw"
- ],
- "application/vnd.sun.wadl+xml": [],
- "application/vnd.sus-calendar": [
- "sus",
- "susp"
- ],
- "application/vnd.svd": [
- "svd"
- ],
- "application/vnd.swiftview-ics": [],
- "application/vnd.symbian.install": [
- "sis",
- "sisx"
- ],
- "application/vnd.syncml+xml": [
- "xsm"
- ],
- "application/vnd.syncml.dm+wbxml": [
- "bdm"
- ],
- "application/vnd.syncml.dm+xml": [
- "xdm"
- ],
- "application/vnd.syncml.dm.notification": [],
- "application/vnd.syncml.ds.notification": [],
- "application/vnd.tao.intent-module-archive": [
- "tao"
- ],
- "application/vnd.tcpdump.pcap": [
- "pcap",
- "cap",
- "dmp"
- ],
- "application/vnd.tmobile-livetv": [
- "tmo"
- ],
- "application/vnd.trid.tpt": [
- "tpt"
- ],
- "application/vnd.triscape.mxs": [
- "mxs"
- ],
- "application/vnd.trueapp": [
- "tra"
- ],
- "application/vnd.truedoc": [],
- "application/vnd.ubisoft.webplayer": [],
- "application/vnd.ufdl": [
- "ufd",
- "ufdl"
- ],
- "application/vnd.uiq.theme": [
- "utz"
- ],
- "application/vnd.umajin": [
- "umj"
- ],
- "application/vnd.unity": [
- "unityweb"
- ],
- "application/vnd.uoml+xml": [
- "uoml"
- ],
- "application/vnd.uplanet.alert": [],
- "application/vnd.uplanet.alert-wbxml": [],
- "application/vnd.uplanet.bearer-choice": [],
- "application/vnd.uplanet.bearer-choice-wbxml": [],
- "application/vnd.uplanet.cacheop": [],
- "application/vnd.uplanet.cacheop-wbxml": [],
- "application/vnd.uplanet.channel": [],
- "application/vnd.uplanet.channel-wbxml": [],
- "application/vnd.uplanet.list": [],
- "application/vnd.uplanet.list-wbxml": [],
- "application/vnd.uplanet.listcmd": [],
- "application/vnd.uplanet.listcmd-wbxml": [],
- "application/vnd.uplanet.signal": [],
- "application/vnd.vcx": [
- "vcx"
- ],
- "application/vnd.vd-study": [],
- "application/vnd.vectorworks": [],
- "application/vnd.verimatrix.vcas": [],
- "application/vnd.vidsoft.vidconference": [],
- "application/vnd.visio": [
- "vsd",
- "vst",
- "vss",
- "vsw"
- ],
- "application/vnd.visionary": [
- "vis"
- ],
- "application/vnd.vividence.scriptfile": [],
- "application/vnd.vsf": [
- "vsf"
- ],
- "application/vnd.wap.sic": [],
- "application/vnd.wap.slc": [],
- "application/vnd.wap.wbxml": [
- "wbxml"
- ],
- "application/vnd.wap.wmlc": [
- "wmlc"
- ],
- "application/vnd.wap.wmlscriptc": [
- "wmlsc"
- ],
- "application/vnd.webturbo": [
- "wtb"
- ],
- "application/vnd.wfa.wsc": [],
- "application/vnd.wmc": [],
- "application/vnd.wmf.bootstrap": [],
- "application/vnd.wolfram.mathematica": [],
- "application/vnd.wolfram.mathematica.package": [],
- "application/vnd.wolfram.player": [
- "nbp"
- ],
- "application/vnd.wordperfect": [
- "wpd"
- ],
- "application/vnd.wqd": [
- "wqd"
- ],
- "application/vnd.wrq-hp3000-labelled": [],
- "application/vnd.wt.stf": [
- "stf"
- ],
- "application/vnd.wv.csp+wbxml": [],
- "application/vnd.wv.csp+xml": [],
- "application/vnd.wv.ssp+xml": [],
- "application/vnd.xara": [
- "xar"
- ],
- "application/vnd.xfdl": [
- "xfdl"
- ],
- "application/vnd.xfdl.webform": [],
- "application/vnd.xmi+xml": [],
- "application/vnd.xmpie.cpkg": [],
- "application/vnd.xmpie.dpkg": [],
- "application/vnd.xmpie.plan": [],
- "application/vnd.xmpie.ppkg": [],
- "application/vnd.xmpie.xlim": [],
- "application/vnd.yamaha.hv-dic": [
- "hvd"
- ],
- "application/vnd.yamaha.hv-script": [
- "hvs"
- ],
- "application/vnd.yamaha.hv-voice": [
- "hvp"
- ],
- "application/vnd.yamaha.openscoreformat": [
- "osf"
- ],
- "application/vnd.yamaha.openscoreformat.osfpvg+xml": [
- "osfpvg"
- ],
- "application/vnd.yamaha.remote-setup": [],
- "application/vnd.yamaha.smaf-audio": [
- "saf"
- ],
- "application/vnd.yamaha.smaf-phrase": [
- "spf"
- ],
- "application/vnd.yamaha.through-ngn": [],
- "application/vnd.yamaha.tunnel-udpencap": [],
- "application/vnd.yellowriver-custom-menu": [
- "cmp"
- ],
- "application/vnd.zul": [
- "zir",
- "zirz"
- ],
- "application/vnd.zzazz.deck+xml": [
- "zaz"
- ],
- "application/voicexml+xml": [
- "vxml"
- ],
- "application/vq-rtcpxr": [],
- "application/watcherinfo+xml": [],
- "application/whoispp-query": [],
- "application/whoispp-response": [],
- "application/widget": [
- "wgt"
- ],
- "application/winhlp": [
- "hlp"
- ],
- "application/wita": [],
- "application/wordperfect5.1": [],
- "application/wsdl+xml": [
- "wsdl"
- ],
- "application/wspolicy+xml": [
- "wspolicy"
- ],
- "application/x-7z-compressed": [
- "7z"
- ],
- "application/x-abiword": [
- "abw"
- ],
- "application/x-ace-compressed": [
- "ace"
- ],
- "application/x-amf": [],
- "application/x-apple-diskimage": [
- "dmg"
- ],
- "application/x-authorware-bin": [
- "aab",
- "x32",
- "u32",
- "vox"
- ],
- "application/x-authorware-map": [
- "aam"
- ],
- "application/x-authorware-seg": [
- "aas"
- ],
- "application/x-bcpio": [
- "bcpio"
- ],
- "application/x-bittorrent": [
- "torrent"
- ],
- "application/x-blorb": [
- "blb",
- "blorb"
- ],
- "application/x-bzip": [
- "bz"
- ],
- "application/x-bzip2": [
- "bz2",
- "boz"
- ],
- "application/x-cbr": [
- "cbr",
- "cba",
- "cbt",
- "cbz",
- "cb7"
- ],
- "application/x-cdlink": [
- "vcd"
- ],
- "application/x-cfs-compressed": [
- "cfs"
- ],
- "application/x-chat": [
- "chat"
- ],
- "application/x-chess-pgn": [
- "pgn"
- ],
- "application/x-conference": [
- "nsc"
- ],
- "application/x-compress": [],
- "application/x-cpio": [
- "cpio"
- ],
- "application/x-csh": [
- "csh"
- ],
- "application/x-debian-package": [
- "deb",
- "udeb"
- ],
- "application/x-dgc-compressed": [
- "dgc"
- ],
- "application/x-director": [
- "dir",
- "dcr",
- "dxr",
- "cst",
- "cct",
- "cxt",
- "w3d",
- "fgd",
- "swa"
- ],
- "application/x-doom": [
- "wad"
- ],
- "application/x-dtbncx+xml": [
- "ncx"
- ],
- "application/x-dtbook+xml": [
- "dtb"
- ],
- "application/x-dtbresource+xml": [
- "res"
- ],
- "application/x-dvi": [
- "dvi"
- ],
- "application/x-envoy": [
- "evy"
- ],
- "application/x-eva": [
- "eva"
- ],
- "application/x-font-bdf": [
- "bdf"
- ],
- "application/x-font-dos": [],
- "application/x-font-framemaker": [],
- "application/x-font-ghostscript": [
- "gsf"
- ],
- "application/x-font-libgrx": [],
- "application/x-font-linux-psf": [
- "psf"
- ],
- "application/x-font-otf": [
- "otf"
- ],
- "application/x-font-pcf": [
- "pcf"
- ],
- "application/x-font-snf": [
- "snf"
- ],
- "application/x-font-speedo": [],
- "application/x-font-sunos-news": [],
- "application/x-font-ttf": [
- "ttf",
- "ttc"
- ],
- "application/x-font-type1": [
- "pfa",
- "pfb",
- "pfm",
- "afm"
- ],
- "application/font-woff": [
- "woff"
- ],
- "application/x-font-vfont": [],
- "application/x-freearc": [
- "arc"
- ],
- "application/x-futuresplash": [
- "spl"
- ],
- "application/x-gca-compressed": [
- "gca"
- ],
- "application/x-glulx": [
- "ulx"
- ],
- "application/x-gnumeric": [
- "gnumeric"
- ],
- "application/x-gramps-xml": [
- "gramps"
- ],
- "application/x-gtar": [
- "gtar"
- ],
- "application/x-gzip": [],
- "application/x-hdf": [
- "hdf"
- ],
- "application/x-install-instructions": [
- "install"
- ],
- "application/x-iso9660-image": [
- "iso"
- ],
- "application/x-java-jnlp-file": [
- "jnlp"
- ],
- "application/x-latex": [
- "latex"
- ],
- "application/x-lzh-compressed": [
- "lzh",
- "lha"
- ],
- "application/x-mie": [
- "mie"
- ],
- "application/x-mobipocket-ebook": [
- "prc",
- "mobi"
- ],
- "application/x-ms-application": [
- "application"
- ],
- "application/x-ms-shortcut": [
- "lnk"
- ],
- "application/x-ms-wmd": [
- "wmd"
- ],
- "application/x-ms-wmz": [
- "wmz"
- ],
- "application/x-ms-xbap": [
- "xbap"
- ],
- "application/x-msaccess": [
- "mdb"
- ],
- "application/x-msbinder": [
- "obd"
- ],
- "application/x-mscardfile": [
- "crd"
- ],
- "application/x-msclip": [
- "clp"
- ],
- "application/x-msdownload": [
- "exe",
- "dll",
- "com",
- "bat",
- "msi"
- ],
- "application/x-msmediaview": [
- "mvb",
- "m13",
- "m14"
- ],
- "application/x-msmetafile": [
- "wmf",
- "wmz",
- "emf",
- "emz"
- ],
- "application/x-msmoney": [
- "mny"
- ],
- "application/x-mspublisher": [
- "pub"
- ],
- "application/x-msschedule": [
- "scd"
- ],
- "application/x-msterminal": [
- "trm"
- ],
- "application/x-mswrite": [
- "wri"
- ],
- "application/x-netcdf": [
- "nc",
- "cdf"
- ],
- "application/x-nzb": [
- "nzb"
- ],
- "application/x-pkcs12": [
- "p12",
- "pfx"
- ],
- "application/x-pkcs7-certificates": [
- "p7b",
- "spc"
- ],
- "application/x-pkcs7-certreqresp": [
- "p7r"
- ],
- "application/x-rar-compressed": [
- "rar"
- ],
- "application/x-research-info-systems": [
- "ris"
- ],
- "application/x-sh": [
- "sh"
- ],
- "application/x-shar": [
- "shar"
- ],
- "application/x-shockwave-flash": [
- "swf"
- ],
- "application/x-silverlight-app": [
- "xap"
- ],
- "application/x-sql": [
- "sql"
- ],
- "application/x-stuffit": [
- "sit"
- ],
- "application/x-stuffitx": [
- "sitx"
- ],
- "application/x-subrip": [
- "srt"
- ],
- "application/x-sv4cpio": [
- "sv4cpio"
- ],
- "application/x-sv4crc": [
- "sv4crc"
- ],
- "application/x-t3vm-image": [
- "t3"
- ],
- "application/x-tads": [
- "gam"
- ],
- "application/x-tar": [
- "tar"
- ],
- "application/x-tcl": [
- "tcl"
- ],
- "application/x-tex": [
- "tex"
- ],
- "application/x-tex-tfm": [
- "tfm"
- ],
- "application/x-texinfo": [
- "texinfo",
- "texi"
- ],
- "application/x-tgif": [
- "obj"
- ],
- "application/x-ustar": [
- "ustar"
- ],
- "application/x-wais-source": [
- "src"
- ],
- "application/x-x509-ca-cert": [
- "der",
- "crt"
- ],
- "application/x-xfig": [
- "fig"
- ],
- "application/x-xliff+xml": [
- "xlf"
- ],
- "application/x-xpinstall": [
- "xpi"
- ],
- "application/x-xz": [
- "xz"
- ],
- "application/x-zmachine": [
- "z1",
- "z2",
- "z3",
- "z4",
- "z5",
- "z6",
- "z7",
- "z8"
- ],
- "application/x400-bp": [],
- "application/xaml+xml": [
- "xaml"
- ],
- "application/xcap-att+xml": [],
- "application/xcap-caps+xml": [],
- "application/xcap-diff+xml": [
- "xdf"
- ],
- "application/xcap-el+xml": [],
- "application/xcap-error+xml": [],
- "application/xcap-ns+xml": [],
- "application/xcon-conference-info-diff+xml": [],
- "application/xcon-conference-info+xml": [],
- "application/xenc+xml": [
- "xenc"
- ],
- "application/xhtml+xml": [
- "xhtml",
- "xht"
- ],
- "application/xhtml-voice+xml": [],
- "application/xml": [
- "xml",
- "xsl"
- ],
- "application/xml-dtd": [
- "dtd"
- ],
- "application/xml-external-parsed-entity": [],
- "application/xmpp+xml": [],
- "application/xop+xml": [
- "xop"
- ],
- "application/xproc+xml": [
- "xpl"
- ],
- "application/xslt+xml": [
- "xslt"
- ],
- "application/xspf+xml": [
- "xspf"
- ],
- "application/xv+xml": [
- "mxml",
- "xhvml",
- "xvml",
- "xvm"
- ],
- "application/yang": [
- "yang"
- ],
- "application/yin+xml": [
- "yin"
- ],
- "application/zip": [
- "zip"
- ],
- "audio/1d-interleaved-parityfec": [],
- "audio/32kadpcm": [],
- "audio/3gpp": [],
- "audio/3gpp2": [],
- "audio/ac3": [],
- "audio/adpcm": [
- "adp"
- ],
- "audio/amr": [],
- "audio/amr-wb": [],
- "audio/amr-wb+": [],
- "audio/asc": [],
- "audio/atrac-advanced-lossless": [],
- "audio/atrac-x": [],
- "audio/atrac3": [],
- "audio/basic": [
- "au",
- "snd"
- ],
- "audio/bv16": [],
- "audio/bv32": [],
- "audio/clearmode": [],
- "audio/cn": [],
- "audio/dat12": [],
- "audio/dls": [],
- "audio/dsr-es201108": [],
- "audio/dsr-es202050": [],
- "audio/dsr-es202211": [],
- "audio/dsr-es202212": [],
- "audio/dv": [],
- "audio/dvi4": [],
- "audio/eac3": [],
- "audio/evrc": [],
- "audio/evrc-qcp": [],
- "audio/evrc0": [],
- "audio/evrc1": [],
- "audio/evrcb": [],
- "audio/evrcb0": [],
- "audio/evrcb1": [],
- "audio/evrcwb": [],
- "audio/evrcwb0": [],
- "audio/evrcwb1": [],
- "audio/example": [],
- "audio/fwdred": [],
- "audio/g719": [],
- "audio/g722": [],
- "audio/g7221": [],
- "audio/g723": [],
- "audio/g726-16": [],
- "audio/g726-24": [],
- "audio/g726-32": [],
- "audio/g726-40": [],
- "audio/g728": [],
- "audio/g729": [],
- "audio/g7291": [],
- "audio/g729d": [],
- "audio/g729e": [],
- "audio/gsm": [],
- "audio/gsm-efr": [],
- "audio/gsm-hr-08": [],
- "audio/ilbc": [],
- "audio/ip-mr_v2.5": [],
- "audio/isac": [],
- "audio/l16": [],
- "audio/l20": [],
- "audio/l24": [],
- "audio/l8": [],
- "audio/lpc": [],
- "audio/midi": [
- "mid",
- "midi",
- "kar",
- "rmi"
- ],
- "audio/mobile-xmf": [],
- "audio/mp4": [
- "mp4a"
- ],
- "audio/mp4a-latm": [],
- "audio/mpa": [],
- "audio/mpa-robust": [],
- "audio/mpeg": [
- "mpga",
- "mp2",
- "mp2a",
- "mp3",
- "m2a",
- "m3a"
- ],
- "audio/mpeg4-generic": [],
- "audio/musepack": [],
- "audio/ogg": [
- "oga",
- "ogg",
- "spx"
- ],
- "audio/opus": [],
- "audio/parityfec": [],
- "audio/pcma": [],
- "audio/pcma-wb": [],
- "audio/pcmu-wb": [],
- "audio/pcmu": [],
- "audio/prs.sid": [],
- "audio/qcelp": [],
- "audio/red": [],
- "audio/rtp-enc-aescm128": [],
- "audio/rtp-midi": [],
- "audio/rtx": [],
- "audio/s3m": [
- "s3m"
- ],
- "audio/silk": [
- "sil"
- ],
- "audio/smv": [],
- "audio/smv0": [],
- "audio/smv-qcp": [],
- "audio/sp-midi": [],
- "audio/speex": [],
- "audio/t140c": [],
- "audio/t38": [],
- "audio/telephone-event": [],
- "audio/tone": [],
- "audio/uemclip": [],
- "audio/ulpfec": [],
- "audio/vdvi": [],
- "audio/vmr-wb": [],
- "audio/vnd.3gpp.iufp": [],
- "audio/vnd.4sb": [],
- "audio/vnd.audiokoz": [],
- "audio/vnd.celp": [],
- "audio/vnd.cisco.nse": [],
- "audio/vnd.cmles.radio-events": [],
- "audio/vnd.cns.anp1": [],
- "audio/vnd.cns.inf1": [],
- "audio/vnd.dece.audio": [
- "uva",
- "uvva"
- ],
- "audio/vnd.digital-winds": [
- "eol"
- ],
- "audio/vnd.dlna.adts": [],
- "audio/vnd.dolby.heaac.1": [],
- "audio/vnd.dolby.heaac.2": [],
- "audio/vnd.dolby.mlp": [],
- "audio/vnd.dolby.mps": [],
- "audio/vnd.dolby.pl2": [],
- "audio/vnd.dolby.pl2x": [],
- "audio/vnd.dolby.pl2z": [],
- "audio/vnd.dolby.pulse.1": [],
- "audio/vnd.dra": [
- "dra"
- ],
- "audio/vnd.dts": [
- "dts"
- ],
- "audio/vnd.dts.hd": [
- "dtshd"
- ],
- "audio/vnd.dvb.file": [],
- "audio/vnd.everad.plj": [],
- "audio/vnd.hns.audio": [],
- "audio/vnd.lucent.voice": [
- "lvp"
- ],
- "audio/vnd.ms-playready.media.pya": [
- "pya"
- ],
- "audio/vnd.nokia.mobile-xmf": [],
- "audio/vnd.nortel.vbk": [],
- "audio/vnd.nuera.ecelp4800": [
- "ecelp4800"
- ],
- "audio/vnd.nuera.ecelp7470": [
- "ecelp7470"
- ],
- "audio/vnd.nuera.ecelp9600": [
- "ecelp9600"
- ],
- "audio/vnd.octel.sbc": [],
- "audio/vnd.qcelp": [],
- "audio/vnd.rhetorex.32kadpcm": [],
- "audio/vnd.rip": [
- "rip"
- ],
- "audio/vnd.sealedmedia.softseal.mpeg": [],
- "audio/vnd.vmx.cvsd": [],
- "audio/vorbis": [],
- "audio/vorbis-config": [],
- "audio/webm": [
- "weba"
- ],
- "audio/x-aac": [
- "aac"
- ],
- "audio/x-aiff": [
- "aif",
- "aiff",
- "aifc"
- ],
- "audio/x-caf": [
- "caf"
- ],
- "audio/x-flac": [
- "flac"
- ],
- "audio/x-matroska": [
- "mka"
- ],
- "audio/x-mpegurl": [
- "m3u"
- ],
- "audio/x-ms-wax": [
- "wax"
- ],
- "audio/x-ms-wma": [
- "wma"
- ],
- "audio/x-pn-realaudio": [
- "ram",
- "ra"
- ],
- "audio/x-pn-realaudio-plugin": [
- "rmp"
- ],
- "audio/x-tta": [],
- "audio/x-wav": [
- "wav"
- ],
- "audio/xm": [
- "xm"
- ],
- "chemical/x-cdx": [
- "cdx"
- ],
- "chemical/x-cif": [
- "cif"
- ],
- "chemical/x-cmdf": [
- "cmdf"
- ],
- "chemical/x-cml": [
- "cml"
- ],
- "chemical/x-csml": [
- "csml"
- ],
- "chemical/x-pdb": [],
- "chemical/x-xyz": [
- "xyz"
- ],
- "image/bmp": [
- "bmp"
- ],
- "image/cgm": [
- "cgm"
- ],
- "image/example": [],
- "image/fits": [],
- "image/g3fax": [
- "g3"
- ],
- "image/gif": [
- "gif"
- ],
- "image/ief": [
- "ief"
- ],
- "image/jp2": [],
- "image/jpeg": [
- "jpeg",
- "jpg",
- "jpe"
- ],
- "image/jpm": [],
- "image/jpx": [],
- "image/ktx": [
- "ktx"
- ],
- "image/naplps": [],
- "image/png": [
- "png"
- ],
- "image/prs.btif": [
- "btif"
- ],
- "image/prs.pti": [],
- "image/sgi": [
- "sgi"
- ],
- "image/svg+xml": [
- "svg",
- "svgz"
- ],
- "image/t38": [],
- "image/tiff": [
- "tiff",
- "tif"
- ],
- "image/tiff-fx": [],
- "image/vnd.adobe.photoshop": [
- "psd"
- ],
- "image/vnd.cns.inf2": [],
- "image/vnd.dece.graphic": [
- "uvi",
- "uvvi",
- "uvg",
- "uvvg"
- ],
- "image/vnd.dvb.subtitle": [
- "sub"
- ],
- "image/vnd.djvu": [
- "djvu",
- "djv"
- ],
- "image/vnd.dwg": [
- "dwg"
- ],
- "image/vnd.dxf": [
- "dxf"
- ],
- "image/vnd.fastbidsheet": [
- "fbs"
- ],
- "image/vnd.fpx": [
- "fpx"
- ],
- "image/vnd.fst": [
- "fst"
- ],
- "image/vnd.fujixerox.edmics-mmr": [
- "mmr"
- ],
- "image/vnd.fujixerox.edmics-rlc": [
- "rlc"
- ],
- "image/vnd.globalgraphics.pgb": [],
- "image/vnd.microsoft.icon": [],
- "image/vnd.mix": [],
- "image/vnd.ms-modi": [
- "mdi"
- ],
- "image/vnd.ms-photo": [
- "wdp"
- ],
- "image/vnd.net-fpx": [
- "npx"
- ],
- "image/vnd.radiance": [],
- "image/vnd.sealed.png": [],
- "image/vnd.sealedmedia.softseal.gif": [],
- "image/vnd.sealedmedia.softseal.jpg": [],
- "image/vnd.svf": [],
- "image/vnd.wap.wbmp": [
- "wbmp"
- ],
- "image/vnd.xiff": [
- "xif"
- ],
- "image/webp": [
- "webp"
- ],
- "image/x-3ds": [
- "3ds"
- ],
- "image/x-cmu-raster": [
- "ras"
- ],
- "image/x-cmx": [
- "cmx"
- ],
- "image/x-freehand": [
- "fh",
- "fhc",
- "fh4",
- "fh5",
- "fh7"
- ],
- "image/x-icon": [
- "ico"
- ],
- "image/x-mrsid-image": [
- "sid"
- ],
- "image/x-pcx": [
- "pcx"
- ],
- "image/x-pict": [
- "pic",
- "pct"
- ],
- "image/x-portable-anymap": [
- "pnm"
- ],
- "image/x-portable-bitmap": [
- "pbm"
- ],
- "image/x-portable-graymap": [
- "pgm"
- ],
- "image/x-portable-pixmap": [
- "ppm"
- ],
- "image/x-rgb": [
- "rgb"
- ],
- "image/x-tga": [
- "tga"
- ],
- "image/x-xbitmap": [
- "xbm"
- ],
- "image/x-xpixmap": [
- "xpm"
- ],
- "image/x-xwindowdump": [
- "xwd"
- ],
- "message/cpim": [],
- "message/delivery-status": [],
- "message/disposition-notification": [],
- "message/example": [],
- "message/external-body": [],
- "message/feedback-report": [],
- "message/global": [],
- "message/global-delivery-status": [],
- "message/global-disposition-notification": [],
- "message/global-headers": [],
- "message/http": [],
- "message/imdn+xml": [],
- "message/news": [],
- "message/partial": [],
- "message/rfc822": [
- "eml",
- "mime"
- ],
- "message/s-http": [],
- "message/sip": [],
- "message/sipfrag": [],
- "message/tracking-status": [],
- "message/vnd.si.simp": [],
- "model/example": [],
- "model/iges": [
- "igs",
- "iges"
- ],
- "model/mesh": [
- "msh",
- "mesh",
- "silo"
- ],
- "model/vnd.collada+xml": [
- "dae"
- ],
- "model/vnd.dwf": [
- "dwf"
- ],
- "model/vnd.flatland.3dml": [],
- "model/vnd.gdl": [
- "gdl"
- ],
- "model/vnd.gs-gdl": [],
- "model/vnd.gs.gdl": [],
- "model/vnd.gtw": [
- "gtw"
- ],
- "model/vnd.moml+xml": [],
- "model/vnd.mts": [
- "mts"
- ],
- "model/vnd.parasolid.transmit.binary": [],
- "model/vnd.parasolid.transmit.text": [],
- "model/vnd.vtu": [
- "vtu"
- ],
- "model/vrml": [
- "wrl",
- "vrml"
- ],
- "model/x3d+binary": [
- "x3db",
- "x3dbz"
- ],
- "model/x3d+vrml": [
- "x3dv",
- "x3dvz"
- ],
- "model/x3d+xml": [
- "x3d",
- "x3dz"
- ],
- "multipart/alternative": [],
- "multipart/appledouble": [],
- "multipart/byteranges": [],
- "multipart/digest": [],
- "multipart/encrypted": [],
- "multipart/example": [],
- "multipart/form-data": [],
- "multipart/header-set": [],
- "multipart/mixed": [],
- "multipart/parallel": [],
- "multipart/related": [],
- "multipart/report": [],
- "multipart/signed": [],
- "multipart/voice-message": [],
- "text/1d-interleaved-parityfec": [],
- "text/cache-manifest": [
- "appcache"
- ],
- "text/calendar": [
- "ics",
- "ifb"
- ],
- "text/css": [
- "css"
- ],
- "text/csv": [
- "csv"
- ],
- "text/directory": [],
- "text/dns": [],
- "text/ecmascript": [],
- "text/enriched": [],
- "text/example": [],
- "text/fwdred": [],
- "text/html": [
- "html",
- "htm"
- ],
- "text/javascript": [],
- "text/n3": [
- "n3"
- ],
- "text/parityfec": [],
- "text/plain": [
- "txt",
- "text",
- "conf",
- "def",
- "list",
- "log",
- "in"
- ],
- "text/prs.fallenstein.rst": [],
- "text/prs.lines.tag": [
- "dsc"
- ],
- "text/vnd.radisys.msml-basic-layout": [],
- "text/red": [],
- "text/rfc822-headers": [],
- "text/richtext": [
- "rtx"
- ],
- "text/rtf": [],
- "text/rtp-enc-aescm128": [],
- "text/rtx": [],
- "text/sgml": [
- "sgml",
- "sgm"
- ],
- "text/t140": [],
- "text/tab-separated-values": [
- "tsv"
- ],
- "text/troff": [
- "t",
- "tr",
- "roff",
- "man",
- "me",
- "ms"
- ],
- "text/turtle": [
- "ttl"
- ],
- "text/ulpfec": [],
- "text/uri-list": [
- "uri",
- "uris",
- "urls"
- ],
- "text/vcard": [
- "vcard"
- ],
- "text/vnd.abc": [],
- "text/vnd.curl": [
- "curl"
- ],
- "text/vnd.curl.dcurl": [
- "dcurl"
- ],
- "text/vnd.curl.scurl": [
- "scurl"
- ],
- "text/vnd.curl.mcurl": [
- "mcurl"
- ],
- "text/vnd.dmclientscript": [],
- "text/vnd.dvb.subtitle": [
- "sub"
- ],
- "text/vnd.esmertec.theme-descriptor": [],
- "text/vnd.fly": [
- "fly"
- ],
- "text/vnd.fmi.flexstor": [
- "flx"
- ],
- "text/vnd.graphviz": [
- "gv"
- ],
- "text/vnd.in3d.3dml": [
- "3dml"
- ],
- "text/vnd.in3d.spot": [
- "spot"
- ],
- "text/vnd.iptc.newsml": [],
- "text/vnd.iptc.nitf": [],
- "text/vnd.latex-z": [],
- "text/vnd.motorola.reflex": [],
- "text/vnd.ms-mediapackage": [],
- "text/vnd.net2phone.commcenter.command": [],
- "text/vnd.si.uricatalogue": [],
- "text/vnd.sun.j2me.app-descriptor": [
- "jad"
- ],
- "text/vnd.trolltech.linguist": [],
- "text/vnd.wap.si": [],
- "text/vnd.wap.sl": [],
- "text/vnd.wap.wml": [
- "wml"
- ],
- "text/vnd.wap.wmlscript": [
- "wmls"
- ],
- "text/x-asm": [
- "s",
- "asm"
- ],
- "text/x-c": [
- "c",
- "cc",
- "cxx",
- "cpp",
- "h",
- "hh",
- "dic"
- ],
- "text/x-fortran": [
- "f",
- "for",
- "f77",
- "f90"
- ],
- "text/x-java-source": [
- "java"
- ],
- "text/x-opml": [
- "opml"
- ],
- "text/x-pascal": [
- "p",
- "pas"
- ],
- "text/x-nfo": [
- "nfo"
- ],
- "text/x-setext": [
- "etx"
- ],
- "text/x-sfv": [
- "sfv"
- ],
- "text/x-uuencode": [
- "uu"
- ],
- "text/x-vcalendar": [
- "vcs"
- ],
- "text/x-vcard": [
- "vcf"
- ],
- "text/xml": [],
- "text/xml-external-parsed-entity": [],
- "video/1d-interleaved-parityfec": [],
- "video/3gpp": [
- "3gp"
- ],
- "video/3gpp-tt": [],
- "video/3gpp2": [
- "3g2"
- ],
- "video/bmpeg": [],
- "video/bt656": [],
- "video/celb": [],
- "video/dv": [],
- "video/example": [],
- "video/h261": [
- "h261"
- ],
- "video/h263": [
- "h263"
- ],
- "video/h263-1998": [],
- "video/h263-2000": [],
- "video/h264": [
- "h264"
- ],
- "video/h264-rcdo": [],
- "video/h264-svc": [],
- "video/jpeg": [
- "jpgv"
- ],
- "video/jpeg2000": [],
- "video/jpm": [
- "jpm",
- "jpgm"
- ],
- "video/mj2": [
- "mj2",
- "mjp2"
- ],
- "video/mp1s": [],
- "video/mp2p": [],
- "video/mp2t": [],
- "video/mp4": [
- "mp4",
- "mp4v",
- "mpg4"
- ],
- "video/mp4v-es": [],
- "video/mpeg": [
- "mpeg",
- "mpg",
- "mpe",
- "m1v",
- "m2v"
- ],
- "video/mpeg4-generic": [],
- "video/mpv": [],
- "video/nv": [],
- "video/ogg": [
- "ogv"
- ],
- "video/parityfec": [],
- "video/pointer": [],
- "video/quicktime": [
- "qt",
- "mov"
- ],
- "video/raw": [],
- "video/rtp-enc-aescm128": [],
- "video/rtx": [],
- "video/smpte292m": [],
- "video/ulpfec": [],
- "video/vc1": [],
- "video/vnd.cctv": [],
- "video/vnd.dece.hd": [
- "uvh",
- "uvvh"
- ],
- "video/vnd.dece.mobile": [
- "uvm",
- "uvvm"
- ],
- "video/vnd.dece.mp4": [],
- "video/vnd.dece.pd": [
- "uvp",
- "uvvp"
- ],
- "video/vnd.dece.sd": [
- "uvs",
- "uvvs"
- ],
- "video/vnd.dece.video": [
- "uvv",
- "uvvv"
- ],
- "video/vnd.directv.mpeg": [],
- "video/vnd.directv.mpeg-tts": [],
- "video/vnd.dlna.mpeg-tts": [],
- "video/vnd.dvb.file": [
- "dvb"
- ],
- "video/vnd.fvt": [
- "fvt"
- ],
- "video/vnd.hns.video": [],
- "video/vnd.iptvforum.1dparityfec-1010": [],
- "video/vnd.iptvforum.1dparityfec-2005": [],
- "video/vnd.iptvforum.2dparityfec-1010": [],
- "video/vnd.iptvforum.2dparityfec-2005": [],
- "video/vnd.iptvforum.ttsavc": [],
- "video/vnd.iptvforum.ttsmpeg2": [],
- "video/vnd.motorola.video": [],
- "video/vnd.motorola.videop": [],
- "video/vnd.mpegurl": [
- "mxu",
- "m4u"
- ],
- "video/vnd.ms-playready.media.pyv": [
- "pyv"
- ],
- "video/vnd.nokia.interleaved-multimedia": [],
- "video/vnd.nokia.videovoip": [],
- "video/vnd.objectvideo": [],
- "video/vnd.sealed.mpeg1": [],
- "video/vnd.sealed.mpeg4": [],
- "video/vnd.sealed.swf": [],
- "video/vnd.sealedmedia.softseal.mov": [],
- "video/vnd.uvvu.mp4": [
- "uvu",
- "uvvu"
- ],
- "video/vnd.vivo": [
- "viv"
- ],
- "video/webm": [
- "webm"
- ],
- "video/x-f4v": [
- "f4v"
- ],
- "video/x-fli": [
- "fli"
- ],
- "video/x-flv": [
- "flv"
- ],
- "video/x-m4v": [
- "m4v"
- ],
- "video/x-matroska": [
- "mkv",
- "mk3d",
- "mks"
- ],
- "video/x-mng": [
- "mng"
- ],
- "video/x-ms-asf": [
- "asf",
- "asx"
- ],
- "video/x-ms-vob": [
- "vob"
- ],
- "video/x-ms-wm": [
- "wm"
- ],
- "video/x-ms-wmv": [
- "wmv"
- ],
- "video/x-ms-wmx": [
- "wmx"
- ],
- "video/x-ms-wvx": [
- "wvx"
- ],
- "video/x-msvideo": [
- "avi"
- ],
- "video/x-sgi-movie": [
- "movie"
- ],
- "video/x-smv": [
- "smv"
- ],
- "x-conference/x-cooltalk": [
- "ice"
- ]
-}
+++ /dev/null
-{
- "text/vtt": [
- "vtt"
- ],
- "application/x-chrome-extension": [
- "crx"
- ],
- "text/x-component": [
- "htc"
- ],
- "text/cache-manifest": [
- "manifest"
- ],
- "application/octet-stream": [
- "buffer"
- ],
- "application/mp4": [
- "m4p"
- ],
- "audio/mp4": [
- "m4a"
- ],
- "video/MP2T": [
- "ts"
- ],
- "application/x-web-app-manifest+json": [
- "webapp"
- ],
- "text/x-lua": [
- "lua"
- ],
- "application/x-lua-bytecode": [
- "luac"
- ],
- "text/x-markdown": [
- "markdown",
- "md",
- "mkd"
- ],
- "text/plain": [
- "ini"
- ],
- "application/dash+xml": [
- "mdp"
- ],
- "font/opentype": [
- "otf"
- ],
- "application/json": [
- "map"
- ],
- "application/xml": [
- "xsd"
- ]
-}
--- /dev/null
+1.6.1 / 2015-02-05
+==================
+
+ * Community extensions ownership transferred from `node-mime`
+
+1.6.0 / 2015-01-29
+==================
+
+ * Add `application/jose`
+ * Add `application/jose+json`
+ * Add `application/json-seq`
+ * Add `application/jwk+json`
+ * Add `application/jwk-set+json`
+ * Add `application/jwt`
+ * Add `application/rdap+json`
+ * Add `application/vnd.gov.sk.e-form+xml`
+ * Add `application/vnd.ims.imsccv1p3`
+
+1.5.0 / 2014-12-30
+==================
+
+ * Add `application/vnd.oracle.resource+json`
+ * Fix various invalid MIME type entries
+ - `application/mbox+xml`
+ - `application/oscp-response`
+ - `application/vwg-multiplexed`
+ - `audio/g721`
+
+1.4.0 / 2014-12-21
+==================
+
+ * Add `application/vnd.ims.imsccv1p2`
+ * Fix various invalid MIME type entries
+ - `application/vnd-acucobol`
+ - `application/vnd-curl`
+ - `application/vnd-dart`
+ - `application/vnd-dxr`
+ - `application/vnd-fdf`
+ - `application/vnd-mif`
+ - `application/vnd-sema`
+ - `application/vnd-wap-wmlc`
+ - `application/vnd.adobe.flash-movie`
+ - `application/vnd.dece-zip`
+ - `application/vnd.dvb_service`
+ - `application/vnd.micrografx-igx`
+ - `application/vnd.sealed-doc`
+ - `application/vnd.sealed-eml`
+ - `application/vnd.sealed-mht`
+ - `application/vnd.sealed-ppt`
+ - `application/vnd.sealed-tiff`
+ - `application/vnd.sealed-xls`
+ - `application/vnd.sealedmedia.softseal-html`
+ - `application/vnd.sealedmedia.softseal-pdf`
+ - `application/vnd.wap-slc`
+ - `application/vnd.wap-wbxml`
+ - `audio/vnd.sealedmedia.softseal-mpeg`
+ - `image/vnd-djvu`
+ - `image/vnd-svf`
+ - `image/vnd-wap-wbmp`
+ - `image/vnd.sealed-png`
+ - `image/vnd.sealedmedia.softseal-gif`
+ - `image/vnd.sealedmedia.softseal-jpg`
+ - `model/vnd-dwf`
+ - `model/vnd.parasolid.transmit-binary`
+ - `model/vnd.parasolid.transmit-text`
+ - `text/vnd-a`
+ - `text/vnd-curl`
+ - `text/vnd.wap-wml`
+ * Remove example template MIME types
+ - `application/example`
+ - `audio/example`
+ - `image/example`
+ - `message/example`
+ - `model/example`
+ - `multipart/example`
+ - `text/example`
+ - `video/example`
+
+1.3.1 / 2014-12-16
+==================
+
+ * Fix missing extensions
+ - `application/json5`
+ - `text/hjson`
+
+1.3.0 / 2014-12-07
+==================
+
+ * Add `application/a2l`
+ * Add `application/aml`
+ * Add `application/atfx`
+ * Add `application/atxml`
+ * Add `application/cdfx+xml`
+ * Add `application/dii`
+ * Add `application/json5`
+ * Add `application/lxf`
+ * Add `application/mf4`
+ * Add `application/vnd.apache.thrift.compact`
+ * Add `application/vnd.apache.thrift.json`
+ * Add `application/vnd.coffeescript`
+ * Add `application/vnd.enphase.envoy`
+ * Add `application/vnd.ims.imsccv1p1`
+ * Add `text/csv-schema`
+ * Add `text/hjson`
+ * Add `text/markdown`
+ * Add `text/yaml`
+
+1.2.0 / 2014-11-09
+==================
+
+ * Add `application/cea`
+ * Add `application/dit`
+ * Add `application/vnd.gov.sk.e-form+zip`
+ * Add `application/vnd.tmd.mediaflex.api+xml`
+ * Type `application/epub+zip` is now IANA-registered
+
+1.1.2 / 2014-10-23
+==================
+
+ * Rebuild database for `application/x-www-form-urlencoded` change
+
+1.1.1 / 2014-10-20
+==================
+
+ * Mark `application/x-www-form-urlencoded` as compressible.
+
+1.1.0 / 2014-09-28
+==================
+
+ * Add `application/font-woff2`
+
+1.0.3 / 2014-09-25
+==================
+
+ * Fix engine requirement in package
+
+1.0.2 / 2014-09-25
+==================
+
+ * Add `application/coap-group+json`
+ * Add `application/dcd`
+ * Add `application/vnd.apache.thrift.binary`
+ * Add `image/vnd.tencent.tap`
+ * Mark all JSON-derived types as compressible
+ * Update `text/vtt` data
+
+1.0.1 / 2014-08-30
+==================
+
+ * Fix extension ordering
+
+1.0.0 / 2014-08-30
+==================
+
+ * Add `application/atf`
+ * Add `application/merge-patch+json`
+ * Add `multipart/x-mixed-replace`
+ * Add `source: 'apache'` metadata
+ * Add `source: 'iana'` metadata
+ * Remove badly-assumed charset data
[![Coverage Status][coveralls-image]][coveralls-url]
This is a database of all mime types.
-It consistents of a single, public JSON file and does not include any logic,
-allowing it to remain as unopinionated as possible with an API.
+It consists of a single, public JSON file and does not include any logic,
+allowing it to remain as un-opinionated as possible with an API.
It aggregates data from the following sources:
- http://www.iana.org/assignments/media-types/media-types.xhtml
- http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types
-## Usage
+## Installation
```bash
-npm i mime-db
-```
-
-```js
-var db = require('mime-db');
-
-// grab data on .js files
-var data = db['application/javascript'];
+npm install mime-db
```
If you're crazy enough to use this in the browser,
https://cdn.rawgit.com/jshttp/mime-db/master/db.json
```
+## Usage
+
+```js
+var db = require('mime-db');
+
+// grab data on .js files
+var data = db['application/javascript'];
+```
+
## Data Structure
The JSON file is a map lookup for lowercased mime types.
To edit the database, only make PRs against files in the `lib/` folder.
To update the build, run `npm run update`.
+## Adding Custom Media Types
+
+The best way to get new media types included in this library is to register
+them with the IANA. The community registration procedure is outlined in
+[RFC 6838 section 5](http://tools.ietf.org/html/rfc6838#section-5). Types
+registered with the IANA are automatically pulled into this library.
+
[npm-version-image]: https://img.shields.io/npm/v/mime-db.svg?style=flat
[npm-downloads-image]: https://img.shields.io/npm/dm/mime-db.svg?style=flat
[npm-url]: https://npmjs.org/package/mime-db
"application/eshop": {
"source": "iana"
},
- "application/example": {
- "source": "iana"
- },
"application/exi": {
"source": "iana",
"extensions": ["exi"]
"compressible": true,
"extensions": ["js"]
},
+ "application/jose": {
+ "source": "iana"
+ },
+ "application/jose+json": {
+ "source": "iana",
+ "compressible": true
+ },
"application/jrd+json": {
"source": "iana",
"compressible": true
"source": "iana",
"compressible": true
},
+ "application/json-seq": {
+ "source": "iana"
+ },
+ "application/json5": {
+ "extensions": ["json5"]
+ },
"application/jsonml+json": {
"source": "apache",
"compressible": true,
"extensions": ["jsonml"]
},
+ "application/jwk+json": {
+ "source": "iana",
+ "compressible": true
+ },
+ "application/jwk-set+json": {
+ "source": "iana",
+ "compressible": true
+ },
+ "application/jwt": {
+ "source": "iana"
+ },
"application/kpml-request+xml": {
"source": "iana"
},
"source": "iana"
},
"application/mbox": {
- "source": "apache",
+ "source": "iana",
"extensions": ["mbox"]
},
- "application/mbox+xml": {
- "source": "iana"
- },
"application/media-policy-dataset+xml": {
"source": "iana"
},
"source": "iana"
},
"application/ocsp-response": {
- "source": "apache"
+ "source": "iana"
},
"application/octet-stream": {
"source": "iana",
"source": "apache",
"extensions": ["onetoc","onetoc2","onetmp","onepkg"]
},
- "application/oscp-response": {
- "source": "iana"
- },
"application/oxps": {
"source": "iana",
"extensions": ["oxps"]
"application/raptorfec": {
"source": "iana"
},
+ "application/rdap+json": {
+ "source": "iana",
+ "compressible": true
+ },
"application/rdf+xml": {
"source": "iana",
"compressible": true,
"application/vividence.scriptfile": {
"source": "apache"
},
- "application/vnd-acucobol": {
- "source": "iana"
- },
- "application/vnd-curl": {
- "source": "iana"
- },
- "application/vnd-dart": {
- "source": "iana"
- },
- "application/vnd-dxr": {
- "source": "iana"
- },
- "application/vnd-fdf": {
- "source": "iana"
- },
- "application/vnd-mif": {
- "source": "iana"
- },
- "application/vnd-sema": {
- "source": "iana"
- },
- "application/vnd-wap-wmlc": {
- "source": "iana"
- },
"application/vnd.3gpp.bsf+xml": {
"source": "iana"
},
"extensions": ["imp"]
},
"application/vnd.acucobol": {
- "source": "apache",
+ "source": "iana",
"extensions": ["acu"]
},
"application/vnd.acucorp": {
"source": "apache",
"extensions": ["air"]
},
- "application/vnd.adobe.flash-movie": {
+ "application/vnd.adobe.flash.movie": {
"source": "iana"
},
"application/vnd.adobe.formscentral.fcdt": {
"source": "iana"
},
"application/vnd.curl": {
- "source": "apache"
+ "source": "iana"
},
"application/vnd.curl.car": {
"source": "apache",
"source": "iana"
},
"application/vnd.dart": {
- "source": "apache",
+ "source": "iana",
"compressible": true,
"extensions": ["dart"]
},
"application/vnd.debian.binary-package": {
"source": "iana"
},
- "application/vnd.dece-zip": {
- "source": "iana"
- },
"application/vnd.dece.data": {
"source": "iana",
"extensions": ["uvf","uvvf","uvd","uvvd"]
"extensions": ["uvx","uvvx"]
},
"application/vnd.dece.zip": {
- "source": "apache",
+ "source": "iana",
"extensions": ["uvz","uvvz"]
},
"application/vnd.denovo.fcselayout-link": {
"source": "iana"
},
"application/vnd.dvb.service": {
- "source": "apache",
+ "source": "iana",
"extensions": ["svc"]
},
- "application/vnd.dvb_service": {
- "source": "iana"
- },
"application/vnd.dxr": {
- "source": "apache"
+ "source": "iana"
},
"application/vnd.dynageo": {
"source": "iana",
"source": "iana"
},
"application/vnd.fdf": {
- "source": "apache",
+ "source": "iana",
"extensions": ["fdf"]
},
"application/vnd.fdsn.mseed": {
"compressible": false,
"extensions": ["kmz"]
},
+ "application/vnd.gov.sk.e-form+xml": {
+ "source": "iana"
+ },
"application/vnd.gov.sk.e-form+zip": {
"source": "iana"
},
"application/vnd.ims.imsccv1p1": {
"source": "iana"
},
+ "application/vnd.ims.imsccv1p2": {
+ "source": "iana"
+ },
+ "application/vnd.ims.imsccv1p3": {
+ "source": "iana"
+ },
"application/vnd.ims.lis.v2.result+json": {
"source": "iana",
"compressible": true
"source": "iana",
"extensions": ["mfm"]
},
- "application/vnd.micrografx-igx": {
- "source": "iana"
- },
"application/vnd.micrografx.flo": {
"source": "iana",
"extensions": ["flo"]
},
"application/vnd.micrografx.igx": {
- "source": "apache",
+ "source": "iana",
"extensions": ["igx"]
},
"application/vnd.miele+json": {
"compressible": true
},
"application/vnd.mif": {
- "source": "apache",
+ "source": "iana",
"extensions": ["mif"]
},
"application/vnd.minisoft-hp3000-save": {
"application/vnd.openxmlformats-package.relationships+xml": {
"source": "iana"
},
+ "application/vnd.oracle.resource+json": {
+ "source": "iana",
+ "compressible": true
+ },
"application/vnd.orange.indata": {
"source": "iana"
},
"extensions": ["ptid"]
},
"application/vnd.pwg-multiplexed": {
- "source": "apache"
+ "source": "iana"
},
"application/vnd.pwg-xhtml-print+xml": {
"source": "iana"
"application/vnd.scribus": {
"source": "iana"
},
- "application/vnd.sealed-doc": {
- "source": "iana"
- },
- "application/vnd.sealed-eml": {
- "source": "iana"
- },
- "application/vnd.sealed-mht": {
- "source": "iana"
- },
- "application/vnd.sealed-ppt": {
- "source": "iana"
- },
- "application/vnd.sealed-tiff": {
- "source": "iana"
- },
- "application/vnd.sealed-xls": {
- "source": "iana"
- },
"application/vnd.sealed.3df": {
"source": "iana"
},
"source": "iana"
},
"application/vnd.sealed.doc": {
- "source": "apache"
+ "source": "iana"
},
"application/vnd.sealed.eml": {
- "source": "apache"
+ "source": "iana"
},
"application/vnd.sealed.mht": {
- "source": "apache"
+ "source": "iana"
},
"application/vnd.sealed.net": {
"source": "iana"
},
"application/vnd.sealed.ppt": {
- "source": "apache"
+ "source": "iana"
},
"application/vnd.sealed.tiff": {
- "source": "apache"
- },
- "application/vnd.sealed.xls": {
- "source": "apache"
- },
- "application/vnd.sealedmedia.softseal-html": {
"source": "iana"
},
- "application/vnd.sealedmedia.softseal-pdf": {
+ "application/vnd.sealed.xls": {
"source": "iana"
},
"application/vnd.sealedmedia.softseal.html": {
- "source": "apache"
+ "source": "iana"
},
"application/vnd.sealedmedia.softseal.pdf": {
- "source": "apache"
+ "source": "iana"
},
"application/vnd.seemail": {
"source": "iana",
"extensions": ["see"]
},
"application/vnd.sema": {
- "source": "apache",
+ "source": "iana",
"extensions": ["sema"]
},
"application/vnd.semd": {
"source": "iana",
"extensions": ["vsf"]
},
- "application/vnd.wap-slc": {
- "source": "iana"
- },
- "application/vnd.wap-wbxml": {
- "source": "iana"
- },
"application/vnd.wap.sic": {
"source": "iana"
},
"application/vnd.wap.slc": {
- "source": "apache"
+ "source": "iana"
},
"application/vnd.wap.wbxml": {
- "source": "apache",
+ "source": "iana",
"extensions": ["wbxml"]
},
"application/vnd.wap.wmlc": {
- "source": "apache",
+ "source": "iana",
"extensions": ["wmlc"]
},
"application/vnd.wap.wmlscriptc": {
"application/vq-rtcpxr": {
"source": "iana"
},
- "application/vwg-multiplexed": {
- "source": "iana"
- },
"application/watcherinfo+xml": {
"source": "iana"
},
"audio/evrcwb1": {
"source": "iana"
},
- "audio/example": {
- "source": "iana"
- },
"audio/fwdred": {
"source": "iana"
},
"audio/g719": {
"source": "iana"
},
- "audio/g721": {
- "source": "iana"
- },
"audio/g722": {
"source": "iana"
},
"audio/g7221": {
- "source": "apache"
+ "source": "iana"
},
"audio/g723": {
"source": "iana"
"audio/vnd.rn-realaudio": {
"compressible": false
},
- "audio/vnd.sealedmedia.softseal-mpeg": {
- "source": "iana"
- },
"audio/vnd.sealedmedia.softseal.mpeg": {
- "source": "apache"
+ "source": "iana"
},
"audio/vnd.vmx.cvsd": {
"source": "iana"
"source": "iana",
"extensions": ["cgm"]
},
- "image/example": {
- "source": "iana"
- },
"image/fits": {
"source": "iana"
},
"image/tiff-fx": {
"source": "iana"
},
- "image/vnd-djvu": {
- "source": "iana"
- },
- "image/vnd-svf": {
- "source": "iana"
- },
- "image/vnd-wap-wbmp": {
- "source": "iana"
- },
"image/vnd.adobe.photoshop": {
"source": "iana",
"compressible": true,
"extensions": ["uvi","uvvi","uvg","uvvg"]
},
"image/vnd.djvu": {
- "source": "apache",
+ "source": "iana",
"extensions": ["djvu","djv"]
},
"image/vnd.dvb.subtitle": {
"image/vnd.radiance": {
"source": "iana"
},
- "image/vnd.sealed-png": {
- "source": "iana"
- },
"image/vnd.sealed.png": {
- "source": "apache"
- },
- "image/vnd.sealedmedia.softseal-gif": {
- "source": "iana"
- },
- "image/vnd.sealedmedia.softseal-jpg": {
"source": "iana"
},
"image/vnd.sealedmedia.softseal.gif": {
- "source": "apache"
+ "source": "iana"
},
"image/vnd.sealedmedia.softseal.jpg": {
- "source": "apache"
+ "source": "iana"
},
"image/vnd.svf": {
- "source": "apache"
+ "source": "iana"
},
"image/vnd.tencent.tap": {
"source": "iana"
"source": "iana"
},
"image/vnd.wap.wbmp": {
- "source": "apache",
+ "source": "iana",
"extensions": ["wbmp"]
},
"image/vnd.xiff": {
"message/disposition-notification": {
"source": "iana"
},
- "message/example": {
- "source": "iana"
- },
"message/external-body": {
"source": "iana"
},
"message/vnd.wfa.wsc": {
"source": "iana"
},
- "model/example": {
- "source": "iana",
- "compressible": false
- },
"model/iges": {
"source": "iana",
"compressible": false,
"compressible": false,
"extensions": ["msh","mesh","silo"]
},
- "model/vnd-dwf": {
- "source": "iana"
- },
"model/vnd.collada+xml": {
"source": "iana",
"extensions": ["dae"]
},
"model/vnd.dwf": {
- "source": "apache",
+ "source": "iana",
"extensions": ["dwf"]
},
"model/vnd.flatland.3dml": {
"extensions": ["gdl"]
},
"model/vnd.gs-gdl": {
- "source": "iana"
+ "source": "apache"
},
"model/vnd.gs.gdl": {
- "source": "apache"
+ "source": "iana"
},
"model/vnd.gtw": {
"source": "iana",
"model/vnd.opengex": {
"source": "iana"
},
- "model/vnd.parasolid.transmit-binary": {
- "source": "iana"
- },
- "model/vnd.parasolid.transmit-text": {
- "source": "iana"
- },
"model/vnd.parasolid.transmit.binary": {
- "source": "apache"
+ "source": "iana"
},
"model/vnd.parasolid.transmit.text": {
- "source": "apache"
+ "source": "iana"
},
"model/vnd.valve.source.compiled-map": {
"source": "iana"
"source": "iana",
"compressible": false
},
- "multipart/example": {
- "source": "iana"
- },
"multipart/form-data": {
"source": "iana",
"compressible": false
"text/enriched": {
"source": "iana"
},
- "text/example": {
- "source": "iana"
- },
"text/fwdred": {
"source": "iana"
},
"text/grammar-ref-list": {
"source": "iana"
},
+ "text/hjson": {
+ "extensions": ["hjson"]
+ },
"text/html": {
"source": "iana",
"compressible": true,
"compressible": true,
"extensions": ["vcard"]
},
- "text/vnd-a": {
- "source": "iana"
- },
- "text/vnd-curl": {
+ "text/vnd.a": {
"source": "iana"
},
"text/vnd.abc": {
"source": "iana"
},
"text/vnd.curl": {
- "source": "apache",
+ "source": "iana",
"extensions": ["curl"]
},
"text/vnd.curl.dcurl": {
"text/vnd.trolltech.linguist": {
"source": "iana"
},
- "text/vnd.wap-wml": {
- "source": "iana"
- },
"text/vnd.wap.si": {
"source": "iana"
},
"source": "iana"
},
"text/vnd.wap.wml": {
- "source": "apache",
+ "source": "iana",
"extensions": ["wml"]
},
"text/vnd.wap.wmlscript": {
"video/dv": {
"source": "apache"
},
- "video/example": {
- "source": "apache"
- },
"video/h261": {
"source": "apache",
"extensions": ["h261"]
{
"name": "mime-db",
"description": "Media Type Database",
- "version": "1.3.0",
+ "version": "1.6.1",
"author": {
"name": "Jonathan Ong",
"email": "me@jongleberry.com",
"url": "http://jongleberry.com"
},
+ "contributors": [
+ {
+ "name": "Douglas Christopher Wilson",
+ "email": "doug@somethingdoug.com"
+ },
+ {
+ "name": "Robert Kieffer",
+ "email": "robert@broofa.com",
+ "url": "http://github.com/broofa"
+ }
+ ],
"license": "MIT",
+ "keywords": [
+ "mime",
+ "db",
+ "type",
+ "types",
+ "database",
+ "charset",
+ "charsets"
+ ],
"repository": {
"type": "git",
"url": "https://github.com/jshttp/mime-db"
},
"devDependencies": {
- "co": "3",
+ "co": "4",
"cogent": "1",
"csv-parse": "0",
"gnode": "0.1.0",
- "istanbul": "0.3.4",
+ "istanbul": "0.3.5",
"mocha": "~1.21.4",
+ "raw-body": "~1.3.2",
"stream-to-array": "2"
},
- "engines": {
- "node": ">= 0.6"
- },
"files": [
+ "HISTORY.md",
"LICENSE",
+ "README.md",
"db.json",
"index.js"
],
+ "engines": {
+ "node": ">= 0.6"
+ },
"scripts": {
"update": "gnode scripts/extensions && gnode scripts/types && node scripts/build",
"clean": "rm src/*",
"test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot --check-leaks test/",
"test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter spec --check-leaks test/"
},
- "keywords": [
- "mime",
- "db",
- "type",
- "types",
- "database",
- "charset",
- "charsets"
- ],
- "gitHead": "dc3a4d4948e9e6814404712d0f3560f1fffe7d73",
+ "gitHead": "7f07ff87267625b73dcf73b97b2530a37a85d079",
"bugs": {
"url": "https://github.com/jshttp/mime-db/issues"
},
"homepage": "https://github.com/jshttp/mime-db",
- "_id": "mime-db@1.3.0",
- "_shasum": "5fefeb25dd9b097c5d45091c60f8149b98d749ec",
- "_from": "mime-db@>=1.3.0 <1.4.0",
- "_npmVersion": "1.4.21",
+ "_id": "mime-db@1.6.1",
+ "_shasum": "6e85cd87c961d130d6ebd37efdfc2c0e06fdfcd3",
+ "_from": "mime-db@>=1.6.0 <1.7.0",
+ "_npmVersion": "1.4.28",
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"dist": {
- "shasum": "5fefeb25dd9b097c5d45091c60f8149b98d749ec",
- "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.3.0.tgz"
+ "shasum": "6e85cd87c961d130d6ebd37efdfc2c0e06fdfcd3",
+ "tarball": "http://registry.npmjs.org/mime-db/-/mime-db-1.6.1.tgz"
},
"directories": {},
- "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.3.0.tgz",
+ "_resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.6.1.tgz",
"readme": "ERROR: No README data found!"
}
{
"name": "mime-types",
"description": "The ultimate javascript content-type utility.",
- "version": "1.0.2",
- "author": {
- "name": "Jonathan Ong",
- "email": "me@jongleberry.com",
- "url": "http://jongleberry.com"
- },
+ "version": "2.0.8",
"contributors": [
{
+ "name": "Douglas Christopher Wilson",
+ "email": "doug@somethingdoug.com"
+ },
+ {
"name": "Jeremiah Senkpiel",
"email": "fishrock123@rocketmail.com",
"url": "https://searchbeam.jit.su"
+ },
+ {
+ "name": "Jonathan Ong",
+ "email": "me@jongleberry.com",
+ "url": "http://jongleberry.com"
}
],
+ "license": "MIT",
+ "keywords": [
+ "mime",
+ "types"
+ ],
"repository": {
"type": "git",
- "url": "https://github.com/expressjs/mime-types"
+ "url": "https://github.com/jshttp/mime-types"
+ },
+ "dependencies": {
+ "mime-db": "~1.6.0"
},
- "license": "MIT",
- "main": "lib",
"devDependencies": {
- "co": "3",
- "cogent": "0",
- "mocha": "1",
- "should": "3"
+ "istanbul": "0.3.5",
+ "mocha": "~1.21.5"
},
+ "files": [
+ "HISTORY.md",
+ "LICENSE",
+ "index.js"
+ ],
"engines": {
- "node": ">= 0.8.0"
+ "node": ">= 0.6"
},
"scripts": {
- "test": "make test"
+ "test": "mocha --reporter spec test/test.js",
+ "test-cov": "istanbul cover node_modules/mocha/bin/_mocha -- --reporter dot test/test.js",
+ "test-travis": "istanbul cover node_modules/mocha/bin/_mocha --report lcovonly -- --reporter dot test/test.js"
},
- "gitHead": "e82b23836eb42003b8346fb31769da2fb7eb54e8",
+ "gitHead": "19e01e8bd630a1719ada4a3e3e9b7192b4ddb034",
"bugs": {
- "url": "https://github.com/expressjs/mime-types/issues"
+ "url": "https://github.com/jshttp/mime-types/issues"
},
- "homepage": "https://github.com/expressjs/mime-types",
- "_id": "mime-types@1.0.2",
- "_shasum": "995ae1392ab8affcbfcb2641dd054e943c0d5dce",
- "_from": "mime-types@>=1.0.1 <1.1.0",
- "_npmVersion": "1.4.21",
+ "homepage": "https://github.com/jshttp/mime-types",
+ "_id": "mime-types@2.0.8",
+ "_shasum": "5612bf6b9ec8a1285a81184fa4237fbfdbb89a7e",
+ "_from": "mime-types@>=2.0.1 <2.1.0",
+ "_npmVersion": "1.4.28",
"_npmUser": {
"name": "dougwilson",
"email": "doug@somethingdoug.com"
}
],
"dist": {
- "shasum": "995ae1392ab8affcbfcb2641dd054e943c0d5dce",
- "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz"
+ "shasum": "5612bf6b9ec8a1285a81184fa4237fbfdbb89a7e",
+ "tarball": "http://registry.npmjs.org/mime-types/-/mime-types-2.0.8.tgz"
},
"directories": {},
- "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-1.0.2.tgz",
+ "_resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.0.8.tgz",
"readme": "ERROR: No README data found!"
}
return rsa(key, base)
}
+function plaintext (consumer_secret, token_secret) {
+ var key = [
+ consumer_secret || '',
+ token_secret || ''
+ ].map(rfc3986).join('&')
+
+ return key
+}
+
function sign (signMethod, httpMethod, base_uri, params, consumer_secret, token_secret) {
var method
+ var skipArgs = 1
switch (signMethod) {
case 'RSA-SHA1':
case 'HMAC-SHA1':
method = hmacsign
break
+ case 'PLAINTEXT':
+ method = plaintext
+ skipArgs = 4
+ break
default:
throw new Error("Signature method not supported: " + signMethod)
}
- return method.apply(null, [].slice.call(arguments, 1))
+ return method.apply(null, [].slice.call(arguments, skipArgs))
}
exports.hmacsign = hmacsign
exports.rsasign = rsasign
+exports.plaintext = plaintext
exports.sign = sign
exports.rfc3986 = rfc3986
},
"name": "oauth-sign",
"description": "OAuth 1 signing. Formerly a vendor lib in mikeal/request, now a standalone module.",
- "version": "0.5.0",
+ "version": "0.6.0",
"repository": {
"url": "https://github.com/mikeal/oauth-sign"
},
"scripts": {
"test": "node test.js"
},
- "gitHead": "6fea86c2d4a38e1b3780ad0cc56f00196e5213c1",
+ "gitHead": "f1b5d7714712ab7eec485cca9d18ae95db58aa6b",
"bugs": {
"url": "https://github.com/mikeal/oauth-sign/issues"
},
"homepage": "https://github.com/mikeal/oauth-sign",
- "_id": "oauth-sign@0.5.0",
- "_shasum": "d767f5169325620eab2e087ef0c472e773db6461",
- "_from": "oauth-sign@>=0.5.0 <0.6.0",
- "_npmVersion": "2.0.0",
+ "_id": "oauth-sign@0.6.0",
+ "_shasum": "7dbeae44f6ca454e1f168451d630746735813ce3",
+ "_from": "oauth-sign@>=0.6.0 <0.7.0",
+ "_npmVersion": "1.4.14",
"_npmUser": {
- "name": "mikeal",
- "email": "mikeal.rogers@gmail.com"
+ "name": "nylen",
+ "email": "jnylen@gmail.com"
},
"maintainers": [
{
"name": "mikeal",
"email": "mikeal.rogers@gmail.com"
+ },
+ {
+ "name": "nylen",
+ "email": "jnylen@gmail.com"
}
],
"dist": {
- "shasum": "d767f5169325620eab2e087ef0c472e773db6461",
- "tarball": "http://registry.npmjs.org/oauth-sign/-/oauth-sign-0.5.0.tgz"
+ "shasum": "7dbeae44f6ca454e1f168451d630746735813ce3",
+ "tarball": "http://registry.npmjs.org/oauth-sign/-/oauth-sign-0.6.0.tgz"
},
"directories": {},
- "_resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.5.0.tgz",
+ "_resolved": "https://registry.npmjs.org/oauth-sign/-/oauth-sign-0.6.0.tgz",
"readme": "ERROR: No README data found!"
}
-var hmacsign = require('./index').hmacsign
+var oauth = require('./index')
+ , hmacsign = oauth.hmacsign
, assert = require('assert')
, qs = require('querystring')
;
console.log('r6/TJjbCOr97/+UU0NsvSne7s5g=')
assert.equal(rfc5849sign, 'r6/TJjbCOr97/+UU0NsvSne7s5g=')
+
+// PLAINTEXT
+
+var plainSign = oauth.sign('PLAINTEXT', 'GET', 'http://dummy.com', {}, 'consumer_secret', 'token_secret')
+console.log(plainSign)
+assert.equal(plainSign, 'consumer_secret&token_secret')
+
+plainSign = oauth.plaintext('consumer_secret', 'token_secret')
+console.log(plainSign)
+assert.equal(plainSign, 'consumer_secret&token_secret')
"util",
"utility"
],
- "version": "2.51.0",
+ "version": "2.53.0",
"author": {
"name": "Mikeal Rogers",
"email": "mikeal.rogers@gmail.com"
"main": "index.js",
"dependencies": {
"bl": "~0.9.0",
- "caseless": "~0.8.0",
+ "caseless": "~0.9.0",
"forever-agent": "~0.5.0",
"form-data": "~0.2.0",
"json-stringify-safe": "~5.0.0",
- "mime-types": "~1.0.1",
+ "mime-types": "~2.0.1",
"node-uuid": "~1.4.0",
"qs": "~2.3.1",
"tunnel-agent": "~0.4.0",
"tough-cookie": ">=0.12.0",
"http-signature": "~0.10.0",
- "oauth-sign": "~0.5.0",
- "hawk": "1.1.1",
+ "oauth-sign": "~0.6.0",
+ "hawk": "~2.3.0",
"aws-sign2": "~0.5.0",
"stringstream": "~0.0.4",
- "combined-stream": "~0.0.5"
+ "combined-stream": "~0.0.5",
+ "isstream": "~0.1.1"
},
"scripts": {
- "test": "npm run lint && node node_modules/.bin/taper tests/test-*.js && npm run test-browser",
- "test-browser": "browserify tests/browser/test.js -o tests/browser/test-browser.js && karma start tests/browser/karma.conf.js",
+ "test": "npm run lint && node node_modules/.bin/taper tests/test-*.js && npm run test-browser && npm run clean",
+ "test-browser": "node tests/browser/start.js",
"lint": "node node_modules/.bin/eslint lib/ *.js tests/ && echo Lint passed."
},
"devDependencies": {
"browserify": "~5.9.1",
+ "browserify-istanbul": "~0.1.3",
"coveralls": "~2.11.2",
"eslint": "0.5.1",
"function-bind": "~1.0.0",
"istanbul": "~0.3.2",
"karma": "~0.12.21",
+ "karma-browserify": "~3.0.1",
"karma-cli": "0.0.4",
+ "karma-coverage": "0.2.6",
"karma-phantomjs-launcher": "~0.1.4",
"karma-tap": "~1.0.1",
"rimraf": "~2.2.8",
+ "server-destroy": "~1.0.0",
"tape": "~3.0.0",
- "taper": "~0.3.0"
+ "taper": "~0.4.0"
},
- "gitHead": "1c8aca6a9205df58660c676005fb8ec4603d5265",
+ "gitHead": "541ce25648bc2ecab924d7d7197a2685fa16d348",
"homepage": "https://github.com/request/request",
- "_id": "request@2.51.0",
- "_shasum": "35d00bbecc012e55f907b1bd9e0dbd577bfef26e",
- "_from": "request@>=2.51.0 <2.52.0",
+ "_id": "request@2.53.0",
+ "_shasum": "180a3ae92b7b639802e4f9545dd8fcdeb71d760c",
+ "_from": "request@>=2.53.0 <2.54.0",
"_npmVersion": "1.4.14",
"_npmUser": {
"name": "nylen",
}
],
"dist": {
- "shasum": "35d00bbecc012e55f907b1bd9e0dbd577bfef26e",
- "tarball": "http://registry.npmjs.org/request/-/request-2.51.0.tgz"
+ "shasum": "180a3ae92b7b639802e4f9545dd8fcdeb71d760c",
+ "tarball": "http://registry.npmjs.org/request/-/request-2.53.0.tgz"
},
"directories": {},
- "_resolved": "https://registry.npmjs.org/request/-/request-2.51.0.tgz",
+ "_resolved": "https://registry.npmjs.org/request/-/request-2.53.0.tgz",
"readme": "ERROR: No README data found!"
}
, zlib = require('zlib')
, helpers = require('./lib/helpers')
, bl = require('bl')
- , oauth = require('oauth-sign')
, hawk = require('hawk')
, aws = require('aws-sign2')
, httpSignature = require('http-signature')
, FormData = require('form-data')
, cookies = require('./lib/cookies')
, copy = require('./lib/copy')
- , debug = require('./lib/debug')
, net = require('net')
, CombinedStream = require('combined-stream')
+ , isstream = require('isstream')
+ , getProxyFromURI = require('./lib/getProxyFromURI')
+ , Auth = require('./lib/auth').Auth
+ , oauth = require('./lib/oauth')
var safeStringify = helpers.safeStringify
, md5 = helpers.md5
}, {})
}
-function construcTunnelOptions(request) {
+function getTunnelOption(self, options) {
+ // Tunnel HTTPS by default, or if a previous request in the redirect chain
+ // was tunneled. Allow the user to override this setting.
+
+ // If self.tunnel is already set (because this is a redirect), use the
+ // existing value.
+ if (typeof self.tunnel !== 'undefined') {
+ return self.tunnel
+ }
+
+ // If options.tunnel is set (the user specified a value), use it.
+ if (typeof options.tunnel !== 'undefined') {
+ return options.tunnel
+ }
+
+ // If the destination is HTTPS, tunnel.
+ if (self.uri.protocol === 'https:') {
+ return true
+ }
+
+ // Otherwise, leave tunnel unset, because if a later request in the redirect
+ // chain is HTTPS then that request (and any subsequent ones) should be
+ // tunneled.
+ return undefined
+}
+
+function constructTunnelOptions(request) {
var proxy = request.proxy
var tunnelOptions = {
- proxy: {
- host: proxy.hostname,
- port: +proxy.port,
- proxyAuth: proxy.auth,
- headers: request.proxyHeaders
+ proxy : {
+ host : proxy.hostname,
+ port : +proxy.port,
+ proxyAuth : proxy.auth,
+ headers : request.proxyHeaders
},
- rejectUnauthorized: request.rejectUnauthorized,
- headers: request.headers,
- ca: request.ca,
- cert: request.cert,
- key: request.key
+ headers : request.headers,
+ ca : request.ca,
+ cert : request.cert,
+ key : request.key,
+ passphrase : request.passphrase,
+ pfx : request.pfx,
+ ciphers : request.ciphers,
+ rejectUnauthorized : request.rejectUnauthorized,
+ secureOptions : request.secureOptions,
+ secureProtocol : request.secureProtocol
}
return tunnelOptions
return tunnel[tunnelFnName]
}
-// Decide the proper request proxy to use based on the request URI object and the
-// environmental variables (NO_PROXY, HTTP_PROXY, etc.)
-function getProxyFromURI(uri) {
- // respect NO_PROXY environment variables (see: http://lynx.isc.org/current/breakout/lynx_help/keystrokes/environments.html)
- var noProxy = process.env.NO_PROXY || process.env.no_proxy || null
-
- // easy case first - if NO_PROXY is '*'
- if (noProxy === '*') {
- return null
- }
-
- // otherwise, parse the noProxy value to see if it applies to the URL
- if (noProxy !== null) {
- var noProxyItem, hostname, port, noProxyItemParts, noProxyHost, noProxyPort, noProxyList
-
- // canonicalize the hostname, so that 'oogle.com' won't match 'google.com'
- hostname = uri.hostname.replace(/^\.*/, '.').toLowerCase()
- noProxyList = noProxy.split(',')
-
- for (var i = 0, len = noProxyList.length; i < len; i++) {
- noProxyItem = noProxyList[i].trim().toLowerCase()
-
- // no_proxy can be granular at the port level, which complicates things a bit.
- if (noProxyItem.indexOf(':') > -1) {
- noProxyItemParts = noProxyItem.split(':', 2)
- noProxyHost = noProxyItemParts[0].replace(/^\.*/, '.')
- noProxyPort = noProxyItemParts[1]
- port = uri.port || (uri.protocol === 'https:' ? '443' : '80')
-
- // we've found a match - ports are same and host ends with no_proxy entry.
- if (port === noProxyPort && hostname.indexOf(noProxyHost) === hostname.length - noProxyHost.length) {
- return null
- }
- } else {
- noProxyItem = noProxyItem.replace(/^\.*/, '.')
- var isMatchedAt = hostname.indexOf(noProxyItem)
- if (isMatchedAt > -1 && isMatchedAt === hostname.length - noProxyItem.length) {
- return null
- }
- }
- }
- }
-
- // check for HTTP(S)_PROXY environment variables
- if (uri.protocol === 'http:') {
- return process.env.HTTP_PROXY || process.env.http_proxy || null
- } else if (uri.protocol === 'https:') {
- return process.env.HTTPS_PROXY || process.env.https_proxy || process.env.HTTP_PROXY || process.env.http_proxy || null
- }
-
- // return null if all else fails (What uri protocol are you using then?)
- return null
-}
-
// Function for properly handling a connection error
function connectionErrorHandler(error) {
var socket = this
}
}
+// encode rfc3986 characters
+function rfc3986 (str) {
+ return str.replace(/[!'()*]/g, function(c) {
+ return '%' + c.charCodeAt(0).toString(16).toUpperCase()
+ })
+}
+
function Request (options) {
- // if tunnel property of options was not given default to false
// if given the method property in options, set property explicitMethod to true
// extend the Request instance with any non-reserved properties
self.readable = true
self.writable = true
- if (typeof options.tunnel === 'undefined') {
- options.tunnel = false
- }
if (options.method) {
self.explicitMethod = true
}
- self.canTunnel = options.tunnel !== false && tunnel
self.init(options)
}
util.inherits(Request, stream.Stream)
-Request.prototype.setupTunnel = function () {
- // Set up the tunneling agent if necessary
- // Only send the proxy whitelisted header names.
- // Turn on tunneling for the rest of request.
+// Debugging
+Request.debug = process.env.NODE_DEBUG && /\brequest\b/.test(process.env.NODE_DEBUG)
+function debug() {
+ if (Request.debug) {
+ console.error('REQUEST %s', util.format.apply(util, arguments))
+ }
+}
+Request.prototype.setupTunnel = function () {
var self = this
if (typeof self.proxy === 'string') {
self.proxy = url.parse(self.proxy)
}
- if (!self.proxy) {
+ if (!self.proxy || !self.tunnel) {
return false
}
- if (!self.tunnel && self.uri.protocol !== 'https:') {
- return false
- }
-
- // Always include `defaultProxyHeaderExclusiveList`
-
- if (!self.proxyHeaderExclusiveList) {
- self.proxyHeaderExclusiveList = []
- }
-
+ // Setup Proxy Header Exclusive List and White List
+ self.proxyHeaderExclusiveList = self.proxyHeaderExclusiveList || []
+ self.proxyHeaderWhiteList = self.proxyHeaderWhiteList || defaultProxyHeaderWhiteList
var proxyHeaderExclusiveList = self.proxyHeaderExclusiveList.concat(defaultProxyHeaderExclusiveList)
-
- // Treat `proxyHeaderExclusiveList` as part of `proxyHeaderWhiteList`
-
- if (!self.proxyHeaderWhiteList) {
- self.proxyHeaderWhiteList = defaultProxyHeaderWhiteList
- }
-
var proxyHeaderWhiteList = self.proxyHeaderWhiteList.concat(proxyHeaderExclusiveList)
- var proxyHost = constructProxyHost(self.uri)
+ // Setup Proxy Headers and Proxy Headers Host
+ // Only send the Proxy White Listed Header names
self.proxyHeaders = constructProxyHeaderWhiteList(self.headers, proxyHeaderWhiteList)
- self.proxyHeaders.host = proxyHost
-
+ self.proxyHeaders.host = constructProxyHost(self.uri)
proxyHeaderExclusiveList.forEach(self.removeHeader, self)
+ // Set Agent from Tunnel Data
var tunnelFn = getTunnelFn(self)
- var tunnelOptions = construcTunnelOptions(self)
-
+ var tunnelOptions = constructTunnelOptions(self)
self.agent = tunnelFn(tunnelOptions)
- self.tunnel = true
+
return true
}
self.proxy = getProxyFromURI(self.uri)
}
- // Pass in `tunnel:true` to *always* tunnel through proxies
- self.tunnel = !!options.tunnel
+ self.tunnel = getTunnelOption(self, options)
if (self.proxy) {
self.setupTunnel()
}
}
// Auth must happen last in case signing is dependent on other headers
+ self._auth = new Auth()
+
if (options.oauth) {
self.oauth(options.oauth)
}
options.cert = self.cert
}
+ if (self.pfx) {
+ options.pfx = self.pfx
+ }
+
+ if (self.passphrase) {
+ options.passphrase = self.passphrase
+ }
+
var poolKey = ''
// different types of agents are in different pools
}
if (options.cert) {
+ if (poolKey) {
+ poolKey += ':'
+ }
poolKey += options.cert.toString('ascii') + options.key.toString('ascii')
}
+ if (options.pfx) {
+ if (poolKey) {
+ poolKey += ':'
+ }
+ poolKey += options.pfx.toString('ascii')
+ }
+
if (options.ciphers) {
if (poolKey) {
poolKey += ':'
break
}
}
- } else if (response.statusCode === 401 && self._hasAuth && !self._sentAuth) {
- var authHeader = response.caseless.get('www-authenticate')
- var authVerb = authHeader && authHeader.split(' ')[0].toLowerCase()
- debug('reauth', authVerb)
-
- switch (authVerb) {
- case 'basic':
- self.auth(self._user, self._pass, true)
- redirectTo = self.uri
- break
-
- case 'bearer':
- self.auth(null, null, true, self._bearer)
- redirectTo = self.uri
- break
-
- case 'digest':
- // TODO: More complete implementation of RFC 2617.
- // - check challenge.algorithm
- // - support algorithm="MD5-sess"
- // - handle challenge.domain
- // - support qop="auth-int" only
- // - handle Authentication-Info (not necessarily?)
- // - check challenge.stale (not necessarily?)
- // - increase nc (not necessarily?)
- // For reference:
- // http://tools.ietf.org/html/rfc2617#section-3
- // https://github.com/bagder/curl/blob/master/lib/http_digest.c
-
- var challenge = {}
- var re = /([a-z0-9_-]+)=(?:"([^"]+)"|([a-z0-9_-]+))/gi
- for (;;) {
- var match = re.exec(authHeader)
- if (!match) {
- break
- }
- challenge[match[1]] = match[2] || match[3]
- }
-
- var ha1 = md5(self._user + ':' + challenge.realm + ':' + self._pass)
- var ha2 = md5(self.method + ':' + self.uri.path)
- var qop = /(^|,)\s*auth\s*($|,)/.test(challenge.qop) && 'auth'
- var nc = qop && '00000001'
- var cnonce = qop && uuid().replace(/-/g, '')
- var digestResponse = qop ? md5(ha1 + ':' + challenge.nonce + ':' + nc + ':' + cnonce + ':' + qop + ':' + ha2) : md5(ha1 + ':' + challenge.nonce + ':' + ha2)
- var authValues = {
- username: self._user,
- realm: challenge.realm,
- nonce: challenge.nonce,
- uri: self.uri.path,
- qop: qop,
- response: digestResponse,
- nc: nc,
- cnonce: cnonce,
- algorithm: challenge.algorithm,
- opaque: challenge.opaque
- }
-
- authHeader = []
- for (var k in authValues) {
- if (authValues[k]) {
- if (k === 'qop' || k === 'nc' || k === 'algorithm') {
- authHeader.push(k + '=' + authValues[k])
- } else {
- authHeader.push(k + '="' + authValues[k] + '"')
- }
- }
- }
- authHeader = 'Digest ' + authHeader.join(', ')
- self.setHeader('authorization', authHeader)
- self._sentAuth = true
-
- redirectTo = self.uri
- break
+ } else if (response.statusCode === 401) {
+ var authHeader = self._auth.response(self.method, self.uri.path, response.headers)
+ if (authHeader) {
+ self.setHeader('authorization', authHeader)
+ redirectTo = self.uri
}
}
}
debug('emitting complete', self.uri.href)
if(typeof response.body === 'undefined' && !self._json) {
- response.body = ''
+ response.body = self.encoding === null ? new Buffer(0) : ''
}
self.emit('complete', response, response.body)
})
return self
}
- self.uri = url.parse(self.uri.href.split('?')[0] + '?' + self.qsLib.stringify(base))
+ var qs = self.qsLib.stringify(base)
+
+ self.uri = url.parse(self.uri.href.split('?')[0] + '?' + rfc3986(qs))
self.url = self.uri
self.path = self.uri.path
if (form) {
self.setHeader('content-type', 'application/x-www-form-urlencoded')
self.body = (typeof form === 'string') ? form.toString('utf8') : self.qsLib.stringify(form).toString('utf8')
+ self.body = rfc3986(self.body)
return self
}
// create form-data object
self._form = new FormData()
+ self._form.on('error',function(err) {
+ err.message = 'form-data: ' + err.message
+ self.emit('error', err)
+ self.abort()
+ })
return self._form
}
Request.prototype.multipart = function (multipart) {
var self = this
- var chunked = (multipart instanceof Array) || (multipart.chunked === undefined) || multipart.chunked
- multipart = multipart.data || multipart
+ var chunked = false
+ var _multipart = multipart.data || multipart
- var items = chunked ? new CombinedStream() : []
- function add (part) {
- return chunked ? items.append(part) : items.push(new Buffer(part))
+ if (!_multipart.forEach) {
+ throw new Error('Argument error, options.multipart.')
+ }
+
+ if (self.getHeader('transfer-encoding') === 'chunked') {
+ chunked = true
+ }
+ if (multipart.chunked !== undefined) {
+ chunked = multipart.chunked
+ }
+ if (!chunked) {
+ _multipart.forEach(function (part) {
+ if(typeof part.body === 'undefined') {
+ throw new Error('Body attribute missing in multipart.')
+ }
+ if (isstream(part.body)) {
+ chunked = true
+ }
+ })
}
- if (chunked) {
+ if (chunked && !self.hasHeader('transfer-encoding')) {
self.setHeader('transfer-encoding', 'chunked')
}
self.setHeader(headerName, self.headers[headerName].split(';')[0] + '; boundary=' + self.boundary)
}
- if (!multipart.forEach) {
- throw new Error('Argument error, options.multipart.')
+ var parts = chunked ? new CombinedStream() : []
+ function add (part) {
+ return chunked ? parts.append(part) : parts.push(new Buffer(part))
}
if (self.preambleCRLF) {
add('\r\n')
}
- multipart.forEach(function (part) {
+ _multipart.forEach(function (part) {
var body = part.body
- if(typeof body === 'undefined') {
- throw new Error('Body attribute missing in multipart.')
- }
var preamble = '--' + self.boundary + '\r\n'
Object.keys(part).forEach(function (key) {
if (key === 'body') { return }
add('\r\n')
}
- self[chunked ? '_multipart' : 'body'] = items
+ self[chunked ? '_multipart' : 'body'] = parts
return self
}
Request.prototype.json = function (val) {
self._json = true
if (typeof val === 'boolean') {
- if (self.body !== undefined && self.getHeader('content-type') !== 'application/x-www-form-urlencoded') {
- self.body = safeStringify(self.body)
+ if (self.body !== undefined) {
+ if (!/^application\/x-www-form-urlencoded\b/.test(self.getHeader('content-type'))) {
+ self.body = safeStringify(self.body)
+ } else {
+ self.body = rfc3986(self.body)
+ }
if (!self.hasHeader('content-type')) {
self.setHeader('content-type', 'application/json')
}
Request.prototype.auth = function (user, pass, sendImmediately, bearer) {
var self = this
+
+ var authHeader
if (bearer !== undefined) {
- self._bearer = bearer
- self._hasAuth = true
- if (sendImmediately || typeof sendImmediately === 'undefined') {
- if (typeof bearer === 'function') {
- bearer = bearer()
- }
- self.setHeader('authorization', 'Bearer ' + bearer)
- self._sentAuth = true
- }
- return self
- }
- if (typeof user !== 'string' || (pass !== undefined && typeof pass !== 'string')) {
- throw new Error('auth() received invalid user or password')
+ authHeader = self._auth.bearer(bearer, sendImmediately)
+ } else {
+ authHeader = self._auth.basic(user, pass, sendImmediately)
}
- self._user = user
- self._pass = pass
- self._hasAuth = true
- var header = typeof pass !== 'undefined' ? user + ':' + pass : user
- if (sendImmediately || typeof sendImmediately === 'undefined') {
- self.setHeader('authorization', 'Basic ' + toBase64(header))
- self._sentAuth = true
+ if (authHeader) {
+ self.setHeader('authorization', authHeader)
}
+
return self
}
Request.prototype.oauth = function (_oauth) {
var self = this
- var form, query
- if (self.hasHeader('content-type') &&
- self.getHeader('content-type').slice(0, 'application/x-www-form-urlencoded'.length) ===
- 'application/x-www-form-urlencoded'
- ) {
- form = self.body
- }
- if (self.uri.query) {
- query = self.uri.query
- }
- var oa = {}
- for (var i in _oauth) {
- oa['oauth_' + i] = _oauth[i]
- }
- if ('oauth_realm' in oa) {
- delete oa.oauth_realm
- }
- if (!oa.oauth_version) {
- oa.oauth_version = '1.0'
- }
- if (!oa.oauth_timestamp) {
- oa.oauth_timestamp = Math.floor( Date.now() / 1000 ).toString()
+ var result = oauth.oauth({
+ uri: self.uri,
+ method: self.method,
+ headers: self.headers,
+ body: self.body,
+ oauth: _oauth,
+ qsLib: self.qsLib
+ })
+
+ if (result.transport === 'header') {
+ self.setHeader('Authorization', result.oauth)
}
- if (!oa.oauth_nonce) {
- oa.oauth_nonce = uuid().replace(/-/g, '')
+ else if (result.transport === 'query') {
+ self.path += result.oauth
}
- if (!oa.oauth_signature_method) {
- oa.oauth_signature_method = 'HMAC-SHA1'
+ else if (result.transport === 'body') {
+ self.body = result.oauth
}
- var consumer_secret_or_private_key = oa.oauth_consumer_secret || oa.oauth_private_key
- delete oa.oauth_consumer_secret
- delete oa.oauth_private_key
- var token_secret = oa.oauth_token_secret
- delete oa.oauth_token_secret
-
- var baseurl = self.uri.protocol + '//' + self.uri.host + self.uri.pathname
- var params = self.qsLib.parse([].concat(query, form, self.qsLib.stringify(oa)).join('&'))
-
- var signature = oauth.sign(
- oa.oauth_signature_method,
- self.method,
- baseurl,
- params,
- consumer_secret_or_private_key,
- token_secret)
-
- var realm = _oauth.realm ? 'realm="' + _oauth.realm + '",' : ''
- var authHeader = 'OAuth ' + realm +
- Object.keys(oa).sort().map(function (i) {return i + '="' + oauth.rfc3986(oa[i]) + '"'}).join(',')
- authHeader += ',oauth_signature="' + oauth.rfc3986(signature) + '"'
- self.setHeader('Authorization', authHeader)
return self
}
+
Request.prototype.jar = function (jar) {
var self = this
var cookies
{
- "version": "2.4.1",
+ "version": "2.5.1",
"name": "npm",
- "description": "A package manager for node",
+ "description": "a package manager for JavaScript",
"keywords": [
"package manager",
"modules",
"chmodr": "~0.1.0",
"chownr": "0",
"cmd-shim": "~2.0.1",
- "columnify": "~1.3.2",
+ "columnify": "~1.4.1",
"config-chain": "~1.1.8",
"dezalgo": "~1.0.1",
"editor": "~0.1.0",
"fs-vacuum": "~1.2.5",
"fs-write-stream-atomic": "~1.0.2",
- "fstream": "~1.0.3",
+ "fstream": "~1.0.4",
"fstream-npm": "~1.0.1",
"github-url-from-git": "~1.4.0",
"github-url-from-username-repo": "~1.0.2",
"npm-cache-filename": "~1.0.1",
"npm-install-checks": "~1.0.5",
"npm-package-arg": "~2.1.3",
- "npm-registry-client": "~6.0.3",
+ "npm-registry-client": "~6.0.7",
"npm-user-validate": "~0.1.1",
"npmlog": "~0.1.1",
"once": "~1.3.1",
"read-package-json": "~1.2.7",
"readable-stream": "~1.0.33",
"realize-package-specifier": "~1.3.0",
- "request": "~2.51.0",
+ "request": "~2.53.0",
"retry": "~0.6.1",
"rimraf": "~2.2.8",
"semver": "~4.2.0",
"write-file-atomic"
],
"devDependencies": {
- "marked": "~0.3.2",
+ "marked": "~0.3.3",
"marked-man": "~0.1.4",
- "nock": "~0.57.0",
+ "nock": "~0.59.0",
"npm-registry-couchapp": "~2.6.2",
- "npm-registry-mock": "~0.6.3",
+ "npm-registry-mock": "~1.0.0",
"require-inject": "~1.1.0",
"tap": "~0.5.0"
},
--- /dev/null
+#!/bin/sh
+
+git log --reverse --format='%aN <%aE>' | awk '
+BEGIN {
+ print "# Authors sorted by whether or not they'\''re me";
+}
+
+{
+ if (all[$NF] != 1) {
+ all[$NF] = 1;
+ ordered[length(all)] = $0;
+ }
+}
+
+END {
+ for (i in ordered) {
+ print ordered[i];
+ }
+}
+' > AUTHORS
\ No newline at end of file
var npm_config_cache = path.resolve(__dirname, "npm_cache")
process.env.npm_config_cache = exports.npm_config_cache = npm_config_cache
+process.env.npm_config_userconfig = exports.npm_config_userconfig = path.join(__dirname, "fixtures", "config", "userconfig")
+process.env.random_env_var = "foo"
var bin = exports.bin = require.resolve("../bin/npm-cli.js")
var once = require("once")
process.chdir(pkg)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (s) {
npm.load({
cache: pkg + '/cache'
, loglevel: 'silent'
test("cleanup", function (t) {
cleanup()
t.end()
-})
\ No newline at end of file
+})
function setup (cb) {
cleanup(function (er) {
if (er) return cb(er)
- execChain([ [ "node \""+npmcli+"\" install \""+npmpkg+"\"", root ],
- [ "npm config set package-config:foo boo", root ]
- ], cb)
+ exec("node \""+npmcli+"\" install \""+npmpkg+"\"", root, false, cb)
})
}
process.chdir(pkg)
}
-function performInstall(cb) {
- mr(common.port, function (s) { // create mock registry.
+function plugin (server) {
+ server.get("/test-npm-404-parent-test")
+ .reply(404, {"error": "version not found"})
+}
+
+function performInstall (cb) {
+ mr({port : common.port, plugin : plugin}, function (er, s) { // create mock registry.
npm.load({registry: common.registry}, function () {
npm.commands.install(pkg, [], function (err) {
cb(err)
mkdirp(pkg, function (er) {
t.ifError(er, pkg + " made successfully")
- mr({port : common.port, mocks : mocks}, function (s) {
+ mr({port : common.port, plugin : mocks}, function (err, s) {
server = s
fs.writeFile(
}
test("npm login", function (t) {
- mr({port : common.port, mocks : mocks}, function (s) {
+ mr({port : common.port, plugin : mocks}, function (er, s) {
var runner = common.npm(
[
"login",
})
test("npm login --always-auth", function (t) {
- mr({port : common.port, mocks : mocks}, function (s) {
+ mr({port : common.port, plugin : mocks}, function (er, s) {
var runner = common.npm(
[
"login",
})
test("npm login --no-always-auth", function (t) {
- mr({port : common.port, mocks : mocks}, function (s) {
+ mr({port : common.port, plugin : mocks}, function (er, s) {
var runner = common.npm(
[
"login",
})
test("npm login", function (t) {
- mr({port : common.port, mocks : mocks}, function (s) {
+ mr({port : common.port, plugin : mocks}, function (er, s) {
var runner = common.npm(
[
"login",
})
test("npm bugs underscore", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
"bugs", "underscore",
"--registry=" + common.registry,
})
test("npm bugs optimist - github (https://)", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
"bugs", "optimist",
"--registry=" + common.registry,
})
test("npm bugs npm-test-peer-deps - no repo", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
"bugs", "npm-test-peer-deps",
"--registry=" + common.registry,
})
test("npm bugs test-repo-url-http - non-github (http://)", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
"bugs", "test-repo-url-http",
"--registry=" + common.registry,
})
test("npm bugs test-repo-url-https - non-github (https://)", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
"bugs", "test-repo-url-https",
"--registry=" + common.registry,
})
test("npm bugs test-repo-url-ssh - non-github (ssh://)", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
"bugs", "test-repo-url-ssh",
"--registry=" + common.registry,
mkdirp.sync(cache)
rimraf.sync(cwd)
mkdirp.sync(path.join(cwd, "node_modules"))
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
server = s
t.pass("ok")
t.end()
test("mock reg", function (t) {
rimraf.sync(cache)
mkdirp.sync(cache)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
server = s
t.pass("ok")
t.end()
process.chdir(path.resolve(pkg, "minimist"))
fs.mkdirSync(path.resolve(pkg, "minimist/node_modules"))
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
server = s
npm.load({
loglevel: "silent",
function setup (cb) {
process.chdir(path.join(__dirname, "dedupe"))
- mr(common.port, function (s) { // create mock registry.
+ mr({port : common.port}, function (er, s) { // create mock registry.
rimraf.sync(path.join(__dirname, "dedupe", "node_modules"))
fs.mkdirSync(path.join(__dirname, "dedupe", "node_modules"))
cb(s)
mkdirp(pkg, function (er) {
t.ifError(er, pkg + " made successfully")
- mr({port : common.port, mocks : mocks}, function (s) {
+ mr({port : common.port, plugin : mocks}, function (er, s) {
server = s
fs.writeFile(
test("not every pkg.name can be required", function (t) {
t.plan(3)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
"install", ".",
"--cache", cache,
var mocks = {
"get": {
- "/@bigco%2fsample/1.2.3" : [200, JSON.stringify(BIGCO_SAMPLE)]
+ "/@bigco%2fsample/1.2.3" : [200, BIGCO_SAMPLE]
}
}
test("setup", function (t) {
mkdirp.sync(CACHE_DIR)
- mr({port: common.port, mocks: mocks}, function (s) {
- npm.load({cache: CACHE_DIR, registry: common.registry}, function (err) {
- t.ifError(err)
+ mr({port: common.port, mocks: mocks}, function (er, s) {
+ t.ifError(er)
+ npm.load({cache: CACHE_DIR, registry: common.registry}, function (er) {
+ t.ifError(er)
server = s
t.end()
})
var scoped = common.registry + "/@bigco%2fsample/1.2.3"
npm.registry.get(scoped, PARAMS, function (er, data) {
t.ifError(er, "loaded all metadata")
- t.deepEqual(data.name, "@bigco/sample")
+ t.equal(data.name, "@bigco/sample")
fs.stat(getCachePath(scoped), function (er) {
t.ifError(er, "scoped cache data written")
})
}
test("ignore-shrinkwrap: using the option", function (t) {
- mr({port: common.port, mocks: customMocks}, function (s) {
+ mr({port: common.port, mocks: customMocks}, function (err, s) {
s._server.on("request", function (req) {
switch (req.url) {
case "/shrinkwrap.js":
})
test("ignore-shrinkwrap: NOT using the option", function (t) {
- mr({port: common.port, mocks: customMocks}, function (s) {
+ mr({port: common.port, mocks: customMocks}, function (err, s) {
s._server.on("request", function (req) {
switch (req.url) {
case "/shrinkwrap.js":
test("does not use unicode with --unicode false", function (t) {
t.plan(5)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm(["install", "--unicode", "false", "read"], EXEC_OPTS, function (err, code, stdout) {
t.ifError(err, "install package read without unicode success")
t.notOk(code, "npm install exited with code 0")
})
test("cleanup", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm(["uninstall", "read"], EXEC_OPTS, function (err, code) {
t.ifError(err, "uninstall read package success")
t.notOk(code, "npm uninstall exited with code 0")
test("\"npm install --save --save-exact\" should install local pkg", function (t) {
resetPackageJSON(pkg)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
npm.load({
cache: pkg + "/cache",
loglevel: "silent",
test("\"npm install --save-dev --save-exact\" should install local pkg", function (t) {
resetPackageJSON(pkg)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
npm.load({
cache: pkg + "/cache",
loglevel: "silent",
test("npm install --save with default save-prefix should install local pkg versioned to allow minor updates", function (t) {
resetPackageJSON(pkg)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
npm.load({
cache: pkg + "/cache",
loglevel: "silent",
test("npm install --save-dev with default save-prefix should install local pkg to dev dependencies versioned to allow minor updates", function (t) {
resetPackageJSON(pkg)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
npm.load({
cache: pkg + "/cache",
loglevel: "silent",
test("npm install --save with \"~\" save-prefix should install local pkg versioned to allow patch updates", function (t) {
resetPackageJSON(pkg)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
npm.load({
cache: pkg + "/cache",
loglevel: "silent",
test("npm install --save-dev with \"~\" save-prefix should install local pkg to dev dependencies versioned to allow patch updates", function (t) {
resetPackageJSON(pkg)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
npm.load({
cache: pkg + "/cache",
loglevel: "silent",
test("prefers version from dependencies over devDependencies", function (t) {
t.plan(1)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
setup(function (err) {
if (err) return t.fail(err)
cleanup()
mkdirp.sync(pkg + "/cache")
mkdirp.sync(pkg + "/tmp")
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
var cmd = ["install", "--registry=" + common.registry]
common.npm(cmd, opts, function (er, c) {
if (er) throw er
cleanup()
mkdirp.sync(cache)
mkdirp.sync(tmp)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
var cmd = ["install", "underscore@1.3.1", "mkdirp", "test-package-with-one-dep", "--registry=" + common.registry]
common.npm(cmd, opts, function (er, c) {
if (er) throw er
test("setup", function (t) {
setup()
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
server = s
t.end()
writePackageJson()
t.plan(1)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
var child = createChild([npm, "install"])
child.on("close", function () {
var text = JSON.stringify(fs.readFileSync(pkg + "/package.json", "utf8"))
writePackageJson()
t.plan(1)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
var child = createChild([npm, "install", "underscore"])
child.on("close", function () {
var text = JSON.stringify(fs.readFileSync(pkg + "/package.json", "utf8"))
// it"s not running in a tty
test("does not use ansi styling", function (t) {
t.plan(4)
- mr(common.port, function (s) { // create mock registry.
+ mr({port : common.port}, function (er, s) { // create mock registry.
common.npm(
[
"outdated",
process.chdir(pkg)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
npm.load({
cache: cache
, loglevel: "silent"
test("includes devDependencies in outdated", function (t) {
process.chdir(pkg)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
npm.load({cache: cache, registry: common.registry}, function () {
npm.outdated(function (er, d) {
t.equal("1.5.1", d[0][3])
cleanup()
process.chdir(pkg)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
npm.load({
cache: pkg + "/cache",
loglevel: "silent",
--- /dev/null
+var path = require("path")
+
+var mr = require("npm-registry-mock")
+var rimraf = require("rimraf")
+var test = require("tap").test
+
+var common = require("../common-tap.js")
+var npm = require("../../")
+
+// config
+var pkg = path.resolve(__dirname, "outdated")
+var cache = path.resolve(pkg, "cache")
+var nodeModules = path.resolve(pkg, "node_modules")
+
+test("it should not throw", function (t) {
+ cleanup()
+ process.chdir(pkg)
+
+ var originalLog = console.log
+ var output = []
+ var expOut = [ path.resolve(__dirname, "outdated/node_modules/underscore"),
+ path.resolve(__dirname, "outdated/node_modules/underscore")
+ + ":underscore@1.3.1"
+ + ":underscore@1.3.1"
+ + ":underscore@1.5.1"
+ + ":dependencies" ]
+ var expData = [ [ path.resolve(__dirname, "outdated"),
+ "underscore",
+ "1.3.1",
+ "1.3.1",
+ "1.5.1",
+ "1.3.1",
+ "dependencies" ] ]
+
+ console.log = function () {
+ output.push.apply(output, arguments)
+ }
+ mr({port : common.port}, function (er, s) {
+ npm.load({
+ cache : "cache",
+ loglevel : "silent",
+ parseable : true,
+ registry : common.registry
+ },
+ function () {
+ npm.install(".", function (err) {
+ t.ifError(err, "install success")
+ npm.config.set("long", true)
+ npm.outdated(function (er, d) {
+ t.ifError(er, "outdated success")
+ console.log = originalLog
+ t.same(output, expOut)
+ t.same(d, expData)
+ s.close()
+ t.end()
+ })
+ })
+ })
+ })
+})
+
+test("cleanup", function (t) {
+ cleanup()
+ t.end()
+})
+
+function cleanup () {
+ rimraf.sync(nodeModules)
+ rimraf.sync(cache)
+}
process.chdir(pkg)
t.plan(2)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
npm.load({cache: cache, registry: common.registry}, function () {
npm.outdated(function (er, d) {
for (var i = 0; i < d.length; i++) {
test("outdated-target: if no viable version is found, show error", function (t) {
t.plan(1)
setup()
- mr({port: common.port}, function (s) {
+ mr({port : common.port}, function (er, s) {
npm.load({ cache: cache, registry: common.registry}, function () {
npm.commands.update(function (er) {
t.equal(er.code, "ETARGET")
test("outdated ignores private modules", function (t) {
t.plan(3)
process.chdir(pkg)
- mr({ port : common.port }, function (s) {
+ mr({ port : common.port }, function (err, s) {
npm.load(
{
loglevel : "silent",
console.log = function () {
output.push.apply(output, arguments)
}
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
npm.load({
cache: "cache",
loglevel: "silent",
t.ifError(err, "npm cache clean ran without error")
t.notOk(code, "npm cache clean exited cleanly")
- mr({ port : common.port, mocks : mocks }, function (s) {
+ mr({ port : common.port, plugin : mocks }, function (err, s) {
server = s
t.end()
})
var common = require("../common-tap")
-var fs = require("fs")
var path = require("path")
var test = require("tap").test
var rimraf = require("rimraf")
var cache = path.resolve(pkg, "cache")
var nodeModules = path.resolve(pkg, "node_modules")
-var okFile = fs.readFileSync(path.join(pkg, "file-ok.js"), "utf8")
-var failFile = fs.readFileSync(path.join(pkg, "file-fail.js"), "utf8")
-
test("installing dependencies that have conflicting peerDependencies", function (t) {
rimraf.sync(nodeModules)
rimraf.sync(cache)
var customMocks = {
"get": {
- "/ok.js": [200, okFile],
- "/invalid.js": [200, failFile]
+ "/ok.js": [200, path.join(pkg, "file-ok.js")],
+ "/invalid.js": [200, path.join(pkg, "file-fail.js")]
}
}
- mr({port: common.port, mocks: customMocks}, function (s) { // create mock registry.
+ mr({port: common.port, mocks: customMocks}, function (err, s) { // create mock registry.
+ t.ifError(err, "mock registry started")
npm.load({
cache: cache,
registry: common.registry
var desiredResultsPath = path.resolve(pkg, "desired-ls-results.json")
test("installs the peer dependency directory structure", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
setup(function (err) {
t.ifError(err, "setup ran successfully")
var cache = path.resolve(pkg, "cache")
var nodeModules = path.resolve(pkg, "node_modules")
-var js = fs.readFileSync(path.join(pkg, "file-js.js"), "utf8")
test("installing a peerDependencies-using package without a package.json present (GH-3049)", function (t) {
rimraf.sync(nodeModules)
var customMocks = {
"get": {
- "/ok.js": [200, js]
+ "/ok.js": [200, path.join(pkg, "file-js.js")]
}
}
- mr({port: common.port, mocks: customMocks}, function (s) { // create mock registry.
+ mr({port: common.port, mocks: customMocks}, function (err, s) {
+ t.ifError(err, "mock registry booted")
npm.load({
registry: common.registry,
cache: cache
}, function () {
npm.install(common.registry + "/ok.js", function (err) {
- if (err) {
- t.fail(err)
- } else {
- t.ok(fs.existsSync(path.join(nodeModules, "/npm-test-peer-deps-file")))
- t.ok(fs.existsSync(path.join(nodeModules, "/underscore")))
- }
+ t.ifError(err, "installed ok.js")
+
+ t.ok(
+ fs.existsSync(path.join(nodeModules, "/npm-test-peer-deps-file")),
+ "passive peer dep installed"
+ )
+ t.ok(
+ fs.existsSync(path.join(nodeModules, "/underscore")),
+ "underscore installed"
+ )
+
t.end()
s.close() // shutdown mock registry.
})
var desiredResultsPath = path.resolve(pkg, "desired-ls-results.json")
test("installs the peer dependency directory structure", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
setup(function (err) {
if (err) return t.fail(err)
var server
test("reg mock", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
server = s
t.pass("registry mock started")
t.end()
}
})
-test("scoped packages should default to restricted access", function (t) {
+test("scoped packages pass public access if set", function (t) {
var put = nock(common.registry)
.put("/@bigco%2fpublish-access")
.reply(201, verify)
+ npm.config.set("access", "public")
npm.commands.publish([], false, function (er) {
t.ifError(er, "published without error")
function verify (_, body) {
t.doesNotThrow(function () {
var parsed = JSON.parse(body)
- t.equal(parsed.access, "restricted", "access level is correct")
+ t.equal(parsed.access, "public", "access level is correct")
}, "converted body back into object")
return {ok: true}
--- /dev/null
+var fs = require("fs")
+var path = require("path")
+
+var test = require("tap").test
+var mkdirp = require("mkdirp")
+var rimraf = require("rimraf")
+
+var npm = require("../../")
+var common = require("../common-tap.js")
+
+var pkg = path.join(__dirname, "publish-access-unscoped")
+
+// TODO: nock uses setImmediate, breaks 0.8: replace with mockRegistry
+if (!global.setImmediate) {
+ global.setImmediate = function () {
+ var args = [arguments[0], 0].concat([].slice.call(arguments, 1))
+ setTimeout.apply(this, args)
+ }
+}
+
+test("setup", function (t) {
+ mkdirp(path.join(pkg, "cache"), function () {
+ var configuration = {
+ cache : path.join(pkg, "cache"),
+ loglevel : "silent",
+ registry : common.registry
+ }
+
+ npm.load(configuration, next)
+ })
+
+ function next (er) {
+ t.ifError(er, "npm loaded successfully")
+
+ process.chdir(pkg)
+ fs.writeFile(
+ path.join(pkg, "package.json"),
+ JSON.stringify({
+ name: "publish-access",
+ version: "1.2.5"
+ }),
+ "ascii",
+ function (er) {
+ t.ifError(er)
+
+ t.pass("setup done")
+ t.end()
+ }
+ )
+ }
+})
+
+test("unscoped packages cannot be restricted", function (t) {
+ npm.config.set("access", "restricted")
+ npm.commands.publish([], false, function (er) {
+ t.ok(er, "got an error back")
+ t.equal(er.message, "Can't restrict access to unscoped packages.")
+
+ t.end()
+ })
+})
+
+test("cleanup", function (t) {
+ process.chdir(__dirname)
+ rimraf(pkg, function (er) {
+ t.ifError(er)
+
+ t.end()
+ })
+})
}
})
-test("scoped packages should default to restricted access", function (t) {
+test("unscoped packages can be explicitly set as public", function (t) {
var put = nock(common.registry)
.put("/publish-access")
.reply(201, verify)
+ npm.config.set("access", "public")
npm.commands.publish([], false, function (er) {
t.ifError(er, "published without error")
})
test("npm repo underscore", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
'repo', 'underscore',
'--registry=' + common.registry,
test('npm repo optimist - github (https://)', function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
'repo', 'optimist',
'--registry=' + common.registry,
})
test("npm repo npm-test-peer-deps - no repo", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
'repo', 'npm-test-peer-deps',
'--registry=' + common.registry,
})
test("npm repo test-repo-url-http - non-github (http://)", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
'repo', 'test-repo-url-http',
'--registry=' + common.registry,
})
test("npm repo test-repo-url-https - non-github (https://)", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
'repo', 'test-repo-url-https',
'--registry=' + common.registry,
})
test("npm repo test-repo-url-ssh - non-github (ssh://)", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
common.npm([
'repo', 'test-repo-url-ssh',
'--registry=' + common.registry,
test("No previous cache, init cache triggered by first search", function(t) {
cleanupCache()
- mr({ port: common.port, mocks: mocks.allFutureUpdatedOnly }, function (s) {
+ mr({ port: common.port, plugin: mocks.allFutureUpdatedOnly }, function (err, s) {
common.npm([
"search", "do not do extra search work on my behalf",
"--registry", common.registry,
m(server)
})
}
- mr({ port: common.port, mocks: m }, function (s) {
+ mr({ port: common.port, plugin: m }, function (err, s) {
common.npm([
"search", "do not do extra search work on my behalf",
"--registry", common.registry,
searches.forEach(function(search) {
test(search.description + " search in color", function(t) {
cleanupCache()
- mr({ port: common.port, mocks: mocks.all }, function (s) {
+ mr({ port: common.port, plugin: mocks.all }, function (er, s) {
common.npm([
"search", search.term,
"--registry", common.registry,
test("shrinkwrap doesn't strip out the dependency", function (t) {
t.plan(1)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
setup({ production: true }, function (err) {
if (err) return t.fail(err)
cleanup()
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
setup(function () {
npm.shrinkwrap([], function (err) {
if (err) return t.fail(err)
}
test("setup", function (t) {
- mr({ port : common.port, mocks : mocks }, function (s) {
+ mr({ port : common.port, plugin : mocks }, function (err, s) {
server = s
t.ok(s, "set up mock registry")
setup()
test("shrinkwrap doesn't strip out the shared dependency", function (t) {
t.plan(1)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
setup(function (err) {
if (err) return t.fail(err)
var before = JSON.parse(fs.readFileSync(packageJson).toString())
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
// underscore is already in the package.json,
// but --save will trigger a rewrite with sort
var child = spawn(node, [npm, "install", "--save", "underscore@1.3.3"], {
test("returns a list of removed items", function (t) {
t.plan(1)
- mr(common.port, function (s) {
+ mr({port : common.port}, function (er, s) {
setup(function () {
npm.install(".", function (err) {
if (err) return t.fail(err)
function setup (t, mock) {
mkdirp.sync(CACHE_DIR)
- mr({ port: common.port, mocks: mock }, function (s) {
+ mr({ port: common.port, plugin: mock }, function (er, s) {
npm.load({ cache: CACHE_DIR, registry: common.registry }, function (err) {
t.ifError(err, "no error")
server = s
}
function cleanup (t) {
- server.close()
- rimraf.sync(PKG_DIR)
+ server.close(function () {
+ rimraf.sync(PKG_DIR)
- t.end()
+ t.end()
+ })
}
test("setup basic", function (t) {
test("cleanup auth", cleanup)
var mocks = {
- basic: function (server) {
- server.get("/-/all").reply(200, allMock)
+ basic: function (mock) {
+ mock.get("/-/all").reply(200, allMock)
},
- auth: function (server) {
+ auth: function (mock) {
var littleBobbyTablesAuth = new Buffer("bobby:tables").toString("base64")
var auth = "Basic " + littleBobbyTablesAuth
- server.get("/-/all", { authorization: auth }).reply(200, allMock)
- server.get("/-/all").reply(401, {
+ mock.get("/-/all", { authorization: auth }).reply(200, allMock)
+ mock.get("/-/all").reply(401, {
error: "unauthorized",
reason: "You are not authorized to access this db."
})
stdio: "ignore",
env: {
"npm_config_registry": common.registry,
- "npm_config_loglevel": "verbose"
+ "npm_config_loglevel": "verbose",
+ "npm_config_save_prefix": "^"
}
}
test("setup", function (t) {
resetPackage()
- mr(common.port, function (server) {
+ mr({port : common.port}, function (er, server) {
npm.load({cache: CACHE_DIR, registry: common.registry}, function (err) {
t.ifError(err)
s = server
}
function performInstall (t, cb) {
- mr({port: common.port, mocks: mockRoutes}, function (s) {
+ mr({port: common.port, mocks: mockRoutes}, function (er, s) {
var opts = {
cwd : pkg,
env: {
t.end()
})
+function plugin (server) {
+ server
+ .get("/biscuits")
+ .many()
+ .reply(404, {"error": "version not found"})
+}
+
test("npm view . in global mode", function (t) {
process.chdir(t1dir)
common.npm([
test("npm view . with no published package", function (t) {
process.chdir(t3dir)
- mr(common.port, function (s) {
+ mr({port : common.port, plugin : plugin}, function (er, s) {
common.npm([
"view"
, "."
test("npm view .", function (t) {
process.chdir(t2dir)
- mr(common.port, function (s) {
+ mr({port : common.port, plugin : plugin}, function (er, s) {
common.npm([
"view"
, "."
test("npm view . select fields", function (t) {
process.chdir(t2dir)
- mr(common.port, function (s) {
+ mr({port : common.port, plugin : plugin}, function (er, s) {
common.npm([
"view"
, "."
test("npm view .@<version>", function (t) {
process.chdir(t2dir)
- mr(common.port, function (s) {
+ mr({port : common.port, plugin : plugin}, function (er, s) {
common.npm([
"view"
, ".@0.0.0"
test("npm view .@<version> --json", function (t) {
process.chdir(t2dir)
- mr(common.port, function (s) {
+ mr({port : common.port, plugin : plugin}, function (er, s) {
common.npm([
"view"
, ".@0.0.0"
})
test("npm view <package name>", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port, plugin : plugin}, function (er, s) {
common.npm([
"view"
, "underscore"
})
test("npm view <package name> --global", function(t) {
- mr(common.port, function(s) {
+ mr({port : common.port, plugin : plugin}, function (er, s) {
common.npm([
"view"
, "underscore"
test("npm view <package name> --json", function(t) {
t.plan(3)
- mr(common.port, function (s) {
+ mr({port : common.port, plugin : plugin}, function (er, s) {
common.npm([
"view"
, "underscore"
})
test("npm view <package name> <field>", function (t) {
- mr(common.port, function (s) {
+ mr({port : common.port, plugin : plugin}, function (er, s) {
common.npm([
"view"
, "underscore"