diff --git a/.npmignore b/.npmignore index 45906a25d..a7e4f5b25 100644 --- a/.npmignore +++ b/.npmignore @@ -1 +1,9 @@ - **/.* +**/.* +**/*.js +**/webpack.* +/node_modules/ +/bower_components/ +/coverage/ +/examples/ +/src/ +/test/ diff --git a/CHANGELOG b/CHANGELOG index 956a31f6a..eb9708b2f 100644 --- a/CHANGELOG +++ b/CHANGELOG @@ -1,3 +1,49 @@ +v1.0.0-alpha.2 +-------------- +This is the second (of many) alpha and is **NOT ready for production** yet. + +There is only one change in this alpha that needs user testing and feedback, the long awaited and much desired support for $ref. + +## Changes + +### Added + - $ref support for relative and local lookups based on [workaround example](https://github.com/json-schema-form/angular-schema-form/issues/69#issuecomment-176635926) provided by @AndreNel7 + +v1.0.0-alpha.1 +-------------- +## Changes + +### Breaking + - Some add-ons will not be working yet, if an add-on is updated to use the new function it *should* work again, but there is more work to do here to make the upgrade seamless before a **beta** can be released. + - Decorators should be updated to use the `defineDecorator` syntax with builders prior to the 1.0.0 release. + +### Added + - **23 test cases** added to ASF and a further **30 test cases** to json-schema-form-core + - Integration with **json-schema-form-core**, this is the main purpose of this release as we move as much code to plain Javascript es6+ as possible to re-use the code in an **Angular 2+** release + - #596 arrayIndices allows access to the current path for conditions in pr #742 + - #560 All fields should now have classes, names and ids that match and can be used for easier test writing and scripting. The classes are provided with and without array indexes so they can be accessed as a group or individually, fixed in PR #578 + - #748 New key, include all undefined schema fields in the form that are not already added with `[ '...' ]` + +### Fixes + - Tests fixed and running + - Travis builds fixed and running + - #828 schemaFormValidate event doesn't trigger past v0.8.2 + - #680 Pristine option was not behaving in pr #771 + - Add support for templates with leading whitespaces in pr #725 + - Improve sfNewArray Directive's titleMapValues Binding in pr #705 + - #590 Problems with model binding when using nested Arrays in pr #672, #742 + - Pass optional form name when broadcast error in in PR #656 + - Fix for #121 to redraw with proper defaults in PR #647 + - Revalidate model after successful custom validation event broadcasted in PR #642 + - Fixed angular element children selector usage partially in PR #605 + - Allow broadcasting of the formName to validate in PR #589 + - Ensure key is set in fieldsets in PR #578 + +Special thanks to all the following people for their help in the last year preparing for the move to this version: +@AndreNel7 @apinnecke @blackmiaool @CatherineH @cepauskas @chargrove @donalmurtagh @edclements @elbunuelo @ErichBSchulz @jozefizso @illiano @kyse @LeonardoGentile @mathroc @plong0 @pvgnd @stanimoto @tisto @tomsowerby @zackbloom + +Extra special thanks to @handrews @joelwkent @nicklasb for insight, ideas and support as we head toward version 1.0.0! + v0.8.13 ------- * Bugfix copy the initial form default on form redraw @stanimoto @@ -85,6 +131,7 @@ v0.8.1 v0.8.0 +------ Loads of stuff happened this release, so we're bumping version to 0.8.0. Note as well that there is a small change to `tabsarray` type regarding its title, the title is now interpolated instead of eval'd. So if you have any problems slap on a `{{ }}` around the tab title. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 9e3a2741f..ad6eebebb 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -1,5 +1,65 @@ Contributing ------------- +============ + - [How to setup to develop](#setup) + - [How to build the package](#build) + - [Working on the libraries](#work) + - [PR requirements](#requirements) + + +## How to setup to develop +To get started clone all json-schema-form library repos into sibling folders. + json-schema-form-core + angular-schema-form + angular-schema-form-bootstrap + angular-schema-form-material + +Once cloned each repo has npm commands for assisting development +```bash +# Run unit tests +npm run test + +# Run the build +npm run build + +# Run the build and minify +npm run dist # not in json-schema-form-core + +# Run the build and watch for changes +npm run watch +``` + + +## How to build the package +When working on `angular-schema-form` running the `npm build` will look for a sibling +folder when importing `json-schema-form-core`. This allows you to work on bugs or +issues that require work on both libraries simultaneously. + +This is set up for bootstrap and material design decorators also. + +The bootstrap repo is required to build `angular-schema-form` with the bootstrap +decorator bundle distribution. + + +## Working on the libraries +When I work on the libraries I use a multi-tab console tool like +Terminator (Linux) or ConEmu (Windows) + +Run each of the following in a separate tab: +```bash +json-schema-form-core> npm run watch +json-schema-form-core> npm run test +angular-schema-form> npm run watch +angular-schema-form> npm run test +``` +This will re-compile all the libraries after changes that affect them which +then runs the related tests. + +A static file web server is required to run the examples, but the example +can be used to run saved gist of the example app. It can help to add a model +to one of the example app json files to test with. + + +## PR requirements We love contributions! **Please base any merge request on the *development* branch instead of *master*.** diff --git a/README.md b/README.md index 32712b228..1d6e623d2 100644 --- a/README.md +++ b/README.md @@ -94,16 +94,28 @@ Then load them into Schema Form using the `sfSchema`, `sfForm`, and `sfModel` di Installation ------------ +### NPM + +```bash +npm i angular-schema-form@latest +``` +For the latest pre-release (alpha) +```bash +npm i angular-schema-form@pre-release +``` + ### Bower It's simplest to install Schema Form using [Bower](http://bower.io/). +If you use the bootstrap decorator use the one from the angular-schema-form-bootstrap repo ```bash -bower install angular-schema-form +bower install angular-schema-form angular-schema-form-bootstrap +bower install angular-schema-form angular-schema-form-bootstrap ``` This will install the latest release and basic dependencies. See -[dependecies section below](#dependencies). +[dependencies section below](#dependencies). You can also load the files via [cdnjs.com](https://cdnjs.com/libraries/angular-schema-form). @@ -115,26 +127,23 @@ You can also just download the contents of the `dist/` folder and add dependenci Schema form has a lot of dependencies, most of which are optional. Schema Form depends on: -1. [AngularJS](https://angularjs.org/) version 1.3.x is recomended. Version 1.2.x +1. [AngularJS](https://angularjs.org/) version 1.3.x is recommended. Version 1.2.x has some limitation. See [known limitations](docs/knownlimitations.md). 2. [angular-sanitize](https://docs.angularjs.org/api/ngSanitize) 3. [tv4](https://github.com/geraintluff/tv4) -4. [objectpath](https://github.com/mike-marcacci/objectpath) -5. [bootstrap 3](http://getbootstrap.com/) +4. [bootstrap 3](http://getbootstrap.com/) If you install via bower you get all of the above except bootstrap since we don't want to push a certain version or flavor on you. Also make sure you got the angular version you actually want. - -#### Additional dependecies +#### Additional dependencies 1. If you'd like to use drag-and-drop reordering of arrays, you'll also need [ui-sortable](https://github.com/angular-ui/ui-sortable) and its [jQueryUI](http://jqueryui.com/) dependencies. See the *ui-sortable* documentation for details about which parts of jQueryUI are needed. You can safely ignore these if you don't need reordering. 2. Schema Form provides tabbed arrays through the form type `tabarray`. Tab arrays default to tabs on the left side. For these to work, you'll need to include the CSS from [bootstrap-vertical-tabs](https://github.com/dbtek/bootstrap-vertical-tabs). However, you won't need Bootstrap Vertical Tabs for horizontal tabs (the `tabType: "top"` option). The minified files include templates - no need to load additional HTML files. - ### Script Loading Schema form is split into two main files, `dist/schema-form.min.js` and @@ -142,7 +151,6 @@ Schema form is split into two main files, `dist/schema-form.min.js` and [tv4](https://github.com/geraintluff/tv4) and [objectpath](https://github.com/mike-marcacci/objectpath) also needs to be loaded *before* Schema Form. - ```html @@ -186,10 +194,6 @@ obviously need the same version! ### Add-on To see how to make an **add-on** work I have now included the **calculate** add-on file within the **examples/add-on** directory. -## Yet to be migrated -Currently **copyValueTo** and some **array** related features are not working as expected and remain the highest priority to ensure backwards compatibility is maintained where possible. - - ## Tests Unit tests are run with [karma](http://karma-runner.github.io) and written using [mocha](http://visionmedia.github.io/mocha/), [chai](http://chaijs.com/) and diff --git a/dist/angular-schema-form-bootstrap.js b/dist/angular-schema-form-bootstrap.js index c4e0e62cd..ecd418de2 100644 --- a/dist/angular-schema-form-bootstrap.js +++ b/dist/angular-schema-form-bootstrap.js @@ -1,7 +1,7 @@ /*! * angular-schema-form - * @version 1.0.0-alpha.1 - * @date Sat, 04 Feb 2017 11:08:45 GMT + * @version 1.0.0-alpha.2 + * @date Sun, 19 Feb 2017 13:13:18 GMT * @link https://github.com/json-schema-form/angular-schema-form * @license MIT * Copyright (c) 2014-2017 JSON Schema Form @@ -41,16 +41,18 @@ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; -/******/ // identity function for calling harmory imports with the correct context +/******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; -/******/ // define getter function for harmory exports +/******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { -/******/ Object.defineProperty(exports, name, { -/******/ configurable: false, -/******/ enumerable: true, -/******/ get: getter -/******/ }); +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } /******/ }; /******/ // getDefaultExport function for compatibility with non-harmony modules @@ -69,24 +71,24 @@ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 17); +/******/ return __webpack_require__(__webpack_require__.s = 20); /******/ }) /************************************************************************/ /******/ ({ -/***/ 17: -/***/ function(module, exports, __webpack_require__) { +/***/ 20: +/***/ (function(module, exports, __webpack_require__) { -module.exports = __webpack_require__(2); +module.exports = __webpack_require__(3); -/***/ }, +/***/ }), -/***/ 2: -/***/ function(module, exports) { +/***/ 3: +/***/ (function(module, exports, __webpack_require__) { "use strict"; -'use strict'; + /*! * angular-schema-form-bootstrap @@ -516,6 +518,6 @@ module.exports = __webpack_require__(2); } /******/]); -/***/ } +/***/ }) /******/ }); \ No newline at end of file diff --git a/dist/angular-schema-form-bootstrap.min.js b/dist/angular-schema-form-bootstrap.min.js index 9de7f1479..65aa1d8de 100644 --- a/dist/angular-schema-form-bootstrap.min.js +++ b/dist/angular-schema-form-bootstrap.min.js @@ -1,12 +1,12 @@ /*! * angular-schema-form - * @version 1.0.0-alpha.1 - * @date Sat, 04 Feb 2017 11:08:45 GMT + * @version 1.0.0-alpha.2 + * @date Sun, 19 Feb 2017 13:13:18 GMT * @link https://github.com/json-schema-form/angular-schema-form * @license MIT * Copyright (c) 2014-2017 JSON Schema Form */ -!function(e){function r(a){if(n[a])return n[a].exports;var l=n[a]={i:a,l:!1,exports:{}};return e[a].call(l.exports,l,l.exports,r),l.l=!0,l.exports}var n={};return r.m=e,r.c=n,r.i=function(e){return e},r.d=function(e,r,n){Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},r.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(n,"a",n),n},r.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},r.p="",r(r.s=18)}({18:function(e,r,n){e.exports=n(2)},2:function(e,r){"use strict";/*! +!function(e){function r(a){if(n[a])return n[a].exports;var l=n[a]={i:a,l:!1,exports:{}};return e[a].call(l.exports,l,l.exports,r),l.l=!0,l.exports}var n={};return r.m=e,r.c=n,r.i=function(e){return e},r.d=function(e,n,a){r.o(e,n)||Object.defineProperty(e,n,{configurable:!1,enumerable:!0,get:a})},r.n=function(e){var n=e&&e.__esModule?function(){return e.default}:function(){return e};return r.d(n,"a",n),n},r.o=function(e,r){return Object.prototype.hasOwnProperty.call(e,r)},r.p="",r(r.s=20)}({20:function(e,r,n){e.exports=n(3)},3:function(e,r,n){"use strict";/*! * angular-schema-form-bootstrap * @version 1.0.0-alpha.1 * @date Sun, 29 Jan 2017 00:45:28 GMT diff --git a/dist/angular-schema-form.js b/dist/angular-schema-form.js index dd1a50e9e..8afa7c40a 100644 --- a/dist/angular-schema-form.js +++ b/dist/angular-schema-form.js @@ -1,7 +1,7 @@ /*! * angular-schema-form - * @version 1.0.0-alpha.1 - * @date Sat, 04 Feb 2017 11:08:45 GMT + * @version 1.0.0-alpha.2 + * @date Sun, 19 Feb 2017 13:13:18 GMT * @link https://github.com/json-schema-form/angular-schema-form * @license MIT * Copyright (c) 2014-2017 JSON Schema Form @@ -41,16 +41,18 @@ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; -/******/ // identity function for calling harmory imports with the correct context +/******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; -/******/ // define getter function for harmory exports +/******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { -/******/ Object.defineProperty(exports, name, { -/******/ configurable: false, -/******/ enumerable: true, -/******/ get: getter -/******/ }); +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } /******/ }; /******/ // getDefaultExport function for compatibility with non-harmony modules @@ -69,23 +71,23 @@ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 16); +/******/ return __webpack_require__(__webpack_require__.s = 21); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ -/***/ function(module, exports) { +/***/ (function(module, exports) { module.exports = angular; -/***/ }, +/***/ }), /* 1 */ -/***/ function(module, exports) { +/***/ (function(module, exports, __webpack_require__) { -/*! +/* WEBPACK VAR INJECTION */(function(global, setImmediate) {/*! * json-schema-form-core - * @version 1.0.0-alpha.1 - * @date Mon, 16 Jan 2017 13:06:10 GMT + * @version 1.0.0-alpha.2 + * @date Sun, 19 Feb 2017 13:06:51 GMT * @link https://github.com/json-schema-form/json-schema-form-core * @license MIT * Copyright (c) 2014-2017 JSON Schema Form @@ -126,16 +128,18 @@ module.exports = /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ -/******/ // identity function for calling harmory imports with the correct context +/******/ // identity function for calling harmony imports with the correct context /******/ __webpack_require__.i = function(value) { return value; }; /******/ -/******/ // define getter function for harmory exports +/******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { -/******/ Object.defineProperty(exports, name, { -/******/ configurable: false, -/******/ enumerable: true, -/******/ get: getter -/******/ }); +/******/ if(!__webpack_require__.o(exports, name)) { +/******/ Object.defineProperty(exports, name, { +/******/ configurable: false, +/******/ enumerable: true, +/******/ get: getter +/******/ }); +/******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules @@ -154,20 +158,21 @@ module.exports = /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports -/******/ return __webpack_require__(__webpack_require__.s = 11); +/******/ return __webpack_require__(__webpack_require__.s = 13); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ -/***/ function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_objectpath__ = __webpack_require__(2); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_objectpath___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_objectpath__); -/* harmony export (immutable) */ exports["name"] = name; -/* harmony reexport (binding) */ if(__webpack_require__.o(__WEBPACK_IMPORTED_MODULE_0_objectpath__, "parse")) __webpack_require__.d(exports, "parse", function() { return __WEBPACK_IMPORTED_MODULE_0_objectpath__["parse"]; }); -/* harmony reexport (binding) */ if(__webpack_require__.o(__WEBPACK_IMPORTED_MODULE_0_objectpath__, "stringify")) __webpack_require__.d(exports, "stringify", function() { return __WEBPACK_IMPORTED_MODULE_0_objectpath__["stringify"]; }); -/* harmony reexport (binding) */ if(__webpack_require__.o(__WEBPACK_IMPORTED_MODULE_0_objectpath__, "normalize")) __webpack_require__.d(exports, "normalize", function() { return __WEBPACK_IMPORTED_MODULE_0_objectpath__["normalize"]; }); +/* harmony reexport (binding) */ if(__webpack_require__.o(__WEBPACK_IMPORTED_MODULE_0_objectpath__, "parse")) __webpack_require__.d(__webpack_exports__, "parse", function() { return __WEBPACK_IMPORTED_MODULE_0_objectpath__["parse"]; }); +/* harmony reexport (binding) */ if(__webpack_require__.o(__WEBPACK_IMPORTED_MODULE_0_objectpath__, "stringify")) __webpack_require__.d(__webpack_exports__, "stringify", function() { return __WEBPACK_IMPORTED_MODULE_0_objectpath__["stringify"]; }); +/* harmony reexport (binding) */ if(__webpack_require__.o(__WEBPACK_IMPORTED_MODULE_0_objectpath__, "normalize")) __webpack_require__.d(__webpack_exports__, "normalize", function() { return __WEBPACK_IMPORTED_MODULE_0_objectpath__["normalize"]; }); +/* harmony export (immutable) */ __webpack_exports__["name"] = name; @@ -202,15 +207,15 @@ function name(key, separator) { return ''; }; -/***/ }, +/***/ }), /* 1 */ -/***/ function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; // Takes a titleMap in either object or list format and returns one -/* harmony default export */ exports["a"] = function (titleMap, originalEnum) { +/* harmony default export */ __webpack_exports__["a"] = function (titleMap, originalEnum) { if (!Array.isArray(titleMap)) { var _ret = function () { var canonical = []; @@ -233,32 +238,33 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol return titleMap; }; -/***/ }, +/***/ }), /* 2 */ -/***/ function(module, exports, __webpack_require__) { +/***/ (function(module, exports, __webpack_require__) { -module.exports = __webpack_require__(9).ObjectPath; +module.exports = __webpack_require__(11).ObjectPath; -/***/ }, +/***/ }), /* 3 */ -/***/ function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__sf_path__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__canonical_title_map__ = __webpack_require__(1); -/* harmony export (immutable) */ exports["defaultFormDefinition"] = defaultFormDefinition; -/* harmony export (immutable) */ exports["stdFormObj"] = stdFormObj; -/* harmony export (immutable) */ exports["text"] = text; -/* harmony export (immutable) */ exports["number"] = number; -/* harmony export (immutable) */ exports["integer"] = integer; -/* harmony export (immutable) */ exports["checkbox"] = checkbox; -/* harmony export (immutable) */ exports["select"] = select; -/* harmony export (immutable) */ exports["checkboxes"] = checkboxes; -/* harmony export (immutable) */ exports["fieldset"] = fieldset; -/* harmony export (immutable) */ exports["array"] = array; -/* harmony export (immutable) */ exports["createDefaults"] = createDefaults; -/* harmony export (immutable) */ exports["defaultForm"] = defaultForm; +/* harmony export (immutable) */ __webpack_exports__["defaultFormDefinition"] = defaultFormDefinition; +/* harmony export (immutable) */ __webpack_exports__["stdFormObj"] = stdFormObj; +/* harmony export (immutable) */ __webpack_exports__["text"] = text; +/* harmony export (immutable) */ __webpack_exports__["number"] = number; +/* harmony export (immutable) */ __webpack_exports__["integer"] = integer; +/* harmony export (immutable) */ __webpack_exports__["checkbox"] = checkbox; +/* harmony export (immutable) */ __webpack_exports__["select"] = select; +/* harmony export (immutable) */ __webpack_exports__["checkboxes"] = checkboxes; +/* harmony export (immutable) */ __webpack_exports__["fieldset"] = fieldset; +/* harmony export (immutable) */ __webpack_exports__["array"] = array; +/* harmony export (immutable) */ __webpack_exports__["createDefaults"] = createDefaults; +/* harmony export (immutable) */ __webpack_exports__["defaultForm"] = defaultForm; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; @@ -550,26 +556,30 @@ function defaultForm(schema, defaultSchemaTypes, ignore, globalOptions) { return { form: form, lookup: lookup }; } -/***/ }, +/***/ }), /* 4 */ -/***/ function(module, exports, __webpack_require__) { +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__lib_schema_defaults__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__lib_sf_path__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__lib_canonical_title_map__ = __webpack_require__(1); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__lib_merge__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__lib_select__ = __webpack_require__(6); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__lib_traverse__ = __webpack_require__(7); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__lib_validate__ = __webpack_require__(8); -/* harmony export (binding) */ __webpack_require__.d(exports, "sfPath", function() { return sfPath; }); -/* harmony export (binding) */ __webpack_require__.d(exports, "schemaDefaults", function() { return schemaDefaults; }); -/* harmony export (binding) */ __webpack_require__.d(exports, "canonicalTitleMap", function() { return canonicalTitleMap; }); -/* harmony reexport (binding) */ __webpack_require__.d(exports, "merge", function() { return __WEBPACK_IMPORTED_MODULE_3__lib_merge__["a"]; }); -/* harmony reexport (binding) */ __webpack_require__.d(exports, "select", function() { return __WEBPACK_IMPORTED_MODULE_4__lib_select__["a"]; }); -/* harmony reexport (binding) */ __webpack_require__.d(exports, "traverseSchema", function() { return __WEBPACK_IMPORTED_MODULE_5__lib_traverse__["a"]; }); -/* harmony reexport (binding) */ __webpack_require__.d(exports, "traverseForm", function() { return __WEBPACK_IMPORTED_MODULE_5__lib_traverse__["b"]; }); -/* harmony reexport (binding) */ __webpack_require__.d(exports, "validate", function() { return __WEBPACK_IMPORTED_MODULE_6__lib_validate__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__lib_merge__ = __webpack_require__(6); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "merge", function() { return __WEBPACK_IMPORTED_MODULE_3__lib_merge__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__lib_select__ = __webpack_require__(8); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "select", function() { return __WEBPACK_IMPORTED_MODULE_4__lib_select__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__lib_resolve__ = __webpack_require__(7); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "jsonref", function() { return __WEBPACK_IMPORTED_MODULE_5__lib_resolve__["a"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__lib_traverse__ = __webpack_require__(9); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "traverseSchema", function() { return __WEBPACK_IMPORTED_MODULE_6__lib_traverse__["a"]; }); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "traverseForm", function() { return __WEBPACK_IMPORTED_MODULE_6__lib_traverse__["b"]; }); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__lib_validate__ = __webpack_require__(10); +/* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "validate", function() { return __WEBPACK_IMPORTED_MODULE_7__lib_validate__["a"]; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "sfPath", function() { return sfPath; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "schemaDefaults", function() { return schemaDefaults; }); +/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "canonicalTitleMap", function() { return canonicalTitleMap; }); + @@ -583,15 +593,1643 @@ var sfPath = __WEBPACK_IMPORTED_MODULE_1__lib_sf_path__; var schemaDefaults = __WEBPACK_IMPORTED_MODULE_0__lib_schema_defaults__; var canonicalTitleMap = __WEBPACK_IMPORTED_MODULE_2__lib_canonical_title_map__["a" /* default */]; -/***/ }, +/***/ }), /* 5 */ -/***/ function(module, exports, __webpack_require__) { +/***/ (function(module, exports, __webpack_require__) { + +var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;var require;var require;var _typeof=typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"?function(obj){return typeof obj;}:function(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;};(function(f){if(( false?"undefined":_typeof(exports))==="object"&&typeof module!=="undefined"){module.exports=f();}else if(true){!(__WEBPACK_AMD_DEFINE_ARRAY__ = [], __WEBPACK_AMD_DEFINE_FACTORY__ = (f), + __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ? + (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));}else{var g;if(typeof window!=="undefined"){g=window;}else if(typeof global!=="undefined"){g=global;}else if(typeof self!=="undefined"){g=self;}else{g=this;}g.JsonRefs=f();}})(function(){var define,module,exports;return function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return require(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f;}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e);},l,l.exports,e,t,n,r);}return n[o].exports;}var i=typeof require=="function"&&require;for(var o=0;o-1){combinedDetails=u2Details;}else{u1Details=isType(u1,'Undefined')?undefined:parseURI(u1);if(!isType(u1Details,'Undefined')){combinedDetails=u1Details;// Join the paths +combinedDetails.path=slash(path.join(u1Details.path,u2Details.path));// Join query parameters +combinedDetails.query=combineQueryParams(u1Details.query,u2Details.query);}else{combinedDetails=u2Details;}}// Remove the fragment +combinedDetails.fragment=undefined;// For relative URIs, add back the '..' since it was removed above +return(remoteUriTypes.indexOf(combinedDetails.reference)===-1&&combinedDetails.path.indexOf('../')===0?'../':'')+URI.serialize(combinedDetails);}function findAncestors(obj,path){var ancestors=[];var node;if(path.length>0){node=obj;path.slice(0,path.length-1).forEach(function(seg){if(seg in node){node=node[seg];ancestors.push(node);}});}return ancestors;}function processSubDocument(mode,doc,subDocPath,refDetails,options,parents,parentPtrs,allRefs,indirect){var refValue;var rOptions;if(subDocPath.length>0){try{refValue=findValue(doc,subDocPath);}catch(err){// We only mark missing remote references as missing because local references can have deferred values +if(mode==='remote'){refDetails.error=err.message;refDetails.missing=true;}}}else{refValue=doc;}if(!isType(refValue,'Undefined')){refDetails.value=refValue;}if(isType(refValue,'Array')||isType(refValue,'Object')){rOptions=clone(options);if(mode==='local'){delete rOptions.subDocPath;// Traverse the dereferenced value +doc=refValue;}else{rOptions.relativeBase=path.dirname(parents[parents.length-1]);if(subDocPath.length===0){delete rOptions.subDocPath;}else{rOptions.subDocPath=subDocPath;}}return findRefsRecursive(doc,rOptions,parents,parentPtrs,allRefs,indirect);}}// Should this be its own exported API? +function findRefsRecursive(obj,options,parents,parentPtrs,allRefs,indirect){var allTasks=Promise.resolve();var parentPath=parentPtrs.length?pathFromPtr(parentPtrs[parentPtrs.length-1]):[];var refs=findRefs(obj,options);var subDocPath=options.subDocPath||[];var subDocPtr=pathToPtr(subDocPath);var ancestorPtrs=['#'];parents.forEach(function(parent,index){if(parent.charAt(0)!=='#'){ancestorPtrs.push(parentPtrs[index]);}});// Reverse the order so we search them in the proper order +ancestorPtrs.reverse();if((parents[parents.length-1]||'').charAt(0)!=='#'){allRefs.documents[pathToPtr(parentPath)]=obj;}Object.keys(refs).forEach(function(refPtr){var refDetails=refs[refPtr];var location;var parentIndex;var refFullPath;var refFullPtr;// If there are no parents, treat the reference pointer as-is. Otherwise, the reference is a reference within a +// remote document and its sub document path prefix must be removed. +if(parents.length===0){refFullPath=parentPath.concat(pathFromPtr(refPtr));}else{refFullPath=parentPath.concat(pathFromPtr(refPtr).slice(parents.length===0?0:subDocPath.length));}refFullPtr=pathToPtr(refFullPath);// It is possible to process the same reference more than once in the event of hierarchical references so we avoid +// processing a reference if we've already done so. +if(!isType(allRefs[refFullPtr],'Undefined')){return;}// Record the reference metadata +allRefs.refs[refFullPtr]=refs[refPtr];// Do not process invalid references +if(isType(refDetails.error,'Undefined')&&refDetails.type!=='invalid'){if(remoteTypes.indexOf(refDetails.type)>-1){location=combineURIs(options.relativeBase,refDetails.uri);parentIndex=parents.indexOf(location);}else{location=refDetails.uri;parentIndex=parentPtrs.indexOf(location);}// Record ancestor paths +refDetails.ancestorPtrs=ancestorPtrs;// Record if the reference is indirect based on its parent +refDetails.indirect=indirect;// Only process non-circular references further +if(parentIndex===-1){if(remoteTypes.indexOf(refDetails.type)>-1){allTasks=allTasks.then(function(){return getRemoteDocument(location,options).then(function(doc){return processSubDocument('remote',doc,isType(refDetails.uriDetails.fragment,'Undefined')?[]:pathFromPtr(decodeURI(refDetails.uriDetails.fragment)),refDetails,options,parents.concat(location),parentPtrs.concat(refFullPtr),allRefs,indirect);}).catch(function(err){refDetails.error=err.message;refDetails.missing=true;});});}else{if(refFullPtr.indexOf(location+'/')!==0&&refFullPtr!==location&&subDocPtr.indexOf(location+'/')!==0&&subDocPtr!==location){if(location.indexOf(subDocPtr+'/')!==0){allTasks=allTasks.then(function(){return processSubDocument('local',obj,pathFromPtr(location),refDetails,options,parents.concat(location),parentPtrs.concat(refFullPtr),allRefs,indirect||location.indexOf(subDocPtr+'/')===-1&&location!==subDocPtr);});}}else{refDetails.circular=true;}}}else{// Mark seen ancestors as circular +parentPtrs.slice(parentIndex).forEach(function(parentPtr){allRefs.refs[parentPtr].circular=true;});refDetails.circular=true;}}});allTasks=allTasks.then(function(){// Identify indirect, local circular references (Issue 82) +var circulars=[];var processedRefPtrs=[];var processedRefs=[];function walkRefs(parentPtrs,parentRefs,refPtr,ref){Object.keys(allRefs.refs).forEach(function(dRefPtr){var dRefDetails=allRefs.refs[dRefPtr];// Do not process already processed references or references that are not a nested references +if(processedRefs.indexOf(ref)===-1&&processedRefPtrs.indexOf(refPtr)===-1&&circulars.indexOf(ref)===-1&&dRefPtr!==refPtr&&dRefPtr.indexOf(ref+'/')===0){if(parentRefs.indexOf(ref)>-1){parentRefs.forEach(function(parentRef){if(circulars.indexOf(ref)===-1){circulars.push(parentRef);}});}else{walkRefs(parentPtrs.concat(refPtr),parentRefs.concat(ref),dRefPtr,dRefDetails.uri);}processedRefPtrs.push(refPtr);processedRefs.push(ref);}});}Object.keys(allRefs.refs).forEach(function(refPtr){var refDetails=allRefs.refs[refPtr];// Only process local, non-circular references +if(refDetails.type==='local'&&!refDetails.circular&&circulars.indexOf(refDetails.uri)===-1){walkRefs([],[],refPtr,refDetails.uri);}});Object.keys(allRefs.refs).forEach(function(refPtr){var refDetails=allRefs.refs[refPtr];if(circulars.indexOf(refDetails.uri)>-1){refDetails.circular=true;}});}).then(function(){return allRefs;});return allTasks;}function findValue(obj,path){var value=obj;path.forEach(function(seg){seg=decodeURI(seg);if(seg in value){value=value[seg];}else{throw Error('JSON Pointer points to missing location: '+pathToPtr(path));}});return value;}function getExtraRefKeys(ref){return Object.keys(ref).filter(function(key){return key!=='$ref';});}function getRefType(refDetails){var type;// Convert the URI reference to one of our types +switch(refDetails.uriDetails.reference){case'absolute':case'uri':type='remote';break;case'same-document':type='local';break;default:type=refDetails.uriDetails.reference;}return type;}function getRemoteDocument(url,options){var cacheEntry=remoteCache[url];var allTasks=Promise.resolve();var loaderOptions=clone(options.loaderOptions||{});if(isType(cacheEntry,'Undefined')){// If there is no content processor, default to processing the raw response as JSON +if(isType(loaderOptions.processContent,'Undefined')){loaderOptions.processContent=function(res,callback){callback(undefined,JSON.parse(res.text));};}// Attempt to load the resource using path-loader +allTasks=PathLoader.load(decodeURI(url),loaderOptions);// Update the cache +allTasks=allTasks.then(function(res){remoteCache[url]={value:res};return res;}).catch(function(err){remoteCache[url]={error:err};throw err;});}else{// Return the cached version +allTasks=allTasks.then(function(){return cacheEntry.value;});}// Return a cloned version to avoid updating the cache +allTasks=allTasks.then(function(res){return clone(res);});return allTasks;}function isRefLike(obj,throwWithDetails){var refLike=true;try{if(!isType(obj,'Object')){throw new Error('obj is not an Object');}else if(!isType(obj.$ref,'String')){throw new Error('obj.$ref is not a String');}}catch(err){if(throwWithDetails){throw err;}refLike=false;}return refLike;}function isType(obj,type){// A PhantomJS bug (https://github.com/ariya/phantomjs/issues/11722) prohibits us from using the same approach for +// undefined checking that we use for other types. +if(type==='Undefined'){return typeof obj==='undefined';}else{return Object.prototype.toString.call(obj)==='[object '+type+']';}}function makeRefFilter(options){var refFilter;var validTypes;if(isType(options.filter,'Array')||isType(options.filter,'String')){validTypes=isType(options.filter,'String')?[options.filter]:options.filter;refFilter=function refFilter(refDetails){// Check the exact type or for invalid URIs, check its original type +return validTypes.indexOf(refDetails.type)>-1||validTypes.indexOf(getRefType(refDetails))>-1;};}else if(isType(options.filter,'Function')){refFilter=options.filter;}else if(isType(options.filter,'Undefined')){refFilter=function refFilter(){return true;};}return function(refDetails,path){return(refDetails.type!=='invalid'||options.includeInvalid===true)&&refFilter(refDetails,path);};}function makeSubDocPath(options){var subDocPath;if(isType(options.subDocPath,'Array')){subDocPath=options.subDocPath;}else if(isType(options.subDocPath,'String')){subDocPath=pathFromPtr(options.subDocPath);}else if(isType(options.subDocPath,'Undefined')){subDocPath=[];}return subDocPath;}function parseURI(uri){// We decode first to avoid doubly encoding +return URI.parse(encodeURI(decodeURI(uri)));}function setValue(obj,refPath,value){findValue(obj,refPath.slice(0,refPath.length-1))[decodeURI(refPath[refPath.length-1])]=value;}function walk(ancestors,node,path,fn){var processChildren=true;function walkItem(item,segment){path.push(segment);walk(ancestors,item,path,fn);path.pop();}// Call the iteratee +if(isType(fn,'Function')){processChildren=fn(ancestors,node,path);}// We do not process circular objects again +if(ancestors.indexOf(node)===-1){ancestors.push(node);if(processChildren!==false){if(isType(node,'Array')){node.forEach(function(member,index){walkItem(member,index.toString());});}else if(isType(node,'Object')){Object.keys(node).forEach(function(key){walkItem(node[key],key);});}}}ancestors.pop();}function validateOptions(options,obj){if(isType(options,'Undefined')){// Default to an empty options object +options={};}else{// Clone the options so we do not alter the ones passed in +options=clone(options);}if(!isType(options,'Object')){throw new TypeError('options must be an Object');}else if(!isType(options.filter,'Undefined')&&!isType(options.filter,'Array')&&!isType(options.filter,'Function')&&!isType(options.filter,'String')){throw new TypeError('options.filter must be an Array, a Function of a String');}else if(!isType(options.includeInvalid,'Undefined')&&!isType(options.includeInvalid,'Boolean')){throw new TypeError('options.includeInvalid must be a Boolean');}else if(!isType(options.refPreProcessor,'Undefined')&&!isType(options.refPreProcessor,'Function')){throw new TypeError('options.refPreProcessor must be a Function');}else if(!isType(options.refPostProcessor,'Undefined')&&!isType(options.refPostProcessor,'Function')){throw new TypeError('options.refPostProcessor must be a Function');}else if(!isType(options.subDocPath,'Undefined')&&!isType(options.subDocPath,'Array')&&!isPtr(options.subDocPath)){// If a pointer is provided, throw an error if it's not the proper type +throw new TypeError('options.subDocPath must be an Array of path segments or a valid JSON Pointer');}options.filter=makeRefFilter(options);// Set the subDocPath to avoid everyone else having to compute it +options.subDocPath=makeSubDocPath(options);if(!isType(obj,'Undefined')){try{findValue(obj,options.subDocPath);}catch(err){err.message=err.message.replace('JSON Pointer','options.subDocPath');throw err;}}return options;}/* Module Members *//* + * Each of the functions below are defined as function statements and *then* exported in two steps instead of one due + * to a bug in jsdoc (https://github.com/jsdoc2md/jsdoc-parse/issues/18) that causes our documentation to be + * generated improperly. The impact to the user is significant enough for us to warrant working around it until this + * is fixed. + *//** + * The options used for various JsonRefs APIs. + * + * @typedef {object} JsonRefsOptions + * + * @param {string|string[]|function} [filter=function () {return true;}] - The filter to use when gathering JSON + * References *(If this value is a single string or an array of strings, the value(s) are expected to be the `type(s)` + * you are interested in collecting as described in {@link module:JsonRefs.getRefDetails}. If it is a function, it is + * expected that the function behaves like {@link module:JsonRefs~RefDetailsFilter}.)* + * @param {boolean} [includeInvalid=false] - Whether or not to include invalid JSON Reference details *(This will make + * it so that objects that are like JSON Reference objects, as in they are an `Object` and the have a `$ref` property, + * but fail validation will be included. This is very useful for when you want to know if you have invalid JSON + * Reference definitions. This will not mean that APIs will process invalid JSON References but the reasons as to why + * the JSON References are invalid will be included in the returned metadata.)* + * @param {object} [loaderOptions] - The options to pass to + * {@link https://github.com/whitlockjc/path-loader/blob/master/docs/API.md#module_PathLoader.load|PathLoader~load} + * @param {module:JsonRefs~RefPreProcessor} [refPreProcessor] - The callback used to pre-process a JSON Reference like + * object *(This is called prior to validating the JSON Reference like object and getting its details)* + * @param {module:JsonRefs~RefPostProcessor} [refPostProcessor] - The callback used to post-process the JSON Reference + * metadata *(This is called prior filtering the references)* + * @param {string} [options.relativeBase] - The base location to use when resolving relative references *(Only useful + * for APIs that do remote reference resolution. If this value is not defined, + * {@link https://github.com/whitlockjc/path-loader|path-loader} will use `window.location.href` for the browser and + * `process.cwd()` for Node.js.)* + * @param {string|string[]} [options.subDocPath=[]] - The JSON Pointer or array of path segments to the sub document + * location to search from + *//** + * Simple function used to filter out JSON References. + * + * @typedef {function} RefDetailsFilter + * + * @param {module:JsonRefs~UnresolvedRefDetails} refDetails - The JSON Reference details to test + * @param {string[]} path - The path to the JSON Reference + * + * @returns {boolean} whether the JSON Reference should be filtered *(out)* or not + *//** + * Simple function used to pre-process a JSON Reference like object. + * + * @typedef {function} RefPreProcessor + * + * @param {object} obj - The JSON Reference like object + * @param {string[]} path - The path to the JSON Reference like object + * + * @returns {object} the processed JSON Reference like object + *//** + * Simple function used to post-process a JSON Reference details. + * + * @typedef {function} RefPostProcessor + * + * @param {module:JsonRefs~UnresolvedRefDetails} refDetails - The JSON Reference details to test + * @param {string[]} path - The path to the JSON Reference + * + * @returns {object} the processed JSON Reference details object + *//** + * Detailed information about resolved JSON References. + * + * @typedef {module:JsonRefs~UnresolvedRefDetails} ResolvedRefDetails + * + * @property {boolean} [circular] - Whether or not the JSON Reference is circular *(Will not be set if the JSON + * Reference is not circular)* + * @property {boolean} [missing] - Whether or not the referenced value was missing or not *(Will not be set if the + * referenced value is not missing)* + * @property {*} [value] - The referenced value *(Will not be set if the referenced value is missing)* + *//** + * The results of resolving the JSON References of an array/object. + * + * @typedef {object} ResolvedRefsResults + * + * @property {module:JsonRefs~ResolvedRefDetails} refs - An object whose keys are JSON Pointers *(fragment version)* + * to where the JSON Reference is defined and whose values are {@link module:JsonRefs~ResolvedRefDetails} + * @property {object} resolved - The array/object with its JSON References fully resolved + *//** + * An object containing the retrieved document and detailed information about its JSON References. + * + * @typedef {module:JsonRefs~ResolvedRefsResults} RetrievedRefsResults + * + * @property {object} value - The retrieved document + *//** + * An object containing the retrieved document, the document with its references resolved and detailed information + * about its JSON References. + * + * @typedef {object} RetrievedResolvedRefsResults + * + * @property {module:JsonRefs~UnresolvedRefDetails} refs - An object whose keys are JSON Pointers *(fragment version)* + * to where the JSON Reference is defined and whose values are {@link module:JsonRefs~UnresolvedRefDetails} + * @property {ResolvedRefsResults} - An object whose keys are JSON Pointers *(fragment version)* + * to where the JSON Reference is defined and whose values are {@link module:JsonRefs~ResolvedRefDetails} + * @property {object} value - The retrieved document + *//** + * Detailed information about unresolved JSON References. + * + * @typedef {object} UnresolvedRefDetails + * + * @property {object} def - The JSON Reference definition + * @property {string} [error] - The error information for invalid JSON Reference definition *(Only present when the + * JSON Reference definition is invalid or there was a problem retrieving a remote reference during resolution)* + * @property {string} uri - The URI portion of the JSON Reference + * @property {object} uriDetails - Detailed information about the URI as provided by + * {@link https://github.com/garycourt/uri-js|URI.parse}. + * @property {string} type - The JSON Reference type *(This value can be one of the following: `invalid`, `local`, + * `relative` or `remote`.)* + * @property {string} [warning] - The warning information *(Only present when the JSON Reference definition produces a + * warning)* + *//** + * Clears the internal cache of remote documents, reference details, etc. + * + * @alias module:JsonRefs.clearCache + */function clearCache(){remoteCache={};}/** + * Takes an array of path segments and decodes the JSON Pointer tokens in them. + * + * @param {string[]} path - The array of path segments + * + * @returns {string} the array of path segments with their JSON Pointer tokens decoded + * + * @throws {Error} if the path is not an `Array` + * + * @see {@link https://tools.ietf.org/html/rfc6901#section-3} + * + * @alias module:JsonRefs.decodePath + */function decodePath(path){if(!isType(path,'Array')){throw new TypeError('path must be an array');}return path.map(function(seg){if(!isType(seg,'String')){seg=JSON.stringify(seg);}return decodeURI(seg.replace(/~1/g,'/').replace(/~0/g,'~'));});}/** + * Takes an array of path segments and encodes the special JSON Pointer characters in them. + * + * @param {string[]} path - The array of path segments + * + * @returns {string} the array of path segments with their JSON Pointer tokens encoded + * + * @throws {Error} if the path is not an `Array` + * + * @see {@link https://tools.ietf.org/html/rfc6901#section-3} + * + * @alias module:JsonRefs.encodePath + */function encodePath(path){if(!isType(path,'Array')){throw new TypeError('path must be an array');}return path.map(function(seg){if(!isType(seg,'String')){seg=JSON.stringify(seg);}return seg.replace(/~/g,'~0').replace(/\//g,'~1');});}/** + * Finds JSON References defined within the provided array/object. + * + * @param {array|object} obj - The structure to find JSON References within + * @param {module:JsonRefs~JsonRefsOptions} [options] - The JsonRefs options + * + * @returns {object} an object whose keys are JSON Pointers *(fragment version)* to where the JSON Reference is defined + * and whose values are {@link module:JsonRefs~UnresolvedRefDetails}. + * + * @throws {Error} when the input arguments fail validation or if `options.subDocPath` points to an invalid location + * + * @alias module:JsonRefs.findRefs + * + * @example + * // Finding all valid references + * var allRefs = JsonRefs.findRefs(obj); + * // Finding all remote references + * var remoteRefs = JsonRefs.findRefs(obj, {filter: ['relative', 'remote']}); + * // Finding all invalid references + * var invalidRefs = JsonRefs.findRefs(obj, {filter: 'invalid', includeInvalid: true}); + */function findRefs(obj,options){var refs={};// Validate the provided document +if(!isType(obj,'Array')&&!isType(obj,'Object')){throw new TypeError('obj must be an Array or an Object');}// Validate options +options=validateOptions(options,obj);// Walk the document (or sub document) and find all JSON References +walk(findAncestors(obj,options.subDocPath),findValue(obj,options.subDocPath),clone(options.subDocPath),function(ancestors,node,path){var processChildren=true;var refDetails;if(isRefLike(node)){// Pre-process the node when necessary +if(!isType(options.refPreProcessor,'Undefined')){node=options.refPreProcessor(clone(node),path);}refDetails=getRefDetails(node);// Post-process the reference details +if(!isType(options.refPostProcessor,'Undefined')){refDetails=options.refPostProcessor(refDetails,path);}if(options.filter(refDetails,path)){refs[pathToPtr(path)]=refDetails;}// Whenever a JSON Reference has extra children, its children should not be processed. +// See: http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3 +if(getExtraRefKeys(node).length>0){processChildren=false;}}return processChildren;});return refs;}/** + * Finds JSON References defined within the document at the provided location. + * + * This API is identical to {@link module:JsonRefs.findRefs} except this API will retrieve a remote document and then + * return the result of {@link module:JsonRefs.findRefs} on the retrieved document. + * + * @param {string} location - The location to retrieve *(Can be relative or absolute, just make sure you look at the + * {@link module:JsonRefs~JsonRefsOptions|options documentation} to see how relative references are handled.)* + * @param {module:JsonRefs~JsonRefsOptions} [options] - The JsonRefs options + * + * @returns {Promise} a promise that resolves a {@link module:JsonRefs~RetrievedRefsResults} and rejects with an + * `Error` when the input arguments fail validation, when `options.subDocPath` points to an invalid location or when + * the location argument points to an unloadable resource + * + * @alias module:JsonRefs.findRefsAt + * + * @example + * // Example that only resolves references within a sub document + * JsonRefs.findRefsAt('http://petstore.swagger.io/v2/swagger.json', { + * subDocPath: '#/definitions' + * }) + * .then(function (res) { + * // Do something with the response + * // + * // res.refs: JSON Reference locations and details + * // res.value: The retrieved document + * }, function (err) { + * console.log(err.stack); + * }); + */function findRefsAt(location,options){var allTasks=Promise.resolve();allTasks=allTasks.then(function(){// Validate the provided location +if(!isType(location,'String')){throw new TypeError('location must be a string');}// Validate options +options=validateOptions(options);// Combine the location and the optional relative base +location=combineURIs(options.relativeBase,location);return getRemoteDocument(location,options);}).then(function(res){var cacheEntry=clone(remoteCache[location]);var cOptions=clone(options);var uriDetails=parseURI(location);if(isType(cacheEntry.refs,'Undefined')){// Do not filter any references so the cache is complete +delete cOptions.filter;delete cOptions.subDocPath;cOptions.includeInvalid=true;remoteCache[location].refs=findRefs(res,cOptions);}// Add the filter options back +if(!isType(options.filter,'Undefined')){cOptions.filter=options.filter;}if(!isType(uriDetails.fragment,'Undefined')){cOptions.subDocPath=pathFromPtr(decodeURI(uriDetails.fragment));}else if(!isType(uriDetails.subDocPath,'Undefined')){cOptions.subDocPath=options.subDocPath;}// This will use the cache so don't worry about calling it twice +return{refs:findRefs(res,cOptions),value:res};});return allTasks;}/** + * Returns detailed information about the JSON Reference. + * + * @param {object} obj - The JSON Reference definition + * + * @returns {module:JsonRefs~UnresolvedRefDetails} the detailed information + * + * @alias module:JsonRefs.getRefDetails + */function getRefDetails(obj){var details={def:obj};var cacheKey;var extraKeys;var uriDetails;try{if(isRefLike(obj,true)){cacheKey=obj.$ref;uriDetails=uriDetailsCache[cacheKey];if(isType(uriDetails,'Undefined')){uriDetails=uriDetailsCache[cacheKey]=parseURI(cacheKey);}details.uri=cacheKey;details.uriDetails=uriDetails;if(isType(uriDetails.error,'Undefined')){details.type=getRefType(details);}else{details.error=details.uriDetails.error;details.type='invalid';}// Identify warning +extraKeys=getExtraRefKeys(obj);if(extraKeys.length>0){details.warning='Extra JSON Reference properties will be ignored: '+extraKeys.join(', ');}}else{details.type='invalid';}}catch(err){details.error=err.message;details.type='invalid';}return details;}/** + * Returns whether the argument represents a JSON Pointer. + * + * A string is a JSON Pointer if the following are all true: + * + * * The string is of type `String` + * * The string must be empty, `#` or start with a `/` or `#/` + * + * @param {string} ptr - The string to check + * @param {boolean} [throwWithDetails=false] - Whether or not to throw an `Error` with the details as to why the value + * provided is invalid + * + * @returns {boolean} the result of the check + * + * @throws {error} when the provided value is invalid and the `throwWithDetails` argument is `true` + * + * @alias module:JsonRefs.isPtr + * + * @see {@link https://tools.ietf.org/html/rfc6901#section-3} + * + * @example + * // Separating the different ways to invoke isPtr for demonstration purposes + * if (isPtr(str)) { + * // Handle a valid JSON Pointer + * } else { + * // Get the reason as to why the value is not a JSON Pointer so you can fix/report it + * try { + * isPtr(str, true); + * } catch (err) { + * // The error message contains the details as to why the provided value is not a JSON Pointer + * } + * } + */function isPtr(ptr,throwWithDetails){var valid=true;var firstChar;try{if(isType(ptr,'String')){if(ptr!==''){firstChar=ptr.charAt(0);if(['#','/'].indexOf(firstChar)===-1){throw new Error('ptr must start with a / or #/');}else if(firstChar==='#'&&ptr!=='#'&&ptr.charAt(1)!=='/'){throw new Error('ptr must start with a / or #/');}else if(ptr.match(badPtrTokenRegex)){throw new Error('ptr has invalid token(s)');}}}else{throw new Error('ptr is not a String');}}catch(err){if(throwWithDetails===true){throw err;}valid=false;}return valid;}/** + * Returns whether the argument represents a JSON Reference. + * + * An object is a JSON Reference only if the following are all true: + * + * * The object is of type `Object` + * * The object has a `$ref` property + * * The `$ref` property is a valid URI *(We do not require 100% strict URIs and will handle unescaped special + * characters.)* + * + * @param {object} obj - The object to check + * @param {boolean} [throwWithDetails=false] - Whether or not to throw an `Error` with the details as to why the value + * provided is invalid + * + * @returns {boolean} the result of the check + * + * @throws {error} when the provided value is invalid and the `throwWithDetails` argument is `true` + * + * @alias module:JsonRefs.isRef + * + * @see {@link http://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03#section-3} + * + * @example + * // Separating the different ways to invoke isRef for demonstration purposes + * if (isRef(obj)) { + * // Handle a valid JSON Reference + * } else { + * // Get the reason as to why the value is not a JSON Reference so you can fix/report it + * try { + * isRef(str, true); + * } catch (err) { + * // The error message contains the details as to why the provided value is not a JSON Reference + * } + * } + */function isRef(obj,throwWithDetails){return isRefLike(obj,throwWithDetails)&&getRefDetails(obj,throwWithDetails).type!=='invalid';}/** + * Returns an array of path segments for the provided JSON Pointer. + * + * @param {string} ptr - The JSON Pointer + * + * @returns {string[]} the path segments + * + * @throws {Error} if the provided `ptr` argument is not a JSON Pointer + * + * @alias module:JsonRefs.pathFromPtr + */function pathFromPtr(ptr){if(!isPtr(ptr)){throw new Error('ptr must be a JSON Pointer');}var segments=ptr.split('/');// Remove the first segment +segments.shift();return decodePath(segments);}/** + * Returns a JSON Pointer for the provided array of path segments. + * + * **Note:** If a path segment in `path` is not a `String`, it will be converted to one using `JSON.stringify`. + * + * @param {string[]} path - The array of path segments + * @param {boolean} [hashPrefix=true] - Whether or not create a hash-prefixed JSON Pointer + * + * @returns {string} the corresponding JSON Pointer + * + * @throws {Error} if the `path` argument is not an array + * + * @alias module:JsonRefs.pathToPtr + */function pathToPtr(path,hashPrefix){if(!isType(path,'Array')){throw new Error('path must be an Array');}// Encode each segment and return +return(hashPrefix!==false?'#':'')+(path.length>0?'/':'')+encodePath(path).join('/');}/** + * Finds JSON References defined within the provided array/object and resolves them. + * + * @param {array|object} obj - The structure to find JSON References within + * @param {module:JsonRefs~JsonRefsOptions} [options] - The JsonRefs options + * + * @returns {Promise} a promise that resolves a {@link module:JsonRefs~ResolvedRefsResults} and rejects with an + * `Error` when the input arguments fail validation, when `options.subDocPath` points to an invalid location or when + * the location argument points to an unloadable resource + * + * @alias module:JsonRefs.resolveRefs + * + * @example + * // Example that only resolves relative and remote references + * JsonRefs.resolveRefs(swaggerObj, { + * filter: ['relative', 'remote'] + * }) + * .then(function (res) { + * // Do something with the response + * // + * // res.refs: JSON Reference locations and details + * // res.resolved: The document with the appropriate JSON References resolved + * }, function (err) { + * console.log(err.stack); + * }); + */function resolveRefs(obj,options){var allTasks=Promise.resolve();allTasks=allTasks.then(function(){// Validate the provided document +if(!isType(obj,'Array')&&!isType(obj,'Object')){throw new TypeError('obj must be an Array or an Object');}// Validate options +options=validateOptions(options,obj);// Clone the input so we do not alter it +obj=clone(obj);}).then(function(){return findRefsRecursive(obj,options,[],[],{documents:{},refs:{}});}).then(function(allRefs){var deferredRefs={};var refs={};function pathSorter(p1,p2){return pathFromPtr(p1).length-pathFromPtr(p2).length;}// Resolve all references with a known value +Object.keys(allRefs.refs).sort(pathSorter).forEach(function(refPtr){var refDetails=allRefs.refs[refPtr];// Record all direct references +if(!refDetails.indirect){refs[refPtr]=refDetails;}// Delete helper property +delete refDetails.indirect;if(isType(refDetails.error,'Undefined')&&refDetails.type!=='invalid'){if(isType(refDetails.value,'Undefined')&&refDetails.circular){refDetails.value=refDetails.def;}// We defer processing all references without a value until later +if(isType(refDetails.value,'Undefined')){deferredRefs[refPtr]=refDetails;}else{if(refPtr==='#'){obj=refDetails.value;}else{setValue(obj,pathFromPtr(refPtr),refDetails.value);}// Delete helper property +delete refDetails.ancestorPtrs;}}else{// Delete helper property +delete refDetails.ancestorPtrs;}});// Resolve all deferred references +Object.keys(deferredRefs).forEach(function(refPtr){var refDetails=deferredRefs[refPtr];// Attempt to resolve the value against all if its ancestors in order +refDetails.ancestorPtrs.forEach(function(ancestorPtr,index){if(isType(refDetails.value,'Undefined')){try{refDetails.value=findValue(allRefs.documents[ancestorPtr],pathFromPtr(refDetails.uri));// Delete helper property +delete refDetails.ancestorPtrs;setValue(obj,pathFromPtr(refPtr),refDetails.value);}catch(err){if(index===refDetails.ancestorPtrs.length-1){refDetails.error=err.message;refDetails.missing=true;// Delete helper property +delete refDetails.ancestorPtrs;}}}});});return{refs:refs,resolved:obj};});return allTasks;}/** + * Resolves JSON References defined within the document at the provided location. + * + * This API is identical to {@link module:JsonRefs.resolveRefs} except this API will retrieve a remote document and then + * return the result of {@link module:JsonRefs.resolveRefs} on the retrieved document. + * + * @param {string} location - The location to retrieve *(Can be relative or absolute, just make sure you look at the + * {@link module:JsonRefs~JsonRefsOptions|options documentation} to see how relative references are handled.)* + * @param {module:JsonRefs~JsonRefsOptions} [options] - The JsonRefs options + * + * @returns {Promise} a promise that resolves a {@link module:JsonRefs~RetrievedResolvedRefsResults} and rejects with an + * `Error` when the input arguments fail validation, when `options.subDocPath` points to an invalid location or when + * the location argument points to an unloadable resource + * + * @alias module:JsonRefs.resolveRefsAt + * + * @example + * // Example that loads a JSON document (No options.loaderOptions.processContent required) and resolves all references + * JsonRefs.resolveRefsAt('./swagger.json') + * .then(function (res) { + * // Do something with the response + * // + * // res.refs: JSON Reference locations and details + * // res.resolved: The document with the appropriate JSON References resolved + * // res.value: The retrieved document + * }, function (err) { + * console.log(err.stack); + * }); + */function resolveRefsAt(location,options){var allTasks=Promise.resolve();allTasks=allTasks.then(function(){// Validate the provided location +if(!isType(location,'String')){throw new TypeError('location must be a string');}// Validate options +options=validateOptions(options);// Combine the location and the optional relative base +location=combineURIs(options.relativeBase,location);return getRemoteDocument(location,options);}).then(function(res){var cOptions=clone(options);var uriDetails=parseURI(location);// Set the sub document path if necessary +if(!isType(uriDetails.fragment,'Undefined')){cOptions.subDocPath=pathFromPtr(decodeURI(uriDetails.fragment));}// Update the relative base based on the retrieved location +cOptions.relativeBase=path.dirname(location);return resolveRefs(res,cOptions).then(function(res2){return{refs:res2.refs,resolved:res2.resolved,value:res};});});return allTasks;}/* Export the module members */module.exports.clearCache=clearCache;module.exports.decodePath=decodePath;module.exports.encodePath=encodePath;module.exports.findRefs=findRefs;module.exports.findRefsAt=findRefsAt;module.exports.getRefDetails=getRefDetails;module.exports.isPtr=isPtr;module.exports.isRef=isRef;module.exports.pathFromPtr=pathFromPtr;module.exports.pathToPtr=pathToPtr;module.exports.resolveRefs=resolveRefs;module.exports.resolveRefsAt=resolveRefsAt;},{"native-promise-only":3,"path":4,"path-loader":5,"querystring":11,"slash":13,"uri-js":23}],2:[function(require,module,exports){/** + * Expose `Emitter`. + */module.exports=Emitter;/** + * Initialize a new `Emitter`. + * + * @api public + */function Emitter(obj){if(obj)return mixin(obj);};/** + * Mixin the emitter properties. + * + * @param {Object} obj + * @return {Object} + * @api private + */function mixin(obj){for(var key in Emitter.prototype){obj[key]=Emitter.prototype[key];}return obj;}/** + * Listen on the given `event` with `fn`. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */Emitter.prototype.on=Emitter.prototype.addEventListener=function(event,fn){this._callbacks=this._callbacks||{};(this._callbacks['$'+event]=this._callbacks['$'+event]||[]).push(fn);return this;};/** + * Adds an `event` listener that will be invoked a single + * time then automatically removed. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */Emitter.prototype.once=function(event,fn){function on(){this.off(event,on);fn.apply(this,arguments);}on.fn=fn;this.on(event,on);return this;};/** + * Remove the given callback for `event` or all + * registered callbacks. + * + * @param {String} event + * @param {Function} fn + * @return {Emitter} + * @api public + */Emitter.prototype.off=Emitter.prototype.removeListener=Emitter.prototype.removeAllListeners=Emitter.prototype.removeEventListener=function(event,fn){this._callbacks=this._callbacks||{};// all +if(0==arguments.length){this._callbacks={};return this;}// specific event +var callbacks=this._callbacks['$'+event];if(!callbacks)return this;// remove all handlers +if(1==arguments.length){delete this._callbacks['$'+event];return this;}// remove specific handler +var cb;for(var i=0;i0){schedule(notify,self);}}}catch(err){reject.call(new MakeDefWrapper(self),err);}}function reject(msg){var self=this;// already triggered? +if(self.triggered){return;}self.triggered=true;// unwrap +if(self.def){self=self.def;}self.msg=msg;self.state=2;if(self.chain.length>0){schedule(notify,self);}}function iteratePromises(Constructor,arr,resolver,rejecter){for(var idx=0;idx 0 +var up=0;for(var i=parts.length-1;i>=0;i--){var last=parts[i];if(last==='.'){parts.splice(i,1);}else if(last==='..'){parts.splice(i,1);up++;}else if(up){parts.splice(i,1);up--;}}// if the path is allowed to go above the root, restore leading ..s +if(allowAboveRoot){for(;up--;up){parts.unshift('..');}}return parts;}// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;var splitPath=function splitPath(filename){return splitPathRe.exec(filename).slice(1);};// path.resolve([from ...], to) +// posix version +exports.resolve=function(){var resolvedPath='',resolvedAbsolute=false;for(var i=arguments.length-1;i>=-1&&!resolvedAbsolute;i--){var path=i>=0?arguments[i]:process.cwd();// Skip empty and invalid entries +if(typeof path!=='string'){throw new TypeError('Arguments to path.resolve must be strings');}else if(!path){continue;}resolvedPath=path+'/'+resolvedPath;resolvedAbsolute=path.charAt(0)==='/';}// At this point the path should be resolved to a full absolute path, but +// handle relative paths to be safe (might happen when process.cwd() fails) +// Normalize the path +resolvedPath=normalizeArray(filter(resolvedPath.split('/'),function(p){return!!p;}),!resolvedAbsolute).join('/');return(resolvedAbsolute?'/':'')+resolvedPath||'.';};// path.normalize(path) +// posix version +exports.normalize=function(path){var isAbsolute=exports.isAbsolute(path),trailingSlash=substr(path,-1)==='/';// Normalize the path +path=normalizeArray(filter(path.split('/'),function(p){return!!p;}),!isAbsolute).join('/');if(!path&&!isAbsolute){path='.';}if(path&&trailingSlash){path+='/';}return(isAbsolute?'/':'')+path;};// posix version +exports.isAbsolute=function(path){return path.charAt(0)==='/';};// posix version +exports.join=function(){var paths=Array.prototype.slice.call(arguments,0);return exports.normalize(filter(paths,function(p,index){if(typeof p!=='string'){throw new TypeError('Arguments to path.join must be strings');}return p;}).join('/'));};// path.relative(from, to) +// posix version +exports.relative=function(from,to){from=exports.resolve(from).substr(1);to=exports.resolve(to).substr(1);function trim(arr){var start=0;for(;start=0;end--){if(arr[end]!=='')break;}if(start>end)return[];return arr.slice(start,end-start+1);}var fromParts=trim(from.split('/'));var toParts=trim(to.split('/'));var length=Math.min(fromParts.length,toParts.length);var samePartsLength=length;for(var i=0;i1){for(var i=1;i0&&len>maxKeys){len=maxKeys;}for(var i=0;i=0){kstr=x.substr(0,idx);vstr=x.substr(idx+1);}else{kstr=x;vstr='';}k=decodeURIComponent(kstr);v=decodeURIComponent(vstr);if(!hasOwnProperty(obj,k)){obj[k]=v;}else if(isArray(obj[k])){obj[k].push(v);}else{obj[k]=[obj[k],v];}}return obj;};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==='[object Array]';};},{}],10:[function(require,module,exports){// Copyright Joyent, Inc. and other Node contributors. +// +// 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. +'use strict';var stringifyPrimitive=function stringifyPrimitive(v){switch(typeof v==="undefined"?"undefined":_typeof(v)){case'string':return v;case'boolean':return v?'true':'false';case'number':return isFinite(v)?v:'';default:return'';}};module.exports=function(obj,sep,eq,name){sep=sep||'&';eq=eq||'=';if(obj===null){obj=undefined;}if((typeof obj==="undefined"?"undefined":_typeof(obj))==='object'){return map(objectKeys(obj),function(k){var ks=encodeURIComponent(stringifyPrimitive(k))+eq;if(isArray(obj[k])){return map(obj[k],function(v){return ks+encodeURIComponent(stringifyPrimitive(v));}).join(sep);}else{return ks+encodeURIComponent(stringifyPrimitive(obj[k]));}}).join(sep);}if(!name)return'';return encodeURIComponent(stringifyPrimitive(name))+eq+encodeURIComponent(stringifyPrimitive(obj));};var isArray=Array.isArray||function(xs){return Object.prototype.toString.call(xs)==='[object Array]';};function map(xs,f){if(xs.map)return xs.map(f);var res=[];for(var i=0;i=200&&res.status<300){return self.callback(err,res);}var new_err=new Error(res.statusText||'Unsuccessful HTTP response');new_err.original=err;new_err.response=res;new_err.status=res.status;self.callback(new_err,res);});}/** + * Mixin `Emitter` and `requestBase`. + */Emitter(Request.prototype);for(var key in requestBase){Request.prototype[key]=requestBase[key];}/** + * Abort the request, and clear potential timeout. + * + * @return {Request} + * @api public + */Request.prototype.abort=function(){if(this.aborted)return;this.aborted=true;this.xhr.abort();this.clearTimeout();this.emit('abort');return this;};/** + * Set Content-Type to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.xml = 'application/xml'; + * + * request.post('/') + * .type('xml') + * .send(xmlstring) + * .end(callback); + * + * request.post('/') + * .type('application/xml') + * .send(xmlstring) + * .end(callback); + * + * @param {String} type + * @return {Request} for chaining + * @api public + */Request.prototype.type=function(type){this.set('Content-Type',request.types[type]||type);return this;};/** + * Set responseType to `val`. Presently valid responseTypes are 'blob' and + * 'arraybuffer'. + * + * Examples: + * + * req.get('/') + * .responseType('blob') + * .end(callback); + * + * @param {String} val + * @return {Request} for chaining + * @api public + */Request.prototype.responseType=function(val){this._responseType=val;return this;};/** + * Set Accept to `type`, mapping values from `request.types`. + * + * Examples: + * + * superagent.types.json = 'application/json'; + * + * request.get('/agent') + * .accept('json') + * .end(callback); + * + * request.get('/agent') + * .accept('application/json') + * .end(callback); + * + * @param {String} accept + * @return {Request} for chaining + * @api public + */Request.prototype.accept=function(type){this.set('Accept',request.types[type]||type);return this;};/** + * Set Authorization field value with `user` and `pass`. + * + * @param {String} user + * @param {String} pass + * @param {Object} options with 'type' property 'auto' or 'basic' (default 'basic') + * @return {Request} for chaining + * @api public + */Request.prototype.auth=function(user,pass,options){if(!options){options={type:'basic'};}switch(options.type){case'basic':var str=btoa(user+':'+pass);this.set('Authorization','Basic '+str);break;case'auto':this.username=user;this.password=pass;break;}return this;};/** +* Add query-string `val`. +* +* Examples: +* +* request.get('/shoes') +* .query('size=10') +* .query({ color: 'blue' }) +* +* @param {Object|String} val +* @return {Request} for chaining +* @api public +*/Request.prototype.query=function(val){if('string'!=typeof val)val=serialize(val);if(val)this._query.push(val);return this;};/** + * Queue the given `file` as an attachment to the specified `field`, + * with optional `filename`. + * + * ``` js + * request.post('/upload') + * .attach(new Blob(['hey!'], { type: "text/html"})) + * .end(callback); + * ``` + * + * @param {String} field + * @param {Blob|File} file + * @param {String} filename + * @return {Request} for chaining + * @api public + */Request.prototype.attach=function(field,file,filename){this._getFormData().append(field,file,filename||file.name);return this;};Request.prototype._getFormData=function(){if(!this._formData){this._formData=new root.FormData();}return this._formData;};/** + * Send `data` as the request body, defaulting the `.type()` to "json" when + * an object is given. + * + * Examples: + * + * // manual json + * request.post('/user') + * .type('json') + * .send('{"name":"tj"}') + * .end(callback) + * + * // auto json + * request.post('/user') + * .send({ name: 'tj' }) + * .end(callback) + * + * // manual x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send('name=tj') + * .end(callback) + * + * // auto x-www-form-urlencoded + * request.post('/user') + * .type('form') + * .send({ name: 'tj' }) + * .end(callback) + * + * // defaults to x-www-form-urlencoded + * request.post('/user') + * .send('name=tobi') + * .send('species=ferret') + * .end(callback) + * + * @param {String|Object} data + * @return {Request} for chaining + * @api public + */Request.prototype.send=function(data){var obj=isObject(data);var type=this._header['content-type'];// merge +if(obj&&isObject(this._data)){for(var key in data){this._data[key]=data[key];}}else if('string'==typeof data){if(!type)this.type('form');type=this._header['content-type'];if('application/x-www-form-urlencoded'==type){this._data=this._data?this._data+'&'+data:data;}else{this._data=(this._data||'')+data;}}else{this._data=data;}if(!obj||isHost(data))return this;if(!type)this.type('json');return this;};/** + * @deprecated + */Response.prototype.parse=function serialize(fn){if(root.console){console.warn("Client-side parse() method has been renamed to serialize(). This method is not compatible with superagent v2.0");}this.serialize(fn);return this;};Response.prototype.serialize=function serialize(fn){this._parser=fn;return this;};/** + * Invoke the callback with `err` and `res` + * and handle arity check. + * + * @param {Error} err + * @param {Response} res + * @api private + */Request.prototype.callback=function(err,res){var fn=this._callback;this.clearTimeout();fn(err,res);};/** + * Invoke callback with x-domain error. + * + * @api private + */Request.prototype.crossDomainError=function(){var err=new Error('Request has been terminated\nPossible causes: the network is offline, Origin is not allowed by Access-Control-Allow-Origin, the page is being unloaded, etc.');err.crossDomain=true;err.status=this.status;err.method=this.method;err.url=this.url;this.callback(err);};/** + * Invoke callback with timeout error. + * + * @api private + */Request.prototype.timeoutError=function(){var timeout=this._timeout;var err=new Error('timeout of '+timeout+'ms exceeded');err.timeout=timeout;this.callback(err);};/** + * Enable transmission of cookies with x-domain requests. + * + * Note that for this to work the origin must not be + * using "Access-Control-Allow-Origin" with a wildcard, + * and also must set "Access-Control-Allow-Credentials" + * to "true". + * + * @api public + */Request.prototype.withCredentials=function(){this._withCredentials=true;return this;};/** + * Initiate request, invoking callback `fn(res)` + * with an instanceof `Response`. + * + * @param {Function} fn + * @return {Request} for chaining + * @api public + */Request.prototype.end=function(fn){var self=this;var xhr=this.xhr=request.getXHR();var query=this._query.join('&');var timeout=this._timeout;var data=this._formData||this._data;// store callback +this._callback=fn||noop;// state change +xhr.onreadystatechange=function(){if(4!=xhr.readyState)return;// In IE9, reads to any property (e.g. status) off of an aborted XHR will +// result in the error "Could not complete the operation due to error c00c023f" +var status;try{status=xhr.status;}catch(e){status=0;}if(0==status){if(self.timedout)return self.timeoutError();if(self.aborted)return;return self.crossDomainError();}self.emit('end');};// progress +var handleProgress=function handleProgress(e){if(e.total>0){e.percent=e.loaded/e.total*100;}e.direction='download';self.emit('progress',e);};if(this.hasListeners('progress')){xhr.onprogress=handleProgress;}try{if(xhr.upload&&this.hasListeners('progress')){xhr.upload.onprogress=handleProgress;}}catch(e){}// Accessing xhr.upload fails in IE from a web worker, so just pretend it doesn't exist. +// Reported here: +// https://connect.microsoft.com/IE/feedback/details/837245/xmlhttprequest-upload-throws-invalid-argument-when-used-from-web-worker-context +// timeout +if(timeout&&!this._timer){this._timer=setTimeout(function(){self.timedout=true;self.abort();},timeout);}// querystring +if(query){query=request.serializeObject(query);this.url+=~this.url.indexOf('?')?'&'+query:'?'+query;}// initiate request +if(this.username&&this.password){xhr.open(this.method,this.url,true,this.username,this.password);}else{xhr.open(this.method,this.url,true);}// CORS +if(this._withCredentials)xhr.withCredentials=true;// body +if('GET'!=this.method&&'HEAD'!=this.method&&'string'!=typeof data&&!isHost(data)){// serialize stuff +var contentType=this._header['content-type'];var serialize=this._parser||request.serialize[contentType?contentType.split(';')[0]:''];if(!serialize&&isJSON(contentType))serialize=request.serialize['application/json'];if(serialize)data=serialize(data);}// set header fields +for(var field in this.header){if(null==this.header[field])continue;xhr.setRequestHeader(field,this.header[field]);}if(this._responseType){xhr.responseType=this._responseType;}// send stuff +this.emit('request',this);// IE11 xhr.send(undefined) sends 'undefined' string as POST payload (instead of nothing) +// We need null here if data is undefined +xhr.send(typeof data!=='undefined'?data:null);return this;};/** + * Expose `Request`. + */request.Request=Request;/** + * GET `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */request.get=function(url,data,fn){var req=request('GET',url);if('function'==typeof data)fn=data,data=null;if(data)req.query(data);if(fn)req.end(fn);return req;};/** + * HEAD `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */request.head=function(url,data,fn){var req=request('HEAD',url);if('function'==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req;};/** + * DELETE `url` with optional callback `fn(res)`. + * + * @param {String} url + * @param {Function} fn + * @return {Request} + * @api public + */function del(url,fn){var req=request('DELETE',url);if(fn)req.end(fn);return req;};request['del']=del;request['delete']=del;/** + * PATCH `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} data + * @param {Function} fn + * @return {Request} + * @api public + */request.patch=function(url,data,fn){var req=request('PATCH',url);if('function'==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req;};/** + * POST `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed} data + * @param {Function} fn + * @return {Request} + * @api public + */request.post=function(url,data,fn){var req=request('POST',url);if('function'==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req;};/** + * PUT `url` with optional `data` and callback `fn(res)`. + * + * @param {String} url + * @param {Mixed|Function} data or fn + * @param {Function} fn + * @return {Request} + * @api public + */request.put=function(url,data,fn){var req=request('PUT',url);if('function'==typeof data)fn=data,data=null;if(data)req.send(data);if(fn)req.end(fn);return req;};},{"./is-object":15,"./request":17,"./request-base":16,"emitter":2,"reduce":12}],15:[function(require,module,exports){/** + * Check if `obj` is an object. + * + * @param {Object} obj + * @return {Boolean} + * @api private + */function isObject(obj){return null!=obj&&'object'==(typeof obj==="undefined"?"undefined":_typeof(obj));}module.exports=isObject;},{}],16:[function(require,module,exports){/** + * Module of mixed-in functions shared between node and client code + */var isObject=require('./is-object');/** + * Clear previous timeout. + * + * @return {Request} for chaining + * @api public + */exports.clearTimeout=function _clearTimeout(){this._timeout=0;clearTimeout(this._timer);return this;};/** + * Force given parser + * + * Sets the body parser no matter type. + * + * @param {Function} + * @api public + */exports.parse=function parse(fn){this._parser=fn;return this;};/** + * Set timeout to `ms`. + * + * @param {Number} ms + * @return {Request} for chaining + * @api public + */exports.timeout=function timeout(ms){this._timeout=ms;return this;};/** + * Faux promise support + * + * @param {Function} fulfill + * @param {Function} reject + * @return {Request} + */exports.then=function then(fulfill,reject){return this.end(function(err,res){err?reject(err):fulfill(res);});};/** + * Allow for extension + */exports.use=function use(fn){fn(this);return this;};/** + * Get request header `field`. + * Case-insensitive. + * + * @param {String} field + * @return {String} + * @api public + */exports.get=function(field){return this._header[field.toLowerCase()];};/** + * Get case-insensitive header `field` value. + * This is a deprecated internal API. Use `.get(field)` instead. + * + * (getHeader is no longer used internally by the superagent code base) + * + * @param {String} field + * @return {String} + * @api private + * @deprecated + */exports.getHeader=exports.get;/** + * Set header `field` to `val`, or multiple fields with one object. + * Case-insensitive. + * + * Examples: + * + * req.get('/') + * .set('Accept', 'application/json') + * .set('X-API-Key', 'foobar') + * .end(callback); + * + * req.get('/') + * .set({ Accept: 'application/json', 'X-API-Key': 'foobar' }) + * .end(callback); + * + * @param {String|Object} field + * @param {String} val + * @return {Request} for chaining + * @api public + */exports.set=function(field,val){if(isObject(field)){for(var key in field){this.set(key,field[key]);}return this;}this._header[field.toLowerCase()]=val;this.header[field]=val;return this;};/** + * Remove header `field`. + * Case-insensitive. + * + * Example: + * + * req.get('/') + * .unset('User-Agent') + * .end(callback); + * + * @param {String} field + */exports.unset=function(field){delete this._header[field.toLowerCase()];delete this.header[field];return this;};/** + * Write the field `name` and `val` for "multipart/form-data" + * request bodies. + * + * ``` js + * request.post('/upload') + * .field('foo', 'bar') + * .end(callback); + * ``` + * + * @param {String} name + * @param {String|Blob|File|Buffer|fs.ReadStream} val + * @return {Request} for chaining + * @api public + */exports.field=function(name,val){this._getFormData().append(name,val);return this;};},{"./is-object":15}],17:[function(require,module,exports){// The node and browser modules expose versions of this with the +// appropriate constructor function bound as first argument +/** + * Issue a request: + * + * Examples: + * + * request('GET', '/users').end(callback) + * request('/users').end(callback) + * request('/users', callback) + * + * @param {String} method + * @param {String|Function} url or callback + * @return {Request} + * @api public + */function request(RequestConstructor,method,url){// callback +if('function'==typeof url){return new RequestConstructor('GET',method).end(url);}// url first +if(2==arguments.length){return new RequestConstructor('GET',method);}return new RequestConstructor(method,url);}module.exports=request;},{}],18:[function(require,module,exports){/*! https://mths.be/punycode v1.3.2 by @mathias, modified for URI.js */var punycode=function(){/** + * The `punycode` object. + * @name punycode + * @type Object + */var punycode,/** Highest positive signed 32-bit float value */maxInt=2147483647,// aka. 0x7FFFFFFF or 2^31-1 +/** Bootstring parameters */base=36,tMin=1,tMax=26,skew=38,damp=700,initialBias=72,initialN=128,// 0x80 +delimiter='-',// '\x2D' +/** Regular expressions */regexPunycode=/^xn--/,regexNonASCII=/[^\x20-\x7E]/,// unprintable ASCII chars + non-ASCII chars +regexSeparators=/[\x2E\u3002\uFF0E\uFF61]/g,// RFC 3490 separators +/** Error messages */errors={'overflow':'Overflow: input needs wider integers to process','not-basic':'Illegal input >= 0x80 (not a basic code point)','invalid-input':'Invalid input'},/** Convenience shortcuts */baseMinusTMin=base-tMin,floor=Math.floor,stringFromCharCode=String.fromCharCode,/** Temporary variable */key;/*--------------------------------------------------------------------------*//** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */function error(type){throw new RangeError(errors[type]);}/** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */function map(array,fn){var length=array.length;var result=[];while(length--){result[length]=fn(array[length]);}return result;}/** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */function mapDomain(string,fn){var parts=string.split('@');var result='';if(parts.length>1){// In email addresses, only the domain name should be punycoded. Leave +// the local part (i.e. everything up to `@`) intact. +result=parts[0]+'@';string=parts[1];}// Avoid `split(regex)` for IE8 compatibility. See #17. +string=string.replace(regexSeparators,'\x2E');var labels=string.split('.');var encoded=map(labels,fn).join('.');return result+encoded;}/** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */function ucs2decode(string){var output=[],counter=0,length=string.length,value,extra;while(counter=0xD800&&value<=0xDBFF&&counter0xFFFF){value-=0x10000;output+=stringFromCharCode(value>>>10&0x3FF|0xD800);value=0xDC00|value&0x3FF;}output+=stringFromCharCode(value);return output;}).join('');}/** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */function basicToDigit(codePoint){if(codePoint-48<10){return codePoint-22;}if(codePoint-65<26){return codePoint-65;}if(codePoint-97<26){return codePoint-97;}return base;}/** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */function digitToBasic(digit,flag){// 0..25 map to ASCII a..z or A..Z +// 26..35 map to ASCII 0..9 +return digit+22+75*(digit<26)-((flag!=0)<<5);}/** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */function adapt(delta,numPoints,firstTime){var k=0;delta=firstTime?floor(delta/damp):delta>>1;delta+=floor(delta/numPoints);for(;/* no initialization */delta>baseMinusTMin*tMax>>1;k+=base){delta=floor(delta/baseMinusTMin);}return floor(k+(baseMinusTMin+1)*delta/(delta+skew));}/** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */function decode(input){// Don't use UCS-2 +var output=[],inputLength=input.length,out,i=0,n=initialN,bias=initialBias,basic,j,index,oldi,w,k,digit,t,/** Cached calculation results */baseMinusT;// Handle the basic code points: let `basic` be the number of input code +// points before the last delimiter, or `0` if there is none, then copy +// the first basic code points to the output. +basic=input.lastIndexOf(delimiter);if(basic<0){basic=0;}for(j=0;j=0x80){error('not-basic');}output.push(input.charCodeAt(j));}// Main decoding loop: start just after the last delimiter if any basic code +// points were copied; start at the beginning otherwise. +for(index=basic>0?basic+1:0;index=inputLength){error('invalid-input');}digit=basicToDigit(input.charCodeAt(index++));if(digit>=base||digit>floor((maxInt-i)/w)){error('overflow');}i+=digit*w;t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(digitfloor(maxInt/baseMinusT)){error('overflow');}w*=baseMinusT;}out=output.length+1;bias=adapt(i-oldi,out,oldi==0);// `i` was supposed to wrap around from `out` to `0`, +// incrementing `n` each time, so we'll fix that now: +if(floor(i/out)>maxInt-n){error('overflow');}n+=floor(i/out);i%=out;// Insert `n` at position `i` of the output +output.splice(i++,0,n);}return ucs2encode(output);}/** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */function encode(input){var n,delta,handledCPCount,basicLength,bias,j,m,q,k,t,currentValue,output=[],/** `inputLength` will hold the number of code points in `input`. */inputLength,/** Cached calculation results */handledCPCountPlusOne,baseMinusT,qMinusT;// Convert the input in UCS-2 to Unicode +input=ucs2decode(input);// Cache the length +inputLength=input.length;// Initialize the state +n=initialN;delta=0;bias=initialBias;// Handle the basic code points +for(j=0;j=n&¤tValue state to , +// but guard against overflow +handledCPCountPlusOne=handledCPCount+1;if(m-n>floor((maxInt-delta)/handledCPCountPlusOne)){error('overflow');}delta+=(m-n)*handledCPCountPlusOne;n=m;for(j=0;jmaxInt){error('overflow');}if(currentValue==n){// Represent delta as a generalized variable-length integer +for(q=delta,k=base;;/* no condition */k+=base){t=k<=bias?tMin:k>=bias+tMax?tMax:k-bias;if(q + * @memberOf punycode + * @type Object + */ucs2:{decode:ucs2decode,encode:ucs2encode},decode:decode,encode:encode,toASCII:toASCII,toUnicode:toUnicode};return punycode;}();if(typeof COMPILED==="undefined"&&typeof module!=="undefined")module.exports=punycode;},{}],19:[function(require,module,exports){/// +require("./schemes/http");require("./schemes/urn");require("./schemes/mailto");},{"./schemes/http":20,"./schemes/mailto":21,"./schemes/urn":22}],20:[function(require,module,exports){/// +if(typeof COMPILED==="undefined"&&typeof URI==="undefined"&&typeof require==="function")var URI=require("../uri");URI.SCHEMES["http"]=URI.SCHEMES["https"]={domainHost:true,parse:function parse(components,options){//report missing host +if(!components.host){components.error=components.error||"HTTP URIs must have a host.";}return components;},serialize:function serialize(components,options){//normalize the default port +if(components.port===(String(components.scheme).toLowerCase()!=="https"?80:443)||components.port===""){components.port=undefined;}//normalize the empty path +if(!components.path){components.path="/";}//NOTE: We do not parse query strings for HTTP URIs +//as WWW Form Url Encoded query strings are part of the HTML4+ spec, +//and not the HTTP spec. +return components;}};},{"../uri":23}],21:[function(require,module,exports){/// +if(typeof COMPILED==="undefined"&&typeof URI==="undefined"&&typeof require==="function"){var URI=require("../uri"),punycode=require("../punycode");}(function(){function merge(){var sets=[];for(var _i=0;_i1){sets[0]=sets[0].slice(0,-1);var xl=sets.length-1;for(var x=1;x ASCII IDN +try{addr[1]=punycode.toASCII(URI.unescapeComponent(addr[1],options).toLowerCase());}catch(e){components.error=components.error||"Email address's domain name can not be converted to ASCII via punycode: "+e;}}else{addr[1]=URI.unescapeComponent(addr[1],options).toLowerCase();}to[x]=addr.join("@");}return components;},serialize:function serialize(components,options){var to=toArray(components.to);if(to){for(var x=0,xl=to.length;x +if(typeof COMPILED==="undefined"&&typeof URI==="undefined"&&typeof require==="function")var URI=require("../uri");(function(){var pctEncChar=URI.pctEncChar,NID$="(?:[0-9A-Za-z][0-9A-Za-z\\-]{1,31})",PCT_ENCODED$="(?:\\%[0-9A-Fa-f]{2})",TRANS$$="[0-9A-Za-z\\(\\)\\+\\,\\-\\.\\:\\=\\@\\;\\$\\_\\!\\*\\'\\/\\?\\#]",NSS$="(?:(?:"+PCT_ENCODED$+"|"+TRANS$$+")+)",URN_SCHEME=new RegExp("^urn\\:("+NID$+")$"),URN_PATH=new RegExp("^("+NID$+")\\:("+NSS$+")$"),URN_PARSE=/^([^\:]+)\:(.*)/,URN_EXCLUDED=/[\x00-\x20\\\"\&\<\>\[\]\^\`\{\|\}\~\x7F-\xFF]/g,UUID=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/;//RFC 2141 +URI.SCHEMES["urn"]={parse:function parse(components,options){var matches=components.path.match(URN_PATH),scheme,schemeHandler;if(!matches){if(!options.tolerant){components.error=components.error||"URN is not strictly valid.";}matches=components.path.match(URN_PARSE);}if(matches){scheme="urn:"+matches[1].toLowerCase();schemeHandler=URI.SCHEMES[scheme];//in order to serialize properly, +//every URN must have a serializer that calls the URN serializer +if(!schemeHandler){//create fake scheme handler +schemeHandler=URI.SCHEMES[scheme]={parse:function parse(components,options){return components;},serialize:URI.SCHEMES["urn"].serialize};}components.scheme=scheme;components.path=matches[2];components=schemeHandler.parse(components,options);}else{components.error=components.error||"URN can not be parsed.";}return components;},serialize:function serialize(components,options){var scheme=components.scheme||options.scheme,matches;if(scheme&&scheme!=="urn"){var matches=scheme.match(URN_SCHEME);if(!matches){matches=["urn:"+scheme,scheme];}components.scheme="urn";components.path=matches[1]+":"+(components.path?components.path.replace(URN_EXCLUDED,pctEncChar):"");}return components;}};//RFC 4122 +URI.SCHEMES["urn:uuid"]={parse:function parse(components,options){if(!options.tolerant&&(!components.path||!components.path.match(UUID))){components.error=components.error||"UUID is not valid.";}return components;},serialize:function serialize(components,options){//ensure UUID is valid +if(!options.tolerant&&(!components.path||!components.path.match(UUID))){//invalid UUIDs can not have this scheme +components.scheme=undefined;}else{//normalize UUID +components.path=(components.path||"").toLowerCase();}return URI.SCHEMES["urn"].serialize(components,options);}};})();},{"../uri":23}],23:[function(require,module,exports){/** + * URI.js + * + * @fileoverview An RFC 3986 compliant, scheme extendable URI parsing/validating/resolving library for JavaScript. + * @author Gary Court + * @version 2.0.0 + * @see http://github.com/garycourt/uri-js + * @license URI.js v2.0.0 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js + *//** + * Copyright 2011 Gary Court. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without modification, are + * permitted provided that the following conditions are met: + * + * 1. Redistributions of source code must retain the above copyright notice, this list of + * conditions and the following disclaimer. + * + * 2. 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. + * + * THIS SOFTWARE IS PROVIDED BY GARY COURT ``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 GARY COURT OR + * 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 views and conclusions contained in the software and documentation are those of the + * authors and should not be interpreted as representing official policies, either expressed + * or implied, of Gary Court. + *//// +/// +/** + * Compiler switch for indicating code is compiled + * @define {boolean} + */var COMPILED=false;/** + * Compiler switch for supporting IRI URIs + * @define {boolean} + */var URI__IRI_SUPPORT=true;/** + * Compiler switch for supporting URI validation + * @define {boolean} + */var URI__VALIDATE_SUPPORT=true;var URI=function(){function merge(){var sets=[];for(var _i=0;_i1){sets[0]=sets[0].slice(0,-1);var xl=sets.length-1;for(var x=1;x>6|192).toString(16).toUpperCase()+"%"+(c&63|128).toString(16).toUpperCase();else e="%"+(c>>12|224).toString(16).toUpperCase()+"%"+(c>>6&63|128).toString(16).toUpperCase()+"%"+(c&63|128).toString(16).toUpperCase();return e;}function pctDecChars(str){var newStr="",i=0,il=str.length,c,c2,c3;while(i=194&&c<224){if(il-i>=6){c2=parseInt(str.substr(i+4,2),16);newStr+=String.fromCharCode((c&31)<<6|c2&63);}else{newStr+=str.substr(i,6);}i+=6;}else if(c>=224){if(il-i>=9){c2=parseInt(str.substr(i+4,2),16);c3=parseInt(str.substr(i+7,2),16);newStr+=String.fromCharCode((c&15)<<12|(c2&63)<<6|c3&63);}else{newStr+=str.substr(i,9);}i+=9;}else{newStr+=str.substr(i,3);i+=3;}}return newStr;}function typeOf(o){return o===undefined?"undefined":o===null?"null":Object.prototype.toString.call(o).split(" ").pop().split("]").shift().toLowerCase();}function toUpperCase(str){return str.toUpperCase();}var SCHEMES={};function _normalizeComponentEncoding(components,protocol){function decodeUnreserved(str){var decStr=pctDecChars(str);return!decStr.match(protocol.UNRESERVED)?str:decStr;}if(components.scheme)components.scheme=String(components.scheme).replace(protocol.PCT_ENCODED,decodeUnreserved).toLowerCase().replace(protocol.NOT_SCHEME,"");if(components.userinfo!==undefined)components.userinfo=String(components.userinfo).replace(protocol.PCT_ENCODED,decodeUnreserved).replace(protocol.NOT_USERINFO,pctEncChar).replace(protocol.PCT_ENCODED,toUpperCase);if(components.host!==undefined)components.host=String(components.host).replace(protocol.PCT_ENCODED,decodeUnreserved).toLowerCase().replace(protocol.NOT_HOST,pctEncChar).replace(protocol.PCT_ENCODED,toUpperCase);if(components.path!==undefined)components.path=String(components.path).replace(protocol.PCT_ENCODED,decodeUnreserved).replace(components.scheme?protocol.NOT_PATH:protocol.NOT_PATH_NOSCHEME,pctEncChar).replace(protocol.PCT_ENCODED,toUpperCase);if(components.query!==undefined)components.query=String(components.query).replace(protocol.PCT_ENCODED,decodeUnreserved).replace(protocol.NOT_QUERY,pctEncChar).replace(protocol.PCT_ENCODED,toUpperCase);if(components.fragment!==undefined)components.fragment=String(components.fragment).replace(protocol.PCT_ENCODED,decodeUnreserved).replace(protocol.NOT_FRAGMENT,pctEncChar).replace(protocol.PCT_ENCODED,toUpperCase);return components;};function parse(uriString,options){if(options===void 0){options={};}var protocol=URI__IRI_SUPPORT&&options.iri!==false?IRI_PROTOCOL:URI_PROTOCOL,matches,parseError=false,components={},schemeHandler;if(options.reference==="suffix")uriString=(options.scheme?options.scheme+":":"")+"//"+uriString;if(URI__VALIDATE_SUPPORT){matches=uriString.match(protocol.URI_REF);if(matches){if(matches[1]){//generic URI +matches=matches.slice(1,10);}else{//relative URI +matches=matches.slice(10,19);}}if(!matches){parseError=true;if(!options.tolerant)components.error=components.error||"URI is not strictly valid.";matches=uriString.match(URI_PARSE);}}else{matches=uriString.match(URI_PARSE);}if(matches){if(NO_MATCH_IS_UNDEFINED){//store each component +components.scheme=matches[1];//components.authority = matches[2]; +components.userinfo=matches[3];components.host=matches[4];components.port=parseInt(matches[5],10);components.path=matches[6]||"";components.query=matches[7];components.fragment=matches[8];//fix port number +if(isNaN(components.port)){components.port=matches[5];}}else{//store each component +components.scheme=matches[1]||undefined;//components.authority = (uriString.indexOf("//") !== -1 ? matches[2] : undefined); +components.userinfo=uriString.indexOf("@")!==-1?matches[3]:undefined;components.host=uriString.indexOf("//")!==-1?matches[4]:undefined;components.port=parseInt(matches[5],10);components.path=matches[6]||"";components.query=uriString.indexOf("?")!==-1?matches[7]:undefined;components.fragment=uriString.indexOf("#")!==-1?matches[8]:undefined;//fix port number +if(isNaN(components.port)){components.port=uriString.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?matches[4]:undefined;}}//determine reference type +if(components.scheme===undefined&&components.userinfo===undefined&&components.host===undefined&&components.port===undefined&&!components.path&&components.query===undefined){components.reference="same-document";}else if(components.scheme===undefined){components.reference="relative";}else if(components.fragment===undefined){components.reference="absolute";}else{components.reference="uri";}//check for reference errors +if(options.reference&&options.reference!=="suffix"&&options.reference!==components.reference){components.error=components.error||"URI is not a "+options.reference+" reference.";}//find scheme handler +schemeHandler=SCHEMES[(options.scheme||components.scheme||"").toLowerCase()];//check if scheme can't handle IRIs +if(URI__IRI_SUPPORT&&typeof punycode!=="undefined"&&!options.unicodeSupport&&(!schemeHandler||!schemeHandler.unicodeSupport)){//if host component is a domain name +if(components.host&&(options.domainHost||schemeHandler&&schemeHandler.domainHost)){//convert Unicode IDN -> ASCII IDN +try{components.host=punycode.toASCII(components.host.replace(protocol.PCT_ENCODED,pctDecChars).toLowerCase());}catch(e){components.error=components.error||"Host's domain name can not be converted to ASCII via punycode: "+e;}}//convert IRI -> URI +_normalizeComponentEncoding(components,URI_PROTOCOL);}else{//normalize encodings +_normalizeComponentEncoding(components,protocol);}//perform scheme specific parsing +if(schemeHandler&&schemeHandler.parse){schemeHandler.parse(components,options);}}else{parseError=true;components.error=components.error||"URI can not be parsed.";}return components;};function _recomposeAuthority(components,options){var uriTokens=[];if(components.userinfo!==undefined){uriTokens.push(components.userinfo);uriTokens.push("@");}if(components.host!==undefined){uriTokens.push(components.host);}if(typeof components.port==="number"){uriTokens.push(":");uriTokens.push(components.port.toString(10));}return uriTokens.length?uriTokens.join(""):undefined;};function removeDotSegments(input){var output=[],s;while(input.length){if(input.match(RDS1)){input=input.replace(RDS1,"");}else if(input.match(RDS2)){input=input.replace(RDS2,"/");}else if(input.match(RDS3)){input=input.replace(RDS3,"/");output.pop();}else if(input==="."||input===".."){input="";}else{s=input.match(RDS5)[0];input=input.slice(s.length);output.push(s);}}return output.join("");};function serialize(components,options){if(options===void 0){options={};}var protocol=URI__IRI_SUPPORT&&options.iri?IRI_PROTOCOL:URI_PROTOCOL,uriTokens=[],schemeHandler,authority,s;//find scheme handler +schemeHandler=SCHEMES[(options.scheme||components.scheme||"").toLowerCase()];//perform scheme specific serialization +if(schemeHandler&&schemeHandler.serialize)schemeHandler.serialize(components,options);//if host component is a domain name +if(URI__IRI_SUPPORT&&typeof punycode!=="undefined"&&components.host&&(options.domainHost||schemeHandler&&schemeHandler.domainHost)){//convert IDN via punycode +try{components.host=!options.iri?punycode.toASCII(components.host.replace(protocol.PCT_ENCODED,pctDecChars).toLowerCase()):punycode.toUnicode(components.host);}catch(e){components.error=components.error||"Host's domain name can not be converted to "+(!options.iri?"ASCII":"Unicode")+" via punycode: "+e;}}//normalize encoding +_normalizeComponentEncoding(components,protocol);if(options.reference!=="suffix"&&components.scheme){uriTokens.push(components.scheme);uriTokens.push(":");}authority=_recomposeAuthority(components,options);if(authority!==undefined){if(options.reference!=="suffix"){uriTokens.push("//");}uriTokens.push(authority);if(components.path&&components.path.charAt(0)!=="/"){uriTokens.push("/");}}if(components.path!==undefined){s=components.path;if(!options.absolutePath&&(!schemeHandler||!schemeHandler.absolutePath)){s=removeDotSegments(s);}if(authority===undefined){s=s.replace(/^\/\//,"/%2F");//don't allow the path to start with "//" +}uriTokens.push(s);}if(components.query!==undefined){uriTokens.push("?");uriTokens.push(components.query);}if(components.fragment!==undefined){uriTokens.push("#");uriTokens.push(components.fragment);}return uriTokens.join('');//merge tokens into a string +};function resolveComponents(base,relative,options,skipNormalization){if(options===void 0){options={};}var target={};if(!skipNormalization){base=parse(serialize(base,options),options);//normalize base components +relative=parse(serialize(relative,options),options);//normalize relative components +}options=options||{};if(!options.tolerant&&relative.scheme){target.scheme=relative.scheme;//target.authority = relative.authority; +target.userinfo=relative.userinfo;target.host=relative.host;target.port=relative.port;target.path=removeDotSegments(relative.path);target.query=relative.query;}else{if(relative.userinfo!==undefined||relative.host!==undefined||relative.port!==undefined){//target.authority = relative.authority; +target.userinfo=relative.userinfo;target.host=relative.host;target.port=relative.port;target.path=removeDotSegments(relative.path);target.query=relative.query;}else{if(!relative.path){target.path=base.path;if(relative.query!==undefined){target.query=relative.query;}else{target.query=base.query;}}else{if(relative.path.charAt(0)==="/"){target.path=removeDotSegments(relative.path);}else{if((base.userinfo!==undefined||base.host!==undefined||base.port!==undefined)&&!base.path){target.path="/"+relative.path;}else if(!base.path){target.path=relative.path;}else{target.path=base.path.slice(0,base.path.lastIndexOf("/")+1)+relative.path;}target.path=removeDotSegments(target.path);}target.query=relative.query;}//target.authority = base.authority; +target.userinfo=base.userinfo;target.host=base.host;target.port=base.port;}target.scheme=base.scheme;}target.fragment=relative.fragment;return target;};function resolve(baseURI,relativeURI,options){return serialize(resolveComponents(parse(baseURI,options),parse(relativeURI,options),options,true),options);};function normalize(uri,options){if(typeof uri==="string"){uri=serialize(parse(uri,options),options);}else if(typeOf(uri)==="object"){uri=parse(serialize(uri,options),options);}return uri;};function equal(uriA,uriB,options){if(typeof uriA==="string"){uriA=serialize(parse(uriA,options),options);}else if(typeOf(uriA)==="object"){uriA=serialize(uriA,options);}if(typeof uriB==="string"){uriB=serialize(parse(uriB,options),options);}else if(typeOf(uriB)==="object"){uriB=serialize(uriB,options);}return uriA===uriB;};function escapeComponent(str,options){return str&&str.toString().replace(!URI__IRI_SUPPORT||!options||!options.iri?URI_PROTOCOL.ESCAPE:IRI_PROTOCOL.ESCAPE,pctEncChar);};function unescapeComponent(str,options){return str&&str.toString().replace(!URI__IRI_SUPPORT||!options||!options.iri?URI_PROTOCOL.PCT_ENCODED:IRI_PROTOCOL.PCT_ENCODED,pctDecChars);};return{IRI_SUPPORT:URI__IRI_SUPPORT,VALIDATE_SUPPORT:URI__VALIDATE_SUPPORT,pctEncChar:pctEncChar,pctDecChars:pctDecChars,SCHEMES:SCHEMES,parse:parse,_recomposeAuthority:_recomposeAuthority,removeDotSegments:removeDotSegments,serialize:serialize,resolveComponents:resolveComponents,resolve:resolve,normalize:normalize,equal:equal,escapeComponent:escapeComponent,unescapeComponent:unescapeComponent};}();if(!COMPILED&&typeof module!=="undefined"&&typeof require==="function"){var punycode=require("./punycode");module.exports=URI;require("./schemes");}},{"./punycode":18,"./schemes":19}]},{},[1])(1);}); + +/***/ }), +/* 6 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__sf_path__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__schema_defaults__ = __webpack_require__(3); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__canonical_title_map__ = __webpack_require__(1); -/* harmony export (immutable) */ exports["a"] = merge; +/* harmony export (immutable) */ __webpack_exports__["a"] = merge; var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; @@ -601,13 +2239,17 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol // export function merge(schema, form, schemaDefaultTypes, ignore, options, readonly, asyncTemplates) { function merge(lookup, form, ignore, options, readonly, asyncTemplates) { var formItems = []; + var formItemRest = []; form = form || []; var idx = form.indexOf('*'); options = options || {}; + var stdForm = {}; + var idxRest = form.indexOf('...'); if ((typeof lookup === 'undefined' ? 'undefined' : _typeof(lookup)) === 'object' && lookup.hasOwnProperty('properties')) { readonly = readonly || lookup.readonly || lookup.readOnly; - var stdForm = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__schema_defaults__["defaultForm"])(lookup, __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__schema_defaults__["createDefaults"])(), ignore, options); + stdForm = __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__schema_defaults__["defaultForm"])(lookup, __webpack_require__.i(__WEBPACK_IMPORTED_MODULE_1__schema_defaults__["createDefaults"])(), ignore, options); + var defaultFormLookup = stdForm.lookup; lookup = defaultFormLookup || lookup; @@ -616,6 +2258,34 @@ function merge(lookup, form, ignore, options, readonly, asyncTemplates) { if (idx !== -1) { form = form.slice(0, idx).concat(formItems).concat(form.slice(idx + 1)); + } + + //simple case, we have a "...", just put the formItemRest there + if (stdForm.form && idxRest !== -1) { + (function () { + var formKeys = form.map(function (obj) { + if (typeof obj === 'string') { + return obj; + } else if (obj.key) { + return obj.key; + }; + }).filter(function (element) { + return element !== undefined; + }); + + formItemRest = formItemRest.concat(stdForm.form.map(function (obj) { + var isInside = formKeys.indexOf(obj.key[0]) !== -1; + if (!isInside) { + return obj; + }; + }).filter(function (element) { + return element !== undefined; + })); + })(); + }; + + if (idxRest !== -1) { + form = form.slice(0, idxRest).concat(formItemRest).concat(form.slice(idxRest + 1)); }; // ok let's merge! @@ -691,13 +2361,45 @@ function merge(lookup, form, ignore, options, readonly, asyncTemplates) { }); } -/***/ }, -/* 6 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 7 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { + +"use strict"; +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__lib_json_refs_standalone__ = __webpack_require__(5); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__lib_json_refs_standalone___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0__lib_json_refs_standalone__); +/* harmony export (immutable) */ __webpack_exports__["a"] = jsonref; + + +function jsonref(schema, callBack) { + var promise = new Promise(function (resolve, reject) { + __WEBPACK_IMPORTED_MODULE_0__lib_json_refs_standalone__["resolveRefs"](schema, { + "filter": ['relative', 'local', 'remote'] + }).then(function (res) { + resolve(res.resolved); + }).catch(function (err) { + reject(new Error(err)); + }); + }); + + if (typeof callBack === 'function') { + promise.then(function (resolved) { + callBack(null, resolved); + }).catch(function (error) { + callBack(error); + }); + } else { + return promise; + } +}; + +/***/ }), +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__sf_path__ = __webpack_require__(0); -/* harmony export (immutable) */ exports["a"] = select; +/* harmony export (immutable) */ __webpack_exports__["a"] = select; var numRe = /^\d+$/; @@ -773,13 +2475,13 @@ function select(projection, obj, valueToSet) { return value; }; -/***/ }, -/* 7 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 9 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -/* harmony export (immutable) */ exports["a"] = traverseSchema; -/* harmony export (immutable) */ exports["b"] = traverseForm; +/* harmony export (immutable) */ __webpack_exports__["a"] = traverseSchema; +/* harmony export (immutable) */ __webpack_exports__["b"] = traverseForm; /** * Traverse a schema, applying a function(schema,path) on every sub schema * i.e. every property of an object. @@ -828,14 +2530,14 @@ function traverseForm(form, fn) { } } -/***/ }, -/* 8 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 10 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tv4__ = __webpack_require__(10); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tv4__ = __webpack_require__(12); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_tv4___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_tv4__); -/* harmony export (immutable) */ exports["a"] = validate; +/* harmony export (immutable) */ __webpack_exports__["a"] = validate; /* Common code for validating a value against its form and schema definition */ @@ -890,12 +2592,12 @@ function validate(form, value) { return __WEBPACK_IMPORTED_MODULE_0_tv4___default.a.validateResult(valueWrap, wrap); }; -/***/ }, -/* 9 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 11 */ +/***/ (function(module, exports, __webpack_require__) { "use strict"; -var __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; +var __WEBPACK_AMD_DEFINE_RESULT__; ;!function(undefined) { @@ -984,7 +2686,8 @@ var __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = function() { return {ObjectPath: ObjectPath}; - }.call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); + }.call(exports, __webpack_require__, exports, module), + __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } // CommonJS @@ -999,45 +2702,74 @@ var __WEBPACK_AMD_DEFINE_RESULT__;'use strict'; }(); -/***/ }, -/* 10 */ -/***/ function(module, exports) { +/***/ }), +/* 12 */ +/***/ (function(module, exports) { module.exports = tv4; -/***/ }, -/* 11 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 13 */ +/***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(4); -/***/ } +/***/ }) /******/ ]); //# sourceMappingURL=json-schema-form-core.js.map +/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2), __webpack_require__(19).setImmediate)) -/***/ }, -/* 2 */, -/* 3 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 2 */ +/***/ (function(module, exports) { + +var g; + +// This works in non-strict mode +g = (function() { + return this; +})(); + +try { + // This works if eval is allowed (see CSP) + g = g || Function("return this")() || (1,eval)("this"); +} catch(e) { + // This works if the window reference is available + if(typeof window === "object") + g = window; +} + +// g can still be undefined, but nothing to do about it... +// We return undefined, instead of nothing here, so it's +// easier to handle this case. if(!global) { ...} + +module.exports = g; + + +/***/ }), +/* 3 */, +/* 4 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; +Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_json_schema_form_core__ = __webpack_require__(1); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_json_schema_form_core___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_json_schema_form_core__); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_angular__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_angular___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_angular__); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_sf_builder_provider__ = __webpack_require__(13); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_schema_form_decorators_provider__ = __webpack_require__(11); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_schema_form_provider__ = __webpack_require__(12); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5_sf_error_message_provider__ = __webpack_require__(14); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6_sf_path_provider__ = __webpack_require__(15); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7_sf_changed_directive__ = __webpack_require__(6); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8_sf_field_directive__ = __webpack_require__(7); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9_sf_message_directive__ = __webpack_require__(9); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10_sf_array_directive__ = __webpack_require__(5); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11_sf_key_directive__ = __webpack_require__(8); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12_sf_schema_directive__ = __webpack_require__(10); -/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13_schema_validate_directive__ = __webpack_require__(4); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_sf_builder_provider__ = __webpack_require__(14); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_schema_form_decorators_provider__ = __webpack_require__(12); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_schema_form_provider__ = __webpack_require__(13); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5_sf_error_message_provider__ = __webpack_require__(15); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6_sf_path_provider__ = __webpack_require__(16); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7_sf_changed_directive__ = __webpack_require__(7); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_8_sf_field_directive__ = __webpack_require__(8); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_9_sf_message_directive__ = __webpack_require__(10); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_10_sf_array_directive__ = __webpack_require__(6); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_11_sf_key_directive__ = __webpack_require__(9); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_12_sf_schema_directive__ = __webpack_require__(11); +/* harmony import */ var __WEBPACK_IMPORTED_MODULE_13_schema_validate_directive__ = __webpack_require__(5); @@ -1082,24 +2814,24 @@ __WEBPACK_IMPORTED_MODULE_1_angular___default.a.module('schemaForm', deps) // Providers and services .provider('sfPath', __WEBPACK_IMPORTED_MODULE_6_sf_path_provider__["a" /* default */]).provider('sfBuilder', ['sfPathProvider', __WEBPACK_IMPORTED_MODULE_2_sf_builder_provider__["a" /* default */]]).provider('schemaFormDecorators', ['$compileProvider', 'sfPathProvider', __WEBPACK_IMPORTED_MODULE_3_schema_form_decorators_provider__["a" /* default */]]).provider('sfErrorMessage', __WEBPACK_IMPORTED_MODULE_5_sf_error_message_provider__["a" /* default */]).provider('schemaForm', ['sfPathProvider', __WEBPACK_IMPORTED_MODULE_4_schema_form_provider__["a" /* default */]]).factory('sfSelect', function () { - return __WEBPACK_IMPORTED_MODULE_0_json_schema_form_core___default.a.select; + return __WEBPACK_IMPORTED_MODULE_0_json_schema_form_core__["select"]; }).factory('sfValidator', function () { - return __WEBPACK_IMPORTED_MODULE_0_json_schema_form_core___default.a.validate; + return __WEBPACK_IMPORTED_MODULE_0_json_schema_form_core__["validate"]; }) // Directives .directive('sfChanged', __WEBPACK_IMPORTED_MODULE_7_sf_changed_directive__["a" /* default */]).directive('sfField', ['$parse', '$compile', '$http', '$templateCache', '$interpolate', '$q', 'sfErrorMessage', 'sfPath', 'sfSelect', __WEBPACK_IMPORTED_MODULE_8_sf_field_directive__["a" /* default */]]).directive('sfMessage', ['$injector', 'sfErrorMessage', __WEBPACK_IMPORTED_MODULE_9_sf_message_directive__["a" /* default */]]).directive('sfNewArray', ['sfSelect', 'sfPath', 'schemaForm', __WEBPACK_IMPORTED_MODULE_10_sf_array_directive__["a" /* default */]]).directive('sfSchema', ['$compile', '$http', '$templateCache', '$q', 'schemaForm', 'schemaFormDecorators', 'sfSelect', 'sfPath', 'sfBuilder', __WEBPACK_IMPORTED_MODULE_12_sf_schema_directive__["a" /* default */]]).directive('schemaValidate', ['sfValidator', '$parse', 'sfSelect', __WEBPACK_IMPORTED_MODULE_13_schema_validate_directive__["a" /* default */]]).directive('sfKeyController', ['schemaForm', 'sfPath', __WEBPACK_IMPORTED_MODULE_11_sf_key_directive__["a" /* default */]]); -/***/ }, -/* 4 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 5 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_angular__); -/* harmony default export */ exports["a"] = function (sfValidator, $parse, sfSelect) { +/* harmony default export */ __webpack_exports__["a"] = function (sfValidator, $parse, sfSelect) { return { restrict: 'A', scope: false, @@ -1277,9 +3009,9 @@ __WEBPACK_IMPORTED_MODULE_1_angular___default.a.module('schemaForm', deps) }; }; -/***/ }, -/* 5 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 6 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular__ = __webpack_require__(0); @@ -1289,7 +3021,7 @@ __WEBPACK_IMPORTED_MODULE_1_angular___default.a.module('schemaForm', deps) /** * Directive that handles the model arrays */ -/* harmony default export */ exports["a"] = function (sel, sfPath, schemaForm) { +/* harmony default export */ __webpack_exports__["a"] = function (sel, sfPath, schemaForm) { return { scope: true, controller: ['$scope', function SFArrayController($scope) { @@ -1528,9 +3260,9 @@ __WEBPACK_IMPORTED_MODULE_1_angular___default.a.module('schemaForm', deps) }; }; -/***/ }, -/* 6 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 7 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular__ = __webpack_require__(0); @@ -1544,7 +3276,7 @@ __WEBPACK_IMPORTED_MODULE_1_angular___default.a.module('schemaForm', deps) * Takes the form definition as argument. * If the form definition has a "onChange" defined as either a function or */ -/* harmony default export */ exports["a"] = function () { +/* harmony default export */ __webpack_exports__["a"] = function () { return { require: 'ngModel', restrict: 'AC', @@ -1574,9 +3306,9 @@ __WEBPACK_IMPORTED_MODULE_1_angular___default.a.module('schemaForm', deps) }; }; -/***/ }, -/* 7 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 8 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular__ = __webpack_require__(0); @@ -1585,7 +3317,7 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol -/* harmony default export */ exports["a"] = function ($parse, $compile, $http, $templateCache, $interpolate, $q, sfErrorMessage, sfPath, sfSelect) { +/* harmony default export */ __webpack_exports__["a"] = function ($parse, $compile, $http, $templateCache, $interpolate, $q, sfErrorMessage, sfPath, sfSelect) { var keyFormat = { COMPLETE: '*', @@ -1903,15 +3635,15 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol }; }; -/***/ }, -/* 8 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 9 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /** * Directive that handles keys and array indexes */ -/* harmony default export */ exports["a"] = function (schemaForm, sfPath) { +/* harmony default export */ __webpack_exports__["a"] = function (schemaForm, sfPath) { return { scope: true, require: ['?^^sfNewArray'], @@ -1942,16 +3674,16 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol }; };; -/***/ }, -/* 9 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 10 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_angular__); -/* harmony default export */ exports["a"] = function ($injector, sfErrorMessage) { +/* harmony default export */ __webpack_exports__["a"] = function ($injector, sfErrorMessage) { //Inject sanitizer if it exists var $sanitize = $injector.has('$sanitize') ? $injector.get('$sanitize') : function (html) { @@ -2046,9 +3778,9 @@ var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol }; }; -/***/ }, -/* 10 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 11 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular__ = __webpack_require__(0); @@ -2060,7 +3792,7 @@ FIXME: real documentation
*/ -/* harmony default export */ exports["a"] = function ($compile, $http, $templateCache, $q, schemaForm, schemaFormDecorators, sfSelect, sfPath, sfBuilder) { +/* harmony default export */ __webpack_exports__["a"] = function ($compile, $http, $templateCache, $q, schemaForm, schemaFormDecorators, sfSelect, sfPath, sfBuilder) { return { scope: { @@ -2118,7 +3850,17 @@ FIXME: real documentation var childScope; // Common renderer function, can either be triggered by a watch or by an event. - var render = function render(schema, form) { + scope.resolveReferences = function (schema, form) { + schemaForm.jsonref(schema).then(function (resolved) { + scope.render(resolved, form); + }).catch(function (err) { + new Error(err); + }); + }; + + scope.render = function (schema, form) { + //console.log("schema:", JSON.stringify(schema)); + //console.log("resolv:", JSON.stringify(resolved)); var asyncTemplates = []; var merged = schemaForm.merge(schema, form, ignore, scope.options, undefined, asyncTemplates); @@ -2129,14 +3871,14 @@ FIXME: real documentation form.template = res.data; }); })).then(function () { - internalRender(schema, form, merged); + scope.internalRender(schema, form, merged); }); } else { - internalRender(schema, form, merged); + scope.internalRender(schema, form, merged); }; }; - var internalRender = function internalRender(schema, form, merged) { + scope.internalRender = function (schema, form, merged) { // Create a new form and destroy the old one. // Not doing keeps old form elements hanging around after // they have been removed from the DOM @@ -2215,7 +3957,7 @@ FIXME: real documentation lastDigest.schema = schema; lastDigest.form = form; - render(schema, form); + scope.resolveReferences(schema, form); } }); @@ -2225,7 +3967,7 @@ FIXME: real documentation var schema = scope.schema; var form = scope.initialForm ? __WEBPACK_IMPORTED_MODULE_0_angular___default.a.copy(scope.initialForm) : ['*']; if (schema) { - render(schema, form); + scope.resolveReferences(schema, form); } }); @@ -2254,16 +3996,16 @@ FIXME: real documentation }; }; -/***/ }, -/* 11 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 12 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_angular__); -/* harmony default export */ exports["a"] = function ($compileProvider, sfPathProvider) { +/* harmony default export */ __webpack_exports__["a"] = function ($compileProvider, sfPathProvider) { var defaultDecorator = ''; var decorators = {}; @@ -2797,9 +4539,9 @@ FIXME: real documentation createDirective('sfDecorator'); };; -/***/ }, -/* 12 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 13 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular__ = __webpack_require__(0); @@ -2813,7 +4555,7 @@ FIXME: real documentation /** * Schema form service. */ -/* harmony default export */ exports["a"] = function () { +/* harmony default export */ __webpack_exports__["a"] = function () { var postProcessFn = function postProcessFn(form) { return form; }; @@ -2881,6 +4623,8 @@ FIXME: real documentation var service = {}; var typeDefault = this.defaults; + service.jsonref = __WEBPACK_IMPORTED_MODULE_1_json_schema_form_core__["jsonref"]; + service.merge = function (schema) { var form = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ['*']; var ignore = arguments[2]; @@ -2920,14 +4664,14 @@ FIXME: real documentation }; }; -/***/ }, -/* 13 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 14 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; // FIXME: type template (using custom builder) -/* harmony default export */ exports["a"] = function (sfPathProvider) { +/* harmony default export */ __webpack_exports__["a"] = function (sfPathProvider) { var SNAKE_CASE_REGEXP = /[A-Z]/g; var snakeCase = function snakeCase(name, separator) { @@ -3248,16 +4992,16 @@ FIXME: real documentation }]; }; -/***/ }, -/* 14 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 15 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular__ = __webpack_require__(0); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_angular___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_angular__); -/* harmony default export */ exports["a"] = function () { +/* harmony default export */ __webpack_exports__["a"] = function () { // The codes are tv4 error codes. // Not all of these can actually happen in a field, but for @@ -3385,9 +5129,9 @@ FIXME: real documentation }]; }; -/***/ }, -/* 15 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 16 */ +/***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_json_schema_form_core__ = __webpack_require__(1); @@ -3423,15 +5167,454 @@ var sfPathProviderClass = function () { return sfPathProviderClass; }(); -/* harmony default export */ exports["a"] = sfPathProviderClass; +/* harmony default export */ __webpack_exports__["a"] = sfPathProviderClass; -/***/ }, -/* 16 */ -/***/ function(module, exports, __webpack_require__) { +/***/ }), +/* 17 */ +/***/ (function(module, exports) { + +// shim for using process in browser +var process = module.exports = {}; + +// cached from whatever global is present so that test runners that stub it +// don't break things. But we need to wrap it in a try catch in case it is +// wrapped in strict mode code which doesn't define any globals. It's inside a +// function because try/catches deoptimize in certain engines. + +var cachedSetTimeout; +var cachedClearTimeout; + +function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); +} +function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); +} +(function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } +} ()) +function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + +} +function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + +} +var queue = []; +var draining = false; +var currentQueue; +var queueIndex = -1; + +function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } +} + +function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); +} + +process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } +}; + +// v8 likes predictible objects +function Item(fun, array) { + this.fun = fun; + this.array = array; +} +Item.prototype.run = function () { + this.fun.apply(null, this.array); +}; +process.title = 'browser'; +process.browser = true; +process.env = {}; +process.argv = []; +process.version = ''; // empty string to avoid regexp issues +process.versions = {}; + +function noop() {} + +process.on = noop; +process.addListener = noop; +process.once = noop; +process.off = noop; +process.removeListener = noop; +process.removeAllListeners = noop; +process.emit = noop; + +process.binding = function (name) { + throw new Error('process.binding is not supported'); +}; + +process.cwd = function () { return '/' }; +process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); +}; +process.umask = function() { return 0; }; + + +/***/ }), +/* 18 */ +/***/ (function(module, exports, __webpack_require__) { + +/* WEBPACK VAR INJECTION */(function(global, process) {(function (global, undefined) { + "use strict"; + + if (global.setImmediate) { + return; + } + + var nextHandle = 1; // Spec says greater than zero + var tasksByHandle = {}; + var currentlyRunningATask = false; + var doc = global.document; + var registerImmediate; + + function setImmediate(callback) { + // Callback can either be a function or a string + if (typeof callback !== "function") { + callback = new Function("" + callback); + } + // Copy function arguments + var args = new Array(arguments.length - 1); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i + 1]; + } + // Store and register the task + var task = { callback: callback, args: args }; + tasksByHandle[nextHandle] = task; + registerImmediate(nextHandle); + return nextHandle++; + } + + function clearImmediate(handle) { + delete tasksByHandle[handle]; + } + + function run(task) { + var callback = task.callback; + var args = task.args; + switch (args.length) { + case 0: + callback(); + break; + case 1: + callback(args[0]); + break; + case 2: + callback(args[0], args[1]); + break; + case 3: + callback(args[0], args[1], args[2]); + break; + default: + callback.apply(undefined, args); + break; + } + } + + function runIfPresent(handle) { + // From the spec: "Wait until any invocations of this algorithm started before this one have completed." + // So if we're currently running a task, we'll need to delay this invocation. + if (currentlyRunningATask) { + // Delay by doing a setTimeout. setImmediate was tried instead, but in Firefox 7 it generated a + // "too much recursion" error. + setTimeout(runIfPresent, 0, handle); + } else { + var task = tasksByHandle[handle]; + if (task) { + currentlyRunningATask = true; + try { + run(task); + } finally { + clearImmediate(handle); + currentlyRunningATask = false; + } + } + } + } + + function installNextTickImplementation() { + registerImmediate = function(handle) { + process.nextTick(function () { runIfPresent(handle); }); + }; + } + + function canUsePostMessage() { + // The test against `importScripts` prevents this implementation from being installed inside a web worker, + // where `global.postMessage` means something completely different and can't be used for this purpose. + if (global.postMessage && !global.importScripts) { + var postMessageIsAsynchronous = true; + var oldOnMessage = global.onmessage; + global.onmessage = function() { + postMessageIsAsynchronous = false; + }; + global.postMessage("", "*"); + global.onmessage = oldOnMessage; + return postMessageIsAsynchronous; + } + } + + function installPostMessageImplementation() { + // Installs an event handler on `global` for the `message` event: see + // * https://developer.mozilla.org/en/DOM/window.postMessage + // * http://www.whatwg.org/specs/web-apps/current-work/multipage/comms.html#crossDocumentMessages + + var messagePrefix = "setImmediate$" + Math.random() + "$"; + var onGlobalMessage = function(event) { + if (event.source === global && + typeof event.data === "string" && + event.data.indexOf(messagePrefix) === 0) { + runIfPresent(+event.data.slice(messagePrefix.length)); + } + }; + + if (global.addEventListener) { + global.addEventListener("message", onGlobalMessage, false); + } else { + global.attachEvent("onmessage", onGlobalMessage); + } + + registerImmediate = function(handle) { + global.postMessage(messagePrefix + handle, "*"); + }; + } + + function installMessageChannelImplementation() { + var channel = new MessageChannel(); + channel.port1.onmessage = function(event) { + var handle = event.data; + runIfPresent(handle); + }; + + registerImmediate = function(handle) { + channel.port2.postMessage(handle); + }; + } + + function installReadyStateChangeImplementation() { + var html = doc.documentElement; + registerImmediate = function(handle) { + // Create a