diff --git a/Pcb-1-lan9252/EEPROM_generator/.gitignore b/Pcb-1-lan9252/EEPROM_generator/.gitignore new file mode 100644 index 0000000..dea4cf2 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/.gitignore @@ -0,0 +1,2 @@ +*.bin +node_modules \ No newline at end of file diff --git a/Pcb-1-lan9252/EEPROM_generator/LICENSE b/Pcb-1-lan9252/EEPROM_generator/LICENSE new file mode 100644 index 0000000..9461b83 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/LICENSE @@ -0,0 +1,26 @@ +EEPROM generator + +Victor Sluiter 2013-2018 +Kuba Buda 2020-2022 + +EEPROM generator is free software; you can redistribute it and/or modify it under +the terms of the GNU General Public License version 2 as published by the Free +Software Foundation. + +EEPROM generator is distributed in the hope that it will be useful, but WITHOUT ANY +WARRANTY; without even the implied warranty of MERCHANTABILITY or +FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License +for more details. + +As a special exception, if other files instantiate templates or use macros +or inline functions from this file, or you compile this file and link it +with other works to produce a work based on this file, this file does not +by itself cause the resulting work to be covered by the GNU General Public +License. However the source code for this file must still be made available +in accordance with section (3) of the GNU General Public License. + +This exception does not invalidate any other reasons why a work based on +this file might be covered by the GNU General Public License. + +The EtherCAT Technology, the trade name and logo "EtherCAT" are the intellectual +property of, and protected by Beckhoff Automation GmbH. diff --git a/Pcb-1-lan9252/EEPROM_generator/README.md b/Pcb-1-lan9252/EEPROM_generator/README.md new file mode 100644 index 0000000..9fc7e29 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/README.md @@ -0,0 +1,120 @@ +# [๐Ÿ” EEPROM generator](https://kubabuda.github.io/EEPROM_generator) + +This is basic code generator tool for EtherCAT devices, using [SOES library](https://github.com/OpenEtherCATsociety/SOES). + +[It is available online, here](https://kubabuda.github.io/EEPROM_generator) + +You can configure: +- ESC (Ethercat Slave Chip) +- OD (CANopen Object Dictionary) entries +- PDO mappings (which OD objects are mapped in TX, RX datagrams) + +Tool generates consistent data across C sources, ESI file and EEPROM content. + +It also backs up your current project in localstorage. You can save project to JSON file on your hard drive, restore from it later, and download all files at once. + +## Limitations + +- Only single, non-dynamic PDO is supported for TX and RX respectively +- Some data types might not be supported +- Browsers other than Firefox might not be supported + +If you need more, [RT-Labs](https://rt-labs.com/ethercat/) offers professional IDE - EtherCAT SDK, and training. + +# Development + +Pull requests welcome. + +Source code is intentionally keept in plain Javascript files so that build system like webpack or even web server is not needed. +The only dependency is web browser, that should future proof it. + +## [Unit tests](https://kubabuda.github.io/EEPROM_generator/tests.html) + +[Unit tests](https://kubabuda.github.io/EEPROM_generator/tests.html) are using [Jasmine](https://jasmine.github.io). + +## OD structure + +OD is keept as JSON object. Expected data format: + +```js +{ + '1000': { otype: OTYPE.VAR, dtype: DTYPE.UNSIGNED32, name: 'Device Type', value: 0x1389 }, + '1008': { otype: OTYPE.VAR, dtype: DTYPE.VISIBLE_STRING, name: 'Device Name', data: '' }, + '1009': { otype: OTYPE.VAR, dtype: DTYPE.VISIBLE_STRING, name: 'Hardware Version', data: '' }, + '100A': { otype: OTYPE.VAR, dtype: DTYPE.VISIBLE_STRING, name: 'Software Version', data: '' }, + '1018': { otype: OTYPE.RECORD, name: 'Identity Object', items: [ + { name: 'Max SubIndex' }, + { name: 'Vendor ID', dtype: DTYPE.UNSIGNED32, value: 600 }, + { name: 'Product Code', dtype: DTYPE.UNSIGNED32 }, + { name: 'Revision Number', dtype: DTYPE.UNSIGNED32 }, + { name: 'Serial Number', dtype: DTYPE.UNSIGNED32, data: '&Obj.serial' }, + ]}, + '1C00': { otype: OTYPE.ARRAY, dtype: DTYPE.UNSIGNED8, name: 'Sync Manager Communication Type', items: [ + { name: 'Max SubIndex' }, + { name: 'Communications Type SM0', value: 1 }, + { name: 'Communications Type SM1', value: 2 }, + { name: 'Communications Type SM2', value: 3 }, + { name: 'Communications Type SM3', value: 4 }, + ]}, +} +``` + +OD model for generator has 4 sections: + +- `sdo`, not mapped to PDOs +- `txpdo`, mapped to TXPDO (SM3). Expected format (for OTYPE VAR): +```js +{ + '6000': { otype: OTYPE.VAR, dtype: DTYPE.UNSIGNED32, name: 'TXPDO', value: 0x1389, pdo_mappings: ['tx'] }, +} +``` +- `rxpdo`, same as above, but `pdo_mappings: ['rx']` +- mandatory objects. These are added at code gen stage, with values populated form UI controls. + +Code generation copies all values into single OD, adds PDO mappings and SM assignments. + +## PDO mappings + +Currently single, non-dynamic PDO is supported for TX and RX respectively. + +## Binary file comparison tool for Windows: [VBinDiff](https://www.cjmweb.net/vbindiff/VBinDiff-Win32) + +```cmd +VBinDiff et1100.bin lan9252.bin +``` + + +# TODO + +- add support for 64bit number types +- why default dark mode has dark text in Chromium but not Firefox, when OS is in dark mode +- generate .h file for EEPROM emulation +- add support for LAN9253 Direct, XMC4300, XMC4800 +- check output for boolean ARRAY +- check output for VISIBLE_STRING ARRAY +- check output for VISIBLE_STRING RECORD subitem +- dynamic/multiple PDOs +- more unit tests +- SM2 offset: regardles of value set, SDK generates RXPDO mappings as SDO1600. SM2 offset change affects + - `ecat_options.h` #define SM2_sma, MAX_TXPDO_SIZE and MAX_RXPDO_SIZE + - `esi.xml` `Outputs` + currently this tool mirrors SDK behavior, check if this hack is needed or just duplicated SDK bug +- calculate `MAX_RXPDO_SIZE`, `MAX_TXPDO_SIZE` based on selected SM2 offset +- modular device profile +- set project name from device name +- DC config in ESI .bin + +- use [XML parsing](https://www.w3schools.com/xml/xml_parser.asp) for cleaner builiding ESI XML output +- read XML files: make reverse eningeering 3rd party devices easier +- add indexes list to OD model, to decrease parametes count in methods +- 0x1001 UINT8 Error Register is mandatory according to CiA DS301 +- 0x1C12/0x1C13 `PdoAssign` and 0x1608/0x1A08 `PdoMapping` [should be RW](https://infosys.beckhoff.com/english.php?content=../content/1033/el6695/1317558667.html&id=) + +### Code optimization + +- reuse repeated string constants in objlist.c names, test if does any good or compiler does that for you anyway + +# Disclaimer + +The EtherCAT Technology, the trade name and logo "EtherCAT" are the intellectual +property of, and protected by Beckhoff Automation GmbH. diff --git a/Pcb-1-lan9252/EEPROM_generator/img/banner.JPG b/Pcb-1-lan9252/EEPROM_generator/img/banner.JPG new file mode 100644 index 0000000..aeaf46c Binary files /dev/null and b/Pcb-1-lan9252/EEPROM_generator/img/banner.JPG differ diff --git a/Pcb-1-lan9252/EEPROM_generator/img/logo.JPG b/Pcb-1-lan9252/EEPROM_generator/img/logo.JPG new file mode 100644 index 0000000..1879cab Binary files /dev/null and b/Pcb-1-lan9252/EEPROM_generator/img/logo.JPG differ diff --git a/Pcb-1-lan9252/EEPROM_generator/index.html b/Pcb-1-lan9252/EEPROM_generator/index.html new file mode 100644 index 0000000..847285d --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/index.html @@ -0,0 +1,415 @@ + + + ๐Ÿ” EEPROM Generator | ESI, EEPORM, SOES C code configuration tool + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ +

๐Ÿ” EEPROM generator

+
+ +
+
+ +
+
+

EtherCAT EEPROM + SOES OD configuration tool

+

+ This page serves as a tool to generate consistent data across your code, ESI file and EEPROM data. + Hover over the fields to get additional info about the items you can change.
+ For more detail on how these values translate to the corresponding files, and where you can find more info in the ETG documentation, + look into javascript source that generates these files.
+

+ C source code is generated for SOES: Simple Open source EtherCAT Slave stack. + Its source code with example applications is available on Github. + Docs with basic tutorial can be found on rt-labs page +

+
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Item:ValueESIEEPROMobjectlist.cecat_options.h
Name of Vendor:x   
VendorID:xxx 
ProductCode:xxx 
Profile No:x 
RevisionNumber:xxx 
SerialNumber:xxx 
Hardware version:xxx 
Software version:xxx 

+
Number of bytes in EEPROM:xx  
RxMailbox Offset:xx x
TxMailbox Offset:xx x
Tx AND Rx Mailbox Size:xx x
SyncManager 2 offset:xx x
SyncManager 3 offset:xx x

+
Group Type:xx  
Group Name:x   
Image Name: x  
Device Type:xx  
Device Name:xxx 

+
Port 0 Physical interface:xx  
Port 1 Physical interface:xx  
Port 2 Physical interface:xx  
Port 3 Physical interface:xx  

+
ESC (EtherCAT Slave Chip):xx  
SPI mode:xx  

+
+ Enable SDO
+ Enable SDO Info
+ Enable PDO Assign
+ Enable PDO Configuration
+ Enable Upload at startup
+ Enable SDO complete access
+
 xx  

+
+

+ SDO + + + + + +

+
+

+
+

+ TXPDO (slv to master) + + + + + +

+
+

+
+

+ RXPDO (master to slv) + + + + + +

+
+

+

+ Synchronization + + + +

+
+ +

+ +
+ + + + + +
+
+ +

+
+ ESI file: + +
+

+ EEPROM HEX file: + + +
+ To flash slave device with generated EEPROM content, you can install SOEM + and run command (for Intel Hex): +

sudo ./eepromtool 1 eth0 -wi eeprom.hex

+ +

+ ecat_options.h: + +
+

+ objectlist.c: + +
+

+ utypes.h: + +
+

+ +
+
+ \ No newline at end of file diff --git a/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/boot.js b/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/boot.js new file mode 100644 index 0000000..e1e20f1 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/boot.js @@ -0,0 +1,139 @@ +/** + Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js` and `jasmine_html.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. + + If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. + + The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. + + [jasmine-gem]: http://github.com/pivotal/jasmine-gem + */ + +(function() { + var jasmineRequire = window.jasmineRequire || require('./jasmine.js'); + + /** + * ## Require & Instantiate + * + * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. + */ + var jasmine = jasmineRequire.core(jasmineRequire), + global = jasmine.getGlobal(); + global.jasmine = jasmine; + + /** + * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. + */ + jasmineRequire.html(jasmine); + + /** + * Create the Jasmine environment. This is used to run all specs in a project. + */ + var env = jasmine.getEnv(); + + /** + * ## The Global Interface + * + * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. + */ + var jasmineInterface = jasmineRequire.interface(jasmine, env); + + /** + * Add all of the Jasmine global/public interface to the global scope, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. + */ + extend(global, jasmineInterface); + + /** + * ## Runner Parameters + * + * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. + */ + + var queryString = new jasmine.QueryString({ + getWindowLocation: function() { return window.location; } + }); + + var filterSpecs = !!queryString.getParam("spec"); + + var config = { + failFast: queryString.getParam("failFast"), + oneFailurePerSpec: queryString.getParam("oneFailurePerSpec"), + hideDisabled: queryString.getParam("hideDisabled") + }; + + var random = queryString.getParam("random"); + + if (random !== undefined && random !== "") { + config.random = random; + } + + var seed = queryString.getParam("seed"); + if (seed) { + config.seed = seed; + } + + /** + * ## Reporters + * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). + */ + var htmlReporter = new jasmine.HtmlReporter({ + env: env, + navigateWithNewParam: function(key, value) { return queryString.navigateWithNewParam(key, value); }, + addToExistingQueryString: function(key, value) { return queryString.fullStringWithNewParam(key, value); }, + getContainer: function() { return document.body; }, + createElement: function() { return document.createElement.apply(document, arguments); }, + createTextNode: function() { return document.createTextNode.apply(document, arguments); }, + timer: new jasmine.Timer(), + filterSpecs: filterSpecs + }); + + /** + * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. + */ + env.addReporter(jasmineInterface.jsApiReporter); + env.addReporter(htmlReporter); + + /** + * Filter which specs will be run by matching the start of the full name against the `spec` query param. + */ + var specFilter = new jasmine.HtmlSpecFilter({ + filterString: function() { return queryString.getParam("spec"); } + }); + + config.specFilter = function(spec) { + return specFilter.matches(spec.getFullName()); + }; + + env.configure(config); + + /** + * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. + */ + window.setTimeout = window.setTimeout; + window.setInterval = window.setInterval; + window.clearTimeout = window.clearTimeout; + window.clearInterval = window.clearInterval; + + /** + * ## Execution + * + * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. + */ + var currentWindowOnload = window.onload; + + window.onload = function() { + if (currentWindowOnload) { + currentWindowOnload(); + } + htmlReporter.initialize(); + env.execute(); + }; + + /** + * Helper function for readability above. + */ + function extend(destination, source) { + for (var property in source) destination[property] = source[property]; + return destination; + } + +}()); diff --git a/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/jasmine-html.js b/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/jasmine-html.js new file mode 100644 index 0000000..79e0f45 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/jasmine-html.js @@ -0,0 +1,853 @@ +/* +Copyright (c) 2008-2021 Pivotal Labs + +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. +*/ +var jasmineRequire = window.jasmineRequire || require('./jasmine.js'); + +jasmineRequire.html = function(j$) { + j$.ResultsNode = jasmineRequire.ResultsNode(); + j$.HtmlReporter = jasmineRequire.HtmlReporter(j$); + j$.QueryString = jasmineRequire.QueryString(); + j$.HtmlSpecFilter = jasmineRequire.HtmlSpecFilter(); +}; + +jasmineRequire.HtmlReporter = function(j$) { + function ResultsStateBuilder() { + this.topResults = new j$.ResultsNode({}, '', null); + this.currentParent = this.topResults; + this.specsExecuted = 0; + this.failureCount = 0; + this.pendingSpecCount = 0; + } + + ResultsStateBuilder.prototype.suiteStarted = function(result) { + this.currentParent.addChild(result, 'suite'); + this.currentParent = this.currentParent.last(); + }; + + ResultsStateBuilder.prototype.suiteDone = function(result) { + this.currentParent.updateResult(result); + if (this.currentParent !== this.topResults) { + this.currentParent = this.currentParent.parent; + } + + if (result.status === 'failed') { + this.failureCount++; + } + }; + + ResultsStateBuilder.prototype.specStarted = function(result) {}; + + ResultsStateBuilder.prototype.specDone = function(result) { + this.currentParent.addChild(result, 'spec'); + + if (result.status !== 'excluded') { + this.specsExecuted++; + } + + if (result.status === 'failed') { + this.failureCount++; + } + + if (result.status == 'pending') { + this.pendingSpecCount++; + } + }; + + function HtmlReporter(options) { + var config = function() { + return (options.env && options.env.configuration()) || {}; + }, + getContainer = options.getContainer, + createElement = options.createElement, + createTextNode = options.createTextNode, + navigateWithNewParam = options.navigateWithNewParam || function() {}, + addToExistingQueryString = + options.addToExistingQueryString || defaultQueryString, + filterSpecs = options.filterSpecs, + htmlReporterMain, + symbols, + deprecationWarnings = []; + + this.initialize = function() { + clearPrior(); + htmlReporterMain = createDom( + 'div', + { className: 'jasmine_html-reporter' }, + createDom( + 'div', + { className: 'jasmine-banner' }, + createDom('a', { + className: 'jasmine-title', + href: 'http://jasmine.github.io/', + target: '_blank' + }), + createDom('span', { className: 'jasmine-version' }, j$.version) + ), + createDom('ul', { className: 'jasmine-symbol-summary' }), + createDom('div', { className: 'jasmine-alert' }), + createDom( + 'div', + { className: 'jasmine-results' }, + createDom('div', { className: 'jasmine-failures' }) + ) + ); + getContainer().appendChild(htmlReporterMain); + }; + + var totalSpecsDefined; + this.jasmineStarted = function(options) { + totalSpecsDefined = options.totalSpecsDefined || 0; + }; + + var summary = createDom('div', { className: 'jasmine-summary' }); + + var stateBuilder = new ResultsStateBuilder(); + + this.suiteStarted = function(result) { + stateBuilder.suiteStarted(result); + }; + + this.suiteDone = function(result) { + stateBuilder.suiteDone(result); + + if (result.status === 'failed') { + failures.push(failureDom(result)); + } + addDeprecationWarnings(result, 'suite'); + }; + + this.specStarted = function(result) { + stateBuilder.specStarted(result); + }; + + var failures = []; + this.specDone = function(result) { + stateBuilder.specDone(result); + + if (noExpectations(result)) { + var noSpecMsg = "Spec '" + result.fullName + "' has no expectations."; + if (result.status === 'failed') { + console.error(noSpecMsg); + } else { + console.warn(noSpecMsg); + } + } + + if (!symbols) { + symbols = find('.jasmine-symbol-summary'); + } + + symbols.appendChild( + createDom('li', { + className: this.displaySpecInCorrectFormat(result), + id: 'spec_' + result.id, + title: result.fullName + }) + ); + + if (result.status === 'failed') { + failures.push(failureDom(result)); + } + + addDeprecationWarnings(result, 'spec'); + }; + + this.displaySpecInCorrectFormat = function(result) { + return noExpectations(result) && result.status === 'passed' + ? 'jasmine-empty' + : this.resultStatus(result.status); + }; + + this.resultStatus = function(status) { + if (status === 'excluded') { + return config().hideDisabled + ? 'jasmine-excluded-no-display' + : 'jasmine-excluded'; + } + return 'jasmine-' + status; + }; + + this.jasmineDone = function(doneResult) { + var banner = find('.jasmine-banner'); + var alert = find('.jasmine-alert'); + var order = doneResult && doneResult.order; + var i; + alert.appendChild( + createDom( + 'span', + { className: 'jasmine-duration' }, + 'finished in ' + doneResult.totalTime / 1000 + 's' + ) + ); + + banner.appendChild(optionsMenu(config())); + + if (stateBuilder.specsExecuted < totalSpecsDefined) { + var skippedMessage = + 'Ran ' + + stateBuilder.specsExecuted + + ' of ' + + totalSpecsDefined + + ' specs - run all'; + // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 + var skippedLink = + (window.location.pathname || '') + + addToExistingQueryString('spec', ''); + alert.appendChild( + createDom( + 'span', + { className: 'jasmine-bar jasmine-skipped' }, + createDom( + 'a', + { href: skippedLink, title: 'Run all specs' }, + skippedMessage + ) + ) + ); + } + var statusBarMessage = ''; + var statusBarClassName = 'jasmine-overall-result jasmine-bar '; + var globalFailures = (doneResult && doneResult.failedExpectations) || []; + var failed = stateBuilder.failureCount + globalFailures.length > 0; + + if (totalSpecsDefined > 0 || failed) { + statusBarMessage += + pluralize('spec', stateBuilder.specsExecuted) + + ', ' + + pluralize('failure', stateBuilder.failureCount); + if (stateBuilder.pendingSpecCount) { + statusBarMessage += + ', ' + pluralize('pending spec', stateBuilder.pendingSpecCount); + } + } + + if (doneResult.overallStatus === 'passed') { + statusBarClassName += ' jasmine-passed '; + } else if (doneResult.overallStatus === 'incomplete') { + statusBarClassName += ' jasmine-incomplete '; + statusBarMessage = + 'Incomplete: ' + + doneResult.incompleteReason + + ', ' + + statusBarMessage; + } else { + statusBarClassName += ' jasmine-failed '; + } + + var seedBar; + if (order && order.random) { + seedBar = createDom( + 'span', + { className: 'jasmine-seed-bar' }, + ', randomized with seed ', + createDom( + 'a', + { + title: 'randomized with seed ' + order.seed, + href: seedHref(order.seed) + }, + order.seed + ) + ); + } + + alert.appendChild( + createDom( + 'span', + { className: statusBarClassName }, + statusBarMessage, + seedBar + ) + ); + + var errorBarClassName = 'jasmine-bar jasmine-errored'; + var afterAllMessagePrefix = 'AfterAll '; + + for (i = 0; i < globalFailures.length; i++) { + alert.appendChild( + createDom( + 'span', + { className: errorBarClassName }, + globalFailureMessage(globalFailures[i]) + ) + ); + } + + function globalFailureMessage(failure) { + if (failure.globalErrorType === 'load') { + var prefix = 'Error during loading: ' + failure.message; + + if (failure.filename) { + return ( + prefix + ' in ' + failure.filename + ' line ' + failure.lineno + ); + } else { + return prefix; + } + } else { + return afterAllMessagePrefix + failure.message; + } + } + + addDeprecationWarnings(doneResult); + + for (i = 0; i < deprecationWarnings.length; i++) { + var context; + + switch (deprecationWarnings[i].runnableType) { + case 'spec': + context = '(in spec: ' + deprecationWarnings[i].runnableName + ')'; + break; + case 'suite': + context = '(in suite: ' + deprecationWarnings[i].runnableName + ')'; + break; + default: + context = ''; + } + + alert.appendChild( + createDom( + 'span', + { className: 'jasmine-bar jasmine-warning' }, + 'DEPRECATION: ' + deprecationWarnings[i].message, + createDom('br'), + context + ) + ); + } + + var results = find('.jasmine-results'); + results.appendChild(summary); + + summaryList(stateBuilder.topResults, summary); + + if (failures.length) { + alert.appendChild( + createDom( + 'span', + { className: 'jasmine-menu jasmine-bar jasmine-spec-list' }, + createDom('span', {}, 'Spec List | '), + createDom( + 'a', + { className: 'jasmine-failures-menu', href: '#' }, + 'Failures' + ) + ) + ); + alert.appendChild( + createDom( + 'span', + { className: 'jasmine-menu jasmine-bar jasmine-failure-list' }, + createDom( + 'a', + { className: 'jasmine-spec-list-menu', href: '#' }, + 'Spec List' + ), + createDom('span', {}, ' | Failures ') + ) + ); + + find('.jasmine-failures-menu').onclick = function() { + setMenuModeTo('jasmine-failure-list'); + return false; + }; + find('.jasmine-spec-list-menu').onclick = function() { + setMenuModeTo('jasmine-spec-list'); + return false; + }; + + setMenuModeTo('jasmine-failure-list'); + + var failureNode = find('.jasmine-failures'); + for (i = 0; i < failures.length; i++) { + failureNode.appendChild(failures[i]); + } + } + }; + + return this; + + function failureDom(result) { + var failure = createDom( + 'div', + { className: 'jasmine-spec-detail jasmine-failed' }, + failureDescription(result, stateBuilder.currentParent), + createDom('div', { className: 'jasmine-messages' }) + ); + var messages = failure.childNodes[1]; + + for (var i = 0; i < result.failedExpectations.length; i++) { + var expectation = result.failedExpectations[i]; + messages.appendChild( + createDom( + 'div', + { className: 'jasmine-result-message' }, + expectation.message + ) + ); + messages.appendChild( + createDom( + 'div', + { className: 'jasmine-stack-trace' }, + expectation.stack + ) + ); + } + + if (result.failedExpectations.length === 0) { + messages.appendChild( + createDom( + 'div', + { className: 'jasmine-result-message' }, + 'Spec has no expectations' + ) + ); + } + + return failure; + } + + function summaryList(resultsTree, domParent) { + var specListNode; + for (var i = 0; i < resultsTree.children.length; i++) { + var resultNode = resultsTree.children[i]; + if (filterSpecs && !hasActiveSpec(resultNode)) { + continue; + } + if (resultNode.type === 'suite') { + var suiteListNode = createDom( + 'ul', + { className: 'jasmine-suite', id: 'suite-' + resultNode.result.id }, + createDom( + 'li', + { + className: + 'jasmine-suite-detail jasmine-' + resultNode.result.status + }, + createDom( + 'a', + { href: specHref(resultNode.result) }, + resultNode.result.description + ) + ) + ); + + summaryList(resultNode, suiteListNode); + domParent.appendChild(suiteListNode); + } + if (resultNode.type === 'spec') { + if (domParent.getAttribute('class') !== 'jasmine-specs') { + specListNode = createDom('ul', { className: 'jasmine-specs' }); + domParent.appendChild(specListNode); + } + var specDescription = resultNode.result.description; + if (noExpectations(resultNode.result)) { + specDescription = 'SPEC HAS NO EXPECTATIONS ' + specDescription; + } + if ( + resultNode.result.status === 'pending' && + resultNode.result.pendingReason !== '' + ) { + specDescription = + specDescription + + ' PENDING WITH MESSAGE: ' + + resultNode.result.pendingReason; + } + specListNode.appendChild( + createDom( + 'li', + { + className: 'jasmine-' + resultNode.result.status, + id: 'spec-' + resultNode.result.id + }, + createDom( + 'a', + { href: specHref(resultNode.result) }, + specDescription + ) + ) + ); + } + } + } + + function optionsMenu(config) { + var optionsMenuDom = createDom( + 'div', + { className: 'jasmine-run-options' }, + createDom('span', { className: 'jasmine-trigger' }, 'Options'), + createDom( + 'div', + { className: 'jasmine-payload' }, + createDom( + 'div', + { className: 'jasmine-stop-on-failure' }, + createDom('input', { + className: 'jasmine-fail-fast', + id: 'jasmine-fail-fast', + type: 'checkbox' + }), + createDom( + 'label', + { className: 'jasmine-label', for: 'jasmine-fail-fast' }, + 'stop execution on spec failure' + ) + ), + createDom( + 'div', + { className: 'jasmine-throw-failures' }, + createDom('input', { + className: 'jasmine-throw', + id: 'jasmine-throw-failures', + type: 'checkbox' + }), + createDom( + 'label', + { className: 'jasmine-label', for: 'jasmine-throw-failures' }, + 'stop spec on expectation failure' + ) + ), + createDom( + 'div', + { className: 'jasmine-random-order' }, + createDom('input', { + className: 'jasmine-random', + id: 'jasmine-random-order', + type: 'checkbox' + }), + createDom( + 'label', + { className: 'jasmine-label', for: 'jasmine-random-order' }, + 'run tests in random order' + ) + ), + createDom( + 'div', + { className: 'jasmine-hide-disabled' }, + createDom('input', { + className: 'jasmine-disabled', + id: 'jasmine-hide-disabled', + type: 'checkbox' + }), + createDom( + 'label', + { className: 'jasmine-label', for: 'jasmine-hide-disabled' }, + 'hide disabled tests' + ) + ) + ) + ); + + var failFastCheckbox = optionsMenuDom.querySelector('#jasmine-fail-fast'); + failFastCheckbox.checked = config.failFast; + failFastCheckbox.onclick = function() { + navigateWithNewParam('failFast', !config.failFast); + }; + + var throwCheckbox = optionsMenuDom.querySelector( + '#jasmine-throw-failures' + ); + throwCheckbox.checked = config.oneFailurePerSpec; + throwCheckbox.onclick = function() { + navigateWithNewParam('oneFailurePerSpec', !config.oneFailurePerSpec); + }; + + var randomCheckbox = optionsMenuDom.querySelector( + '#jasmine-random-order' + ); + randomCheckbox.checked = config.random; + randomCheckbox.onclick = function() { + navigateWithNewParam('random', !config.random); + }; + + var hideDisabled = optionsMenuDom.querySelector('#jasmine-hide-disabled'); + hideDisabled.checked = config.hideDisabled; + hideDisabled.onclick = function() { + navigateWithNewParam('hideDisabled', !config.hideDisabled); + }; + + var optionsTrigger = optionsMenuDom.querySelector('.jasmine-trigger'), + optionsPayload = optionsMenuDom.querySelector('.jasmine-payload'), + isOpen = /\bjasmine-open\b/; + + optionsTrigger.onclick = function() { + if (isOpen.test(optionsPayload.className)) { + optionsPayload.className = optionsPayload.className.replace( + isOpen, + '' + ); + } else { + optionsPayload.className += ' jasmine-open'; + } + }; + + return optionsMenuDom; + } + + function failureDescription(result, suite) { + var wrapper = createDom( + 'div', + { className: 'jasmine-description' }, + createDom( + 'a', + { title: result.description, href: specHref(result) }, + result.description + ) + ); + var suiteLink; + + while (suite && suite.parent) { + wrapper.insertBefore(createTextNode(' > '), wrapper.firstChild); + suiteLink = createDom( + 'a', + { href: suiteHref(suite) }, + suite.result.description + ); + wrapper.insertBefore(suiteLink, wrapper.firstChild); + + suite = suite.parent; + } + + return wrapper; + } + + function suiteHref(suite) { + var els = []; + + while (suite && suite.parent) { + els.unshift(suite.result.description); + suite = suite.parent; + } + + // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 + return ( + (window.location.pathname || '') + + addToExistingQueryString('spec', els.join(' ')) + ); + } + + function addDeprecationWarnings(result, runnableType) { + if (result && result.deprecationWarnings) { + for (var i = 0; i < result.deprecationWarnings.length; i++) { + var warning = result.deprecationWarnings[i].message; + if (!j$.util.arrayContains(warning)) { + deprecationWarnings.push({ + message: warning, + runnableName: result.fullName, + runnableType: runnableType + }); + } + } + } + } + + function find(selector) { + return getContainer().querySelector('.jasmine_html-reporter ' + selector); + } + + function clearPrior() { + // return the reporter + var oldReporter = find(''); + + if (oldReporter) { + getContainer().removeChild(oldReporter); + } + } + + function createDom(type, attrs, childrenVarArgs) { + var el = createElement(type); + + for (var i = 2; i < arguments.length; i++) { + var child = arguments[i]; + + if (typeof child === 'string') { + el.appendChild(createTextNode(child)); + } else { + if (child) { + el.appendChild(child); + } + } + } + + for (var attr in attrs) { + if (attr == 'className') { + el[attr] = attrs[attr]; + } else { + el.setAttribute(attr, attrs[attr]); + } + } + + return el; + } + + function pluralize(singular, count) { + var word = count == 1 ? singular : singular + 's'; + + return '' + count + ' ' + word; + } + + function specHref(result) { + // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 + return ( + (window.location.pathname || '') + + addToExistingQueryString('spec', result.fullName) + ); + } + + function seedHref(seed) { + // include window.location.pathname to fix issue with karma-jasmine-html-reporter in angular: see https://github.com/jasmine/jasmine/issues/1906 + return ( + (window.location.pathname || '') + + addToExistingQueryString('seed', seed) + ); + } + + function defaultQueryString(key, value) { + return '?' + key + '=' + value; + } + + function setMenuModeTo(mode) { + htmlReporterMain.setAttribute('class', 'jasmine_html-reporter ' + mode); + } + + function noExpectations(result) { + var allExpectations = + result.failedExpectations.length + result.passedExpectations.length; + + return ( + allExpectations === 0 && + (result.status === 'passed' || result.status === 'failed') + ); + } + + function hasActiveSpec(resultNode) { + if (resultNode.type == 'spec' && resultNode.result.status != 'excluded') { + return true; + } + + if (resultNode.type == 'suite') { + for (var i = 0, j = resultNode.children.length; i < j; i++) { + if (hasActiveSpec(resultNode.children[i])) { + return true; + } + } + } + } + } + + return HtmlReporter; +}; + +jasmineRequire.HtmlSpecFilter = function() { + function HtmlSpecFilter(options) { + var filterString = + options && + options.filterString() && + options.filterString().replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); + var filterPattern = new RegExp(filterString); + + this.matches = function(specName) { + return filterPattern.test(specName); + }; + } + + return HtmlSpecFilter; +}; + +jasmineRequire.ResultsNode = function() { + function ResultsNode(result, type, parent) { + this.result = result; + this.type = type; + this.parent = parent; + + this.children = []; + + this.addChild = function(result, type) { + this.children.push(new ResultsNode(result, type, this)); + }; + + this.last = function() { + return this.children[this.children.length - 1]; + }; + + this.updateResult = function(result) { + this.result = result; + }; + } + + return ResultsNode; +}; + +jasmineRequire.QueryString = function() { + function QueryString(options) { + this.navigateWithNewParam = function(key, value) { + options.getWindowLocation().search = this.fullStringWithNewParam( + key, + value + ); + }; + + this.fullStringWithNewParam = function(key, value) { + var paramMap = queryStringToParamMap(); + paramMap[key] = value; + return toQueryString(paramMap); + }; + + this.getParam = function(key) { + return queryStringToParamMap()[key]; + }; + + return this; + + function toQueryString(paramMap) { + var qStrPairs = []; + for (var prop in paramMap) { + qStrPairs.push( + encodeURIComponent(prop) + '=' + encodeURIComponent(paramMap[prop]) + ); + } + return '?' + qStrPairs.join('&'); + } + + function queryStringToParamMap() { + var paramStr = options.getWindowLocation().search.substring(1), + params = [], + paramMap = {}; + + if (paramStr.length > 0) { + params = paramStr.split('&'); + for (var i = 0; i < params.length; i++) { + var p = params[i].split('='); + var value = decodeURIComponent(p[1]); + if (value === 'true' || value === 'false') { + value = JSON.parse(value); + } + paramMap[decodeURIComponent(p[0])] = value; + } + } + + return paramMap; + } + } + + return QueryString; +}; diff --git a/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/jasmine.css b/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/jasmine.css new file mode 100644 index 0000000..dba3ca9 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/jasmine.css @@ -0,0 +1,271 @@ +@charset "UTF-8"; +body { + overflow-y: scroll; +} + +.jasmine_html-reporter { + width: 100%; + background-color: #eee; + padding: 5px; + margin: -8px; + font-size: 11px; + font-family: Monaco, "Lucida Console", monospace; + line-height: 14px; + color: #333; +} +.jasmine_html-reporter a { + text-decoration: none; +} +.jasmine_html-reporter a:hover { + text-decoration: underline; +} +.jasmine_html-reporter p, .jasmine_html-reporter h1, .jasmine_html-reporter h2, .jasmine_html-reporter h3, .jasmine_html-reporter h4, .jasmine_html-reporter h5, .jasmine_html-reporter h6 { + margin: 0; + line-height: 14px; +} +.jasmine_html-reporter .jasmine-banner, +.jasmine_html-reporter .jasmine-symbol-summary, +.jasmine_html-reporter .jasmine-summary, +.jasmine_html-reporter .jasmine-result-message, +.jasmine_html-reporter .jasmine-spec .jasmine-description, +.jasmine_html-reporter .jasmine-spec-detail .jasmine-description, +.jasmine_html-reporter .jasmine-alert .jasmine-bar, +.jasmine_html-reporter .jasmine-stack-trace { + padding-left: 9px; + padding-right: 9px; +} +.jasmine_html-reporter .jasmine-banner { + position: relative; +} +.jasmine_html-reporter .jasmine-banner .jasmine-title { + background: url("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAFoAAAAZCAMAAACGusnyAAACdlBMVEX/////AP+AgICqVaqAQICZM5mAVYCSSZKAQICOOY6ATYCLRouAQICJO4mSSYCIRIiPQICHPIeOR4CGQ4aMQICGPYaLRoCFQ4WKQICPPYWJRYCOQoSJQICNPoSIRICMQoSHQICHRICKQoOHQICKPoOJO4OJQYOMQICMQ4CIQYKLQICIPoKLQ4CKQICNPoKJQISMQ4KJQoSLQYKJQISLQ4KIQoSKQYKIQICIQISMQoSKQYKLQIOLQoOJQYGLQIOKQIOMQoGKQYOLQYGKQIOLQoGJQYOJQIOKQYGJQIOKQoGKQIGLQIKLQ4KKQoGLQYKJQIGKQYKJQIGKQIKJQoGKQYKLQIGKQYKLQIOJQoKKQoOJQYKKQIOJQoKKQoOKQIOLQoKKQYOLQYKJQIOKQoKKQYKKQoKJQYOKQYKLQIOKQoKLQYOKQYKLQIOJQoGKQYKJQYGJQoGKQYKLQoGLQYGKQoGJQYKKQYGJQIKKQoGJQYKLQIKKQYGLQYKKQYGKQYGKQYKJQYOKQoKJQYOKQYKLQYOLQYOKQYKLQYOKQoKKQYKKQYOKQYOJQYKKQYKLQYKKQIKKQoKKQYKKQYKKQoKJQIKKQYKLQYKKQYKKQIKKQYKKQYKKQYKKQIKKQYKJQYGLQYGKQYKKQYKKQYGKQIKKQYGKQYOJQoKKQYOLQYKKQYOKQoKKQYKKQoKKQYKKQYKJQYKLQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKJQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKLQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKKQYKmIDpEAAAA0XRSTlMAAQIDBAUGBwgJCgsMDQ4PEBESExQVFhcYGRobHB0eHyAiIyQlJycoKissLS4wMTQ1Njc4OTo7PDw+P0BCQ0RISUpLTE1OUFNUVVdYWFlaW15fYGFiY2ZnaGlqa2xtb3BxcnN0dnh5ent8fX5/gIGChIWIioyNjo+QkZOUlZaYmZqbnJ2eoKGio6WmqKmsra6vsLGztre4ubq7vL2+wMHDxMjJysvNzs/Q0dLU1tfY2dvc3t/g4eLj5ebn6Onq6+zt7u/w8vP09fb3+Pn6+/z9/vkVQXAAAAMaSURBVHhe5dXxV1N1GMfxz2ABbDgIAm5VDJOyVDIJLUMaVpBWUZUaGbmqoGpZRSiGiRWp6KoZ5AB0ZY50RImZQIlahKkMYXv/R90dBvET/rJfOr3Ouc8v99zPec59zvf56j+vYKlViSf7250X4Mr3O29Tgq08BdGB4DhcekEJ5YkQKFsgWZdtj9JpV+I8xPjLFqkrsEIqO8PHSpis36jWazcqjEsfJjkvRssVU37SdIOu4XCf5vEJPsnwJpnRNU9JmxhMk8l1gehIrq7hTFjzOD+Vf88629qKMJVNltInFeRexRQyJlNeqd1iGDlSzrIUIyXbyFfm3RYprcQRe7lqtWyGYbfc6dT0R2vmdOOkX3u55C1rP37ftiH+tDby4r/RBT0w8TyEkr+epB9XgPDmSYYWbrhCuFYaIyw3fDQAXTnSkh+ANofiHmWf9l+FY1I90FdQTetstO00o23novzVsJ7uB3/C5TkbjRwZ5JerwV4iRWq9HFbFMaK/d0TYqayRiQPuIxxS3Bu8JWU90/60tKi7vkhaznez0a/TbVOKj5CaOZh6fWG6/Lyv9B/ZLR1gw/S/fpbeVD3MCW1li6SvWDOn65tr99/uvWtBS0XDm4s1t+sOHpG0kpBKx/l77wOSnxLpcx6TXmXLTPQOKYOf9Q1dfr8/SJ2mFdCvl1Yl93DiHUZvXeLJbGSzYu5gVJ2slbSakOR8dxCq5adQ2oFLqsE9Ex3L4qQO0eOPeU5x56bypXp4onSEb5OkICX6lDat55TeoztNKQcJaakrz9KCb95oD69IKq+yKW4XPjknaS52V0TZqE2cTtXjcHSCRmUO88e+85hj3EP74i9p8pylw7lxgMDyyl6OV7ZejnjNMfatu87LxRbH0IS35gt2a4ZjmGpVBdKK3Wr6INk8jWWSGqbA55CKgjBRC6E9w78ydTg3ABS3AFV1QN0Y4Aa2pgEjWnQURj9L0ayK6R2ysEqxHUKzYnLvvyU+i9KM2JHJzE4vyZOyDcOwOsySajeLPc8sNvPJkFlyJd20wpqAzZeAfZ3oWybxd+P/3j+SG3uSBdf2VQAAAABJRU5ErkJggg==") no-repeat; + background: url("data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+CjwhLS0gQ3JlYXRlZCB3aXRoIElua3NjYXBlIChodHRwOi8vd3d3Lmlua3NjYXBlLm9yZy8pIC0tPgoKPHN2ZwogICB4bWxuczpkYz0iaHR0cDovL3B1cmwub3JnL2RjL2VsZW1lbnRzLzEuMS8iCiAgIHhtbG5zOmNjPSJodHRwOi8vY3JlYXRpdmVjb21tb25zLm9yZy9ucyMiCiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIKICAgeG1sbnM6c3ZnPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIKICAgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIgogICB4bWxuczppbmtzY2FwZT0iaHR0cDovL3d3dy5pbmtzY2FwZS5vcmcvbmFtZXNwYWNlcy9pbmtzY2FwZSIKICAgdmVyc2lvbj0iMS4xIgogICB3aWR0aD0iNjgxLjk2MjUyIgogICBoZWlnaHQ9IjE4Ny41IgogICBpZD0ic3ZnMiIKICAgeG1sOnNwYWNlPSJwcmVzZXJ2ZSI+PG1ldGFkYXRhCiAgICAgaWQ9Im1ldGFkYXRhOCI+PHJkZjpSREY+PGNjOldvcmsKICAgICAgICAgcmRmOmFib3V0PSIiPjxkYzpmb3JtYXQ+aW1hZ2Uvc3ZnK3htbDwvZGM6Zm9ybWF0PjxkYzp0eXBlCiAgICAgICAgICAgcmRmOnJlc291cmNlPSJodHRwOi8vcHVybC5vcmcvZGMvZGNtaXR5cGUvU3RpbGxJbWFnZSIgLz48L2NjOldvcms+PC9yZGY6UkRGPjwvbWV0YWRhdGE+PGRlZnMKICAgICBpZD0iZGVmczYiPjxjbGlwUGF0aAogICAgICAgaWQ9ImNsaXBQYXRoMTgiPjxwYXRoCiAgICAgICAgIGQ9Ik0gMCwxNTAwIDAsMCBsIDU0NTUuNzQsMCAwLDE1MDAgTCAwLDE1MDAgeiIKICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgaWQ9InBhdGgyMCIgLz48L2NsaXBQYXRoPjwvZGVmcz48ZwogICAgIHRyYW5zZm9ybT0ibWF0cml4KDEuMjUsMCwwLC0xLjI1LDAsMTg3LjUpIgogICAgIGlkPSJnMTAiPjxnCiAgICAgICB0cmFuc2Zvcm09InNjYWxlKDAuMSwwLjEpIgogICAgICAgaWQ9ImcxMiI+PGcKICAgICAgICAgaWQ9ImcxNCI+PGcKICAgICAgICAgICBjbGlwLXBhdGg9InVybCgjY2xpcFBhdGgxOCkiCiAgICAgICAgICAgaWQ9ImcxNiI+PHBhdGgKICAgICAgICAgICAgIGQ9Im0gMTU0NCw1OTkuNDM0IGMgMC45MiwtNDAuMzUyIDI1LjY4LC04MS42MDIgNzEuNTMsLTgxLjYwMiAyNy41MSwwIDQ3LjY4LDEyLjgzMiA2MS40NCwzNS43NTQgMTIuODMsMjIuOTMgMTIuODMsNTYuODUyIDEyLjgzLDgyLjUyNyBsIDAsMzI5LjE4NCAtNzEuNTIsMCAwLDEwNC41NDMgMjY2LjgzLDAgMCwtMTA0LjU0MyAtNzAuNiwwIDAsLTM0NC43NyBjIDAsLTU4LjY5MSAtMy42OCwtMTA0LjUzMSAtNDQuOTMsLTE1Mi4yMTggLTM2LjY4LC00Mi4xOCAtOTYuMjgsLTY2LjAyIC0xNTMuMTQsLTY2LjAyIC0xMTcuMzcsMCAtMjA3LjI0LDc3Ljk0MSAtMjAyLjY0LDE5Ny4xNDUgbCAxMzAuMiwwIgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoMjIiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDIzMDEuNCw2NjIuNjk1IGMgMCw4MC43MDMgLTY2Ljk0LDE0NS44MTMgLTE0Ny42MywxNDUuODEzIC04My40NCwwIC0xNDcuNjMsLTY4Ljc4MSAtMTQ3LjYzLC0xNTEuMzAxIDAsLTc5Ljc4NSA2Ni45NCwtMTQ1LjgwMSAxNDUuOCwtMTQ1LjgwMSA4NC4zNSwwIDE0OS40Niw2Ny44NTIgMTQ5LjQ2LDE1MS4yODkgeiBtIC0xLjgzLC0xODEuNTQ3IGMgLTM1Ljc3LC01NC4wOTcgLTkzLjUzLC03OC44NTkgLTE1Ny43MiwtNzguODU5IC0xNDAuMywwIC0yNTEuMjQsMTE2LjQ0OSAtMjUxLjI0LDI1NC45MTggMCwxNDIuMTI5IDExMy43LDI2MC40MSAyNTYuNzQsMjYwLjQxIDYzLjI3LDAgMTE4LjI5LC0yOS4zMzYgMTUyLjIyLC04Mi41MjMgbCAwLDY5LjY4NyAxNzUuMTQsMCAwLC0xMDQuNTI3IC02MS40NCwwIDAsLTI4MC41OTggNjEuNDQsMCAwLC0xMDQuNTI3IC0xNzUuMTQsMCAwLDY2LjAxOSIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDI0IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSAyNjIyLjMzLDU1Ny4yNTggYyAzLjY3LC00NC4wMTYgMzMuMDEsLTczLjM0OCA3OC44NiwtNzMuMzQ4IDMzLjkzLDAgNjYuOTMsMjMuODI0IDY2LjkzLDYwLjUwNCAwLDQ4LjYwNiAtNDUuODQsNTYuODU2IC04My40NCw2Ni45NDEgLTg1LjI4LDIyLjAwNCAtMTc4LjgxLDQ4LjYwNiAtMTc4LjgxLDE1NS44NzkgMCw5My41MzYgNzguODYsMTQ3LjYzMyAxNjUuOTgsMTQ3LjYzMyA0NCwwIDgzLjQzLC05LjE3NiAxMTAuOTQsLTQ0LjAwOCBsIDAsMzMuOTIyIDgyLjUzLDAgMCwtMTMyLjk2NSAtMTA4LjIxLDAgYyAtMS44MywzNC44NTYgLTI4LjQyLDU3Ljc3NCAtNjMuMjYsNTcuNzc0IC0zMC4yNiwwIC02Mi4zNSwtMTcuNDIyIC02Mi4zNSwtNTEuMzQ4IDAsLTQ1Ljg0NyA0NC45MywtNTUuOTMgODAuNjksLTY0LjE4IDg4LjAyLC0yMC4xNzUgMTgyLjQ3LC00Ny42OTUgMTgyLjQ3LC0xNTcuNzM0IDAsLTk5LjAyNyAtODMuNDQsLTE1NC4wMzkgLTE3NS4xMywtMTU0LjAzOSAtNDkuNTMsMCAtOTQuNDYsMTUuNTgyIC0xMjYuNTUsNTMuMTggbCAwLC00MC4zNCAtODUuMjcsMCAwLDE0Mi4xMjkgMTE0LjYyLDAiCiAgICAgICAgICAgICBpbmtzY2FwZTpjb25uZWN0b3ItY3VydmF0dXJlPSIwIgogICAgICAgICAgICAgaWQ9InBhdGgyNiIKICAgICAgICAgICAgIHN0eWxlPSJmaWxsOiM4YTQxODI7ZmlsbC1vcGFjaXR5OjE7ZmlsbC1ydWxlOm5vbnplcm87c3Ryb2tlOm5vbmUiIC8+PHBhdGgKICAgICAgICAgICAgIGQ9Im0gMjk4OC4xOCw4MDAuMjU0IC02My4yNiwwIDAsMTA0LjUyNyAxNjUuMDUsMCAwLC03My4zNTUgYyAzMS4xOCw1MS4zNDcgNzguODYsODUuMjc3IDE0MS4yMSw4NS4yNzcgNjcuODUsMCAxMjQuNzEsLTQxLjI1OCAxNTIuMjEsLTEwMi42OTkgMjYuNiw2Mi4zNTEgOTIuNjIsMTAyLjY5OSAxNjAuNDcsMTAyLjY5OSA1My4xOSwwIDEwNS40NiwtMjIgMTQxLjIxLC02Mi4zNTEgMzguNTIsLTQ0LjkzOCAzOC41MiwtOTMuNTMyIDM4LjUyLC0xNDkuNDU3IGwgMCwtMTg1LjIzOSA2My4yNywwIDAsLTEwNC41MjcgLTIzOC40MiwwIDAsMTA0LjUyNyA2My4yOCwwIDAsMTU3LjcxNSBjIDAsMzIuMTAyIDAsNjAuNTI3IC0xNC42Nyw4OC45NTcgLTE4LjM0LDI2LjU4MiAtNDguNjEsNDAuMzQ0IC03OS43Nyw0MC4zNDQgLTMwLjI2LDAgLTYzLjI4LC0xMi44NDQgLTgyLjUzLC0zNi42NzIgLTIyLjkzLC0yOS4zNTUgLTIyLjkzLC01Ni44NjMgLTIyLjkzLC05Mi42MjkgbCAwLC0xNTcuNzE1IDYzLjI3LDAgMCwtMTA0LjUyNyAtMjM4LjQxLDAgMCwxMDQuNTI3IDYzLjI4LDAgMCwxNTAuMzgzIGMgMCwyOS4zNDggMCw2Ni4wMjMgLTE0LjY3LDkxLjY5OSAtMTUuNTksMjkuMzM2IC00Ny42OSw0NC45MzQgLTgwLjcsNDQuOTM0IC0zMS4xOCwwIC01Ny43NywtMTEuMDA4IC03Ny45NCwtMzUuNzc0IC0yNC43NywtMzAuMjUzIC0yNi42LC02Mi4zNDMgLTI2LjYsLTk5Ljk0MSBsIDAsLTE1MS4zMDEgNjMuMjcsMCAwLC0xMDQuNTI3IC0yMzguNCwwIDAsMTA0LjUyNyA2My4yNiwwIDAsMjgwLjU5OCIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDI4IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSAzOTk4LjY2LDk1MS41NDcgLTExMS44NywwIDAsMTE4LjI5MyAxMTEuODcsMCAwLC0xMTguMjkzIHogbSAwLC00MzEuODkxIDYzLjI3LDAgMCwtMTA0LjUyNyAtMjM5LjMzLDAgMCwxMDQuNTI3IDY0LjE5LDAgMCwyODAuNTk4IC02My4yNywwIDAsMTA0LjUyNyAxNzUuMTQsMCAwLC0zODUuMTI1IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoMzAiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDQxNTkuMTIsODAwLjI1NCAtNjMuMjcsMCAwLDEwNC41MjcgMTc1LjE0LDAgMCwtNjkuNjg3IGMgMjkuMzUsNTQuMTAxIDg0LjM2LDgwLjY5OSAxNDQuODcsODAuNjk5IDUzLjE5LDAgMTA1LjQ1LC0yMi4wMTYgMTQxLjIyLC02MC41MjcgNDAuMzQsLTQ0LjkzNCA0MS4yNiwtODguMDMyIDQxLjI2LC0xNDMuOTU3IGwgMCwtMTkxLjY1MyA2My4yNywwIDAsLTEwNC41MjcgLTIzOC40LDAgMCwxMDQuNTI3IDYzLjI2LDAgMCwxNTguNjM3IGMgMCwzMC4yNjIgMCw2MS40MzQgLTE5LjI2LDg4LjAzNSAtMjAuMTcsMjYuNTgyIC01My4xOCwzOS40MTQgLTg2LjE5LDM5LjQxNCAtMzMuOTMsMCAtNjguNzcsLTEzLjc1IC04OC45NCwtNDEuMjUgLTIxLjA5LC0yNy41IC0yMS4wOSwtNjkuNjg3IC0yMS4wOSwtMTAyLjcwNyBsIDAsLTE0Mi4xMjkgNjMuMjYsMCAwLC0xMDQuNTI3IC0yMzguNCwwIDAsMTA0LjUyNyA2My4yNywwIDAsMjgwLjU5OCIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDMyIgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA1MDgyLjQ4LDcwMy45NjUgYyAtMTkuMjQsNzAuNjA1IC04MS42LDExNS41NDcgLTE1NC4wNCwxMTUuNTQ3IC02Ni4wNCwwIC0xMjkuMywtNTEuMzQ4IC0xNDMuMDUsLTExNS41NDcgbCAyOTcuMDksMCB6IG0gODUuMjcsLTE0NC44ODMgYyAtMzguNTEsLTkzLjUyMyAtMTI5LjI3LC0xNTYuNzkzIC0yMzEuMDUsLTE1Ni43OTMgLTE0My4wNywwIC0yNTcuNjgsMTExLjg3MSAtMjU3LjY4LDI1NS44MzYgMCwxNDQuODgzIDEwOS4xMiwyNjEuMzI4IDI1NC45MSwyNjEuMzI4IDY3Ljg3LDAgMTM1LjcyLC0zMC4yNTggMTgzLjM5LC03OC44NjMgNDguNjIsLTUxLjM0NCA2OC43OSwtMTEzLjY5NSA2OC43OSwtMTgzLjM4MyBsIC0zLjY3LC0zOS40MzQgLTM5Ni4xMywwIGMgMTQuNjcsLTY3Ljg2MyA3Ny4wMywtMTE3LjM2MyAxNDYuNzIsLTExNy4zNjMgNDguNTksMCA5MC43NiwxOC4zMjggMTE4LjI4LDU4LjY3MiBsIDExNi40NCwwIgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoMzQiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDY5MC44OTUsODUwLjcwMyA5MC43NSwwIDIyLjU0MywzMS4wMzUgMCwyNDMuMTIyIC0xMzUuODI5LDAgMCwtMjQzLjE0MSAyMi41MzYsLTMxLjAxNiIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDM2IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA2MzIuMzk1LDc0Mi4yNTggMjguMDM5LDg2LjMwNCAtMjIuNTUxLDMxLjA0IC0yMzEuMjIzLDc1LjEyOCAtNDEuOTc2LC0xMjkuMTgzIDIzMS4yNTcsLTc1LjEzNyAzNi40NTQsMTEuODQ4IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoMzgiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDcxNy40NDksNjUzLjEwNSAtNzMuNDEsNTMuMzYgLTM2LjQ4OCwtMTEuODc1IC0xNDIuOTAzLC0xOTYuNjkyIDEwOS44ODMsLTc5LjgyOCAxNDIuOTE4LDE5Ni43MDMgMCwzOC4zMzIiCiAgICAgICAgICAgICBpbmtzY2FwZTpjb25uZWN0b3ItY3VydmF0dXJlPSIwIgogICAgICAgICAgICAgaWQ9InBhdGg0MCIKICAgICAgICAgICAgIHN0eWxlPSJmaWxsOiM4YTQxODI7ZmlsbC1vcGFjaXR5OjE7ZmlsbC1ydWxlOm5vbnplcm87c3Ryb2tlOm5vbmUiIC8+PHBhdGgKICAgICAgICAgICAgIGQ9Im0gODI4LjUyLDcwNi40NjUgLTczLjQyNiwtNTMuMzQgMC4wMTEsLTM4LjM1OSBMIDg5OC4wMDQsNDE4LjA3IDEwMDcuOSw0OTcuODk4IDg2NC45NzMsNjk0LjYwOSA4MjguNTIsNzA2LjQ2NSIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDQyIgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA4MTIuMDg2LDgyOC41ODYgMjguMDU1LC04Ni4zMiAzNi40ODQsLTExLjgzNiAyMzEuMjI1LDc1LjExNyAtNDEuOTcsMTI5LjE4MyAtMjMxLjIzOSwtNzUuMTQgLTIyLjU1NSwtMzEuMDA0IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoNDQiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDczNi4zMDEsMTMzNS44OCBjIC0zMjMuMDQ3LDAgLTU4NS44NzUsLTI2Mi43OCAtNTg1Ljg3NSwtNTg1Ljc4MiAwLC0zMjMuMTE4IDI2Mi44MjgsLTU4NS45NzcgNTg1Ljg3NSwtNTg1Ljk3NyAzMjMuMDE5LDAgNTg1LjgwOSwyNjIuODU5IDU4NS44MDksNTg1Ljk3NyAwLDMyMy4wMDIgLTI2Mi43OSw1ODUuNzgyIC01ODUuODA5LDU4NS43ODIgbCAwLDAgeiBtIDAsLTExOC42MSBjIDI1Ny45NzIsMCA0NjcuMTg5LC0yMDkuMTMgNDY3LjE4OSwtNDY3LjE3MiAwLC0yNTguMTI5IC0yMDkuMjE3LC00NjcuMzQ4IC00NjcuMTg5LC00NjcuMzQ4IC0yNTguMDc0LDAgLTQ2Ny4yNTQsMjA5LjIxOSAtNDY3LjI1NCw0NjcuMzQ4IDAsMjU4LjA0MiAyMDkuMTgsNDY3LjE3MiA0NjcuMjU0LDQ2Ny4xNzIiCiAgICAgICAgICAgICBpbmtzY2FwZTpjb25uZWN0b3ItY3VydmF0dXJlPSIwIgogICAgICAgICAgICAgaWQ9InBhdGg0NiIKICAgICAgICAgICAgIHN0eWxlPSJmaWxsOiM4YTQxODI7ZmlsbC1vcGFjaXR5OjE7ZmlsbC1ydWxlOm5vbnplcm87c3Ryb2tlOm5vbmUiIC8+PHBhdGgKICAgICAgICAgICAgIGQ9Im0gMTA5MS4xMyw2MTkuODgzIC0xNzUuNzcxLDU3LjEyMSAxMS42MjksMzUuODA4IDE3NS43NjIsLTU3LjEyMSAtMTEuNjIsLTM1LjgwOCIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDQ4IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0iTSA4NjYuOTU3LDkwMi4wNzQgODM2LjUsOTI0LjE5OSA5NDUuMTIxLDEwNzMuNzMgOTc1LjU4NiwxMDUxLjYxIDg2Ni45NTcsOTAyLjA3NCIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDUwIgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0iTSA2MDcuNDY1LDkwMy40NDUgNDk4Ljg1NSwxMDUyLjk3IDUyOS4zMiwxMDc1LjEgNjM3LjkzLDkyNS41NjYgNjA3LjQ2NSw5MDMuNDQ1IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoNTIiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjxwYXRoCiAgICAgICAgICAgICBkPSJtIDM4MC42ODgsNjIyLjEyOSAtMTEuNjI2LDM1LjgwMSAxNzUuNzU4LDU3LjA5IDExLjYyMSwtMzUuODAxIC0xNzUuNzUzLC01Ny4wOSIKICAgICAgICAgICAgIGlua3NjYXBlOmNvbm5lY3Rvci1jdXJ2YXR1cmU9IjAiCiAgICAgICAgICAgICBpZD0icGF0aDU0IgogICAgICAgICAgICAgc3R5bGU9ImZpbGw6IzhhNDE4MjtmaWxsLW9wYWNpdHk6MTtmaWxsLXJ1bGU6bm9uemVybztzdHJva2U6bm9uZSIgLz48cGF0aAogICAgICAgICAgICAgZD0ibSA3MTYuMjg5LDM3Ni41OSAzNy42NDA2LDAgMCwxODQuODE2IC0zNy42NDA2LDAgMCwtMTg0LjgxNiB6IgogICAgICAgICAgICAgaW5rc2NhcGU6Y29ubmVjdG9yLWN1cnZhdHVyZT0iMCIKICAgICAgICAgICAgIGlkPSJwYXRoNTYiCiAgICAgICAgICAgICBzdHlsZT0iZmlsbDojOGE0MTgyO2ZpbGwtb3BhY2l0eToxO2ZpbGwtcnVsZTpub256ZXJvO3N0cm9rZTpub25lIiAvPjwvZz48L2c+PC9nPjwvZz48L3N2Zz4=") no-repeat, none; + -moz-background-size: 100%; + -o-background-size: 100%; + -webkit-background-size: 100%; + background-size: 100%; + display: block; + float: left; + width: 90px; + height: 25px; +} +.jasmine_html-reporter .jasmine-banner .jasmine-version { + margin-left: 14px; + position: relative; + top: 6px; +} +.jasmine_html-reporter #jasmine_content { + position: fixed; + right: 100%; +} +.jasmine_html-reporter .jasmine-version { + color: #aaa; +} +.jasmine_html-reporter .jasmine-banner { + margin-top: 14px; +} +.jasmine_html-reporter .jasmine-duration { + color: #fff; + float: right; + line-height: 28px; + padding-right: 9px; +} +.jasmine_html-reporter .jasmine-symbol-summary { + overflow: hidden; + margin: 14px 0; +} +.jasmine_html-reporter .jasmine-symbol-summary li { + display: inline-block; + height: 10px; + width: 14px; + font-size: 16px; +} +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-passed { + font-size: 14px; +} +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-passed:before { + color: #007069; + content: "โ€ข"; +} +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-failed { + line-height: 9px; +} +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-failed:before { + color: #ca3a11; + content: "ร—"; + font-weight: bold; + margin-left: -1px; +} +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-excluded { + font-size: 14px; +} +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-excluded:before { + color: #bababa; + content: "โ€ข"; +} +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-excluded-no-display { + font-size: 14px; + display: none; +} +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-pending { + line-height: 17px; +} +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-pending:before { + color: #ba9d37; + content: "*"; +} +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-empty { + font-size: 14px; +} +.jasmine_html-reporter .jasmine-symbol-summary li.jasmine-empty:before { + color: #ba9d37; + content: "โ€ข"; +} +.jasmine_html-reporter .jasmine-run-options { + float: right; + margin-right: 5px; + border: 1px solid #8a4182; + color: #8a4182; + position: relative; + line-height: 20px; +} +.jasmine_html-reporter .jasmine-run-options .jasmine-trigger { + cursor: pointer; + padding: 8px 16px; +} +.jasmine_html-reporter .jasmine-run-options .jasmine-payload { + position: absolute; + display: none; + right: -1px; + border: 1px solid #8a4182; + background-color: #eee; + white-space: nowrap; + padding: 4px 8px; +} +.jasmine_html-reporter .jasmine-run-options .jasmine-payload.jasmine-open { + display: block; +} +.jasmine_html-reporter .jasmine-bar { + line-height: 28px; + font-size: 14px; + display: block; + color: #eee; +} +.jasmine_html-reporter .jasmine-bar.jasmine-failed, .jasmine_html-reporter .jasmine-bar.jasmine-errored { + background-color: #ca3a11; + border-bottom: 1px solid #eee; +} +.jasmine_html-reporter .jasmine-bar.jasmine-passed { + background-color: #007069; +} +.jasmine_html-reporter .jasmine-bar.jasmine-incomplete { + background-color: #bababa; +} +.jasmine_html-reporter .jasmine-bar.jasmine-skipped { + background-color: #bababa; +} +.jasmine_html-reporter .jasmine-bar.jasmine-warning { + background-color: #ba9d37; + color: #333; +} +.jasmine_html-reporter .jasmine-bar.jasmine-menu { + background-color: #fff; + color: #aaa; +} +.jasmine_html-reporter .jasmine-bar.jasmine-menu a { + color: #333; +} +.jasmine_html-reporter .jasmine-bar a { + color: white; +} +.jasmine_html-reporter.jasmine-spec-list .jasmine-bar.jasmine-menu.jasmine-failure-list, +.jasmine_html-reporter.jasmine-spec-list .jasmine-results .jasmine-failures { + display: none; +} +.jasmine_html-reporter.jasmine-failure-list .jasmine-bar.jasmine-menu.jasmine-spec-list, +.jasmine_html-reporter.jasmine-failure-list .jasmine-summary { + display: none; +} +.jasmine_html-reporter .jasmine-results { + margin-top: 14px; +} +.jasmine_html-reporter .jasmine-summary { + margin-top: 14px; +} +.jasmine_html-reporter .jasmine-summary ul { + list-style-type: none; + margin-left: 14px; + padding-top: 0; + padding-left: 0; +} +.jasmine_html-reporter .jasmine-summary ul.jasmine-suite { + margin-top: 7px; + margin-bottom: 7px; +} +.jasmine_html-reporter .jasmine-summary li.jasmine-passed a { + color: #007069; +} +.jasmine_html-reporter .jasmine-summary li.jasmine-failed a { + color: #ca3a11; +} +.jasmine_html-reporter .jasmine-summary li.jasmine-empty a { + color: #ba9d37; +} +.jasmine_html-reporter .jasmine-summary li.jasmine-pending a { + color: #ba9d37; +} +.jasmine_html-reporter .jasmine-summary li.jasmine-excluded a { + color: #bababa; +} +.jasmine_html-reporter .jasmine-specs li.jasmine-passed a:before { + content: "โ€ข "; +} +.jasmine_html-reporter .jasmine-specs li.jasmine-failed a:before { + content: "ร— "; +} +.jasmine_html-reporter .jasmine-specs li.jasmine-empty a:before { + content: "* "; +} +.jasmine_html-reporter .jasmine-specs li.jasmine-pending a:before { + content: "โ€ข "; +} +.jasmine_html-reporter .jasmine-specs li.jasmine-excluded a:before { + content: "โ€ข "; +} +.jasmine_html-reporter .jasmine-description + .jasmine-suite { + margin-top: 0; +} +.jasmine_html-reporter .jasmine-suite { + margin-top: 14px; +} +.jasmine_html-reporter .jasmine-suite a { + color: #333; +} +.jasmine_html-reporter .jasmine-failures .jasmine-spec-detail { + margin-bottom: 28px; +} +.jasmine_html-reporter .jasmine-failures .jasmine-spec-detail .jasmine-description { + background-color: #ca3a11; + color: white; +} +.jasmine_html-reporter .jasmine-failures .jasmine-spec-detail .jasmine-description a { + color: white; +} +.jasmine_html-reporter .jasmine-result-message { + padding-top: 14px; + color: #333; + white-space: pre-wrap; +} +.jasmine_html-reporter .jasmine-result-message span.jasmine-result { + display: block; +} +.jasmine_html-reporter .jasmine-stack-trace { + margin: 5px 0 0 0; + max-height: 224px; + overflow: auto; + line-height: 18px; + color: #666; + border: 1px solid #ddd; + background: white; + white-space: pre; +} \ No newline at end of file diff --git a/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/jasmine.js b/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/jasmine.js new file mode 100644 index 0000000..40207e6 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/jasmine.js @@ -0,0 +1,9761 @@ +/* +Copyright (c) 2008-2021 Pivotal Labs + +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. +*/ +// eslint-disable-next-line no-unused-vars +var getJasmineRequireObj = (function(jasmineGlobal) { + var jasmineRequire; + + if ( + typeof module !== 'undefined' && + module.exports && + typeof exports !== 'undefined' + ) { + if (typeof global !== 'undefined') { + jasmineGlobal = global; + } else { + jasmineGlobal = {}; + } + jasmineRequire = exports; + } else { + if ( + typeof window !== 'undefined' && + typeof window.toString === 'function' && + window.toString() === '[object GjsGlobal]' + ) { + jasmineGlobal = window; + } + jasmineRequire = jasmineGlobal.jasmineRequire = {}; + } + + function getJasmineRequire() { + return jasmineRequire; + } + + getJasmineRequire().core = function(jRequire) { + var j$ = {}; + + jRequire.base(j$, jasmineGlobal); + j$.util = jRequire.util(j$); + j$.errors = jRequire.errors(); + j$.formatErrorMsg = jRequire.formatErrorMsg(); + j$.Any = jRequire.Any(j$); + j$.Anything = jRequire.Anything(j$); + j$.CallTracker = jRequire.CallTracker(j$); + j$.MockDate = jRequire.MockDate(); + j$.getClearStack = jRequire.clearStack(j$); + j$.Clock = jRequire.Clock(); + j$.DelayedFunctionScheduler = jRequire.DelayedFunctionScheduler(j$); + j$.Env = jRequire.Env(j$); + j$.StackTrace = jRequire.StackTrace(j$); + j$.ExceptionFormatter = jRequire.ExceptionFormatter(j$); + j$.ExpectationFilterChain = jRequire.ExpectationFilterChain(); + j$.Expector = jRequire.Expector(j$); + j$.Expectation = jRequire.Expectation(j$); + j$.buildExpectationResult = jRequire.buildExpectationResult(j$); + j$.JsApiReporter = jRequire.JsApiReporter(j$); + j$.asymmetricEqualityTesterArgCompatShim = jRequire.asymmetricEqualityTesterArgCompatShim( + j$ + ); + j$.makePrettyPrinter = jRequire.makePrettyPrinter(j$); + j$.pp = j$.makePrettyPrinter(); + j$.MatchersUtil = jRequire.MatchersUtil(j$); + j$.matchersUtil = new j$.MatchersUtil({ + customTesters: [], + pp: j$.pp + }); + + j$.ObjectContaining = jRequire.ObjectContaining(j$); + j$.ArrayContaining = jRequire.ArrayContaining(j$); + j$.ArrayWithExactContents = jRequire.ArrayWithExactContents(j$); + j$.MapContaining = jRequire.MapContaining(j$); + j$.SetContaining = jRequire.SetContaining(j$); + j$.QueueRunner = jRequire.QueueRunner(j$); + j$.ReportDispatcher = jRequire.ReportDispatcher(j$); + j$.Spec = jRequire.Spec(j$); + j$.Spy = jRequire.Spy(j$); + j$.SpyFactory = jRequire.SpyFactory(j$); + j$.SpyRegistry = jRequire.SpyRegistry(j$); + j$.SpyStrategy = jRequire.SpyStrategy(j$); + j$.StringMatching = jRequire.StringMatching(j$); + j$.UserContext = jRequire.UserContext(j$); + j$.Suite = jRequire.Suite(j$); + j$.Timer = jRequire.Timer(); + j$.TreeProcessor = jRequire.TreeProcessor(); + j$.version = jRequire.version(); + j$.Order = jRequire.Order(); + j$.DiffBuilder = jRequire.DiffBuilder(j$); + j$.NullDiffBuilder = jRequire.NullDiffBuilder(j$); + j$.ObjectPath = jRequire.ObjectPath(j$); + j$.MismatchTree = jRequire.MismatchTree(j$); + j$.GlobalErrors = jRequire.GlobalErrors(j$); + + j$.Truthy = jRequire.Truthy(j$); + j$.Falsy = jRequire.Falsy(j$); + j$.Empty = jRequire.Empty(j$); + j$.NotEmpty = jRequire.NotEmpty(j$); + + j$.matchers = jRequire.requireMatchers(jRequire, j$); + j$.asyncMatchers = jRequire.requireAsyncMatchers(jRequire, j$); + + return j$; + }; + + return getJasmineRequire; +})(this); + +getJasmineRequireObj().requireMatchers = function(jRequire, j$) { + var availableMatchers = [ + 'nothing', + 'toBe', + 'toBeCloseTo', + 'toBeDefined', + 'toBeInstanceOf', + 'toBeFalse', + 'toBeFalsy', + 'toBeGreaterThan', + 'toBeGreaterThanOrEqual', + 'toBeLessThan', + 'toBeLessThanOrEqual', + 'toBeNaN', + 'toBeNegativeInfinity', + 'toBeNull', + 'toBePositiveInfinity', + 'toBeTrue', + 'toBeTruthy', + 'toBeUndefined', + 'toContain', + 'toEqual', + 'toHaveSize', + 'toHaveBeenCalled', + 'toHaveBeenCalledBefore', + 'toHaveBeenCalledOnceWith', + 'toHaveBeenCalledTimes', + 'toHaveBeenCalledWith', + 'toHaveClass', + 'toMatch', + 'toThrow', + 'toThrowError', + 'toThrowMatching' + ], + matchers = {}; + + for (var i = 0; i < availableMatchers.length; i++) { + var name = availableMatchers[i]; + matchers[name] = jRequire[name](j$); + } + + return matchers; +}; + +getJasmineRequireObj().base = function(j$, jasmineGlobal) { + j$.unimplementedMethod_ = function() { + throw new Error('unimplemented method'); + }; + + /** + * Maximum object depth the pretty printer will print to. + * Set this to a lower value to speed up pretty printing if you have large objects. + * @name jasmine.MAX_PRETTY_PRINT_DEPTH + * @since 1.3.0 + */ + j$.MAX_PRETTY_PRINT_DEPTH = 8; + /** + * Maximum number of array elements to display when pretty printing objects. + * This will also limit the number of keys and values displayed for an object. + * Elements past this number will be ellipised. + * @name jasmine.MAX_PRETTY_PRINT_ARRAY_LENGTH + * @since 2.7.0 + */ + j$.MAX_PRETTY_PRINT_ARRAY_LENGTH = 50; + /** + * Maximum number of characters to display when pretty printing objects. + * Characters past this number will be ellipised. + * @name jasmine.MAX_PRETTY_PRINT_CHARS + * @since 2.9.0 + */ + j$.MAX_PRETTY_PRINT_CHARS = 1000; + /** + * Default number of milliseconds Jasmine will wait for an asynchronous spec to complete. + * @name jasmine.DEFAULT_TIMEOUT_INTERVAL + * @since 1.3.0 + */ + j$.DEFAULT_TIMEOUT_INTERVAL = 5000; + + j$.getGlobal = function() { + return jasmineGlobal; + }; + + /** + * Get the currently booted Jasmine Environment. + * + * @name jasmine.getEnv + * @since 1.3.0 + * @function + * @return {Env} + */ + j$.getEnv = function(options) { + var env = (j$.currentEnv_ = j$.currentEnv_ || new j$.Env(options)); + //jasmine. singletons in here (setTimeout blah blah). + return env; + }; + + j$.isArray_ = function(value) { + return j$.isA_('Array', value); + }; + + j$.isObject_ = function(value) { + return ( + !j$.util.isUndefined(value) && value !== null && j$.isA_('Object', value) + ); + }; + + j$.isString_ = function(value) { + return j$.isA_('String', value); + }; + + j$.isNumber_ = function(value) { + return j$.isA_('Number', value); + }; + + j$.isFunction_ = function(value) { + return j$.isA_('Function', value); + }; + + j$.isAsyncFunction_ = function(value) { + return j$.isA_('AsyncFunction', value); + }; + + j$.isGeneratorFunction_ = function(value) { + return j$.isA_('GeneratorFunction', value); + }; + + j$.isTypedArray_ = function(value) { + return ( + j$.isA_('Float32Array', value) || + j$.isA_('Float64Array', value) || + j$.isA_('Int16Array', value) || + j$.isA_('Int32Array', value) || + j$.isA_('Int8Array', value) || + j$.isA_('Uint16Array', value) || + j$.isA_('Uint32Array', value) || + j$.isA_('Uint8Array', value) || + j$.isA_('Uint8ClampedArray', value) + ); + }; + + j$.isA_ = function(typeName, value) { + return j$.getType_(value) === '[object ' + typeName + ']'; + }; + + j$.isError_ = function(value) { + if (value instanceof Error) { + return true; + } + if (value && value.constructor && value.constructor.constructor) { + var valueGlobal = value.constructor.constructor('return this'); + if (j$.isFunction_(valueGlobal)) { + valueGlobal = valueGlobal(); + } + + if (valueGlobal.Error && value instanceof valueGlobal.Error) { + return true; + } + } + return false; + }; + + j$.isAsymmetricEqualityTester_ = function(obj) { + return obj ? j$.isA_('Function', obj.asymmetricMatch) : false; + }; + + j$.getType_ = function(value) { + return Object.prototype.toString.apply(value); + }; + + j$.isDomNode = function(obj) { + // Node is a function, because constructors + return typeof jasmineGlobal.Node !== 'undefined' + ? obj instanceof jasmineGlobal.Node + : obj !== null && + typeof obj === 'object' && + typeof obj.nodeType === 'number' && + typeof obj.nodeName === 'string'; + // return obj.nodeType > 0; + }; + + j$.isMap = function(obj) { + return ( + obj !== null && + typeof obj !== 'undefined' && + typeof jasmineGlobal.Map !== 'undefined' && + obj.constructor === jasmineGlobal.Map + ); + }; + + j$.isSet = function(obj) { + return ( + obj !== null && + typeof obj !== 'undefined' && + typeof jasmineGlobal.Set !== 'undefined' && + obj.constructor === jasmineGlobal.Set + ); + }; + + j$.isWeakMap = function(obj) { + return ( + obj !== null && + typeof obj !== 'undefined' && + typeof jasmineGlobal.WeakMap !== 'undefined' && + obj.constructor === jasmineGlobal.WeakMap + ); + }; + + j$.isURL = function(obj) { + return ( + obj !== null && + typeof obj !== 'undefined' && + typeof jasmineGlobal.URL !== 'undefined' && + obj.constructor === jasmineGlobal.URL + ); + }; + + j$.isDataView = function(obj) { + return ( + obj !== null && + typeof obj !== 'undefined' && + typeof jasmineGlobal.DataView !== 'undefined' && + obj.constructor === jasmineGlobal.DataView + ); + }; + + j$.isPromise = function(obj) { + return ( + typeof jasmineGlobal.Promise !== 'undefined' && + !!obj && + obj.constructor === jasmineGlobal.Promise + ); + }; + + j$.isPromiseLike = function(obj) { + return !!obj && j$.isFunction_(obj.then); + }; + + j$.fnNameFor = function(func) { + if (func.name) { + return func.name; + } + + var matches = + func.toString().match(/^\s*function\s*(\w+)\s*\(/) || + func.toString().match(/^\s*\[object\s*(\w+)Constructor\]/); + + return matches ? matches[1] : ''; + }; + + j$.isPending_ = function(promise) { + var sentinel = {}; + // eslint-disable-next-line compat/compat + return Promise.race([promise, Promise.resolve(sentinel)]).then( + function(result) { + return result === sentinel; + }, + function() { + return false; + } + ); + }; + + /** + * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared is an instance of the specified class/constructor. + * @name jasmine.any + * @since 1.3.0 + * @function + * @param {Constructor} clazz - The constructor to check against. + */ + j$.any = function(clazz) { + return new j$.Any(clazz); + }; + + /** + * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared is not `null` and not `undefined`. + * @name jasmine.anything + * @since 2.2.0 + * @function + */ + j$.anything = function() { + return new j$.Anything(); + }; + + /** + * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared is `true` or anything truthy. + * @name jasmine.truthy + * @since 3.1.0 + * @function + */ + j$.truthy = function() { + return new j$.Truthy(); + }; + + /** + * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared is `null`, `undefined`, `0`, `false` or anything falsey. + * @name jasmine.falsy + * @since 3.1.0 + * @function + */ + j$.falsy = function() { + return new j$.Falsy(); + }; + + /** + * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared is empty. + * @name jasmine.empty + * @since 3.1.0 + * @function + */ + j$.empty = function() { + return new j$.Empty(); + }; + + /** + * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared is not empty. + * @name jasmine.notEmpty + * @since 3.1.0 + * @function + */ + j$.notEmpty = function() { + return new j$.NotEmpty(); + }; + + /** + * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value being compared contains at least the keys and values. + * @name jasmine.objectContaining + * @since 1.3.0 + * @function + * @param {Object} sample - The subset of properties that _must_ be in the actual. + */ + j$.objectContaining = function(sample) { + return new j$.ObjectContaining(sample); + }; + + /** + * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value is a `String` that matches the `RegExp` or `String`. + * @name jasmine.stringMatching + * @since 2.2.0 + * @function + * @param {RegExp|String} expected + */ + j$.stringMatching = function(expected) { + return new j$.StringMatching(expected); + }; + + /** + * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value is an `Array` that contains at least the elements in the sample. + * @name jasmine.arrayContaining + * @since 2.2.0 + * @function + * @param {Array} sample + */ + j$.arrayContaining = function(sample) { + return new j$.ArrayContaining(sample); + }; + + /** + * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if the actual value is an `Array` that contains all of the elements in the sample in any order. + * @name jasmine.arrayWithExactContents + * @since 2.8.0 + * @function + * @param {Array} sample + */ + j$.arrayWithExactContents = function(sample) { + return new j$.ArrayWithExactContents(sample); + }; + + /** + * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if every key/value pair in the sample passes the deep equality comparison + * with at least one key/value pair in the actual value being compared + * @name jasmine.mapContaining + * @since 3.5.0 + * @function + * @param {Map} sample - The subset of items that _must_ be in the actual. + */ + j$.mapContaining = function(sample) { + return new j$.MapContaining(sample); + }; + + /** + * Get a matcher, usable in any {@link matchers|matcher} that uses Jasmine's equality (e.g. {@link matchers#toEqual|toEqual}, {@link matchers#toContain|toContain}, or {@link matchers#toHaveBeenCalledWith|toHaveBeenCalledWith}), + * that will succeed if every item in the sample passes the deep equality comparison + * with at least one item in the actual value being compared + * @name jasmine.setContaining + * @since 3.5.0 + * @function + * @param {Set} sample - The subset of items that _must_ be in the actual. + */ + j$.setContaining = function(sample) { + return new j$.SetContaining(sample); + }; + + /** + * Determines whether the provided function is a Jasmine spy. + * @name jasmine.isSpy + * @since 2.0.0 + * @function + * @param {Function} putativeSpy - The function to check. + * @return {Boolean} + */ + j$.isSpy = function(putativeSpy) { + if (!putativeSpy) { + return false; + } + return ( + putativeSpy.and instanceof j$.SpyStrategy && + putativeSpy.calls instanceof j$.CallTracker + ); + }; +}; + +getJasmineRequireObj().util = function(j$) { + var util = {}; + + util.inherit = function(childClass, parentClass) { + var Subclass = function() {}; + Subclass.prototype = parentClass.prototype; + childClass.prototype = new Subclass(); + }; + + util.argsToArray = function(args) { + var arrayOfArgs = []; + for (var i = 0; i < args.length; i++) { + arrayOfArgs.push(args[i]); + } + return arrayOfArgs; + }; + + util.isUndefined = function(obj) { + return obj === void 0; + }; + + util.arrayContains = function(array, search) { + var i = array.length; + while (i--) { + if (array[i] === search) { + return true; + } + } + return false; + }; + + util.clone = function(obj) { + if (Object.prototype.toString.apply(obj) === '[object Array]') { + return obj.slice(); + } + + var cloned = {}; + for (var prop in obj) { + if (obj.hasOwnProperty(prop)) { + cloned[prop] = obj[prop]; + } + } + + return cloned; + }; + + util.cloneArgs = function(args) { + var clonedArgs = []; + var argsAsArray = j$.util.argsToArray(args); + for (var i = 0; i < argsAsArray.length; i++) { + var str = Object.prototype.toString.apply(argsAsArray[i]), + primitives = /^\[object (Boolean|String|RegExp|Number)/; + + // All falsey values are either primitives, `null`, or `undefined. + if (!argsAsArray[i] || str.match(primitives)) { + clonedArgs.push(argsAsArray[i]); + } else { + clonedArgs.push(j$.util.clone(argsAsArray[i])); + } + } + return clonedArgs; + }; + + util.getPropertyDescriptor = function(obj, methodName) { + var descriptor, + proto = obj; + + do { + descriptor = Object.getOwnPropertyDescriptor(proto, methodName); + proto = Object.getPrototypeOf(proto); + } while (!descriptor && proto); + + return descriptor; + }; + + util.objectDifference = function(obj, toRemove) { + var diff = {}; + + for (var key in obj) { + if (util.has(obj, key) && !util.has(toRemove, key)) { + diff[key] = obj[key]; + } + } + + return diff; + }; + + util.has = function(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); + }; + + util.errorWithStack = function errorWithStack() { + // Don't throw and catch if we don't have to, because it makes it harder + // for users to debug their code with exception breakpoints. + var error = new Error(); + + if (error.stack) { + return error; + } + + // But some browsers (e.g. Phantom) only provide a stack trace if we throw. + try { + throw new Error(); + } catch (e) { + return e; + } + }; + + function callerFile() { + var trace = new j$.StackTrace(util.errorWithStack()); + return trace.frames[2].file; + } + + util.jasmineFile = (function() { + var result; + + return function() { + if (!result) { + result = callerFile(); + } + + return result; + }; + })(); + + function StopIteration() {} + StopIteration.prototype = Object.create(Error.prototype); + StopIteration.prototype.constructor = StopIteration; + + // useful for maps and sets since `forEach` is the only IE11-compatible way to iterate them + util.forEachBreakable = function(iterable, iteratee) { + function breakLoop() { + throw new StopIteration(); + } + + try { + iterable.forEach(function(value, key) { + iteratee(breakLoop, value, key, iterable); + }); + } catch (error) { + if (!(error instanceof StopIteration)) throw error; + } + }; + + return util; +}; + +getJasmineRequireObj().Spec = function(j$) { + /** + * @interface Spec + * @see Configuration#specFilter + */ + function Spec(attrs) { + this.expectationFactory = attrs.expectationFactory; + this.asyncExpectationFactory = attrs.asyncExpectationFactory; + this.resultCallback = attrs.resultCallback || function() {}; + this.id = attrs.id; + /** + * The description passed to the {@link it} that created this spec. + * @name Spec#description + * @readonly + * @type {string} + */ + this.description = attrs.description || ''; + this.queueableFn = attrs.queueableFn; + this.beforeAndAfterFns = + attrs.beforeAndAfterFns || + function() { + return { befores: [], afters: [] }; + }; + this.userContext = + attrs.userContext || + function() { + return {}; + }; + this.onStart = attrs.onStart || function() {}; + this.getSpecName = + attrs.getSpecName || + function() { + return ''; + }; + this.expectationResultFactory = + attrs.expectationResultFactory || function() {}; + this.queueRunnerFactory = attrs.queueRunnerFactory || function() {}; + this.catchingExceptions = + attrs.catchingExceptions || + function() { + return true; + }; + this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; + this.timer = attrs.timer || new j$.Timer(); + + if (!this.queueableFn.fn) { + this.pend(); + } + + /** + * @typedef SpecResult + * @property {Int} id - The unique id of this spec. + * @property {String} description - The description passed to the {@link it} that created this spec. + * @property {String} fullName - The full description including all ancestors of this spec. + * @property {Expectation[]} failedExpectations - The list of expectations that failed during execution of this spec. + * @property {Expectation[]} passedExpectations - The list of expectations that passed during execution of this spec. + * @property {Expectation[]} deprecationWarnings - The list of deprecation warnings that occurred during execution this spec. + * @property {String} pendingReason - If the spec is {@link pending}, this will be the reason. + * @property {String} status - Once the spec has completed, this string represents the pass/fail status of this spec. + * @property {number} duration - The time in ms used by the spec execution, including any before/afterEach. + * @property {Object} properties - User-supplied properties, if any, that were set using {@link Env#setSpecProperty} + */ + this.result = { + id: this.id, + description: this.description, + fullName: this.getFullName(), + failedExpectations: [], + passedExpectations: [], + deprecationWarnings: [], + pendingReason: '', + duration: null, + properties: null + }; + } + + Spec.prototype.addExpectationResult = function(passed, data, isError) { + var expectationResult = this.expectationResultFactory(data); + if (passed) { + this.result.passedExpectations.push(expectationResult); + } else { + this.result.failedExpectations.push(expectationResult); + + if (this.throwOnExpectationFailure && !isError) { + throw new j$.errors.ExpectationFailed(); + } + } + }; + + Spec.prototype.setSpecProperty = function(key, value) { + this.result.properties = this.result.properties || {}; + this.result.properties[key] = value; + }; + + Spec.prototype.expect = function(actual) { + return this.expectationFactory(actual, this); + }; + + Spec.prototype.expectAsync = function(actual) { + return this.asyncExpectationFactory(actual, this); + }; + + Spec.prototype.execute = function(onComplete, excluded, failSpecWithNoExp) { + var self = this; + + var onStart = { + fn: function(done) { + self.timer.start(); + self.onStart(self, done); + } + }; + + var complete = { + fn: function(done) { + self.queueableFn.fn = null; + self.result.status = self.status(excluded, failSpecWithNoExp); + self.result.duration = self.timer.elapsed(); + self.resultCallback(self.result, done); + } + }; + + var fns = this.beforeAndAfterFns(); + var regularFns = fns.befores.concat(this.queueableFn); + + var runnerConfig = { + isLeaf: true, + queueableFns: regularFns, + cleanupFns: fns.afters, + onException: function() { + self.onException.apply(self, arguments); + }, + onComplete: function() { + onComplete( + self.result.status === 'failed' && + new j$.StopExecutionError('spec failed') + ); + }, + userContext: this.userContext() + }; + + if (this.markedPending || excluded === true) { + runnerConfig.queueableFns = []; + runnerConfig.cleanupFns = []; + } + + runnerConfig.queueableFns.unshift(onStart); + runnerConfig.cleanupFns.push(complete); + + this.queueRunnerFactory(runnerConfig); + }; + + Spec.prototype.onException = function onException(e) { + if (Spec.isPendingSpecException(e)) { + this.pend(extractCustomPendingMessage(e)); + return; + } + + if (e instanceof j$.errors.ExpectationFailed) { + return; + } + + this.addExpectationResult( + false, + { + matcherName: '', + passed: false, + expected: '', + actual: '', + error: e + }, + true + ); + }; + + Spec.prototype.pend = function(message) { + this.markedPending = true; + if (message) { + this.result.pendingReason = message; + } + }; + + Spec.prototype.getResult = function() { + this.result.status = this.status(); + return this.result; + }; + + Spec.prototype.status = function(excluded, failSpecWithNoExpectations) { + if (excluded === true) { + return 'excluded'; + } + + if (this.markedPending) { + return 'pending'; + } + + if ( + this.result.failedExpectations.length > 0 || + (failSpecWithNoExpectations && + this.result.failedExpectations.length + + this.result.passedExpectations.length === + 0) + ) { + return 'failed'; + } + + return 'passed'; + }; + + /** + * The full description including all ancestors of this spec. + * @name Spec#getFullName + * @function + * @returns {string} + */ + Spec.prototype.getFullName = function() { + return this.getSpecName(this); + }; + + Spec.prototype.addDeprecationWarning = function(deprecation) { + if (typeof deprecation === 'string') { + deprecation = { message: deprecation }; + } + this.result.deprecationWarnings.push( + this.expectationResultFactory(deprecation) + ); + }; + + var extractCustomPendingMessage = function(e) { + var fullMessage = e.toString(), + boilerplateStart = fullMessage.indexOf(Spec.pendingSpecExceptionMessage), + boilerplateEnd = + boilerplateStart + Spec.pendingSpecExceptionMessage.length; + + return fullMessage.substr(boilerplateEnd); + }; + + Spec.pendingSpecExceptionMessage = '=> marked Pending'; + + Spec.isPendingSpecException = function(e) { + return !!( + e && + e.toString && + e.toString().indexOf(Spec.pendingSpecExceptionMessage) !== -1 + ); + }; + + return Spec; +}; + +if (typeof window == void 0 && typeof exports == 'object') { + /* globals exports */ + exports.Spec = jasmineRequire.Spec; +} + +/*jshint bitwise: false*/ + +getJasmineRequireObj().Order = function() { + function Order(options) { + this.random = 'random' in options ? options.random : true; + var seed = (this.seed = options.seed || generateSeed()); + this.sort = this.random ? randomOrder : naturalOrder; + + function naturalOrder(items) { + return items; + } + + function randomOrder(items) { + var copy = items.slice(); + copy.sort(function(a, b) { + return jenkinsHash(seed + a.id) - jenkinsHash(seed + b.id); + }); + return copy; + } + + function generateSeed() { + return String(Math.random()).slice(-5); + } + + // Bob Jenkins One-at-a-Time Hash algorithm is a non-cryptographic hash function + // used to get a different output when the key changes slightly. + // We use your return to sort the children randomly in a consistent way when + // used in conjunction with a seed + + function jenkinsHash(key) { + var hash, i; + for (hash = i = 0; i < key.length; ++i) { + hash += key.charCodeAt(i); + hash += hash << 10; + hash ^= hash >> 6; + } + hash += hash << 3; + hash ^= hash >> 11; + hash += hash << 15; + return hash; + } + } + + return Order; +}; + +getJasmineRequireObj().Env = function(j$) { + /** + * @class Env + * @since 2.0.0 + * @classdesc The Jasmine environment.
+ * _Note:_ Do not construct this directly. You can obtain the Env instance by + * calling {@link jasmine.getEnv}. + * @hideconstructor + */ + function Env(options) { + options = options || {}; + + var self = this; + var global = options.global || j$.getGlobal(); + var customPromise; + + var totalSpecsDefined = 0; + + var realSetTimeout = global.setTimeout; + var realClearTimeout = global.clearTimeout; + var clearStack = j$.getClearStack(global); + this.clock = new j$.Clock( + global, + function() { + return new j$.DelayedFunctionScheduler(); + }, + new j$.MockDate(global) + ); + + var runnableResources = {}; + + var currentSpec = null; + var currentlyExecutingSuites = []; + var currentDeclarationSuite = null; + var hasFailures = false; + + /** + * This represents the available options to configure Jasmine. + * Options that are not provided will use their default values. + * @see Env#configure + * @interface Configuration + * @since 3.3.0 + */ + var config = { + /** + * Whether to randomize spec execution order + * @name Configuration#random + * @since 3.3.0 + * @type Boolean + * @default true + */ + random: true, + /** + * Seed to use as the basis of randomization. + * Null causes the seed to be determined randomly at the start of execution. + * @name Configuration#seed + * @since 3.3.0 + * @type (number|string) + * @default null + */ + seed: null, + /** + * Whether to stop execution of the suite after the first spec failure + * @name Configuration#failFast + * @since 3.3.0 + * @type Boolean + * @default false + */ + failFast: false, + /** + * Whether to fail the spec if it ran no expectations. By default + * a spec that ran no expectations is reported as passed. Setting this + * to true will report such spec as a failure. + * @name Configuration#failSpecWithNoExpectations + * @since 3.5.0 + * @type Boolean + * @default false + */ + failSpecWithNoExpectations: false, + /** + * Whether to cause specs to only have one expectation failure. + * @name Configuration#oneFailurePerSpec + * @since 3.3.0 + * @type Boolean + * @default false + */ + oneFailurePerSpec: false, + /** + * A function that takes a spec and returns true if it should be executed + * or false if it should be skipped. + * @callback SpecFilter + * @param {Spec} spec - The spec that the filter is being applied to. + * @return boolean + */ + /** + * Function to use to filter specs + * @name Configuration#specFilter + * @since 3.3.0 + * @type SpecFilter + * @default A function that always returns true. + */ + specFilter: function() { + return true; + }, + /** + * Whether or not reporters should hide disabled specs from their output. + * Currently only supported by Jasmine's HTMLReporter + * @name Configuration#hideDisabled + * @since 3.3.0 + * @type Boolean + * @default false + */ + hideDisabled: false, + /** + * Set to provide a custom promise library that Jasmine will use if it needs + * to create a promise. If not set, it will default to whatever global Promise + * library is available (if any). + * @name Configuration#Promise + * @since 3.5.0 + * @type function + * @default undefined + */ + Promise: undefined + }; + + var currentSuite = function() { + return currentlyExecutingSuites[currentlyExecutingSuites.length - 1]; + }; + + var currentRunnable = function() { + return currentSpec || currentSuite(); + }; + + var globalErrors = null; + + var installGlobalErrors = function() { + if (globalErrors) { + return; + } + + globalErrors = new j$.GlobalErrors(); + globalErrors.install(); + }; + + if (!options.suppressLoadErrors) { + installGlobalErrors(); + globalErrors.pushListener(function( + message, + filename, + lineno, + colNo, + err + ) { + topSuite.result.failedExpectations.push({ + passed: false, + globalErrorType: 'load', + message: message, + stack: err && err.stack, + filename: filename, + lineno: lineno + }); + }); + } + + /** + * Configure your jasmine environment + * @name Env#configure + * @since 3.3.0 + * @argument {Configuration} configuration + * @function + */ + this.configure = function(configuration) { + if (configuration.specFilter) { + config.specFilter = configuration.specFilter; + } + + if (configuration.hasOwnProperty('random')) { + config.random = !!configuration.random; + } + + if (configuration.hasOwnProperty('seed')) { + config.seed = configuration.seed; + } + + if (configuration.hasOwnProperty('failFast')) { + config.failFast = configuration.failFast; + } + + if (configuration.hasOwnProperty('failSpecWithNoExpectations')) { + config.failSpecWithNoExpectations = + configuration.failSpecWithNoExpectations; + } + + if (configuration.hasOwnProperty('oneFailurePerSpec')) { + config.oneFailurePerSpec = configuration.oneFailurePerSpec; + } + + if (configuration.hasOwnProperty('hideDisabled')) { + config.hideDisabled = configuration.hideDisabled; + } + + // Don't use hasOwnProperty to check for Promise existence because Promise + // can be initialized to undefined, either explicitly or by using the + // object returned from Env#configuration. In particular, Karma does this. + if (configuration.Promise) { + if ( + typeof configuration.Promise.resolve === 'function' && + typeof configuration.Promise.reject === 'function' + ) { + customPromise = configuration.Promise; + } else { + throw new Error( + 'Custom promise library missing `resolve`/`reject` functions' + ); + } + } + }; + + /** + * Get the current configuration for your jasmine environment + * @name Env#configuration + * @since 3.3.0 + * @function + * @returns {Configuration} + */ + this.configuration = function() { + var result = {}; + for (var property in config) { + result[property] = config[property]; + } + return result; + }; + + Object.defineProperty(this, 'specFilter', { + get: function() { + self.deprecated( + 'Getting specFilter directly from Env is deprecated and will be removed in a future version of Jasmine, please check the specFilter option from `configuration`' + ); + return config.specFilter; + }, + set: function(val) { + self.deprecated( + 'Setting specFilter directly on Env is deprecated and will be removed in a future version of Jasmine, please use the specFilter option in `configure`' + ); + config.specFilter = val; + } + }); + + this.setDefaultSpyStrategy = function(defaultStrategyFn) { + if (!currentRunnable()) { + throw new Error( + 'Default spy strategy must be set in a before function or a spec' + ); + } + runnableResources[ + currentRunnable().id + ].defaultStrategyFn = defaultStrategyFn; + }; + + this.addSpyStrategy = function(name, fn) { + if (!currentRunnable()) { + throw new Error( + 'Custom spy strategies must be added in a before function or a spec' + ); + } + runnableResources[currentRunnable().id].customSpyStrategies[name] = fn; + }; + + this.addCustomEqualityTester = function(tester) { + if (!currentRunnable()) { + throw new Error( + 'Custom Equalities must be added in a before function or a spec' + ); + } + runnableResources[currentRunnable().id].customEqualityTesters.push( + tester + ); + }; + + this.addMatchers = function(matchersToAdd) { + if (!currentRunnable()) { + throw new Error( + 'Matchers must be added in a before function or a spec' + ); + } + var customMatchers = + runnableResources[currentRunnable().id].customMatchers; + + for (var matcherName in matchersToAdd) { + customMatchers[matcherName] = matchersToAdd[matcherName]; + } + }; + + this.addAsyncMatchers = function(matchersToAdd) { + if (!currentRunnable()) { + throw new Error( + 'Async Matchers must be added in a before function or a spec' + ); + } + var customAsyncMatchers = + runnableResources[currentRunnable().id].customAsyncMatchers; + + for (var matcherName in matchersToAdd) { + customAsyncMatchers[matcherName] = matchersToAdd[matcherName]; + } + }; + + this.addCustomObjectFormatter = function(formatter) { + if (!currentRunnable()) { + throw new Error( + 'Custom object formatters must be added in a before function or a spec' + ); + } + + runnableResources[currentRunnable().id].customObjectFormatters.push( + formatter + ); + }; + + j$.Expectation.addCoreMatchers(j$.matchers); + j$.Expectation.addAsyncCoreMatchers(j$.asyncMatchers); + + var nextSpecId = 0; + var getNextSpecId = function() { + return 'spec' + nextSpecId++; + }; + + var nextSuiteId = 0; + var getNextSuiteId = function() { + return 'suite' + nextSuiteId++; + }; + + var makePrettyPrinter = function() { + var customObjectFormatters = + runnableResources[currentRunnable().id].customObjectFormatters; + return j$.makePrettyPrinter(customObjectFormatters); + }; + + var makeMatchersUtil = function() { + var customEqualityTesters = + runnableResources[currentRunnable().id].customEqualityTesters; + return new j$.MatchersUtil({ + customTesters: customEqualityTesters, + pp: makePrettyPrinter() + }); + }; + + var expectationFactory = function(actual, spec) { + var customEqualityTesters = + runnableResources[spec.id].customEqualityTesters; + + return j$.Expectation.factory({ + matchersUtil: makeMatchersUtil(), + customEqualityTesters: customEqualityTesters, + customMatchers: runnableResources[spec.id].customMatchers, + actual: actual, + addExpectationResult: addExpectationResult + }); + + function addExpectationResult(passed, result) { + return spec.addExpectationResult(passed, result); + } + }; + + function recordLateExpectation(runable, runableType, result) { + var delayedExpectationResult = {}; + Object.keys(result).forEach(function(k) { + delayedExpectationResult[k] = result[k]; + }); + delayedExpectationResult.passed = false; + delayedExpectationResult.globalErrorType = 'lateExpectation'; + delayedExpectationResult.message = + runableType + + ' "' + + runable.getFullName() + + '" ran a "' + + result.matcherName + + '" expectation after it finished.\n'; + + if (result.message) { + delayedExpectationResult.message += + 'Message: "' + result.message + '"\n'; + } + + delayedExpectationResult.message += + 'Did you forget to return or await the result of expectAsync?'; + + topSuite.result.failedExpectations.push(delayedExpectationResult); + } + + var asyncExpectationFactory = function(actual, spec, runableType) { + return j$.Expectation.asyncFactory({ + matchersUtil: makeMatchersUtil(), + customEqualityTesters: runnableResources[spec.id].customEqualityTesters, + customAsyncMatchers: runnableResources[spec.id].customAsyncMatchers, + actual: actual, + addExpectationResult: addExpectationResult + }); + + function addExpectationResult(passed, result) { + if (currentRunnable() !== spec) { + recordLateExpectation(spec, runableType, result); + } + return spec.addExpectationResult(passed, result); + } + }; + var suiteAsyncExpectationFactory = function(actual, suite) { + return asyncExpectationFactory(actual, suite, 'Suite'); + }; + + var specAsyncExpectationFactory = function(actual, suite) { + return asyncExpectationFactory(actual, suite, 'Spec'); + }; + + var defaultResourcesForRunnable = function(id, parentRunnableId) { + var resources = { + spies: [], + customEqualityTesters: [], + customMatchers: {}, + customAsyncMatchers: {}, + customSpyStrategies: {}, + defaultStrategyFn: undefined, + customObjectFormatters: [] + }; + + if (runnableResources[parentRunnableId]) { + resources.customEqualityTesters = j$.util.clone( + runnableResources[parentRunnableId].customEqualityTesters + ); + resources.customMatchers = j$.util.clone( + runnableResources[parentRunnableId].customMatchers + ); + resources.customAsyncMatchers = j$.util.clone( + runnableResources[parentRunnableId].customAsyncMatchers + ); + resources.customObjectFormatters = j$.util.clone( + runnableResources[parentRunnableId].customObjectFormatters + ); + resources.defaultStrategyFn = + runnableResources[parentRunnableId].defaultStrategyFn; + } + + runnableResources[id] = resources; + }; + + var clearResourcesForRunnable = function(id) { + spyRegistry.clearSpies(); + delete runnableResources[id]; + }; + + var beforeAndAfterFns = function(suite) { + return function() { + var befores = [], + afters = []; + + while (suite) { + befores = befores.concat(suite.beforeFns); + afters = afters.concat(suite.afterFns); + + suite = suite.parentSuite; + } + + return { + befores: befores.reverse(), + afters: afters + }; + }; + }; + + var getSpecName = function(spec, suite) { + var fullName = [spec.description], + suiteFullName = suite.getFullName(); + + if (suiteFullName !== '') { + fullName.unshift(suiteFullName); + } + return fullName.join(' '); + }; + + // TODO: we may just be able to pass in the fn instead of wrapping here + var buildExpectationResult = j$.buildExpectationResult, + exceptionFormatter = new j$.ExceptionFormatter(), + expectationResultFactory = function(attrs) { + attrs.messageFormatter = exceptionFormatter.message; + attrs.stackFormatter = exceptionFormatter.stack; + + return buildExpectationResult(attrs); + }; + + /** + * Sets whether Jasmine should throw an Error when an expectation fails. + * This causes a spec to only have one expectation failure. + * @name Env#throwOnExpectationFailure + * @since 2.3.0 + * @function + * @param {Boolean} value Whether to throw when a expectation fails + * @deprecated Use the `oneFailurePerSpec` option with {@link Env#configure} + */ + this.throwOnExpectationFailure = function(value) { + this.deprecated( + 'Setting throwOnExpectationFailure directly on Env is deprecated and will be removed in a future version of Jasmine, please use the oneFailurePerSpec option in `configure`' + ); + this.configure({ oneFailurePerSpec: !!value }); + }; + + this.throwingExpectationFailures = function() { + this.deprecated( + 'Getting throwingExpectationFailures directly from Env is deprecated and will be removed in a future version of Jasmine, please check the oneFailurePerSpec option from `configuration`' + ); + return config.oneFailurePerSpec; + }; + + /** + * Set whether to stop suite execution when a spec fails + * @name Env#stopOnSpecFailure + * @since 2.7.0 + * @function + * @param {Boolean} value Whether to stop suite execution when a spec fails + * @deprecated Use the `failFast` option with {@link Env#configure} + */ + this.stopOnSpecFailure = function(value) { + this.deprecated( + 'Setting stopOnSpecFailure directly is deprecated and will be removed in a future version of Jasmine, please use the failFast option in `configure`' + ); + this.configure({ failFast: !!value }); + }; + + this.stoppingOnSpecFailure = function() { + this.deprecated( + 'Getting stoppingOnSpecFailure directly from Env is deprecated and will be removed in a future version of Jasmine, please check the failFast option from `configuration`' + ); + return config.failFast; + }; + + /** + * Set whether to randomize test execution order + * @name Env#randomizeTests + * @since 2.4.0 + * @function + * @param {Boolean} value Whether to randomize execution order + * @deprecated Use the `random` option with {@link Env#configure} + */ + this.randomizeTests = function(value) { + this.deprecated( + 'Setting randomizeTests directly is deprecated and will be removed in a future version of Jasmine, please use the random option in `configure`' + ); + config.random = !!value; + }; + + this.randomTests = function() { + this.deprecated( + 'Getting randomTests directly from Env is deprecated and will be removed in a future version of Jasmine, please check the random option from `configuration`' + ); + return config.random; + }; + + /** + * Set the random number seed for spec randomization + * @name Env#seed + * @since 2.4.0 + * @function + * @param {Number} value The seed value + * @deprecated Use the `seed` option with {@link Env#configure} + */ + this.seed = function(value) { + this.deprecated( + 'Setting seed directly is deprecated and will be removed in a future version of Jasmine, please use the seed option in `configure`' + ); + if (value) { + config.seed = value; + } + return config.seed; + }; + + this.hidingDisabled = function(value) { + this.deprecated( + 'Getting hidingDisabled directly from Env is deprecated and will be removed in a future version of Jasmine, please check the hideDisabled option from `configuration`' + ); + return config.hideDisabled; + }; + + /** + * @name Env#hideDisabled + * @since 3.2.0 + * @function + */ + this.hideDisabled = function(value) { + this.deprecated( + 'Setting hideDisabled directly is deprecated and will be removed in a future version of Jasmine, please use the hideDisabled option in `configure`' + ); + config.hideDisabled = !!value; + }; + + this.deprecated = function(deprecation) { + var runnable = currentRunnable() || topSuite; + var context; + + if (runnable === topSuite) { + context = ''; + } else if (runnable === currentSuite()) { + context = ' (in suite: ' + runnable.getFullName() + ')'; + } else { + context = ' (in spec: ' + runnable.getFullName() + ')'; + } + + runnable.addDeprecationWarning(deprecation); + if ( + typeof console !== 'undefined' && + typeof console.error === 'function' + ) { + console.error('DEPRECATION: ' + deprecation + context); + } + }; + + var queueRunnerFactory = function(options, args) { + var failFast = false; + if (options.isLeaf) { + failFast = config.oneFailurePerSpec; + } else if (!options.isReporter) { + failFast = config.failFast; + } + options.clearStack = options.clearStack || clearStack; + options.timeout = { + setTimeout: realSetTimeout, + clearTimeout: realClearTimeout + }; + options.fail = self.fail; + options.globalErrors = globalErrors; + options.completeOnFirstError = failFast; + options.onException = + options.onException || + function(e) { + (currentRunnable() || topSuite).onException(e); + }; + options.deprecated = self.deprecated; + + new j$.QueueRunner(options).execute(args); + }; + + var topSuite = new j$.Suite({ + env: this, + id: getNextSuiteId(), + description: 'Jasmine__TopLevel__Suite', + expectationFactory: expectationFactory, + asyncExpectationFactory: suiteAsyncExpectationFactory, + expectationResultFactory: expectationResultFactory + }); + defaultResourcesForRunnable(topSuite.id); + currentDeclarationSuite = topSuite; + + /** + * Provides the root suite, through which all suites and specs can be + * accessed. + * @function + * @name Env#topSuite + * @return {Suite} the root suite + */ + this.topSuite = function() { + return topSuite; + }; + + /** + * This represents the available reporter callback for an object passed to {@link Env#addReporter}. + * @interface Reporter + * @see custom_reporter + */ + var reporter = new j$.ReportDispatcher( + [ + /** + * `jasmineStarted` is called after all of the specs have been loaded, but just before execution starts. + * @function + * @name Reporter#jasmineStarted + * @param {JasmineStartedInfo} suiteInfo Information about the full Jasmine suite that is being run + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'jasmineStarted', + /** + * When the entire suite has finished execution `jasmineDone` is called + * @function + * @name Reporter#jasmineDone + * @param {JasmineDoneInfo} suiteInfo Information about the full Jasmine suite that just finished running. + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'jasmineDone', + /** + * `suiteStarted` is invoked when a `describe` starts to run + * @function + * @name Reporter#suiteStarted + * @param {SuiteResult} result Information about the individual {@link describe} being run + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'suiteStarted', + /** + * `suiteDone` is invoked when all of the child specs and suites for a given suite have been run + * + * While jasmine doesn't require any specific functions, not defining a `suiteDone` will make it impossible for a reporter to know when a suite has failures in an `afterAll`. + * @function + * @name Reporter#suiteDone + * @param {SuiteResult} result + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'suiteDone', + /** + * `specStarted` is invoked when an `it` starts to run (including associated `beforeEach` functions) + * @function + * @name Reporter#specStarted + * @param {SpecResult} result Information about the individual {@link it} being run + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'specStarted', + /** + * `specDone` is invoked when an `it` and its associated `beforeEach` and `afterEach` functions have been run. + * + * While jasmine doesn't require any specific functions, not defining a `specDone` will make it impossible for a reporter to know when a spec has failed. + * @function + * @name Reporter#specDone + * @param {SpecResult} result + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + * @see async + */ + 'specDone' + ], + queueRunnerFactory + ); + + /** + * Executes the specs. + * + * If called with no parameters or with a falsy value as the first parameter, + * all specs will be executed except those that are excluded by a + * [spec filter]{@link Configuration#specFilter} or other mechanism. If the + * first parameter is a list of spec/suite IDs, only those specs/suites will + * be run. + * + * Both parameters are optional, but a completion callback is only valid as + * the second parameter. To specify a completion callback but not a list of + * specs/suites to run, pass null or undefined as the first parameter. + * + * execute should not be called more than once. + * + * @name Env#execute + * @since 2.0.0 + * @function + * @param {(string[])=} runnablesToRun IDs of suites and/or specs to run + * @param {Function=} onComplete Function that will be called after all specs have run + */ + this.execute = function(runnablesToRun, onComplete) { + installGlobalErrors(); + + if (!runnablesToRun) { + if (focusedRunnables.length) { + runnablesToRun = focusedRunnables; + } else { + runnablesToRun = [topSuite.id]; + } + } + + var order = new j$.Order({ + random: config.random, + seed: config.seed + }); + + var processor = new j$.TreeProcessor({ + tree: topSuite, + runnableIds: runnablesToRun, + queueRunnerFactory: queueRunnerFactory, + failSpecWithNoExpectations: config.failSpecWithNoExpectations, + nodeStart: function(suite, next) { + currentlyExecutingSuites.push(suite); + defaultResourcesForRunnable(suite.id, suite.parentSuite.id); + reporter.suiteStarted(suite.result, next); + suite.startTimer(); + }, + nodeComplete: function(suite, result, next) { + if (suite !== currentSuite()) { + throw new Error('Tried to complete the wrong suite'); + } + + clearResourcesForRunnable(suite.id); + currentlyExecutingSuites.pop(); + + if (result.status === 'failed') { + hasFailures = true; + } + suite.endTimer(); + reporter.suiteDone(result, next); + }, + orderChildren: function(node) { + return order.sort(node.children); + }, + excludeNode: function(spec) { + return !config.specFilter(spec); + } + }); + + if (!processor.processTree().valid) { + throw new Error( + 'Invalid order: would cause a beforeAll or afterAll to be run multiple times' + ); + } + + var jasmineTimer = new j$.Timer(); + jasmineTimer.start(); + + /** + * Information passed to the {@link Reporter#jasmineStarted} event. + * @typedef JasmineStartedInfo + * @property {Int} totalSpecsDefined - The total number of specs defined in this suite. + * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. + */ + reporter.jasmineStarted( + { + totalSpecsDefined: totalSpecsDefined, + order: order + }, + function() { + currentlyExecutingSuites.push(topSuite); + + processor.execute(function() { + clearResourcesForRunnable(topSuite.id); + currentlyExecutingSuites.pop(); + var overallStatus, incompleteReason; + + if (hasFailures || topSuite.result.failedExpectations.length > 0) { + overallStatus = 'failed'; + } else if (focusedRunnables.length > 0) { + overallStatus = 'incomplete'; + incompleteReason = 'fit() or fdescribe() was found'; + } else if (totalSpecsDefined === 0) { + overallStatus = 'incomplete'; + incompleteReason = 'No specs found'; + } else { + overallStatus = 'passed'; + } + + /** + * Information passed to the {@link Reporter#jasmineDone} event. + * @typedef JasmineDoneInfo + * @property {OverallStatus} overallStatus - The overall result of the suite: 'passed', 'failed', or 'incomplete'. + * @property {Int} totalTime - The total time (in ms) that it took to execute the suite + * @property {IncompleteReason} incompleteReason - Explanation of why the suite was incomplete. + * @property {Order} order - Information about the ordering (random or not) of this execution of the suite. + * @property {Expectation[]} failedExpectations - List of expectations that failed in an {@link afterAll} at the global level. + * @property {Expectation[]} deprecationWarnings - List of deprecation warnings that occurred at the global level. + */ + reporter.jasmineDone( + { + overallStatus: overallStatus, + totalTime: jasmineTimer.elapsed(), + incompleteReason: incompleteReason, + order: order, + failedExpectations: topSuite.result.failedExpectations, + deprecationWarnings: topSuite.result.deprecationWarnings + }, + function() { + if (onComplete) { + onComplete(); + } + } + ); + }); + } + ); + }; + + /** + * Add a custom reporter to the Jasmine environment. + * @name Env#addReporter + * @since 2.0.0 + * @function + * @param {Reporter} reporterToAdd The reporter to be added. + * @see custom_reporter + */ + this.addReporter = function(reporterToAdd) { + reporter.addReporter(reporterToAdd); + }; + + /** + * Provide a fallback reporter if no other reporters have been specified. + * @name Env#provideFallbackReporter + * @since 2.5.0 + * @function + * @param {Reporter} reporterToAdd The reporter + * @see custom_reporter + */ + this.provideFallbackReporter = function(reporterToAdd) { + reporter.provideFallbackReporter(reporterToAdd); + }; + + /** + * Clear all registered reporters + * @name Env#clearReporters + * @since 2.5.2 + * @function + */ + this.clearReporters = function() { + reporter.clearReporters(); + }; + + var spyFactory = new j$.SpyFactory( + function getCustomStrategies() { + var runnable = currentRunnable(); + + if (runnable) { + return runnableResources[runnable.id].customSpyStrategies; + } + + return {}; + }, + function getDefaultStrategyFn() { + var runnable = currentRunnable(); + + if (runnable) { + return runnableResources[runnable.id].defaultStrategyFn; + } + + return undefined; + }, + function getPromise() { + return customPromise || global.Promise; + } + ); + + var spyRegistry = new j$.SpyRegistry({ + currentSpies: function() { + if (!currentRunnable()) { + throw new Error( + 'Spies must be created in a before function or a spec' + ); + } + return runnableResources[currentRunnable().id].spies; + }, + createSpy: function(name, originalFn) { + return self.createSpy(name, originalFn); + } + }); + + /** + * Configures whether Jasmine should allow the same function to be spied on + * more than once during the execution of a spec. By default, spying on + * a function that is already a spy will cause an error. + * @name Env#allowRespy + * @function + * @since 2.5.0 + * @param {boolean} allow Whether to allow respying + */ + this.allowRespy = function(allow) { + spyRegistry.allowRespy(allow); + }; + + this.spyOn = function() { + return spyRegistry.spyOn.apply(spyRegistry, arguments); + }; + + this.spyOnProperty = function() { + return spyRegistry.spyOnProperty.apply(spyRegistry, arguments); + }; + + this.spyOnAllFunctions = function() { + return spyRegistry.spyOnAllFunctions.apply(spyRegistry, arguments); + }; + + this.createSpy = function(name, originalFn) { + if (arguments.length === 1 && j$.isFunction_(name)) { + originalFn = name; + name = originalFn.name; + } + + return spyFactory.createSpy(name, originalFn); + }; + + this.createSpyObj = function(baseName, methodNames, propertyNames) { + return spyFactory.createSpyObj(baseName, methodNames, propertyNames); + }; + + var ensureIsFunction = function(fn, caller) { + if (!j$.isFunction_(fn)) { + throw new Error( + caller + ' expects a function argument; received ' + j$.getType_(fn) + ); + } + }; + + var ensureIsFunctionOrAsync = function(fn, caller) { + if (!j$.isFunction_(fn) && !j$.isAsyncFunction_(fn)) { + throw new Error( + caller + ' expects a function argument; received ' + j$.getType_(fn) + ); + } + }; + + function ensureIsNotNested(method) { + var runnable = currentRunnable(); + if (runnable !== null && runnable !== undefined) { + throw new Error( + "'" + method + "' should only be used in 'describe' function" + ); + } + } + + var suiteFactory = function(description) { + var suite = new j$.Suite({ + env: self, + id: getNextSuiteId(), + description: description, + parentSuite: currentDeclarationSuite, + timer: new j$.Timer(), + expectationFactory: expectationFactory, + asyncExpectationFactory: suiteAsyncExpectationFactory, + expectationResultFactory: expectationResultFactory, + throwOnExpectationFailure: config.oneFailurePerSpec + }); + + return suite; + }; + + this.describe = function(description, specDefinitions) { + ensureIsNotNested('describe'); + ensureIsFunction(specDefinitions, 'describe'); + var suite = suiteFactory(description); + if (specDefinitions.length > 0) { + throw new Error('describe does not expect any arguments'); + } + if (currentDeclarationSuite.markedPending) { + suite.pend(); + } + addSpecsToSuite(suite, specDefinitions); + return suite; + }; + + this.xdescribe = function(description, specDefinitions) { + ensureIsNotNested('xdescribe'); + ensureIsFunction(specDefinitions, 'xdescribe'); + var suite = suiteFactory(description); + suite.pend(); + addSpecsToSuite(suite, specDefinitions); + return suite; + }; + + var focusedRunnables = []; + + this.fdescribe = function(description, specDefinitions) { + ensureIsNotNested('fdescribe'); + ensureIsFunction(specDefinitions, 'fdescribe'); + var suite = suiteFactory(description); + suite.isFocused = true; + + focusedRunnables.push(suite.id); + unfocusAncestor(); + addSpecsToSuite(suite, specDefinitions); + + return suite; + }; + + function addSpecsToSuite(suite, specDefinitions) { + var parentSuite = currentDeclarationSuite; + parentSuite.addChild(suite); + currentDeclarationSuite = suite; + + var declarationError = null; + try { + specDefinitions.call(suite); + } catch (e) { + declarationError = e; + } + + if (declarationError) { + suite.onException(declarationError); + } + + currentDeclarationSuite = parentSuite; + } + + function findFocusedAncestor(suite) { + while (suite) { + if (suite.isFocused) { + return suite.id; + } + suite = suite.parentSuite; + } + + return null; + } + + function unfocusAncestor() { + var focusedAncestor = findFocusedAncestor(currentDeclarationSuite); + if (focusedAncestor) { + for (var i = 0; i < focusedRunnables.length; i++) { + if (focusedRunnables[i] === focusedAncestor) { + focusedRunnables.splice(i, 1); + break; + } + } + } + } + + var specFactory = function(description, fn, suite, timeout) { + totalSpecsDefined++; + var spec = new j$.Spec({ + id: getNextSpecId(), + beforeAndAfterFns: beforeAndAfterFns(suite), + expectationFactory: expectationFactory, + asyncExpectationFactory: specAsyncExpectationFactory, + resultCallback: specResultCallback, + getSpecName: function(spec) { + return getSpecName(spec, suite); + }, + onStart: specStarted, + description: description, + expectationResultFactory: expectationResultFactory, + queueRunnerFactory: queueRunnerFactory, + userContext: function() { + return suite.clonedSharedUserContext(); + }, + queueableFn: { + fn: fn, + timeout: timeout || 0 + }, + throwOnExpectationFailure: config.oneFailurePerSpec, + timer: new j$.Timer() + }); + return spec; + + function specResultCallback(result, next) { + clearResourcesForRunnable(spec.id); + currentSpec = null; + + if (result.status === 'failed') { + hasFailures = true; + } + + reporter.specDone(result, next); + } + + function specStarted(spec, next) { + currentSpec = spec; + defaultResourcesForRunnable(spec.id, suite.id); + reporter.specStarted(spec.result, next); + } + }; + + this.it = function(description, fn, timeout) { + ensureIsNotNested('it'); + // it() sometimes doesn't have a fn argument, so only check the type if + // it's given. + if (arguments.length > 1 && typeof fn !== 'undefined') { + ensureIsFunctionOrAsync(fn, 'it'); + } + var spec = specFactory(description, fn, currentDeclarationSuite, timeout); + if (currentDeclarationSuite.markedPending) { + spec.pend(); + } + currentDeclarationSuite.addChild(spec); + return spec; + }; + + this.xit = function(description, fn, timeout) { + ensureIsNotNested('xit'); + // xit(), like it(), doesn't always have a fn argument, so only check the + // type when needed. + if (arguments.length > 1 && typeof fn !== 'undefined') { + ensureIsFunctionOrAsync(fn, 'xit'); + } + var spec = this.it.apply(this, arguments); + spec.pend('Temporarily disabled with xit'); + return spec; + }; + + this.fit = function(description, fn, timeout) { + ensureIsNotNested('fit'); + ensureIsFunctionOrAsync(fn, 'fit'); + var spec = specFactory(description, fn, currentDeclarationSuite, timeout); + currentDeclarationSuite.addChild(spec); + focusedRunnables.push(spec.id); + unfocusAncestor(); + return spec; + }; + + /** + * Sets a user-defined property that will be provided to reporters as part of the properties field of {@link SpecResult} + * @name Env#setSpecProperty + * @since 3.6.0 + * @function + * @param {String} key The name of the property + * @param {*} value The value of the property + */ + this.setSpecProperty = function(key, value) { + if (!currentRunnable() || currentRunnable() == currentSuite()) { + throw new Error( + "'setSpecProperty' was used when there was no current spec" + ); + } + currentRunnable().setSpecProperty(key, value); + }; + + /** + * Sets a user-defined property that will be provided to reporters as part of the properties field of {@link SuiteResult} + * @name Env#setSuiteProperty + * @since 3.6.0 + * @function + * @param {String} key The name of the property + * @param {*} value The value of the property + */ + this.setSuiteProperty = function(key, value) { + if (!currentSuite()) { + throw new Error( + "'setSuiteProperty' was used when there was no current suite" + ); + } + currentSuite().setSuiteProperty(key, value); + }; + + this.expect = function(actual) { + if (!currentRunnable()) { + throw new Error( + "'expect' was used when there was no current spec, this could be because an asynchronous test timed out" + ); + } + + return currentRunnable().expect(actual); + }; + + this.expectAsync = function(actual) { + if (!currentRunnable()) { + throw new Error( + "'expectAsync' was used when there was no current spec, this could be because an asynchronous test timed out" + ); + } + + return currentRunnable().expectAsync(actual); + }; + + this.beforeEach = function(beforeEachFunction, timeout) { + ensureIsNotNested('beforeEach'); + ensureIsFunctionOrAsync(beforeEachFunction, 'beforeEach'); + currentDeclarationSuite.beforeEach({ + fn: beforeEachFunction, + timeout: timeout || 0 + }); + }; + + this.beforeAll = function(beforeAllFunction, timeout) { + ensureIsNotNested('beforeAll'); + ensureIsFunctionOrAsync(beforeAllFunction, 'beforeAll'); + currentDeclarationSuite.beforeAll({ + fn: beforeAllFunction, + timeout: timeout || 0 + }); + }; + + this.afterEach = function(afterEachFunction, timeout) { + ensureIsNotNested('afterEach'); + ensureIsFunctionOrAsync(afterEachFunction, 'afterEach'); + afterEachFunction.isCleanup = true; + currentDeclarationSuite.afterEach({ + fn: afterEachFunction, + timeout: timeout || 0 + }); + }; + + this.afterAll = function(afterAllFunction, timeout) { + ensureIsNotNested('afterAll'); + ensureIsFunctionOrAsync(afterAllFunction, 'afterAll'); + currentDeclarationSuite.afterAll({ + fn: afterAllFunction, + timeout: timeout || 0 + }); + }; + + this.pending = function(message) { + var fullMessage = j$.Spec.pendingSpecExceptionMessage; + if (message) { + fullMessage += message; + } + throw fullMessage; + }; + + this.fail = function(error) { + if (!currentRunnable()) { + throw new Error( + "'fail' was used when there was no current spec, this could be because an asynchronous test timed out" + ); + } + + var message = 'Failed'; + if (error) { + message += ': '; + if (error.message) { + message += error.message; + } else if (j$.isString_(error)) { + message += error; + } else { + // pretty print all kind of objects. This includes arrays. + message += makePrettyPrinter()(error); + } + } + + currentRunnable().addExpectationResult(false, { + matcherName: '', + passed: false, + expected: '', + actual: '', + message: message, + error: error && error.message ? error : null + }); + + if (config.oneFailurePerSpec) { + throw new Error(message); + } + }; + + this.cleanup_ = function() { + if (globalErrors) { + globalErrors.uninstall(); + } + }; + } + + return Env; +}; + +getJasmineRequireObj().JsApiReporter = function(j$) { + /** + * @name jsApiReporter + * @classdesc {@link Reporter} added by default in `boot.js` to record results for retrieval in javascript code. An instance is made available as `jsApiReporter` on the global object. + * @class + * @hideconstructor + */ + function JsApiReporter(options) { + var timer = options.timer || new j$.Timer(), + status = 'loaded'; + + this.started = false; + this.finished = false; + this.runDetails = {}; + + this.jasmineStarted = function() { + this.started = true; + status = 'started'; + timer.start(); + }; + + var executionTime; + + this.jasmineDone = function(runDetails) { + this.finished = true; + this.runDetails = runDetails; + executionTime = timer.elapsed(); + status = 'done'; + }; + + /** + * Get the current status for the Jasmine environment. + * @name jsApiReporter#status + * @since 2.0.0 + * @function + * @return {String} - One of `loaded`, `started`, or `done` + */ + this.status = function() { + return status; + }; + + var suites = [], + suites_hash = {}; + + this.suiteStarted = function(result) { + suites_hash[result.id] = result; + }; + + this.suiteDone = function(result) { + storeSuite(result); + }; + + /** + * Get the results for a set of suites. + * + * Retrievable in slices for easier serialization. + * @name jsApiReporter#suiteResults + * @since 2.1.0 + * @function + * @param {Number} index - The position in the suites list to start from. + * @param {Number} length - Maximum number of suite results to return. + * @return {SuiteResult[]} + */ + this.suiteResults = function(index, length) { + return suites.slice(index, index + length); + }; + + function storeSuite(result) { + suites.push(result); + suites_hash[result.id] = result; + } + + /** + * Get all of the suites in a single object, with their `id` as the key. + * @name jsApiReporter#suites + * @since 2.0.0 + * @function + * @return {Object} - Map of suite id to {@link SuiteResult} + */ + this.suites = function() { + return suites_hash; + }; + + var specs = []; + + this.specDone = function(result) { + specs.push(result); + }; + + /** + * Get the results for a set of specs. + * + * Retrievable in slices for easier serialization. + * @name jsApiReporter#specResults + * @since 2.0.0 + * @function + * @param {Number} index - The position in the specs list to start from. + * @param {Number} length - Maximum number of specs results to return. + * @return {SpecResult[]} + */ + this.specResults = function(index, length) { + return specs.slice(index, index + length); + }; + + /** + * Get all spec results. + * @name jsApiReporter#specs + * @since 2.0.0 + * @function + * @return {SpecResult[]} + */ + this.specs = function() { + return specs; + }; + + /** + * Get the number of milliseconds it took for the full Jasmine suite to run. + * @name jsApiReporter#executionTime + * @since 2.0.0 + * @function + * @return {Number} + */ + this.executionTime = function() { + return executionTime; + }; + } + + return JsApiReporter; +}; + +getJasmineRequireObj().Any = function(j$) { + function Any(expectedObject) { + if (typeof expectedObject === 'undefined') { + throw new TypeError( + 'jasmine.any() expects to be passed a constructor function. ' + + 'Please pass one or use jasmine.anything() to match any object.' + ); + } + this.expectedObject = expectedObject; + } + + Any.prototype.asymmetricMatch = function(other) { + if (this.expectedObject == String) { + return typeof other == 'string' || other instanceof String; + } + + if (this.expectedObject == Number) { + return typeof other == 'number' || other instanceof Number; + } + + if (this.expectedObject == Function) { + return typeof other == 'function' || other instanceof Function; + } + + if (this.expectedObject == Object) { + return other !== null && typeof other == 'object'; + } + + if (this.expectedObject == Boolean) { + return typeof other == 'boolean'; + } + + /* jshint -W122 */ + /* global Symbol */ + if (typeof Symbol != 'undefined' && this.expectedObject == Symbol) { + return typeof other == 'symbol'; + } + /* jshint +W122 */ + + return other instanceof this.expectedObject; + }; + + Any.prototype.jasmineToString = function() { + return ''; + }; + + return Any; +}; + +getJasmineRequireObj().Anything = function(j$) { + function Anything() {} + + Anything.prototype.asymmetricMatch = function(other) { + return !j$.util.isUndefined(other) && other !== null; + }; + + Anything.prototype.jasmineToString = function() { + return ''; + }; + + return Anything; +}; + +getJasmineRequireObj().ArrayContaining = function(j$) { + function ArrayContaining(sample) { + this.sample = sample; + } + + ArrayContaining.prototype.asymmetricMatch = function(other, matchersUtil) { + if (!j$.isArray_(this.sample)) { + throw new Error( + 'You must provide an array to arrayContaining, not ' + + j$.pp(this.sample) + + '.' + ); + } + + // If the actual parameter is not an array, we can fail immediately, since it couldn't + // possibly be an "array containing" anything. However, we also want an empty sample + // array to match anything, so we need to double-check we aren't in that case + if (!j$.isArray_(other) && this.sample.length > 0) { + return false; + } + + for (var i = 0; i < this.sample.length; i++) { + var item = this.sample[i]; + if (!matchersUtil.contains(other, item)) { + return false; + } + } + + return true; + }; + + ArrayContaining.prototype.jasmineToString = function(pp) { + return ''; + }; + + return ArrayContaining; +}; + +getJasmineRequireObj().ArrayWithExactContents = function(j$) { + function ArrayWithExactContents(sample) { + this.sample = sample; + } + + ArrayWithExactContents.prototype.asymmetricMatch = function( + other, + matchersUtil + ) { + if (!j$.isArray_(this.sample)) { + throw new Error( + 'You must provide an array to arrayWithExactContents, not ' + + j$.pp(this.sample) + + '.' + ); + } + + if (this.sample.length !== other.length) { + return false; + } + + for (var i = 0; i < this.sample.length; i++) { + var item = this.sample[i]; + if (!matchersUtil.contains(other, item)) { + return false; + } + } + + return true; + }; + + ArrayWithExactContents.prototype.jasmineToString = function(pp) { + return ''; + }; + + return ArrayWithExactContents; +}; + +getJasmineRequireObj().Empty = function(j$) { + function Empty() {} + + Empty.prototype.asymmetricMatch = function(other) { + if (j$.isString_(other) || j$.isArray_(other) || j$.isTypedArray_(other)) { + return other.length === 0; + } + + if (j$.isMap(other) || j$.isSet(other)) { + return other.size === 0; + } + + if (j$.isObject_(other)) { + return Object.keys(other).length === 0; + } + return false; + }; + + Empty.prototype.jasmineToString = function() { + return ''; + }; + + return Empty; +}; + +getJasmineRequireObj().Falsy = function(j$) { + function Falsy() {} + + Falsy.prototype.asymmetricMatch = function(other) { + return !other; + }; + + Falsy.prototype.jasmineToString = function() { + return ''; + }; + + return Falsy; +}; + +getJasmineRequireObj().MapContaining = function(j$) { + function MapContaining(sample) { + if (!j$.isMap(sample)) { + throw new Error( + 'You must provide a map to `mapContaining`, not ' + j$.pp(sample) + ); + } + + this.sample = sample; + } + + MapContaining.prototype.asymmetricMatch = function(other, matchersUtil) { + if (!j$.isMap(other)) return false; + + var hasAllMatches = true; + j$.util.forEachBreakable(this.sample, function(breakLoop, value, key) { + // for each key/value pair in `sample` + // there should be at least one pair in `other` whose key and value both match + var hasMatch = false; + j$.util.forEachBreakable(other, function(oBreakLoop, oValue, oKey) { + if ( + matchersUtil.equals(oKey, key) && + matchersUtil.equals(oValue, value) + ) { + hasMatch = true; + oBreakLoop(); + } + }); + if (!hasMatch) { + hasAllMatches = false; + breakLoop(); + } + }); + + return hasAllMatches; + }; + + MapContaining.prototype.jasmineToString = function(pp) { + return ''; + }; + + return MapContaining; +}; + +getJasmineRequireObj().NotEmpty = function(j$) { + function NotEmpty() {} + + NotEmpty.prototype.asymmetricMatch = function(other) { + if (j$.isString_(other) || j$.isArray_(other) || j$.isTypedArray_(other)) { + return other.length !== 0; + } + + if (j$.isMap(other) || j$.isSet(other)) { + return other.size !== 0; + } + + if (j$.isObject_(other)) { + return Object.keys(other).length !== 0; + } + + return false; + }; + + NotEmpty.prototype.jasmineToString = function() { + return ''; + }; + + return NotEmpty; +}; + +getJasmineRequireObj().ObjectContaining = function(j$) { + function ObjectContaining(sample) { + this.sample = sample; + } + + function getPrototype(obj) { + if (Object.getPrototypeOf) { + return Object.getPrototypeOf(obj); + } + + if (obj.constructor.prototype == obj) { + return null; + } + + return obj.constructor.prototype; + } + + function hasProperty(obj, property) { + if (!obj || typeof obj !== 'object') { + return false; + } + + if (Object.prototype.hasOwnProperty.call(obj, property)) { + return true; + } + + return hasProperty(getPrototype(obj), property); + } + + ObjectContaining.prototype.asymmetricMatch = function(other, matchersUtil) { + if (typeof this.sample !== 'object') { + throw new Error( + "You must provide an object to objectContaining, not '" + + this.sample + + "'." + ); + } + if (typeof other !== 'object') { + return false; + } + + for (var property in this.sample) { + if ( + !hasProperty(other, property) || + !matchersUtil.equals(this.sample[property], other[property]) + ) { + return false; + } + } + + return true; + }; + + ObjectContaining.prototype.valuesForDiff_ = function(other, pp) { + if (!j$.isObject_(other)) { + return { + self: this.jasmineToString(pp), + other: other + }; + } + + var filteredOther = {}; + Object.keys(this.sample).forEach(function(k) { + // eq short-circuits comparison of objects that have different key sets, + // so include all keys even if undefined. + filteredOther[k] = other[k]; + }); + + return { + self: this.sample, + other: filteredOther + }; + }; + + ObjectContaining.prototype.jasmineToString = function(pp) { + return ''; + }; + + return ObjectContaining; +}; + +getJasmineRequireObj().SetContaining = function(j$) { + function SetContaining(sample) { + if (!j$.isSet(sample)) { + throw new Error( + 'You must provide a set to `setContaining`, not ' + j$.pp(sample) + ); + } + + this.sample = sample; + } + + SetContaining.prototype.asymmetricMatch = function(other, matchersUtil) { + if (!j$.isSet(other)) return false; + + var hasAllMatches = true; + j$.util.forEachBreakable(this.sample, function(breakLoop, item) { + // for each item in `sample` there should be at least one matching item in `other` + // (not using `matchersUtil.contains` because it compares set members by reference, + // not by deep value equality) + var hasMatch = false; + j$.util.forEachBreakable(other, function(oBreakLoop, oItem) { + if (matchersUtil.equals(oItem, item)) { + hasMatch = true; + oBreakLoop(); + } + }); + if (!hasMatch) { + hasAllMatches = false; + breakLoop(); + } + }); + + return hasAllMatches; + }; + + SetContaining.prototype.jasmineToString = function(pp) { + return ''; + }; + + return SetContaining; +}; + +getJasmineRequireObj().StringMatching = function(j$) { + function StringMatching(expected) { + if (!j$.isString_(expected) && !j$.isA_('RegExp', expected)) { + throw new Error('Expected is not a String or a RegExp'); + } + + this.regexp = new RegExp(expected); + } + + StringMatching.prototype.asymmetricMatch = function(other) { + return this.regexp.test(other); + }; + + StringMatching.prototype.jasmineToString = function() { + return ''; + }; + + return StringMatching; +}; + +getJasmineRequireObj().Truthy = function(j$) { + function Truthy() {} + + Truthy.prototype.asymmetricMatch = function(other) { + return !!other; + }; + + Truthy.prototype.jasmineToString = function() { + return ''; + }; + + return Truthy; +}; + +getJasmineRequireObj().asymmetricEqualityTesterArgCompatShim = function(j$) { + /* + Older versions of Jasmine passed an array of custom equality testers as the + second argument to each asymmetric equality tester's `asymmetricMatch` + method. Newer versions will pass a `MatchersUtil` instance. The + asymmetricEqualityTesterArgCompatShim allows for a graceful migration from + the old interface to the new by "being" both an array of custom equality + testers and a `MatchersUtil` at the same time. + + This code should be removed in the next major release. + */ + + var likelyArrayProps = [ + 'concat', + 'constructor', + 'copyWithin', + 'entries', + 'every', + 'fill', + 'filter', + 'find', + 'findIndex', + 'flat', + 'flatMap', + 'forEach', + 'includes', + 'indexOf', + 'join', + 'keys', + 'lastIndexOf', + 'length', + 'map', + 'pop', + 'push', + 'reduce', + 'reduceRight', + 'reverse', + 'shift', + 'slice', + 'some', + 'sort', + 'splice', + 'toLocaleString', + 'toSource', + 'toString', + 'unshift', + 'values' + ]; + + function asymmetricEqualityTesterArgCompatShim( + matchersUtil, + customEqualityTesters + ) { + var self = Object.create(matchersUtil), + props, + i, + k; + + copy(self, customEqualityTesters, 'length'); + + for (i = 0; i < customEqualityTesters.length; i++) { + copy(self, customEqualityTesters, i); + } + + var props = arrayProps(); + + for (i = 0; i < props.length; i++) { + k = props[i]; + // Skip length (dealt with above), and anything that collides with + // MatchesUtil e.g. an Array.prototype.contains method added by user code + if (k !== 'length' && !self[k]) { + copy(self, Array.prototype, k); + } + } + + return self; + } + + function copy(dest, src, propName) { + Object.defineProperty(dest, propName, { + get: function() { + return src[propName]; + } + }); + } + + function arrayProps() { + var props, a, k; + + if (!Object.getOwnPropertyDescriptors) { + return likelyArrayProps.filter(function(k) { + return Array.prototype.hasOwnProperty(k); + }); + } + + props = Object.getOwnPropertyDescriptors(Array.prototype); // eslint-disable-line compat/compat + a = []; + + for (k in props) { + a.push(k); + } + + return a; + } + + return asymmetricEqualityTesterArgCompatShim; +}; + +getJasmineRequireObj().CallTracker = function(j$) { + /** + * @namespace Spy#calls + * @since 2.0.0 + */ + function CallTracker() { + var calls = []; + var opts = {}; + + this.track = function(context) { + if (opts.cloneArgs) { + context.args = j$.util.cloneArgs(context.args); + } + calls.push(context); + }; + + /** + * Check whether this spy has been invoked. + * @name Spy#calls#any + * @since 2.0.0 + * @function + * @return {Boolean} + */ + this.any = function() { + return !!calls.length; + }; + + /** + * Get the number of invocations of this spy. + * @name Spy#calls#count + * @since 2.0.0 + * @function + * @return {Integer} + */ + this.count = function() { + return calls.length; + }; + + /** + * Get the arguments that were passed to a specific invocation of this spy. + * @name Spy#calls#argsFor + * @since 2.0.0 + * @function + * @param {Integer} index The 0-based invocation index. + * @return {Array} + */ + this.argsFor = function(index) { + var call = calls[index]; + return call ? call.args : []; + }; + + /** + * Get the "this" object that was passed to a specific invocation of this spy. + * @name Spy#calls#thisFor + * @function + * @param {Integer} index The 0-based invocation index. + * @return {Object?} + */ + this.thisFor = function(index) { + var call = calls[index]; + return call ? call.object : undefined; + }; + + /** + * Get the raw calls array for this spy. + * @name Spy#calls#all + * @since 2.0.0 + * @function + * @return {Spy.callData[]} + */ + this.all = function() { + return calls; + }; + + /** + * Get all of the arguments for each invocation of this spy in the order they were received. + * @name Spy#calls#allArgs + * @since 2.0.0 + * @function + * @return {Array} + */ + this.allArgs = function() { + var callArgs = []; + for (var i = 0; i < calls.length; i++) { + callArgs.push(calls[i].args); + } + + return callArgs; + }; + + /** + * Get the first invocation of this spy. + * @name Spy#calls#first + * @since 2.0.0 + * @function + * @return {ObjecSpy.callData} + */ + this.first = function() { + return calls[0]; + }; + + /** + * Get the most recent invocation of this spy. + * @name Spy#calls#mostRecent + * @since 2.0.0 + * @function + * @return {ObjecSpy.callData} + */ + this.mostRecent = function() { + return calls[calls.length - 1]; + }; + + /** + * Reset this spy as if it has never been called. + * @name Spy#calls#reset + * @since 2.0.0 + * @function + */ + this.reset = function() { + calls = []; + }; + + /** + * Set this spy to do a shallow clone of arguments passed to each invocation. + * @name Spy#calls#saveArgumentsByValue + * @since 2.5.0 + * @function + */ + this.saveArgumentsByValue = function() { + opts.cloneArgs = true; + }; + } + + return CallTracker; +}; + +getJasmineRequireObj().clearStack = function(j$) { + var maxInlineCallCount = 10; + + function messageChannelImpl(global, setTimeout) { + var channel = new global.MessageChannel(), + head = {}, + tail = head; + + var taskRunning = false; + channel.port1.onmessage = function() { + head = head.next; + var task = head.task; + delete head.task; + + if (taskRunning) { + global.setTimeout(task, 0); + } else { + try { + taskRunning = true; + task(); + } finally { + taskRunning = false; + } + } + }; + + var currentCallCount = 0; + return function clearStack(fn) { + currentCallCount++; + + if (currentCallCount < maxInlineCallCount) { + tail = tail.next = { task: fn }; + channel.port2.postMessage(0); + } else { + currentCallCount = 0; + setTimeout(fn); + } + }; + } + + function getClearStack(global) { + var currentCallCount = 0; + var realSetTimeout = global.setTimeout; + var setTimeoutImpl = function clearStack(fn) { + Function.prototype.apply.apply(realSetTimeout, [global, [fn, 0]]); + }; + + if (j$.isFunction_(global.setImmediate)) { + var realSetImmediate = global.setImmediate; + return function(fn) { + currentCallCount++; + + if (currentCallCount < maxInlineCallCount) { + realSetImmediate(fn); + } else { + currentCallCount = 0; + + setTimeoutImpl(fn); + } + }; + } else if (!j$.util.isUndefined(global.MessageChannel)) { + return messageChannelImpl(global, setTimeoutImpl); + } else { + return setTimeoutImpl; + } + } + + return getClearStack; +}; + +getJasmineRequireObj().Clock = function() { + /* global process */ + var NODE_JS = + typeof process !== 'undefined' && + process.versions && + typeof process.versions.node === 'string'; + + /** + * @class Clock + * @classdesc Jasmine's mock clock is used when testing time dependent code.
+ * _Note:_ Do not construct this directly. You can get the current clock with + * {@link jasmine.clock}. + * @hideconstructor + */ + function Clock(global, delayedFunctionSchedulerFactory, mockDate) { + var self = this, + realTimingFunctions = { + setTimeout: global.setTimeout, + clearTimeout: global.clearTimeout, + setInterval: global.setInterval, + clearInterval: global.clearInterval + }, + fakeTimingFunctions = { + setTimeout: setTimeout, + clearTimeout: clearTimeout, + setInterval: setInterval, + clearInterval: clearInterval + }, + installed = false, + delayedFunctionScheduler, + timer; + + self.FakeTimeout = FakeTimeout; + + /** + * Install the mock clock over the built-in methods. + * @name Clock#install + * @since 2.0.0 + * @function + * @return {Clock} + */ + self.install = function() { + if (!originalTimingFunctionsIntact()) { + throw new Error( + 'Jasmine Clock was unable to install over custom global timer functions. Is the clock already installed?' + ); + } + replace(global, fakeTimingFunctions); + timer = fakeTimingFunctions; + delayedFunctionScheduler = delayedFunctionSchedulerFactory(); + installed = true; + + return self; + }; + + /** + * Uninstall the mock clock, returning the built-in methods to their places. + * @name Clock#uninstall + * @since 2.0.0 + * @function + */ + self.uninstall = function() { + delayedFunctionScheduler = null; + mockDate.uninstall(); + replace(global, realTimingFunctions); + + timer = realTimingFunctions; + installed = false; + }; + + /** + * Execute a function with a mocked Clock + * + * The clock will be {@link Clock#install|install}ed before the function is called and {@link Clock#uninstall|uninstall}ed in a `finally` after the function completes. + * @name Clock#withMock + * @since 2.3.0 + * @function + * @param {Function} closure The function to be called. + */ + self.withMock = function(closure) { + this.install(); + try { + closure(); + } finally { + this.uninstall(); + } + }; + + /** + * Instruct the installed Clock to also mock the date returned by `new Date()` + * @name Clock#mockDate + * @since 2.1.0 + * @function + * @param {Date} [initialDate=now] The `Date` to provide. + */ + self.mockDate = function(initialDate) { + mockDate.install(initialDate); + }; + + self.setTimeout = function(fn, delay, params) { + return Function.prototype.apply.apply(timer.setTimeout, [ + global, + arguments + ]); + }; + + self.setInterval = function(fn, delay, params) { + return Function.prototype.apply.apply(timer.setInterval, [ + global, + arguments + ]); + }; + + self.clearTimeout = function(id) { + return Function.prototype.call.apply(timer.clearTimeout, [global, id]); + }; + + self.clearInterval = function(id) { + return Function.prototype.call.apply(timer.clearInterval, [global, id]); + }; + + /** + * Tick the Clock forward, running any enqueued timeouts along the way + * @name Clock#tick + * @since 1.3.0 + * @function + * @param {int} millis The number of milliseconds to tick. + */ + self.tick = function(millis) { + if (installed) { + delayedFunctionScheduler.tick(millis, function(millis) { + mockDate.tick(millis); + }); + } else { + throw new Error( + 'Mock clock is not installed, use jasmine.clock().install()' + ); + } + }; + + return self; + + function originalTimingFunctionsIntact() { + return ( + global.setTimeout === realTimingFunctions.setTimeout && + global.clearTimeout === realTimingFunctions.clearTimeout && + global.setInterval === realTimingFunctions.setInterval && + global.clearInterval === realTimingFunctions.clearInterval + ); + } + + function replace(dest, source) { + for (var prop in source) { + dest[prop] = source[prop]; + } + } + + function setTimeout(fn, delay) { + if (!NODE_JS) { + return delayedFunctionScheduler.scheduleFunction( + fn, + delay, + argSlice(arguments, 2) + ); + } + + var timeout = new FakeTimeout(); + + delayedFunctionScheduler.scheduleFunction( + fn, + delay, + argSlice(arguments, 2), + false, + timeout + ); + + return timeout; + } + + function clearTimeout(id) { + return delayedFunctionScheduler.removeFunctionWithId(id); + } + + function setInterval(fn, interval) { + if (!NODE_JS) { + return delayedFunctionScheduler.scheduleFunction( + fn, + interval, + argSlice(arguments, 2), + true + ); + } + + var timeout = new FakeTimeout(); + + delayedFunctionScheduler.scheduleFunction( + fn, + interval, + argSlice(arguments, 2), + true, + timeout + ); + + return timeout; + } + + function clearInterval(id) { + return delayedFunctionScheduler.removeFunctionWithId(id); + } + + function argSlice(argsObj, n) { + return Array.prototype.slice.call(argsObj, n); + } + } + + /** + * Mocks Node.js Timeout class + */ + function FakeTimeout() {} + + FakeTimeout.prototype.ref = function() { + return this; + }; + + FakeTimeout.prototype.unref = function() { + return this; + }; + + return Clock; +}; + +getJasmineRequireObj().DelayedFunctionScheduler = function(j$) { + function DelayedFunctionScheduler() { + var self = this; + var scheduledLookup = []; + var scheduledFunctions = {}; + var currentTime = 0; + var delayedFnCount = 0; + var deletedKeys = []; + + self.tick = function(millis, tickDate) { + millis = millis || 0; + var endTime = currentTime + millis; + + runScheduledFunctions(endTime, tickDate); + currentTime = endTime; + }; + + self.scheduleFunction = function( + funcToCall, + millis, + params, + recurring, + timeoutKey, + runAtMillis + ) { + var f; + if (typeof funcToCall === 'string') { + /* jshint evil: true */ + f = function() { + return eval(funcToCall); + }; + /* jshint evil: false */ + } else { + f = funcToCall; + } + + millis = millis || 0; + timeoutKey = timeoutKey || ++delayedFnCount; + runAtMillis = runAtMillis || currentTime + millis; + + var funcToSchedule = { + runAtMillis: runAtMillis, + funcToCall: f, + recurring: recurring, + params: params, + timeoutKey: timeoutKey, + millis: millis + }; + + if (runAtMillis in scheduledFunctions) { + scheduledFunctions[runAtMillis].push(funcToSchedule); + } else { + scheduledFunctions[runAtMillis] = [funcToSchedule]; + scheduledLookup.push(runAtMillis); + scheduledLookup.sort(function(a, b) { + return a - b; + }); + } + + return timeoutKey; + }; + + self.removeFunctionWithId = function(timeoutKey) { + deletedKeys.push(timeoutKey); + + for (var runAtMillis in scheduledFunctions) { + var funcs = scheduledFunctions[runAtMillis]; + var i = indexOfFirstToPass(funcs, function(func) { + return func.timeoutKey === timeoutKey; + }); + + if (i > -1) { + if (funcs.length === 1) { + delete scheduledFunctions[runAtMillis]; + deleteFromLookup(runAtMillis); + } else { + funcs.splice(i, 1); + } + + // intervals get rescheduled when executed, so there's never more + // than a single scheduled function with a given timeoutKey + break; + } + } + }; + + return self; + + function indexOfFirstToPass(array, testFn) { + var index = -1; + + for (var i = 0; i < array.length; ++i) { + if (testFn(array[i])) { + index = i; + break; + } + } + + return index; + } + + function deleteFromLookup(key) { + var value = Number(key); + var i = indexOfFirstToPass(scheduledLookup, function(millis) { + return millis === value; + }); + + if (i > -1) { + scheduledLookup.splice(i, 1); + } + } + + function reschedule(scheduledFn) { + self.scheduleFunction( + scheduledFn.funcToCall, + scheduledFn.millis, + scheduledFn.params, + true, + scheduledFn.timeoutKey, + scheduledFn.runAtMillis + scheduledFn.millis + ); + } + + function forEachFunction(funcsToRun, callback) { + for (var i = 0; i < funcsToRun.length; ++i) { + callback(funcsToRun[i]); + } + } + + function runScheduledFunctions(endTime, tickDate) { + tickDate = tickDate || function() {}; + if (scheduledLookup.length === 0 || scheduledLookup[0] > endTime) { + tickDate(endTime - currentTime); + return; + } + + do { + deletedKeys = []; + var newCurrentTime = scheduledLookup.shift(); + tickDate(newCurrentTime - currentTime); + + currentTime = newCurrentTime; + + var funcsToRun = scheduledFunctions[currentTime]; + + delete scheduledFunctions[currentTime]; + + forEachFunction(funcsToRun, function(funcToRun) { + if (funcToRun.recurring) { + reschedule(funcToRun); + } + }); + + forEachFunction(funcsToRun, function(funcToRun) { + if (j$.util.arrayContains(deletedKeys, funcToRun.timeoutKey)) { + // skip a timeoutKey deleted whilst we were running + return; + } + funcToRun.funcToCall.apply(null, funcToRun.params || []); + }); + deletedKeys = []; + } while ( + scheduledLookup.length > 0 && + // checking first if we're out of time prevents setTimeout(0) + // scheduled in a funcToRun from forcing an extra iteration + currentTime !== endTime && + scheduledLookup[0] <= endTime + ); + + // ran out of functions to call, but still time left on the clock + if (currentTime !== endTime) { + tickDate(endTime - currentTime); + } + } + } + + return DelayedFunctionScheduler; +}; + +getJasmineRequireObj().errors = function() { + function ExpectationFailed() {} + + ExpectationFailed.prototype = new Error(); + ExpectationFailed.prototype.constructor = ExpectationFailed; + + return { + ExpectationFailed: ExpectationFailed + }; +}; + +getJasmineRequireObj().ExceptionFormatter = function(j$) { + var ignoredProperties = [ + 'name', + 'message', + 'stack', + 'fileName', + 'sourceURL', + 'line', + 'lineNumber', + 'column', + 'description', + 'jasmineMessage' + ]; + + function ExceptionFormatter(options) { + var jasmineFile = (options && options.jasmineFile) || j$.util.jasmineFile(); + this.message = function(error) { + var message = ''; + + if (error.jasmineMessage) { + message += error.jasmineMessage; + } else if (error.name && error.message) { + message += error.name + ': ' + error.message; + } else if (error.message) { + message += error.message; + } else { + message += error.toString() + ' thrown'; + } + + if (error.fileName || error.sourceURL) { + message += ' in ' + (error.fileName || error.sourceURL); + } + + if (error.line || error.lineNumber) { + message += ' (line ' + (error.line || error.lineNumber) + ')'; + } + + return message; + }; + + this.stack = function(error) { + if (!error || !error.stack) { + return null; + } + + var stackTrace = new j$.StackTrace(error); + var lines = filterJasmine(stackTrace); + var result = ''; + + if (stackTrace.message) { + lines.unshift(stackTrace.message); + } + + result += formatProperties(error); + result += lines.join('\n'); + + return result; + }; + + function filterJasmine(stackTrace) { + var result = [], + jasmineMarker = + stackTrace.style === 'webkit' ? '' : ' at '; + + stackTrace.frames.forEach(function(frame) { + if (frame.file !== jasmineFile) { + result.push(frame.raw); + } else if (result[result.length - 1] !== jasmineMarker) { + result.push(jasmineMarker); + } + }); + + return result; + } + + function formatProperties(error) { + if (!(error instanceof Object)) { + return; + } + + var result = {}; + var empty = true; + + for (var prop in error) { + if (j$.util.arrayContains(ignoredProperties, prop)) { + continue; + } + result[prop] = error[prop]; + empty = false; + } + + if (!empty) { + return 'error properties: ' + j$.pp(result) + '\n'; + } + + return ''; + } + } + + return ExceptionFormatter; +}; + +getJasmineRequireObj().Expectation = function(j$) { + /** + * Matchers that come with Jasmine out of the box. + * @namespace matchers + */ + function Expectation(options) { + this.expector = new j$.Expector(options); + + var customMatchers = options.customMatchers || {}; + for (var matcherName in customMatchers) { + this[matcherName] = wrapSyncCompare( + matcherName, + customMatchers[matcherName] + ); + } + } + + /** + * Add some context for an {@link expect} + * @function + * @name matchers#withContext + * @since 3.3.0 + * @param {String} message - Additional context to show when the matcher fails + * @return {matchers} + */ + Expectation.prototype.withContext = function withContext(message) { + return addFilter(this, new ContextAddingFilter(message)); + }; + + /** + * Invert the matcher following this {@link expect} + * @member + * @name matchers#not + * @since 1.3.0 + * @type {matchers} + * @example + * expect(something).not.toBe(true); + */ + Object.defineProperty(Expectation.prototype, 'not', { + get: function() { + return addFilter(this, syncNegatingFilter); + } + }); + + /** + * Asynchronous matchers that operate on an actual value which is a promise, + * and return a promise. + * + * Most async matchers will wait indefinitely for the promise to be resolved + * or rejected, resulting in a spec timeout if that never happens. If you + * expect that the promise will already be resolved or rejected at the time + * the matcher is called, you can use the {@link async-matchers#already} + * modifier to get a faster failure with a more helpful message. + * + * Note: Specs must await the result of each async matcher, return the + * promise returned by the matcher, or return a promise that's derived from + * the one returned by the matcher. Otherwise the matcher will not be + * evaluated before the spec completes. + * + * @example + * // Good + * await expectAsync(aPromise).toBeResolved(); + * @example + * // Good + * return expectAsync(aPromise).toBeResolved(); + * @example + * // Good + * return expectAsync(aPromise).toBeResolved() + * .then(function() { + * // more spec code + * }); + * @example + * // Bad + * expectAsync(aPromise).toBeResolved(); + * @namespace async-matchers + */ + function AsyncExpectation(options) { + var global = options.global || j$.getGlobal(); + this.expector = new j$.Expector(options); + + if (!global.Promise) { + throw new Error( + 'expectAsync is unavailable because the environment does not support promises.' + ); + } + + var customAsyncMatchers = options.customAsyncMatchers || {}; + for (var matcherName in customAsyncMatchers) { + this[matcherName] = wrapAsyncCompare( + matcherName, + customAsyncMatchers[matcherName] + ); + } + } + + /** + * Add some context for an {@link expectAsync} + * @function + * @name async-matchers#withContext + * @since 3.3.0 + * @param {String} message - Additional context to show when the async matcher fails + * @return {async-matchers} + */ + AsyncExpectation.prototype.withContext = function withContext(message) { + return addFilter(this, new ContextAddingFilter(message)); + }; + + /** + * Invert the matcher following this {@link expectAsync} + * @member + * @name async-matchers#not + * @type {async-matchers} + * @example + * await expectAsync(myPromise).not.toBeResolved(); + * @example + * return expectAsync(myPromise).not.toBeResolved(); + */ + Object.defineProperty(AsyncExpectation.prototype, 'not', { + get: function() { + return addFilter(this, asyncNegatingFilter); + } + }); + + /** + * Fail as soon as possible if the actual is pending. + * Otherwise evaluate the matcher. + * @member + * @name async-matchers#already + * @type {async-matchers} + * @example + * await expectAsync(myPromise).already.toBeResolved(); + * @example + * return expectAsync(myPromise).already.toBeResolved(); + */ + Object.defineProperty(AsyncExpectation.prototype, 'already', { + get: function() { + return addFilter(this, expectSettledPromiseFilter); + } + }); + + function wrapSyncCompare(name, matcherFactory) { + return function() { + var result = this.expector.compare(name, matcherFactory, arguments); + this.expector.processResult(result); + }; + } + + function wrapAsyncCompare(name, matcherFactory) { + return function() { + var self = this; + + // Capture the call stack here, before we go async, so that it will contain + // frames that are relevant to the user instead of just parts of Jasmine. + var errorForStack = j$.util.errorWithStack(); + + return this.expector + .compare(name, matcherFactory, arguments) + .then(function(result) { + self.expector.processResult(result, errorForStack); + }); + }; + } + + function addCoreMatchers(prototype, matchers, wrapper) { + for (var matcherName in matchers) { + var matcher = matchers[matcherName]; + prototype[matcherName] = wrapper(matcherName, matcher); + } + } + + function addFilter(source, filter) { + var result = Object.create(source); + result.expector = source.expector.addFilter(filter); + return result; + } + + function negatedFailureMessage(result, matcherName, args, matchersUtil) { + if (result.message) { + if (j$.isFunction_(result.message)) { + return result.message(); + } else { + return result.message; + } + } + + args = args.slice(); + args.unshift(true); + args.unshift(matcherName); + return matchersUtil.buildFailureMessage.apply(matchersUtil, args); + } + + function negate(result) { + result.pass = !result.pass; + return result; + } + + var syncNegatingFilter = { + selectComparisonFunc: function(matcher) { + function defaultNegativeCompare() { + return negate(matcher.compare.apply(null, arguments)); + } + + return matcher.negativeCompare || defaultNegativeCompare; + }, + buildFailureMessage: negatedFailureMessage + }; + + var asyncNegatingFilter = { + selectComparisonFunc: function(matcher) { + function defaultNegativeCompare() { + return matcher.compare.apply(this, arguments).then(negate); + } + + return matcher.negativeCompare || defaultNegativeCompare; + }, + buildFailureMessage: negatedFailureMessage + }; + + var expectSettledPromiseFilter = { + selectComparisonFunc: function(matcher) { + return function(actual) { + var matcherArgs = arguments; + + return j$.isPending_(actual).then(function(isPending) { + if (isPending) { + return { + pass: false, + message: + 'Expected a promise to be settled (via ' + + 'expectAsync(...).already) but it was pending.' + }; + } else { + return matcher.compare.apply(null, matcherArgs); + } + }); + }; + } + }; + + function ContextAddingFilter(message) { + this.message = message; + } + + ContextAddingFilter.prototype.modifyFailureMessage = function(msg) { + var nl = msg.indexOf('\n'); + + if (nl === -1) { + return this.message + ': ' + msg; + } else { + return this.message + ':\n' + indent(msg); + } + }; + + function indent(s) { + return s.replace(/^/gm, ' '); + } + + return { + factory: function(options) { + return new Expectation(options || {}); + }, + addCoreMatchers: function(matchers) { + addCoreMatchers(Expectation.prototype, matchers, wrapSyncCompare); + }, + asyncFactory: function(options) { + return new AsyncExpectation(options || {}); + }, + addAsyncCoreMatchers: function(matchers) { + addCoreMatchers(AsyncExpectation.prototype, matchers, wrapAsyncCompare); + } + }; +}; + +getJasmineRequireObj().ExpectationFilterChain = function() { + function ExpectationFilterChain(maybeFilter, prev) { + this.filter_ = maybeFilter; + this.prev_ = prev; + } + + ExpectationFilterChain.prototype.addFilter = function(filter) { + return new ExpectationFilterChain(filter, this); + }; + + ExpectationFilterChain.prototype.selectComparisonFunc = function(matcher) { + return this.callFirst_('selectComparisonFunc', arguments).result; + }; + + ExpectationFilterChain.prototype.buildFailureMessage = function( + result, + matcherName, + args, + matchersUtil + ) { + return this.callFirst_('buildFailureMessage', arguments).result; + }; + + ExpectationFilterChain.prototype.modifyFailureMessage = function(msg) { + var result = this.callFirst_('modifyFailureMessage', arguments).result; + return result || msg; + }; + + ExpectationFilterChain.prototype.callFirst_ = function(fname, args) { + var prevResult; + + if (this.prev_) { + prevResult = this.prev_.callFirst_(fname, args); + + if (prevResult.found) { + return prevResult; + } + } + + if (this.filter_ && this.filter_[fname]) { + return { + found: true, + result: this.filter_[fname].apply(this.filter_, args) + }; + } + + return { found: false }; + }; + + return ExpectationFilterChain; +}; + +//TODO: expectation result may make more sense as a presentation of an expectation. +getJasmineRequireObj().buildExpectationResult = function(j$) { + function buildExpectationResult(options) { + var messageFormatter = options.messageFormatter || function() {}, + stackFormatter = options.stackFormatter || function() {}; + + /** + * @typedef Expectation + * @property {String} matcherName - The name of the matcher that was executed for this expectation. + * @property {String} message - The failure message for the expectation. + * @property {String} stack - The stack trace for the failure if available. + * @property {Boolean} passed - Whether the expectation passed or failed. + * @property {Object} expected - If the expectation failed, what was the expected value. + * @property {Object} actual - If the expectation failed, what actual value was produced. + */ + var result = { + matcherName: options.matcherName, + message: message(), + stack: stack(), + passed: options.passed + }; + + if (!result.passed) { + result.expected = options.expected; + result.actual = options.actual; + + if (options.error && !j$.isString_(options.error)) { + if ('code' in options.error) { + result.code = options.error.code; + } + + if ( + options.error.code === 'ERR_ASSERTION' && + options.expected === '' && + options.actual === '' + ) { + result.expected = options.error.expected; + result.actual = options.error.actual; + result.matcherName = 'assert ' + options.error.operator; + } + } + } + + return result; + + function message() { + if (options.passed) { + return 'Passed.'; + } else if (options.message) { + return options.message; + } else if (options.error) { + return messageFormatter(options.error); + } + return ''; + } + + function stack() { + if (options.passed) { + return ''; + } + + var error = options.error; + if (!error) { + if (options.errorForStack) { + error = options.errorForStack; + } else if (options.stack) { + error = options; + } else { + try { + throw new Error(message()); + } catch (e) { + error = e; + } + } + } + return stackFormatter(error); + } + } + + return buildExpectationResult; +}; + +getJasmineRequireObj().Expector = function(j$) { + function Expector(options) { + this.matchersUtil = options.matchersUtil || { + buildFailureMessage: function() {} + }; + this.customEqualityTesters = options.customEqualityTesters || []; + this.actual = options.actual; + this.addExpectationResult = options.addExpectationResult || function() {}; + this.filters = new j$.ExpectationFilterChain(); + } + + Expector.prototype.instantiateMatcher = function( + matcherName, + matcherFactory, + args + ) { + this.matcherName = matcherName; + this.args = Array.prototype.slice.call(args, 0); + this.expected = this.args.slice(0); + + this.args.unshift(this.actual); + + var matcher = matcherFactory(this.matchersUtil, this.customEqualityTesters); + var comparisonFunc = this.filters.selectComparisonFunc(matcher); + return comparisonFunc || matcher.compare; + }; + + Expector.prototype.buildMessage = function(result) { + var self = this; + + if (result.pass) { + return ''; + } + + var msg = this.filters.buildFailureMessage( + result, + this.matcherName, + this.args, + this.matchersUtil, + defaultMessage + ); + return this.filters.modifyFailureMessage(msg || defaultMessage()); + + function defaultMessage() { + if (!result.message) { + var args = self.args.slice(); + args.unshift(false); + args.unshift(self.matcherName); + return self.matchersUtil.buildFailureMessage.apply( + self.matchersUtil, + args + ); + } else if (j$.isFunction_(result.message)) { + return result.message(); + } else { + return result.message; + } + } + }; + + Expector.prototype.compare = function(matcherName, matcherFactory, args) { + var matcherCompare = this.instantiateMatcher( + matcherName, + matcherFactory, + args + ); + return matcherCompare.apply(null, this.args); + }; + + Expector.prototype.addFilter = function(filter) { + var result = Object.create(this); + result.filters = this.filters.addFilter(filter); + return result; + }; + + Expector.prototype.processResult = function(result, errorForStack) { + var message = this.buildMessage(result); + + if (this.expected.length === 1) { + this.expected = this.expected[0]; + } + + this.addExpectationResult(result.pass, { + matcherName: this.matcherName, + passed: result.pass, + message: message, + error: errorForStack ? undefined : result.error, + errorForStack: errorForStack || undefined, + actual: this.actual, + expected: this.expected // TODO: this may need to be arrayified/sliced + }); + }; + + return Expector; +}; + +getJasmineRequireObj().formatErrorMsg = function() { + function generateErrorMsg(domain, usage) { + var usageDefinition = usage ? '\nUsage: ' + usage : ''; + + return function errorMsg(msg) { + return domain + ' : ' + msg + usageDefinition; + }; + } + + return generateErrorMsg; +}; + +getJasmineRequireObj().GlobalErrors = function(j$) { + function GlobalErrors(global) { + var handlers = []; + global = global || j$.getGlobal(); + + var onerror = function onerror() { + var handler = handlers[handlers.length - 1]; + + if (handler) { + handler.apply(null, Array.prototype.slice.call(arguments, 0)); + } else { + throw arguments[0]; + } + }; + + this.originalHandlers = {}; + this.jasmineHandlers = {}; + this.installOne_ = function installOne_(errorType, jasmineMessage) { + function taggedOnError(error) { + var substituteMsg; + + if (error) { + error.jasmineMessage = jasmineMessage + ': ' + error; + } else { + substituteMsg = jasmineMessage + ' with no error or message'; + + if (errorType === 'unhandledRejection') { + substituteMsg += + '\n' + + '(Tip: to get a useful stack trace, use ' + + 'Promise.reject(new Error(...)) instead of Promise.reject().)'; + } + + error = new Error(substituteMsg); + } + + var handler = handlers[handlers.length - 1]; + + if (handler) { + handler(error); + } else { + throw error; + } + } + + this.originalHandlers[errorType] = global.process.listeners(errorType); + this.jasmineHandlers[errorType] = taggedOnError; + + global.process.removeAllListeners(errorType); + global.process.on(errorType, taggedOnError); + + this.uninstall = function uninstall() { + var errorTypes = Object.keys(this.originalHandlers); + for (var iType = 0; iType < errorTypes.length; iType++) { + var errorType = errorTypes[iType]; + global.process.removeListener( + errorType, + this.jasmineHandlers[errorType] + ); + for (var i = 0; i < this.originalHandlers[errorType].length; i++) { + global.process.on(errorType, this.originalHandlers[errorType][i]); + } + delete this.originalHandlers[errorType]; + delete this.jasmineHandlers[errorType]; + } + }; + }; + + this.install = function install() { + if ( + global.process && + global.process.listeners && + j$.isFunction_(global.process.on) + ) { + this.installOne_('uncaughtException', 'Uncaught exception'); + this.installOne_('unhandledRejection', 'Unhandled promise rejection'); + } else { + var originalHandler = global.onerror; + global.onerror = onerror; + + var browserRejectionHandler = function browserRejectionHandler(event) { + if (j$.isError_(event.reason)) { + event.reason.jasmineMessage = + 'Unhandled promise rejection: ' + event.reason; + global.onerror(event.reason); + } else { + global.onerror('Unhandled promise rejection: ' + event.reason); + } + }; + + if (global.addEventListener) { + global.addEventListener( + 'unhandledrejection', + browserRejectionHandler + ); + } + + this.uninstall = function uninstall() { + global.onerror = originalHandler; + if (global.removeEventListener) { + global.removeEventListener( + 'unhandledrejection', + browserRejectionHandler + ); + } + }; + } + }; + + this.pushListener = function pushListener(listener) { + handlers.push(listener); + }; + + this.popListener = function popListener(listener) { + if (!listener) { + throw new Error('popListener expects a listener'); + } + + handlers.pop(); + }; + } + + return GlobalErrors; +}; + +/* eslint-disable compat/compat */ +getJasmineRequireObj().toBePending = function(j$) { + /** + * Expect a promise to be pending, i.e. the promise is neither resolved nor rejected. + * @function + * @async + * @name async-matchers#toBePending + * @since 3.6 + * @example + * await expectAsync(aPromise).toBePending(); + */ + return function toBePending() { + return { + compare: function(actual) { + if (!j$.isPromiseLike(actual)) { + throw new Error('Expected toBePending to be called on a promise.'); + } + var want = {}; + return Promise.race([actual, Promise.resolve(want)]).then( + function(got) { + return { pass: want === got }; + }, + function() { + return { pass: false }; + } + ); + } + }; + }; +}; + +getJasmineRequireObj().toBeRejected = function(j$) { + /** + * Expect a promise to be rejected. + * @function + * @async + * @name async-matchers#toBeRejected + * @since 3.1.0 + * @example + * await expectAsync(aPromise).toBeRejected(); + * @example + * return expectAsync(aPromise).toBeRejected(); + */ + return function toBeRejected() { + return { + compare: function(actual) { + if (!j$.isPromiseLike(actual)) { + throw new Error('Expected toBeRejected to be called on a promise.'); + } + return actual.then( + function() { + return { pass: false }; + }, + function() { + return { pass: true }; + } + ); + } + }; + }; +}; + +getJasmineRequireObj().toBeRejectedWith = function(j$) { + /** + * Expect a promise to be rejected with a value equal to the expected, using deep equality comparison. + * @function + * @async + * @name async-matchers#toBeRejectedWith + * @since 3.3.0 + * @param {Object} expected - Value that the promise is expected to be rejected with + * @example + * await expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); + * @example + * return expectAsync(aPromise).toBeRejectedWith({prop: 'value'}); + */ + return function toBeRejectedWith(matchersUtil) { + return { + compare: function(actualPromise, expectedValue) { + if (!j$.isPromiseLike(actualPromise)) { + throw new Error( + 'Expected toBeRejectedWith to be called on a promise.' + ); + } + + function prefix(passed) { + return ( + 'Expected a promise ' + + (passed ? 'not ' : '') + + 'to be rejected with ' + + matchersUtil.pp(expectedValue) + ); + } + + return actualPromise.then( + function() { + return { + pass: false, + message: prefix(false) + ' but it was resolved.' + }; + }, + function(actualValue) { + if (matchersUtil.equals(actualValue, expectedValue)) { + return { + pass: true, + message: prefix(true) + '.' + }; + } else { + return { + pass: false, + message: + prefix(false) + + ' but it was rejected with ' + + matchersUtil.pp(actualValue) + + '.' + }; + } + } + ); + } + }; + }; +}; + +getJasmineRequireObj().toBeRejectedWithError = function(j$) { + /** + * Expect a promise to be rejected with a value matched to the expected + * @function + * @async + * @name async-matchers#toBeRejectedWithError + * @since 3.5.0 + * @param {Error} [expected] - `Error` constructor the object that was thrown needs to be an instance of. If not provided, `Error` will be used. + * @param {RegExp|String} [message] - The message that should be set on the thrown `Error` + * @example + * await expectAsync(aPromise).toBeRejectedWithError(MyCustomError, 'Error message'); + * await expectAsync(aPromise).toBeRejectedWithError(MyCustomError, /Error message/); + * await expectAsync(aPromise).toBeRejectedWithError(MyCustomError); + * await expectAsync(aPromise).toBeRejectedWithError('Error message'); + * return expectAsync(aPromise).toBeRejectedWithError(/Error message/); + */ + return function toBeRejectedWithError(matchersUtil) { + return { + compare: function(actualPromise, arg1, arg2) { + if (!j$.isPromiseLike(actualPromise)) { + throw new Error( + 'Expected toBeRejectedWithError to be called on a promise.' + ); + } + + var expected = getExpectedFromArgs(arg1, arg2, matchersUtil); + + return actualPromise.then( + function() { + return { + pass: false, + message: 'Expected a promise to be rejected but it was resolved.' + }; + }, + function(actualValue) { + return matchError(actualValue, expected, matchersUtil); + } + ); + } + }; + }; + + function matchError(actual, expected, matchersUtil) { + if (!j$.isError_(actual)) { + return fail(expected, 'rejected with ' + matchersUtil.pp(actual)); + } + + if (!(actual instanceof expected.error)) { + return fail( + expected, + 'rejected with type ' + j$.fnNameFor(actual.constructor) + ); + } + + var actualMessage = actual.message; + + if ( + actualMessage === expected.message || + typeof expected.message === 'undefined' + ) { + return pass(expected); + } + + if ( + expected.message instanceof RegExp && + expected.message.test(actualMessage) + ) { + return pass(expected); + } + + return fail(expected, 'rejected with ' + matchersUtil.pp(actual)); + } + + function pass(expected) { + return { + pass: true, + message: + 'Expected a promise not to be rejected with ' + + expected.printValue + + ', but it was.' + }; + } + + function fail(expected, message) { + return { + pass: false, + message: + 'Expected a promise to be rejected with ' + + expected.printValue + + ' but it was ' + + message + + '.' + }; + } + + function getExpectedFromArgs(arg1, arg2, matchersUtil) { + var error, message; + + if (isErrorConstructor(arg1)) { + error = arg1; + message = arg2; + } else { + error = Error; + message = arg1; + } + + return { + error: error, + message: message, + printValue: + j$.fnNameFor(error) + + (typeof message === 'undefined' ? '' : ': ' + matchersUtil.pp(message)) + }; + } + + function isErrorConstructor(value) { + return ( + typeof value === 'function' && + (value === Error || j$.isError_(value.prototype)) + ); + } +}; + +getJasmineRequireObj().toBeResolved = function(j$) { + /** + * Expect a promise to be resolved. + * @function + * @async + * @name async-matchers#toBeResolved + * @since 3.1.0 + * @example + * await expectAsync(aPromise).toBeResolved(); + * @example + * return expectAsync(aPromise).toBeResolved(); + */ + return function toBeResolved(matchersUtil) { + return { + compare: function(actual) { + if (!j$.isPromiseLike(actual)) { + throw new Error('Expected toBeResolved to be called on a promise.'); + } + + return actual.then( + function() { + return { pass: true }; + }, + function(e) { + return { + pass: false, + message: + 'Expected a promise to be resolved but it was ' + + 'rejected with ' + + matchersUtil.pp(e) + + '.' + }; + } + ); + } + }; + }; +}; + +getJasmineRequireObj().toBeResolvedTo = function(j$) { + /** + * Expect a promise to be resolved to a value equal to the expected, using deep equality comparison. + * @function + * @async + * @name async-matchers#toBeResolvedTo + * @since 3.1.0 + * @param {Object} expected - Value that the promise is expected to resolve to + * @example + * await expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); + * @example + * return expectAsync(aPromise).toBeResolvedTo({prop: 'value'}); + */ + return function toBeResolvedTo(matchersUtil) { + return { + compare: function(actualPromise, expectedValue) { + if (!j$.isPromiseLike(actualPromise)) { + throw new Error('Expected toBeResolvedTo to be called on a promise.'); + } + + function prefix(passed) { + return ( + 'Expected a promise ' + + (passed ? 'not ' : '') + + 'to be resolved to ' + + matchersUtil.pp(expectedValue) + ); + } + + return actualPromise.then( + function(actualValue) { + if (matchersUtil.equals(actualValue, expectedValue)) { + return { + pass: true, + message: prefix(true) + '.' + }; + } else { + return { + pass: false, + message: + prefix(false) + + ' but it was resolved to ' + + matchersUtil.pp(actualValue) + + '.' + }; + } + }, + function(e) { + return { + pass: false, + message: + prefix(false) + + ' but it was rejected with ' + + matchersUtil.pp(e) + + '.' + }; + } + ); + } + }; + }; +}; + +getJasmineRequireObj().DiffBuilder = function(j$) { + return function DiffBuilder(config) { + var prettyPrinter = (config || {}).prettyPrinter || j$.makePrettyPrinter(), + mismatches = new j$.MismatchTree(), + path = new j$.ObjectPath(), + actualRoot = undefined, + expectedRoot = undefined; + + return { + setRoots: function(actual, expected) { + actualRoot = actual; + expectedRoot = expected; + }, + + recordMismatch: function(formatter) { + mismatches.add(path, formatter); + }, + + getMessage: function() { + var messages = []; + + mismatches.traverse(function(path, isLeaf, formatter) { + var actualCustom, + expectedCustom, + useCustom, + derefResult = dereferencePath( + path, + actualRoot, + expectedRoot, + prettyPrinter + ), + actual = derefResult.actual, + expected = derefResult.expected; + + if (formatter) { + messages.push(formatter(actual, expected, path, prettyPrinter)); + return true; + } + + actualCustom = prettyPrinter.customFormat_(actual); + expectedCustom = prettyPrinter.customFormat_(expected); + useCustom = !( + j$.util.isUndefined(actualCustom) && + j$.util.isUndefined(expectedCustom) + ); + + if (useCustom) { + messages.push( + wrapPrettyPrinted(actualCustom, expectedCustom, path) + ); + return false; // don't recurse further + } + + if (isLeaf) { + messages.push( + defaultFormatter(actual, expected, path, prettyPrinter) + ); + } + + return true; + }); + + return messages.join('\n'); + }, + + withPath: function(pathComponent, block) { + var oldPath = path; + path = path.add(pathComponent); + block(); + path = oldPath; + } + }; + + function defaultFormatter(actual, expected, path, prettyPrinter) { + return wrapPrettyPrinted( + prettyPrinter(actual), + prettyPrinter(expected), + path + ); + } + + function wrapPrettyPrinted(actual, expected, path) { + return ( + 'Expected ' + + path + + (path.depth() ? ' = ' : '') + + actual + + ' to equal ' + + expected + + '.' + ); + } + }; + + function dereferencePath(objectPath, actual, expected, pp) { + function handleAsymmetricExpected() { + if ( + j$.isAsymmetricEqualityTester_(expected) && + j$.isFunction_(expected.valuesForDiff_) + ) { + var asymmetricResult = expected.valuesForDiff_(actual, pp); + expected = asymmetricResult.self; + actual = asymmetricResult.other; + } + } + + var i; + handleAsymmetricExpected(); + + for (i = 0; i < objectPath.components.length; i++) { + actual = actual[objectPath.components[i]]; + expected = expected[objectPath.components[i]]; + handleAsymmetricExpected(); + } + + return { actual: actual, expected: expected }; + } +}; + +getJasmineRequireObj().MatchersUtil = function(j$) { + // TODO: convert all uses of j$.pp to use the injected pp + + /** + * @class MatchersUtil + * @classdesc Utilities for use in implementing matchers.
+ * _Note:_ Do not construct this directly. Jasmine will construct one and + * pass it to matchers and asymmetric equality testers. + * @hideconstructor + */ + function MatchersUtil(options) { + options = options || {}; + this.customTesters_ = options.customTesters || []; + /** + * Formats a value for use in matcher failure messages and similar contexts, + * taking into account the current set of custom value formatters. + * @function + * @name MatchersUtil#pp + * @since 3.6.0 + * @param {*} value The value to pretty-print + * @return {string} The pretty-printed value + */ + this.pp = options.pp || function() {}; + } + + /** + * Determines whether `haystack` contains `needle`, using the same comparison + * logic as {@link MatchersUtil#equals}. + * @function + * @name MatchersUtil#contains + * @since 2.0.0 + * @param {*} haystack The collection to search + * @param {*} needle The value to search for + * @param [customTesters] An array of custom equality testers + * @returns {boolean} True if `needle` was found in `haystack` + */ + MatchersUtil.prototype.contains = function(haystack, needle, customTesters) { + if (j$.isSet(haystack)) { + return haystack.has(needle); + } + + if ( + Object.prototype.toString.apply(haystack) === '[object Array]' || + (!!haystack && !haystack.indexOf) + ) { + for (var i = 0; i < haystack.length; i++) { + if (this.equals(haystack[i], needle, customTesters)) { + return true; + } + } + return false; + } + + return !!haystack && haystack.indexOf(needle) >= 0; + }; + + MatchersUtil.prototype.buildFailureMessage = function() { + var self = this; + var args = Array.prototype.slice.call(arguments, 0), + matcherName = args[0], + isNot = args[1], + actual = args[2], + expected = args.slice(3), + englishyPredicate = matcherName.replace(/[A-Z]/g, function(s) { + return ' ' + s.toLowerCase(); + }); + + var message = + 'Expected ' + + self.pp(actual) + + (isNot ? ' not ' : ' ') + + englishyPredicate; + + if (expected.length > 0) { + for (var i = 0; i < expected.length; i++) { + if (i > 0) { + message += ','; + } + message += ' ' + self.pp(expected[i]); + } + } + + return message + '.'; + }; + + MatchersUtil.prototype.asymmetricDiff_ = function( + a, + b, + aStack, + bStack, + customTesters, + diffBuilder + ) { + if (j$.isFunction_(b.valuesForDiff_)) { + var values = b.valuesForDiff_(a, this.pp); + this.eq_( + values.other, + values.self, + aStack, + bStack, + customTesters, + diffBuilder + ); + } else { + diffBuilder.recordMismatch(); + } + }; + + MatchersUtil.prototype.asymmetricMatch_ = function( + a, + b, + aStack, + bStack, + customTesters, + diffBuilder + ) { + var asymmetricA = j$.isAsymmetricEqualityTester_(a), + asymmetricB = j$.isAsymmetricEqualityTester_(b), + shim, + result; + + if (asymmetricA === asymmetricB) { + return undefined; + } + + shim = j$.asymmetricEqualityTesterArgCompatShim(this, customTesters); + + if (asymmetricA) { + result = a.asymmetricMatch(b, shim); + if (!result) { + diffBuilder.recordMismatch(); + } + return result; + } + + if (asymmetricB) { + result = b.asymmetricMatch(a, shim); + if (!result) { + this.asymmetricDiff_(a, b, aStack, bStack, customTesters, diffBuilder); + } + return result; + } + }; + + /** + * Determines whether two values are deeply equal to each other. + * @function + * @name MatchersUtil#equals + * @since 2.0.0 + * @param {*} a The first value to compare + * @param {*} b The second value to compare + * @param [customTesters] An array of custom equality testers + * @returns {boolean} True if the values are equal + */ + MatchersUtil.prototype.equals = function( + a, + b, + customTestersOrDiffBuilder, + diffBuilderOrNothing + ) { + var customTesters, diffBuilder; + + if (isDiffBuilder(customTestersOrDiffBuilder)) { + diffBuilder = customTestersOrDiffBuilder; + } else { + customTesters = customTestersOrDiffBuilder; + diffBuilder = diffBuilderOrNothing; + } + + customTesters = customTesters || this.customTesters_; + diffBuilder = diffBuilder || j$.NullDiffBuilder(); + diffBuilder.setRoots(a, b); + + return this.eq_(a, b, [], [], customTesters, diffBuilder); + }; + + // Equality function lovingly adapted from isEqual in + // [Underscore](http://underscorejs.org) + MatchersUtil.prototype.eq_ = function( + a, + b, + aStack, + bStack, + customTesters, + diffBuilder + ) { + var result = true, + self = this, + i; + + var asymmetricResult = this.asymmetricMatch_( + a, + b, + aStack, + bStack, + customTesters, + diffBuilder + ); + if (!j$.util.isUndefined(asymmetricResult)) { + return asymmetricResult; + } + + for (i = 0; i < customTesters.length; i++) { + var customTesterResult = customTesters[i](a, b); + if (!j$.util.isUndefined(customTesterResult)) { + if (!customTesterResult) { + diffBuilder.recordMismatch(); + } + return customTesterResult; + } + } + + if (a instanceof Error && b instanceof Error) { + result = a.message == b.message; + if (!result) { + diffBuilder.recordMismatch(); + } + return result; + } + + // Identical objects are equal. `0 === -0`, but they aren't identical. + // See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal). + if (a === b) { + result = a !== 0 || 1 / a == 1 / b; + if (!result) { + diffBuilder.recordMismatch(); + } + return result; + } + // A strict comparison is necessary because `null == undefined`. + if (a === null || b === null) { + result = a === b; + if (!result) { + diffBuilder.recordMismatch(); + } + return result; + } + var className = Object.prototype.toString.call(a); + if (className != Object.prototype.toString.call(b)) { + diffBuilder.recordMismatch(); + return false; + } + switch (className) { + // Strings, numbers, dates, and booleans are compared by value. + case '[object String]': + // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is + // equivalent to `new String("5")`. + result = a == String(b); + if (!result) { + diffBuilder.recordMismatch(); + } + return result; + case '[object Number]': + // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for + // other numeric values. + result = + a != +a ? b != +b : a === 0 && b === 0 ? 1 / a == 1 / b : a == +b; + if (!result) { + diffBuilder.recordMismatch(); + } + return result; + case '[object Date]': + case '[object Boolean]': + // Coerce dates and booleans to numeric primitive values. Dates are compared by their + // millisecond representations. Note that invalid dates with millisecond representations + // of `NaN` are not equivalent. + result = +a == +b; + if (!result) { + diffBuilder.recordMismatch(); + } + return result; + case '[object ArrayBuffer]': + // If we have an instance of ArrayBuffer the Uint8Array ctor + // will be defined as well + return self.eq_( + new Uint8Array(a), // eslint-disable-line compat/compat + new Uint8Array(b), // eslint-disable-line compat/compat + aStack, + bStack, + customTesters, + diffBuilder + ); + // RegExps are compared by their source patterns and flags. + case '[object RegExp]': + return ( + a.source == b.source && + a.global == b.global && + a.multiline == b.multiline && + a.ignoreCase == b.ignoreCase + ); + } + if (typeof a != 'object' || typeof b != 'object') { + diffBuilder.recordMismatch(); + return false; + } + + var aIsDomNode = j$.isDomNode(a); + var bIsDomNode = j$.isDomNode(b); + if (aIsDomNode && bIsDomNode) { + // At first try to use DOM3 method isEqualNode + result = a.isEqualNode(b); + if (!result) { + diffBuilder.recordMismatch(); + } + return result; + } + if (aIsDomNode || bIsDomNode) { + diffBuilder.recordMismatch(); + return false; + } + + var aIsPromise = j$.isPromise(a); + var bIsPromise = j$.isPromise(b); + if (aIsPromise && bIsPromise) { + return a === b; + } + + // Assume equality for cyclic structures. The algorithm for detecting cyclic + // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`. + var length = aStack.length; + while (length--) { + // Linear search. Performance is inversely proportional to the number of + // unique nested structures. + if (aStack[length] == a) { + return bStack[length] == b; + } + } + // Add the first object to the stack of traversed objects. + aStack.push(a); + bStack.push(b); + var size = 0; + // Recursively compare objects and arrays. + // Compare array lengths to determine if a deep comparison is necessary. + if (className == '[object Array]') { + var aLength = a.length; + var bLength = b.length; + + diffBuilder.withPath('length', function() { + if (aLength !== bLength) { + diffBuilder.recordMismatch(); + result = false; + } + }); + + for (i = 0; i < aLength || i < bLength; i++) { + diffBuilder.withPath(i, function() { + if (i >= bLength) { + diffBuilder.recordMismatch( + actualArrayIsLongerFormatter.bind(null, self.pp) + ); + result = false; + } else { + result = + self.eq_( + i < aLength ? a[i] : void 0, + i < bLength ? b[i] : void 0, + aStack, + bStack, + customTesters, + diffBuilder + ) && result; + } + }); + } + if (!result) { + return false; + } + } else if (j$.isMap(a) && j$.isMap(b)) { + if (a.size != b.size) { + diffBuilder.recordMismatch(); + return false; + } + + var keysA = []; + var keysB = []; + a.forEach(function(valueA, keyA) { + keysA.push(keyA); + }); + b.forEach(function(valueB, keyB) { + keysB.push(keyB); + }); + + // For both sets of keys, check they map to equal values in both maps. + // Keep track of corresponding keys (in insertion order) in order to handle asymmetric obj keys. + var mapKeys = [keysA, keysB]; + var cmpKeys = [keysB, keysA]; + var mapIter, mapKey, mapValueA, mapValueB; + var cmpIter, cmpKey; + for (i = 0; result && i < mapKeys.length; i++) { + mapIter = mapKeys[i]; + cmpIter = cmpKeys[i]; + + for (var j = 0; result && j < mapIter.length; j++) { + mapKey = mapIter[j]; + cmpKey = cmpIter[j]; + mapValueA = a.get(mapKey); + + // Only use the cmpKey when one of the keys is asymmetric and the corresponding key matches, + // otherwise explicitly look up the mapKey in the other Map since we want keys with unique + // obj identity (that are otherwise equal) to not match. + if ( + j$.isAsymmetricEqualityTester_(mapKey) || + (j$.isAsymmetricEqualityTester_(cmpKey) && + this.eq_( + mapKey, + cmpKey, + aStack, + bStack, + customTesters, + j$.NullDiffBuilder() + )) + ) { + mapValueB = b.get(cmpKey); + } else { + mapValueB = b.get(mapKey); + } + result = this.eq_( + mapValueA, + mapValueB, + aStack, + bStack, + customTesters, + j$.NullDiffBuilder() + ); + } + } + + if (!result) { + diffBuilder.recordMismatch(); + return false; + } + } else if (j$.isSet(a) && j$.isSet(b)) { + if (a.size != b.size) { + diffBuilder.recordMismatch(); + return false; + } + + var valuesA = []; + a.forEach(function(valueA) { + valuesA.push(valueA); + }); + var valuesB = []; + b.forEach(function(valueB) { + valuesB.push(valueB); + }); + + // For both sets, check they are all contained in the other set + var setPairs = [[valuesA, valuesB], [valuesB, valuesA]]; + var stackPairs = [[aStack, bStack], [bStack, aStack]]; + var baseValues, baseValue, baseStack; + var otherValues, otherValue, otherStack; + var found; + var prevStackSize; + for (i = 0; result && i < setPairs.length; i++) { + baseValues = setPairs[i][0]; + otherValues = setPairs[i][1]; + baseStack = stackPairs[i][0]; + otherStack = stackPairs[i][1]; + // For each value in the base set... + for (var k = 0; result && k < baseValues.length; k++) { + baseValue = baseValues[k]; + found = false; + // ... test that it is present in the other set + for (var l = 0; !found && l < otherValues.length; l++) { + otherValue = otherValues[l]; + prevStackSize = baseStack.length; + // compare by value equality + found = this.eq_( + baseValue, + otherValue, + baseStack, + otherStack, + customTesters, + j$.NullDiffBuilder() + ); + if (!found && prevStackSize !== baseStack.length) { + baseStack.splice(prevStackSize); + otherStack.splice(prevStackSize); + } + } + result = result && found; + } + } + + if (!result) { + diffBuilder.recordMismatch(); + return false; + } + } else if (j$.isURL(a) && j$.isURL(b)) { + // URLs have no enumrable properties, so the default object comparison + // would consider any two URLs to be equal. + return a.toString() === b.toString(); + } else { + // Objects with different constructors are not equivalent, but `Object`s + // or `Array`s from different frames are. + var aCtor = a.constructor, + bCtor = b.constructor; + if ( + aCtor !== bCtor && + isFunction(aCtor) && + isFunction(bCtor) && + a instanceof aCtor && + b instanceof bCtor && + !(aCtor instanceof aCtor && bCtor instanceof bCtor) + ) { + diffBuilder.recordMismatch( + constructorsAreDifferentFormatter.bind(null, this.pp) + ); + return false; + } + } + + // Deep compare objects. + var aKeys = keys(a, className == '[object Array]'), + key; + size = aKeys.length; + + // Ensure that both objects contain the same number of properties before comparing deep equality. + if (keys(b, className == '[object Array]').length !== size) { + diffBuilder.recordMismatch( + objectKeysAreDifferentFormatter.bind(null, this.pp) + ); + return false; + } + + for (i = 0; i < size; i++) { + key = aKeys[i]; + // Deep compare each member + if (!j$.util.has(b, key)) { + diffBuilder.recordMismatch( + objectKeysAreDifferentFormatter.bind(null, this.pp) + ); + result = false; + continue; + } + + diffBuilder.withPath(key, function() { + if ( + !self.eq_(a[key], b[key], aStack, bStack, customTesters, diffBuilder) + ) { + result = false; + } + }); + } + + if (!result) { + return false; + } + + // Remove the first object from the stack of traversed objects. + aStack.pop(); + bStack.pop(); + + return result; + }; + + function keys(obj, isArray) { + var allKeys = Object.keys + ? Object.keys(obj) + : (function(o) { + var keys = []; + for (var key in o) { + if (j$.util.has(o, key)) { + keys.push(key); + } + } + return keys; + })(obj); + + if (!isArray) { + return allKeys; + } + + if (allKeys.length === 0) { + return allKeys; + } + + var extraKeys = []; + for (var i = 0; i < allKeys.length; i++) { + if (!/^[0-9]+$/.test(allKeys[i])) { + extraKeys.push(allKeys[i]); + } + } + + return extraKeys; + } + + function isFunction(obj) { + return typeof obj === 'function'; + } + + function objectKeysAreDifferentFormatter(pp, actual, expected, path) { + var missingProperties = j$.util.objectDifference(expected, actual), + extraProperties = j$.util.objectDifference(actual, expected), + missingPropertiesMessage = formatKeyValuePairs(pp, missingProperties), + extraPropertiesMessage = formatKeyValuePairs(pp, extraProperties), + messages = []; + + if (!path.depth()) { + path = 'object'; + } + + if (missingPropertiesMessage.length) { + messages.push( + 'Expected ' + path + ' to have properties' + missingPropertiesMessage + ); + } + + if (extraPropertiesMessage.length) { + messages.push( + 'Expected ' + path + ' not to have properties' + extraPropertiesMessage + ); + } + + return messages.join('\n'); + } + + function constructorsAreDifferentFormatter(pp, actual, expected, path) { + if (!path.depth()) { + path = 'object'; + } + + return ( + 'Expected ' + + path + + ' to be a kind of ' + + j$.fnNameFor(expected.constructor) + + ', but was ' + + pp(actual) + + '.' + ); + } + + function actualArrayIsLongerFormatter(pp, actual, expected, path) { + return ( + 'Unexpected ' + + path + + (path.depth() ? ' = ' : '') + + pp(actual) + + ' in array.' + ); + } + + function formatKeyValuePairs(pp, obj) { + var formatted = ''; + for (var key in obj) { + formatted += '\n ' + key + ': ' + pp(obj[key]); + } + return formatted; + } + + function isDiffBuilder(obj) { + return obj && typeof obj.recordMismatch === 'function'; + } + + return MatchersUtil; +}; + +/** + * @interface AsymmetricEqualityTester + * @classdesc An asymmetric equality tester is an object that can match multiple + * objects. Examples include jasmine.any() and jasmine.stringMatching(). + * User-defined asymmetric equality testers can also be defined and used in + * expectations. + * @see custom_asymmetric_equality_testers + * @since 2.0.0 + */ +/** + * Determines whether a value matches this tester + * @function + * @name AsymmetricEqualityTester#asymmetricMatch + * @param value {any} The value to test + * @param matchersUtil {MatchersUtil} utilities for testing equality, etc + * @return {Boolean} + */ +/** + * Returns a string representation of this tester to use in matcher failure messages + * @function + * @name AsymmetricEqualityTester#jasmineToString + * @param pp {function} Function that takes a value and returns a pretty-printed representation + * @return {String} + */ + +getJasmineRequireObj().MismatchTree = function(j$) { + /* + To be able to apply custom object formatters at all possible levels of an + object graph, DiffBuilder needs to be able to know not just where the + mismatch occurred but also all ancestors of the mismatched value in both + the expected and actual object graphs. MismatchTree maintains that context + and provides it via the traverse method. + */ + function MismatchTree(path) { + this.path = path || new j$.ObjectPath([]); + this.formatter = undefined; + this.children = []; + this.isMismatch = false; + } + + MismatchTree.prototype.add = function(path, formatter) { + var key, child; + + if (path.depth() === 0) { + this.formatter = formatter; + this.isMismatch = true; + } else { + key = path.components[0]; + path = path.shift(); + child = this.child(key); + + if (!child) { + child = new MismatchTree(this.path.add(key)); + this.children.push(child); + } + + child.add(path, formatter); + } + }; + + MismatchTree.prototype.traverse = function(visit) { + var i, + hasChildren = this.children.length > 0; + + if (this.isMismatch || hasChildren) { + if (visit(this.path, !hasChildren, this.formatter)) { + for (i = 0; i < this.children.length; i++) { + this.children[i].traverse(visit); + } + } + } + }; + + MismatchTree.prototype.child = function(key) { + var i, pathEls; + + for (i = 0; i < this.children.length; i++) { + pathEls = this.children[i].path.components; + if (pathEls[pathEls.length - 1] === key) { + return this.children[i]; + } + } + }; + + return MismatchTree; +}; + +getJasmineRequireObj().nothing = function() { + /** + * {@link expect} nothing explicitly. + * @function + * @name matchers#nothing + * @since 2.8.0 + * @example + * expect().nothing(); + */ + function nothing() { + return { + compare: function() { + return { + pass: true + }; + } + }; + } + + return nothing; +}; + +getJasmineRequireObj().NullDiffBuilder = function(j$) { + return function() { + return { + withPath: function(_, block) { + block(); + }, + setRoots: function() {}, + recordMismatch: function() {} + }; + }; +}; + +getJasmineRequireObj().ObjectPath = function(j$) { + function ObjectPath(components) { + this.components = components || []; + } + + ObjectPath.prototype.toString = function() { + if (this.components.length) { + return '$' + map(this.components, formatPropertyAccess).join(''); + } else { + return ''; + } + }; + + ObjectPath.prototype.add = function(component) { + return new ObjectPath(this.components.concat([component])); + }; + + ObjectPath.prototype.shift = function() { + return new ObjectPath(this.components.slice(1)); + }; + + ObjectPath.prototype.depth = function() { + return this.components.length; + }; + + function formatPropertyAccess(prop) { + if (typeof prop === 'number') { + return '[' + prop + ']'; + } + + if (isValidIdentifier(prop)) { + return '.' + prop; + } + + return "['" + prop + "']"; + } + + function map(array, fn) { + var results = []; + for (var i = 0; i < array.length; i++) { + results.push(fn(array[i])); + } + return results; + } + + function isValidIdentifier(string) { + return /^[A-Za-z\$_][A-Za-z0-9\$_]*$/.test(string); + } + + return ObjectPath; +}; + +getJasmineRequireObj().requireAsyncMatchers = function(jRequire, j$) { + var availableMatchers = [ + 'toBePending', + 'toBeResolved', + 'toBeRejected', + 'toBeResolvedTo', + 'toBeRejectedWith', + 'toBeRejectedWithError' + ], + matchers = {}; + + for (var i = 0; i < availableMatchers.length; i++) { + var name = availableMatchers[i]; + matchers[name] = jRequire[name](j$); + } + + return matchers; +}; + +getJasmineRequireObj().toBe = function(j$) { + /** + * {@link expect} the actual value to be `===` to the expected value. + * @function + * @name matchers#toBe + * @since 1.3.0 + * @param {Object} expected - The expected value to compare against. + * @example + * expect(thing).toBe(realThing); + */ + function toBe(matchersUtil) { + var tip = + ' Tip: To check for deep equality, use .toEqual() instead of .toBe().'; + + return { + compare: function(actual, expected) { + var result = { + pass: actual === expected + }; + + if (typeof expected === 'object') { + result.message = + matchersUtil.buildFailureMessage( + 'toBe', + result.pass, + actual, + expected + ) + tip; + } + + return result; + } + }; + } + + return toBe; +}; + +getJasmineRequireObj().toBeCloseTo = function() { + /** + * {@link expect} the actual value to be within a specified precision of the expected value. + * @function + * @name matchers#toBeCloseTo + * @since 1.3.0 + * @param {Object} expected - The expected value to compare against. + * @param {Number} [precision=2] - The number of decimal points to check. + * @example + * expect(number).toBeCloseTo(42.2, 3); + */ + function toBeCloseTo() { + return { + compare: function(actual, expected, precision) { + if (precision !== 0) { + precision = precision || 2; + } + + if (expected === null || actual === null) { + throw new Error( + 'Cannot use toBeCloseTo with null. Arguments evaluated to: ' + + 'expect(' + + actual + + ').toBeCloseTo(' + + expected + + ').' + ); + } + + var pow = Math.pow(10, precision + 1); + var delta = Math.abs(expected - actual); + var maxDelta = Math.pow(10, -precision) / 2; + + return { + pass: Math.round(delta * pow) <= maxDelta * pow + }; + } + }; + } + + return toBeCloseTo; +}; + +getJasmineRequireObj().toBeDefined = function() { + /** + * {@link expect} the actual value to be defined. (Not `undefined`) + * @function + * @name matchers#toBeDefined + * @since 1.3.0 + * @example + * expect(result).toBeDefined(); + */ + function toBeDefined() { + return { + compare: function(actual) { + return { + pass: void 0 !== actual + }; + } + }; + } + + return toBeDefined; +}; + +getJasmineRequireObj().toBeFalse = function() { + /** + * {@link expect} the actual value to be `false`. + * @function + * @name matchers#toBeFalse + * @since 3.5.0 + * @example + * expect(result).toBeFalse(); + */ + function toBeFalse() { + return { + compare: function(actual) { + return { + pass: actual === false + }; + } + }; + } + + return toBeFalse; +}; + +getJasmineRequireObj().toBeFalsy = function() { + /** + * {@link expect} the actual value to be falsy + * @function + * @name matchers#toBeFalsy + * @since 2.0.0 + * @example + * expect(result).toBeFalsy(); + */ + function toBeFalsy() { + return { + compare: function(actual) { + return { + pass: !actual + }; + } + }; + } + + return toBeFalsy; +}; + +getJasmineRequireObj().toBeGreaterThan = function() { + /** + * {@link expect} the actual value to be greater than the expected value. + * @function + * @name matchers#toBeGreaterThan + * @since 2.0.0 + * @param {Number} expected - The value to compare against. + * @example + * expect(result).toBeGreaterThan(3); + */ + function toBeGreaterThan() { + return { + compare: function(actual, expected) { + return { + pass: actual > expected + }; + } + }; + } + + return toBeGreaterThan; +}; + +getJasmineRequireObj().toBeGreaterThanOrEqual = function() { + /** + * {@link expect} the actual value to be greater than or equal to the expected value. + * @function + * @name matchers#toBeGreaterThanOrEqual + * @since 2.0.0 + * @param {Number} expected - The expected value to compare against. + * @example + * expect(result).toBeGreaterThanOrEqual(25); + */ + function toBeGreaterThanOrEqual() { + return { + compare: function(actual, expected) { + return { + pass: actual >= expected + }; + } + }; + } + + return toBeGreaterThanOrEqual; +}; + +getJasmineRequireObj().toBeInstanceOf = function(j$) { + var usageError = j$.formatErrorMsg( + '', + 'expect(value).toBeInstanceOf()' + ); + + /** + * {@link expect} the actual to be an instance of the expected class + * @function + * @name matchers#toBeInstanceOf + * @since 3.5.0 + * @param {Object} expected - The class or constructor function to check for + * @example + * expect('foo').toBeInstanceOf(String); + * expect(3).toBeInstanceOf(Number); + * expect(new Error()).toBeInstanceOf(Error); + */ + function toBeInstanceOf(matchersUtil) { + return { + compare: function(actual, expected) { + var actualType = + actual && actual.constructor + ? j$.fnNameFor(actual.constructor) + : matchersUtil.pp(actual), + expectedType = expected + ? j$.fnNameFor(expected) + : matchersUtil.pp(expected), + expectedMatcher, + pass; + + try { + expectedMatcher = new j$.Any(expected); + pass = expectedMatcher.asymmetricMatch(actual); + } catch (error) { + throw new Error( + usageError('Expected value is not a constructor function') + ); + } + + if (pass) { + return { + pass: true, + message: + 'Expected instance of ' + + actualType + + ' not to be an instance of ' + + expectedType + }; + } else { + return { + pass: false, + message: + 'Expected instance of ' + + actualType + + ' to be an instance of ' + + expectedType + }; + } + } + }; + } + + return toBeInstanceOf; +}; + +getJasmineRequireObj().toBeLessThan = function() { + /** + * {@link expect} the actual value to be less than the expected value. + * @function + * @name matchers#toBeLessThan + * @since 2.0.0 + * @param {Number} expected - The expected value to compare against. + * @example + * expect(result).toBeLessThan(0); + */ + function toBeLessThan() { + return { + compare: function(actual, expected) { + return { + pass: actual < expected + }; + } + }; + } + + return toBeLessThan; +}; + +getJasmineRequireObj().toBeLessThanOrEqual = function() { + /** + * {@link expect} the actual value to be less than or equal to the expected value. + * @function + * @name matchers#toBeLessThanOrEqual + * @since 2.0.0 + * @param {Number} expected - The expected value to compare against. + * @example + * expect(result).toBeLessThanOrEqual(123); + */ + function toBeLessThanOrEqual() { + return { + compare: function(actual, expected) { + return { + pass: actual <= expected + }; + } + }; + } + + return toBeLessThanOrEqual; +}; + +getJasmineRequireObj().toBeNaN = function(j$) { + /** + * {@link expect} the actual value to be `NaN` (Not a Number). + * @function + * @name matchers#toBeNaN + * @since 1.3.0 + * @example + * expect(thing).toBeNaN(); + */ + function toBeNaN(matchersUtil) { + return { + compare: function(actual) { + var result = { + pass: actual !== actual + }; + + if (result.pass) { + result.message = 'Expected actual not to be NaN.'; + } else { + result.message = function() { + return 'Expected ' + matchersUtil.pp(actual) + ' to be NaN.'; + }; + } + + return result; + } + }; + } + + return toBeNaN; +}; + +getJasmineRequireObj().toBeNegativeInfinity = function(j$) { + /** + * {@link expect} the actual value to be `-Infinity` (-infinity). + * @function + * @name matchers#toBeNegativeInfinity + * @since 2.6.0 + * @example + * expect(thing).toBeNegativeInfinity(); + */ + function toBeNegativeInfinity(matchersUtil) { + return { + compare: function(actual) { + var result = { + pass: actual === Number.NEGATIVE_INFINITY + }; + + if (result.pass) { + result.message = 'Expected actual not to be -Infinity.'; + } else { + result.message = function() { + return 'Expected ' + matchersUtil.pp(actual) + ' to be -Infinity.'; + }; + } + + return result; + } + }; + } + + return toBeNegativeInfinity; +}; + +getJasmineRequireObj().toBeNull = function() { + /** + * {@link expect} the actual value to be `null`. + * @function + * @name matchers#toBeNull + * @since 1.3.0 + * @example + * expect(result).toBeNull(); + */ + function toBeNull() { + return { + compare: function(actual) { + return { + pass: actual === null + }; + } + }; + } + + return toBeNull; +}; + +getJasmineRequireObj().toBePositiveInfinity = function(j$) { + /** + * {@link expect} the actual value to be `Infinity` (infinity). + * @function + * @name matchers#toBePositiveInfinity + * @since 2.6.0 + * @example + * expect(thing).toBePositiveInfinity(); + */ + function toBePositiveInfinity(matchersUtil) { + return { + compare: function(actual) { + var result = { + pass: actual === Number.POSITIVE_INFINITY + }; + + if (result.pass) { + result.message = 'Expected actual not to be Infinity.'; + } else { + result.message = function() { + return 'Expected ' + matchersUtil.pp(actual) + ' to be Infinity.'; + }; + } + + return result; + } + }; + } + + return toBePositiveInfinity; +}; + +getJasmineRequireObj().toBeTrue = function() { + /** + * {@link expect} the actual value to be `true`. + * @function + * @name matchers#toBeTrue + * @since 3.5.0 + * @example + * expect(result).toBeTrue(); + */ + function toBeTrue() { + return { + compare: function(actual) { + return { + pass: actual === true + }; + } + }; + } + + return toBeTrue; +}; + +getJasmineRequireObj().toBeTruthy = function() { + /** + * {@link expect} the actual value to be truthy. + * @function + * @name matchers#toBeTruthy + * @since 2.0.0 + * @example + * expect(thing).toBeTruthy(); + */ + function toBeTruthy() { + return { + compare: function(actual) { + return { + pass: !!actual + }; + } + }; + } + + return toBeTruthy; +}; + +getJasmineRequireObj().toBeUndefined = function() { + /** + * {@link expect} the actual value to be `undefined`. + * @function + * @name matchers#toBeUndefined + * @since 1.3.0 + * @example + * expect(result).toBeUndefined(): + */ + function toBeUndefined() { + return { + compare: function(actual) { + return { + pass: void 0 === actual + }; + } + }; + } + + return toBeUndefined; +}; + +getJasmineRequireObj().toContain = function() { + /** + * {@link expect} the actual value to contain a specific value. + * @function + * @name matchers#toContain + * @since 2.0.0 + * @param {Object} expected - The value to look for. + * @example + * expect(array).toContain(anElement); + * expect(string).toContain(substring); + */ + function toContain(matchersUtil) { + return { + compare: function(actual, expected) { + return { + pass: matchersUtil.contains(actual, expected) + }; + } + }; + } + + return toContain; +}; + +getJasmineRequireObj().toEqual = function(j$) { + /** + * {@link expect} the actual value to be equal to the expected, using deep equality comparison. + * @function + * @name matchers#toEqual + * @since 1.3.0 + * @param {Object} expected - Expected value + * @example + * expect(bigObject).toEqual({"foo": ['bar', 'baz']}); + */ + function toEqual(matchersUtil) { + return { + compare: function(actual, expected) { + var result = { + pass: false + }, + diffBuilder = j$.DiffBuilder({ prettyPrinter: matchersUtil.pp }); + + result.pass = matchersUtil.equals(actual, expected, diffBuilder); + + // TODO: only set error message if test fails + result.message = diffBuilder.getMessage(); + + return result; + } + }; + } + + return toEqual; +}; + +getJasmineRequireObj().toHaveBeenCalled = function(j$) { + var getErrorMsg = j$.formatErrorMsg( + '', + 'expect().toHaveBeenCalled()' + ); + + /** + * {@link expect} the actual (a {@link Spy}) to have been called. + * @function + * @name matchers#toHaveBeenCalled + * @since 1.3.0 + * @example + * expect(mySpy).toHaveBeenCalled(); + * expect(mySpy).not.toHaveBeenCalled(); + */ + function toHaveBeenCalled(matchersUtil) { + return { + compare: function(actual) { + var result = {}; + + if (!j$.isSpy(actual)) { + throw new Error( + getErrorMsg( + 'Expected a spy, but got ' + matchersUtil.pp(actual) + '.' + ) + ); + } + + if (arguments.length > 1) { + throw new Error( + getErrorMsg('Does not take arguments, use toHaveBeenCalledWith') + ); + } + + result.pass = actual.calls.any(); + + result.message = result.pass + ? 'Expected spy ' + actual.and.identity + ' not to have been called.' + : 'Expected spy ' + actual.and.identity + ' to have been called.'; + + return result; + } + }; + } + + return toHaveBeenCalled; +}; + +getJasmineRequireObj().toHaveBeenCalledBefore = function(j$) { + var getErrorMsg = j$.formatErrorMsg( + '', + 'expect().toHaveBeenCalledBefore()' + ); + + /** + * {@link expect} the actual value (a {@link Spy}) to have been called before another {@link Spy}. + * @function + * @name matchers#toHaveBeenCalledBefore + * @since 2.6.0 + * @param {Spy} expected - {@link Spy} that should have been called after the `actual` {@link Spy}. + * @example + * expect(mySpy).toHaveBeenCalledBefore(otherSpy); + */ + function toHaveBeenCalledBefore(matchersUtil) { + return { + compare: function(firstSpy, latterSpy) { + if (!j$.isSpy(firstSpy)) { + throw new Error( + getErrorMsg( + 'Expected a spy, but got ' + matchersUtil.pp(firstSpy) + '.' + ) + ); + } + if (!j$.isSpy(latterSpy)) { + throw new Error( + getErrorMsg( + 'Expected a spy, but got ' + matchersUtil.pp(latterSpy) + '.' + ) + ); + } + + var result = { pass: false }; + + if (!firstSpy.calls.count()) { + result.message = + 'Expected spy ' + firstSpy.and.identity + ' to have been called.'; + return result; + } + if (!latterSpy.calls.count()) { + result.message = + 'Expected spy ' + latterSpy.and.identity + ' to have been called.'; + return result; + } + + var latest1stSpyCall = firstSpy.calls.mostRecent().invocationOrder; + var first2ndSpyCall = latterSpy.calls.first().invocationOrder; + + result.pass = latest1stSpyCall < first2ndSpyCall; + + if (result.pass) { + result.message = + 'Expected spy ' + + firstSpy.and.identity + + ' to not have been called before spy ' + + latterSpy.and.identity + + ', but it was'; + } else { + var first1stSpyCall = firstSpy.calls.first().invocationOrder; + var latest2ndSpyCall = latterSpy.calls.mostRecent().invocationOrder; + + if (first1stSpyCall < first2ndSpyCall) { + result.message = + 'Expected latest call to spy ' + + firstSpy.and.identity + + ' to have been called before first call to spy ' + + latterSpy.and.identity + + ' (no interleaved calls)'; + } else if (latest2ndSpyCall > latest1stSpyCall) { + result.message = + 'Expected first call to spy ' + + latterSpy.and.identity + + ' to have been called after latest call to spy ' + + firstSpy.and.identity + + ' (no interleaved calls)'; + } else { + result.message = + 'Expected spy ' + + firstSpy.and.identity + + ' to have been called before spy ' + + latterSpy.and.identity; + } + } + + return result; + } + }; + } + + return toHaveBeenCalledBefore; +}; + +getJasmineRequireObj().toHaveBeenCalledOnceWith = function(j$) { + var getErrorMsg = j$.formatErrorMsg( + '', + 'expect().toHaveBeenCalledOnceWith(...arguments)' + ); + + /** + * {@link expect} the actual (a {@link Spy}) to have been called exactly once, and exactly with the particular arguments. + * @function + * @name matchers#toHaveBeenCalledOnceWith + * @since 3.6.0 + * @param {...Object} - The arguments to look for + * @example + * expect(mySpy).toHaveBeenCalledOnceWith('foo', 'bar', 2); + */ + function toHaveBeenCalledOnceWith(util) { + return { + compare: function() { + var args = Array.prototype.slice.call(arguments, 0), + actual = args[0], + expectedArgs = args.slice(1); + + if (!j$.isSpy(actual)) { + throw new Error( + getErrorMsg('Expected a spy, but got ' + util.pp(actual) + '.') + ); + } + + var prettyPrintedCalls = actual.calls + .allArgs() + .map(function(argsForCall) { + return ' ' + util.pp(argsForCall); + }); + + if ( + actual.calls.count() === 1 && + util.contains(actual.calls.allArgs(), expectedArgs) + ) { + return { + pass: true, + message: + 'Expected spy ' + + actual.and.identity + + ' to have been called 0 times, multiple times, or once, but with arguments different from:\n' + + ' ' + + util.pp(expectedArgs) + + '\n' + + 'But the actual call was:\n' + + prettyPrintedCalls.join(',\n') + + '.\n\n' + }; + } + + function getDiffs() { + return actual.calls.allArgs().map(function(argsForCall, callIx) { + var diffBuilder = new j$.DiffBuilder(); + util.equals(argsForCall, expectedArgs, diffBuilder); + return diffBuilder.getMessage(); + }); + } + + function butString() { + switch (actual.calls.count()) { + case 0: + return 'But it was never called.\n\n'; + case 1: + return ( + 'But the actual call was:\n' + + prettyPrintedCalls.join(',\n') + + '.\n' + + getDiffs().join('\n') + + '\n\n' + ); + default: + return ( + 'But the actual calls were:\n' + + prettyPrintedCalls.join(',\n') + + '.\n\n' + ); + } + } + + return { + pass: false, + message: + 'Expected spy ' + + actual.and.identity + + ' to have been called only once, and with given args:\n' + + ' ' + + util.pp(expectedArgs) + + '\n' + + butString() + }; + } + }; + } + + return toHaveBeenCalledOnceWith; +}; + +getJasmineRequireObj().toHaveBeenCalledTimes = function(j$) { + var getErrorMsg = j$.formatErrorMsg( + '', + 'expect().toHaveBeenCalledTimes()' + ); + + /** + * {@link expect} the actual (a {@link Spy}) to have been called the specified number of times. + * @function + * @name matchers#toHaveBeenCalledTimes + * @since 2.4.0 + * @param {Number} expected - The number of invocations to look for. + * @example + * expect(mySpy).toHaveBeenCalledTimes(3); + */ + function toHaveBeenCalledTimes(matchersUtil) { + return { + compare: function(actual, expected) { + if (!j$.isSpy(actual)) { + throw new Error( + getErrorMsg( + 'Expected a spy, but got ' + matchersUtil.pp(actual) + '.' + ) + ); + } + + var args = Array.prototype.slice.call(arguments, 0), + result = { pass: false }; + + if (!j$.isNumber_(expected)) { + throw new Error( + getErrorMsg( + 'The expected times failed is a required argument and must be a number.' + ) + ); + } + + actual = args[0]; + var calls = actual.calls.count(); + var timesMessage = expected === 1 ? 'once' : expected + ' times'; + result.pass = calls === expected; + result.message = result.pass + ? 'Expected spy ' + + actual.and.identity + + ' not to have been called ' + + timesMessage + + '. It was called ' + + calls + + ' times.' + : 'Expected spy ' + + actual.and.identity + + ' to have been called ' + + timesMessage + + '. It was called ' + + calls + + ' times.'; + return result; + } + }; + } + + return toHaveBeenCalledTimes; +}; + +getJasmineRequireObj().toHaveBeenCalledWith = function(j$) { + var getErrorMsg = j$.formatErrorMsg( + '', + 'expect().toHaveBeenCalledWith(...arguments)' + ); + + /** + * {@link expect} the actual (a {@link Spy}) to have been called with particular arguments at least once. + * @function + * @name matchers#toHaveBeenCalledWith + * @since 1.3.0 + * @param {...Object} - The arguments to look for + * @example + * expect(mySpy).toHaveBeenCalledWith('foo', 'bar', 2); + */ + function toHaveBeenCalledWith(matchersUtil) { + return { + compare: function() { + var args = Array.prototype.slice.call(arguments, 0), + actual = args[0], + expectedArgs = args.slice(1), + result = { pass: false }; + + if (!j$.isSpy(actual)) { + throw new Error( + getErrorMsg( + 'Expected a spy, but got ' + matchersUtil.pp(actual) + '.' + ) + ); + } + + if (!actual.calls.any()) { + result.message = function() { + return ( + 'Expected spy ' + + actual.and.identity + + ' to have been called with:\n' + + ' ' + + matchersUtil.pp(expectedArgs) + + '\nbut it was never called.' + ); + }; + return result; + } + + if (matchersUtil.contains(actual.calls.allArgs(), expectedArgs)) { + result.pass = true; + result.message = function() { + return ( + 'Expected spy ' + + actual.and.identity + + ' not to have been called with:\n' + + ' ' + + matchersUtil.pp(expectedArgs) + + '\nbut it was.' + ); + }; + } else { + result.message = function() { + var prettyPrintedCalls = actual.calls + .allArgs() + .map(function(argsForCall) { + return ' ' + matchersUtil.pp(argsForCall); + }); + + var diffs = actual.calls + .allArgs() + .map(function(argsForCall, callIx) { + var diffBuilder = new j$.DiffBuilder(); + matchersUtil.equals(argsForCall, expectedArgs, diffBuilder); + return ( + 'Call ' + + callIx + + ':\n' + + diffBuilder.getMessage().replace(/^/gm, ' ') + ); + }); + + return ( + 'Expected spy ' + + actual.and.identity + + ' to have been called with:\n' + + ' ' + + matchersUtil.pp(expectedArgs) + + '\n' + + '' + + 'but actual calls were:\n' + + prettyPrintedCalls.join(',\n') + + '.\n\n' + + diffs.join('\n') + ); + }; + } + + return result; + } + }; + } + + return toHaveBeenCalledWith; +}; + +getJasmineRequireObj().toHaveClass = function(j$) { + /** + * {@link expect} the actual value to be a DOM element that has the expected class + * @function + * @name matchers#toHaveClass + * @since 3.0.0 + * @param {Object} expected - The class name to test for + * @example + * var el = document.createElement('div'); + * el.className = 'foo bar baz'; + * expect(el).toHaveClass('bar'); + */ + function toHaveClass(matchersUtil) { + return { + compare: function(actual, expected) { + if (!isElement(actual)) { + throw new Error(matchersUtil.pp(actual) + ' is not a DOM element'); + } + + return { + pass: actual.classList.contains(expected) + }; + } + }; + } + + function isElement(maybeEl) { + return ( + maybeEl && maybeEl.classList && j$.isFunction_(maybeEl.classList.contains) + ); + } + + return toHaveClass; +}; + +getJasmineRequireObj().toHaveSize = function(j$) { + /** + * {@link expect} the actual size to be equal to the expected, using array-like length or object keys size. + * @function + * @name matchers#toHaveSize + * @since 3.6.0 + * @param {Object} expected - Expected size + * @example + * array = [1,2]; + * expect(array).toHaveSize(2); + */ + function toHaveSize() { + return { + compare: function(actual, expected) { + var result = { + pass: false + }; + + if ( + j$.isA_('WeakSet', actual) || + j$.isWeakMap(actual) || + j$.isDataView(actual) + ) { + throw new Error('Cannot get size of ' + actual + '.'); + } + + if (j$.isSet(actual) || j$.isMap(actual)) { + result.pass = actual.size === expected; + } else if (isLength(actual.length)) { + result.pass = actual.length === expected; + } else { + result.pass = Object.keys(actual).length === expected; + } + + return result; + } + }; + } + + var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || 9007199254740991; // eslint-disable-line compat/compat + function isLength(value) { + return ( + typeof value == 'number' && + value > -1 && + value % 1 === 0 && + value <= MAX_SAFE_INTEGER + ); + } + + return toHaveSize; +}; + +getJasmineRequireObj().toMatch = function(j$) { + var getErrorMsg = j$.formatErrorMsg( + '', + 'expect().toMatch( || )' + ); + + /** + * {@link expect} the actual value to match a regular expression + * @function + * @name matchers#toMatch + * @since 1.3.0 + * @param {RegExp|String} expected - Value to look for in the string. + * @example + * expect("my string").toMatch(/string$/); + * expect("other string").toMatch("her"); + */ + function toMatch() { + return { + compare: function(actual, expected) { + if (!j$.isString_(expected) && !j$.isA_('RegExp', expected)) { + throw new Error(getErrorMsg('Expected is not a String or a RegExp')); + } + + var regexp = new RegExp(expected); + + return { + pass: regexp.test(actual) + }; + } + }; + } + + return toMatch; +}; + +getJasmineRequireObj().toThrow = function(j$) { + var getErrorMsg = j$.formatErrorMsg( + '', + 'expect(function() {}).toThrow()' + ); + + /** + * {@link expect} a function to `throw` something. + * @function + * @name matchers#toThrow + * @since 2.0.0 + * @param {Object} [expected] - Value that should be thrown. If not provided, simply the fact that something was thrown will be checked. + * @example + * expect(function() { return 'things'; }).toThrow('foo'); + * expect(function() { return 'stuff'; }).toThrow(); + */ + function toThrow(matchersUtil) { + return { + compare: function(actual, expected) { + var result = { pass: false }, + threw = false, + thrown; + + if (typeof actual != 'function') { + throw new Error(getErrorMsg('Actual is not a Function')); + } + + try { + actual(); + } catch (e) { + threw = true; + thrown = e; + } + + if (!threw) { + result.message = 'Expected function to throw an exception.'; + return result; + } + + if (arguments.length == 1) { + result.pass = true; + result.message = function() { + return ( + 'Expected function not to throw, but it threw ' + + matchersUtil.pp(thrown) + + '.' + ); + }; + + return result; + } + + if (matchersUtil.equals(thrown, expected)) { + result.pass = true; + result.message = function() { + return ( + 'Expected function not to throw ' + + matchersUtil.pp(expected) + + '.' + ); + }; + } else { + result.message = function() { + return ( + 'Expected function to throw ' + + matchersUtil.pp(expected) + + ', but it threw ' + + matchersUtil.pp(thrown) + + '.' + ); + }; + } + + return result; + } + }; + } + + return toThrow; +}; + +getJasmineRequireObj().toThrowError = function(j$) { + var getErrorMsg = j$.formatErrorMsg( + '', + 'expect(function() {}).toThrowError(, )' + ); + + /** + * {@link expect} a function to `throw` an `Error`. + * @function + * @name matchers#toThrowError + * @since 2.0.0 + * @param {Error} [expected] - `Error` constructor the object that was thrown needs to be an instance of. If not provided, `Error` will be used. + * @param {RegExp|String} [message] - The message that should be set on the thrown `Error` + * @example + * expect(function() { return 'things'; }).toThrowError(MyCustomError, 'message'); + * expect(function() { return 'things'; }).toThrowError(MyCustomError, /bar/); + * expect(function() { return 'stuff'; }).toThrowError(MyCustomError); + * expect(function() { return 'other'; }).toThrowError(/foo/); + * expect(function() { return 'other'; }).toThrowError(); + */ + function toThrowError(matchersUtil) { + return { + compare: function(actual) { + var errorMatcher = getMatcher.apply(null, arguments), + thrown; + + if (typeof actual != 'function') { + throw new Error(getErrorMsg('Actual is not a Function')); + } + + try { + actual(); + return fail('Expected function to throw an Error.'); + } catch (e) { + thrown = e; + } + + if (!j$.isError_(thrown)) { + return fail(function() { + return ( + 'Expected function to throw an Error, but it threw ' + + matchersUtil.pp(thrown) + + '.' + ); + }); + } + + return errorMatcher.match(thrown); + } + }; + + function getMatcher() { + var expected, errorType; + + if (arguments[2]) { + errorType = arguments[1]; + expected = arguments[2]; + if (!isAnErrorType(errorType)) { + throw new Error(getErrorMsg('Expected error type is not an Error.')); + } + + return exactMatcher(expected, errorType); + } else if (arguments[1]) { + expected = arguments[1]; + + if (isAnErrorType(arguments[1])) { + return exactMatcher(null, arguments[1]); + } else { + return exactMatcher(arguments[1], null); + } + } else { + return anyMatcher(); + } + } + + function anyMatcher() { + return { + match: function(error) { + return pass( + 'Expected function not to throw an Error, but it threw ' + + j$.fnNameFor(error) + + '.' + ); + } + }; + } + + function exactMatcher(expected, errorType) { + if (expected && !isStringOrRegExp(expected)) { + if (errorType) { + throw new Error( + getErrorMsg('Expected error message is not a string or RegExp.') + ); + } else { + throw new Error( + getErrorMsg('Expected is not an Error, string, or RegExp.') + ); + } + } + + function messageMatch(message) { + if (typeof expected == 'string') { + return expected == message; + } else { + return expected.test(message); + } + } + + var errorTypeDescription = errorType + ? j$.fnNameFor(errorType) + : 'an exception'; + + function thrownDescription(thrown) { + var thrownName = errorType + ? j$.fnNameFor(thrown.constructor) + : 'an exception', + thrownMessage = ''; + + if (expected) { + thrownMessage = ' with message ' + matchersUtil.pp(thrown.message); + } + + return thrownName + thrownMessage; + } + + function messageDescription() { + if (expected === null) { + return ''; + } else if (expected instanceof RegExp) { + return ' with a message matching ' + matchersUtil.pp(expected); + } else { + return ' with message ' + matchersUtil.pp(expected); + } + } + + function matches(error) { + return ( + (errorType === null || error instanceof errorType) && + (expected === null || messageMatch(error.message)) + ); + } + + return { + match: function(thrown) { + if (matches(thrown)) { + return pass(function() { + return ( + 'Expected function not to throw ' + + errorTypeDescription + + messageDescription() + + '.' + ); + }); + } else { + return fail(function() { + return ( + 'Expected function to throw ' + + errorTypeDescription + + messageDescription() + + ', but it threw ' + + thrownDescription(thrown) + + '.' + ); + }); + } + } + }; + } + + function isStringOrRegExp(potential) { + return potential instanceof RegExp || typeof potential == 'string'; + } + + function isAnErrorType(type) { + if (typeof type !== 'function') { + return false; + } + + var Surrogate = function() {}; + Surrogate.prototype = type.prototype; + return j$.isError_(new Surrogate()); + } + } + + function pass(message) { + return { + pass: true, + message: message + }; + } + + function fail(message) { + return { + pass: false, + message: message + }; + } + + return toThrowError; +}; + +getJasmineRequireObj().toThrowMatching = function(j$) { + var usageError = j$.formatErrorMsg( + '', + 'expect(function() {}).toThrowMatching()' + ); + + /** + * {@link expect} a function to `throw` something matching a predicate. + * @function + * @name matchers#toThrowMatching + * @since 3.0.0 + * @param {Function} predicate - A function that takes the thrown exception as its parameter and returns true if it matches. + * @example + * expect(function() { throw new Error('nope'); }).toThrowMatching(function(thrown) { return thrown.message === 'nope'; }); + */ + function toThrowMatching(matchersUtil) { + return { + compare: function(actual, predicate) { + var thrown; + + if (typeof actual !== 'function') { + throw new Error(usageError('Actual is not a Function')); + } + + if (typeof predicate !== 'function') { + throw new Error(usageError('Predicate is not a Function')); + } + + try { + actual(); + return fail('Expected function to throw an exception.'); + } catch (e) { + thrown = e; + } + + if (predicate(thrown)) { + return pass( + 'Expected function not to throw an exception matching a predicate.' + ); + } else { + return fail(function() { + return ( + 'Expected function to throw an exception matching a predicate, ' + + 'but it threw ' + + thrownDescription(thrown) + + '.' + ); + }); + } + } + }; + + function thrownDescription(thrown) { + if (thrown && thrown.constructor) { + return ( + j$.fnNameFor(thrown.constructor) + + ' with message ' + + matchersUtil.pp(thrown.message) + ); + } else { + return matchersUtil.pp(thrown); + } + } + } + + function pass(message) { + return { + pass: true, + message: message + }; + } + + function fail(message) { + return { + pass: false, + message: message + }; + } + + return toThrowMatching; +}; + +getJasmineRequireObj().MockDate = function() { + function MockDate(global) { + var self = this; + var currentTime = 0; + + if (!global || !global.Date) { + self.install = function() {}; + self.tick = function() {}; + self.uninstall = function() {}; + return self; + } + + var GlobalDate = global.Date; + + self.install = function(mockDate) { + if (mockDate instanceof GlobalDate) { + currentTime = mockDate.getTime(); + } else { + currentTime = new GlobalDate().getTime(); + } + + global.Date = FakeDate; + }; + + self.tick = function(millis) { + millis = millis || 0; + currentTime = currentTime + millis; + }; + + self.uninstall = function() { + currentTime = 0; + global.Date = GlobalDate; + }; + + createDateProperties(); + + return self; + + function FakeDate() { + switch (arguments.length) { + case 0: + return new GlobalDate(currentTime); + case 1: + return new GlobalDate(arguments[0]); + case 2: + return new GlobalDate(arguments[0], arguments[1]); + case 3: + return new GlobalDate(arguments[0], arguments[1], arguments[2]); + case 4: + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3] + ); + case 5: + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3], + arguments[4] + ); + case 6: + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3], + arguments[4], + arguments[5] + ); + default: + return new GlobalDate( + arguments[0], + arguments[1], + arguments[2], + arguments[3], + arguments[4], + arguments[5], + arguments[6] + ); + } + } + + function createDateProperties() { + FakeDate.prototype = GlobalDate.prototype; + + FakeDate.now = function() { + if (GlobalDate.now) { + return currentTime; + } else { + throw new Error('Browser does not support Date.now()'); + } + }; + + FakeDate.toSource = GlobalDate.toSource; + FakeDate.toString = GlobalDate.toString; + FakeDate.parse = GlobalDate.parse; + FakeDate.UTC = GlobalDate.UTC; + } + } + + return MockDate; +}; + +getJasmineRequireObj().makePrettyPrinter = function(j$) { + function SinglePrettyPrintRun(customObjectFormatters, pp) { + this.customObjectFormatters_ = customObjectFormatters; + this.ppNestLevel_ = 0; + this.seen = []; + this.length = 0; + this.stringParts = []; + this.pp_ = pp; + } + + function hasCustomToString(value) { + // value.toString !== Object.prototype.toString if value has no custom toString but is from another context (e.g. + // iframe, web worker) + try { + return ( + j$.isFunction_(value.toString) && + value.toString !== Object.prototype.toString && + value.toString() !== Object.prototype.toString.call(value) + ); + } catch (e) { + // The custom toString() threw. + return true; + } + } + + SinglePrettyPrintRun.prototype.format = function(value) { + this.ppNestLevel_++; + try { + var customFormatResult = this.applyCustomFormatters_(value); + + if (customFormatResult) { + this.emitScalar(customFormatResult); + } else if (j$.util.isUndefined(value)) { + this.emitScalar('undefined'); + } else if (value === null) { + this.emitScalar('null'); + } else if (value === 0 && 1 / value === -Infinity) { + this.emitScalar('-0'); + } else if (value === j$.getGlobal()) { + this.emitScalar(''); + } else if (value.jasmineToString) { + this.emitScalar(value.jasmineToString(this.pp_)); + } else if (typeof value === 'string') { + this.emitString(value); + } else if (j$.isSpy(value)) { + this.emitScalar('spy on ' + value.and.identity); + } else if (j$.isSpy(value.toString)) { + this.emitScalar('spy on ' + value.toString.and.identity); + } else if (value instanceof RegExp) { + this.emitScalar(value.toString()); + } else if (typeof value === 'function') { + this.emitScalar('Function'); + } else if (j$.isDomNode(value)) { + if (value.tagName) { + this.emitDomElement(value); + } else { + this.emitScalar('HTMLNode'); + } + } else if (value instanceof Date) { + this.emitScalar('Date(' + value + ')'); + } else if (j$.isSet(value)) { + this.emitSet(value); + } else if (j$.isMap(value)) { + this.emitMap(value); + } else if (j$.isTypedArray_(value)) { + this.emitTypedArray(value); + } else if ( + value.toString && + typeof value === 'object' && + !j$.isArray_(value) && + hasCustomToString(value) + ) { + try { + this.emitScalar(value.toString()); + } catch (e) { + this.emitScalar('has-invalid-toString-method'); + } + } else if (j$.util.arrayContains(this.seen, value)) { + this.emitScalar( + '' + ); + } else if (j$.isArray_(value) || j$.isA_('Object', value)) { + this.seen.push(value); + if (j$.isArray_(value)) { + this.emitArray(value); + } else { + this.emitObject(value); + } + this.seen.pop(); + } else { + this.emitScalar(value.toString()); + } + } catch (e) { + if (this.ppNestLevel_ > 1 || !(e instanceof MaxCharsReachedError)) { + throw e; + } + } finally { + this.ppNestLevel_--; + } + }; + + SinglePrettyPrintRun.prototype.applyCustomFormatters_ = function(value) { + return customFormat(value, this.customObjectFormatters_); + }; + + SinglePrettyPrintRun.prototype.iterateObject = function(obj, fn) { + var objKeys = keys(obj, j$.isArray_(obj)); + var isGetter = function isGetter(prop) {}; + + if (obj.__lookupGetter__) { + isGetter = function isGetter(prop) { + var getter = obj.__lookupGetter__(prop); + return !j$.util.isUndefined(getter) && getter !== null; + }; + } + var length = Math.min(objKeys.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); + for (var i = 0; i < length; i++) { + var property = objKeys[i]; + fn(property, isGetter(property)); + } + + return objKeys.length > length; + }; + + SinglePrettyPrintRun.prototype.emitScalar = function(value) { + this.append(value); + }; + + SinglePrettyPrintRun.prototype.emitString = function(value) { + this.append("'" + value + "'"); + }; + + SinglePrettyPrintRun.prototype.emitArray = function(array) { + if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { + this.append('Array'); + return; + } + var length = Math.min(array.length, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); + this.append('[ '); + for (var i = 0; i < length; i++) { + if (i > 0) { + this.append(', '); + } + this.format(array[i]); + } + if (array.length > length) { + this.append(', ...'); + } + + var self = this; + var first = array.length === 0; + var truncated = this.iterateObject(array, function(property, isGetter) { + if (first) { + first = false; + } else { + self.append(', '); + } + + self.formatProperty(array, property, isGetter); + }); + + if (truncated) { + this.append(', ...'); + } + + this.append(' ]'); + }; + + SinglePrettyPrintRun.prototype.emitSet = function(set) { + if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { + this.append('Set'); + return; + } + this.append('Set( '); + var size = Math.min(set.size, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); + var i = 0; + set.forEach(function(value, key) { + if (i >= size) { + return; + } + if (i > 0) { + this.append(', '); + } + this.format(value); + + i++; + }, this); + if (set.size > size) { + this.append(', ...'); + } + this.append(' )'); + }; + + SinglePrettyPrintRun.prototype.emitMap = function(map) { + if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { + this.append('Map'); + return; + } + this.append('Map( '); + var size = Math.min(map.size, j$.MAX_PRETTY_PRINT_ARRAY_LENGTH); + var i = 0; + map.forEach(function(value, key) { + if (i >= size) { + return; + } + if (i > 0) { + this.append(', '); + } + this.format([key, value]); + + i++; + }, this); + if (map.size > size) { + this.append(', ...'); + } + this.append(' )'); + }; + + SinglePrettyPrintRun.prototype.emitObject = function(obj) { + var ctor = obj.constructor, + constructorName; + + constructorName = + typeof ctor === 'function' && obj instanceof ctor + ? j$.fnNameFor(obj.constructor) + : 'null'; + + this.append(constructorName); + + if (this.ppNestLevel_ > j$.MAX_PRETTY_PRINT_DEPTH) { + return; + } + + var self = this; + this.append('({ '); + var first = true; + + var truncated = this.iterateObject(obj, function(property, isGetter) { + if (first) { + first = false; + } else { + self.append(', '); + } + + self.formatProperty(obj, property, isGetter); + }); + + if (truncated) { + this.append(', ...'); + } + + this.append(' })'); + }; + + SinglePrettyPrintRun.prototype.emitTypedArray = function(arr) { + var constructorName = j$.fnNameFor(arr.constructor), + limitedArray = Array.prototype.slice.call( + arr, + 0, + j$.MAX_PRETTY_PRINT_ARRAY_LENGTH + ), + itemsString = Array.prototype.join.call(limitedArray, ', '); + + if (limitedArray.length !== arr.length) { + itemsString += ', ...'; + } + + this.append(constructorName + ' [ ' + itemsString + ' ]'); + }; + + SinglePrettyPrintRun.prototype.emitDomElement = function(el) { + var tagName = el.tagName.toLowerCase(), + attrs = el.attributes, + i, + len = attrs.length, + out = '<' + tagName, + attr; + + for (i = 0; i < len; i++) { + attr = attrs[i]; + out += ' ' + attr.name; + + if (attr.value !== '') { + out += '="' + attr.value + '"'; + } + } + + out += '>'; + + if (el.childElementCount !== 0 || el.textContent !== '') { + out += '...'; + } + + this.append(out); + }; + + SinglePrettyPrintRun.prototype.formatProperty = function( + obj, + property, + isGetter + ) { + this.append(property); + this.append(': '); + if (isGetter) { + this.append(''); + } else { + this.format(obj[property]); + } + }; + + SinglePrettyPrintRun.prototype.append = function(value) { + // This check protects us from the rare case where an object has overriden + // `toString()` with an invalid implementation (returning a non-string). + if (typeof value !== 'string') { + value = Object.prototype.toString.call(value); + } + + var result = truncate(value, j$.MAX_PRETTY_PRINT_CHARS - this.length); + this.length += result.value.length; + this.stringParts.push(result.value); + + if (result.truncated) { + throw new MaxCharsReachedError(); + } + }; + + function truncate(s, maxlen) { + if (s.length <= maxlen) { + return { value: s, truncated: false }; + } + + s = s.substring(0, maxlen - 4) + ' ...'; + return { value: s, truncated: true }; + } + + function MaxCharsReachedError() { + this.message = + 'Exceeded ' + + j$.MAX_PRETTY_PRINT_CHARS + + ' characters while pretty-printing a value'; + } + + MaxCharsReachedError.prototype = new Error(); + + function keys(obj, isArray) { + var allKeys = Object.keys + ? Object.keys(obj) + : (function(o) { + var keys = []; + for (var key in o) { + if (j$.util.has(o, key)) { + keys.push(key); + } + } + return keys; + })(obj); + + if (!isArray) { + return allKeys; + } + + if (allKeys.length === 0) { + return allKeys; + } + + var extraKeys = []; + for (var i = 0; i < allKeys.length; i++) { + if (!/^[0-9]+$/.test(allKeys[i])) { + extraKeys.push(allKeys[i]); + } + } + + return extraKeys; + } + + function customFormat(value, customObjectFormatters) { + var i, result; + + for (i = 0; i < customObjectFormatters.length; i++) { + result = customObjectFormatters[i](value); + + if (result !== undefined) { + return result; + } + } + } + + return function(customObjectFormatters) { + customObjectFormatters = customObjectFormatters || []; + + var pp = function(value) { + var prettyPrinter = new SinglePrettyPrintRun(customObjectFormatters, pp); + prettyPrinter.format(value); + return prettyPrinter.stringParts.join(''); + }; + + pp.customFormat_ = function(value) { + return customFormat(value, customObjectFormatters); + }; + + return pp; + }; +}; + +getJasmineRequireObj().QueueRunner = function(j$) { + var nextid = 1; + + function StopExecutionError() {} + StopExecutionError.prototype = new Error(); + j$.StopExecutionError = StopExecutionError; + + function once(fn) { + var called = false; + return function(arg) { + if (!called) { + called = true; + // Direct call using single parameter, because cleanup/next does not need more + fn(arg); + } + return null; + }; + } + + function emptyFn() {} + + function QueueRunner(attrs) { + this.id_ = nextid++; + var queueableFns = attrs.queueableFns || []; + this.queueableFns = queueableFns.concat(attrs.cleanupFns || []); + this.firstCleanupIx = queueableFns.length; + this.onComplete = attrs.onComplete || emptyFn; + this.clearStack = + attrs.clearStack || + function(fn) { + fn(); + }; + this.onException = attrs.onException || emptyFn; + this.userContext = attrs.userContext || new j$.UserContext(); + this.timeout = attrs.timeout || { + setTimeout: setTimeout, + clearTimeout: clearTimeout + }; + this.fail = attrs.fail || emptyFn; + this.globalErrors = attrs.globalErrors || { + pushListener: emptyFn, + popListener: emptyFn + }; + this.completeOnFirstError = !!attrs.completeOnFirstError; + this.errored = false; + + if (typeof this.onComplete !== 'function') { + throw new Error('invalid onComplete ' + JSON.stringify(this.onComplete)); + } + this.deprecated = attrs.deprecated; + } + + QueueRunner.prototype.execute = function() { + var self = this; + this.handleFinalError = function(message, source, lineno, colno, error) { + // Older browsers would send the error as the first parameter. HTML5 + // specifies the the five parameters above. The error instance should + // be preffered, otherwise the call stack would get lost. + self.onException(error || message); + }; + this.globalErrors.pushListener(this.handleFinalError); + this.run(0); + }; + + QueueRunner.prototype.skipToCleanup = function(lastRanIndex) { + if (lastRanIndex < this.firstCleanupIx) { + this.run(this.firstCleanupIx); + } else { + this.run(lastRanIndex + 1); + } + }; + + QueueRunner.prototype.clearTimeout = function(timeoutId) { + Function.prototype.apply.apply(this.timeout.clearTimeout, [ + j$.getGlobal(), + [timeoutId] + ]); + }; + + QueueRunner.prototype.setTimeout = function(fn, timeout) { + return Function.prototype.apply.apply(this.timeout.setTimeout, [ + j$.getGlobal(), + [fn, timeout] + ]); + }; + + QueueRunner.prototype.attempt = function attempt(iterativeIndex) { + var self = this, + completedSynchronously = true, + handleError = function handleError(error) { + onException(error); + next(error); + }, + cleanup = once(function cleanup() { + if (timeoutId !== void 0) { + self.clearTimeout(timeoutId); + } + self.globalErrors.popListener(handleError); + }), + next = once(function next(err) { + cleanup(); + + if (j$.isError_(err)) { + if (!(err instanceof StopExecutionError) && !err.jasmineMessage) { + self.fail(err); + } + self.errored = errored = true; + } + + function runNext() { + if (self.completeOnFirstError && errored) { + self.skipToCleanup(iterativeIndex); + } else { + self.run(iterativeIndex + 1); + } + } + + if (completedSynchronously) { + self.setTimeout(runNext); + } else { + runNext(); + } + }), + errored = false, + queueableFn = self.queueableFns[iterativeIndex], + timeoutId, + maybeThenable; + + next.fail = function nextFail() { + self.fail.apply(null, arguments); + self.errored = errored = true; + next(); + }; + + self.globalErrors.pushListener(handleError); + + if (queueableFn.timeout !== undefined) { + var timeoutInterval = queueableFn.timeout || j$.DEFAULT_TIMEOUT_INTERVAL; + timeoutId = self.setTimeout(function() { + var error = new Error( + 'Timeout - Async function did not complete within ' + + timeoutInterval + + 'ms ' + + (queueableFn.timeout + ? '(custom timeout)' + : '(set by jasmine.DEFAULT_TIMEOUT_INTERVAL)') + ); + onException(error); + next(); + }, timeoutInterval); + } + + try { + if (queueableFn.fn.length === 0) { + maybeThenable = queueableFn.fn.call(self.userContext); + + if (maybeThenable && j$.isFunction_(maybeThenable.then)) { + maybeThenable.then(next, onPromiseRejection); + completedSynchronously = false; + return { completedSynchronously: false }; + } + } else { + maybeThenable = queueableFn.fn.call(self.userContext, next); + this.diagnoseConflictingAsync_(queueableFn.fn, maybeThenable); + completedSynchronously = false; + return { completedSynchronously: false }; + } + } catch (e) { + onException(e); + self.errored = errored = true; + } + + cleanup(); + return { completedSynchronously: true, errored: errored }; + + function onException(e) { + self.onException(e); + self.errored = errored = true; + } + + function onPromiseRejection(e) { + onException(e); + next(); + } + }; + + QueueRunner.prototype.run = function(recursiveIndex) { + var length = this.queueableFns.length, + self = this, + iterativeIndex; + + for ( + iterativeIndex = recursiveIndex; + iterativeIndex < length; + iterativeIndex++ + ) { + var result = this.attempt(iterativeIndex); + + if (!result.completedSynchronously) { + return; + } + + self.errored = self.errored || result.errored; + + if (this.completeOnFirstError && result.errored) { + this.skipToCleanup(iterativeIndex); + return; + } + } + + this.clearStack(function() { + self.globalErrors.popListener(self.handleFinalError); + self.onComplete(self.errored && new StopExecutionError()); + }); + }; + + QueueRunner.prototype.diagnoseConflictingAsync_ = function(fn, retval) { + if (retval && j$.isFunction_(retval.then)) { + // Issue a warning that matches the user's code + if (j$.isAsyncFunction_(fn)) { + this.deprecated( + 'An asynchronous before/it/after ' + + 'function was defined with the async keyword but also took a ' + + 'done callback. This is not supported and will stop working in' + + ' the future. Either remove the done callback (recommended) or ' + + 'remove the async keyword.' + ); + } else { + this.deprecated( + 'An asynchronous before/it/after ' + + 'function took a done callback but also returned a promise. ' + + 'This is not supported and will stop working in the future. ' + + 'Either remove the done callback (recommended) or change the ' + + 'function to not return a promise.' + ); + } + } + }; + + return QueueRunner; +}; + +getJasmineRequireObj().ReportDispatcher = function(j$) { + function ReportDispatcher(methods, queueRunnerFactory) { + var dispatchedMethods = methods || []; + + for (var i = 0; i < dispatchedMethods.length; i++) { + var method = dispatchedMethods[i]; + this[method] = (function(m) { + return function() { + dispatch(m, arguments); + }; + })(method); + } + + var reporters = []; + var fallbackReporter = null; + + this.addReporter = function(reporter) { + reporters.push(reporter); + }; + + this.provideFallbackReporter = function(reporter) { + fallbackReporter = reporter; + }; + + this.clearReporters = function() { + reporters = []; + }; + + return this; + + function dispatch(method, args) { + if (reporters.length === 0 && fallbackReporter !== null) { + reporters.push(fallbackReporter); + } + var onComplete = args[args.length - 1]; + args = j$.util.argsToArray(args).splice(0, args.length - 1); + var fns = []; + for (var i = 0; i < reporters.length; i++) { + var reporter = reporters[i]; + addFn(fns, reporter, method, args); + } + + queueRunnerFactory({ + queueableFns: fns, + onComplete: onComplete, + isReporter: true + }); + } + + function addFn(fns, reporter, method, args) { + var fn = reporter[method]; + if (!fn) { + return; + } + + var thisArgs = j$.util.cloneArgs(args); + if (fn.length <= 1) { + fns.push({ + fn: function() { + return fn.apply(reporter, thisArgs); + } + }); + } else { + fns.push({ + fn: function(done) { + return fn.apply(reporter, thisArgs.concat([done])); + } + }); + } + } + } + + return ReportDispatcher; +}; + +getJasmineRequireObj().interface = function(jasmine, env) { + var jasmineInterface = { + /** + * Callback passed to parts of the Jasmine base interface. + * + * By default Jasmine assumes this function completes synchronously. + * If you have code that you need to test asynchronously, you can declare that you receive a `done` callback, return a Promise, or use the `async` keyword if it is supported in your environment. + * @callback implementationCallback + * @param {Function} [done] Used to specify to Jasmine that this callback is asynchronous and Jasmine should wait until it has been called before moving on. + * @returns {} Optionally return a Promise instead of using `done` to cause Jasmine to wait for completion. + */ + + /** + * Create a group of specs (often called a suite). + * + * Calls to `describe` can be nested within other calls to compose your suite as a tree. + * @name describe + * @since 1.3.0 + * @function + * @global + * @param {String} description Textual description of the group + * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs + */ + describe: function(description, specDefinitions) { + return env.describe(description, specDefinitions); + }, + + /** + * A temporarily disabled [`describe`]{@link describe} + * + * Specs within an `xdescribe` will be marked pending and not executed + * @name xdescribe + * @since 1.3.0 + * @function + * @global + * @param {String} description Textual description of the group + * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs + */ + xdescribe: function(description, specDefinitions) { + return env.xdescribe(description, specDefinitions); + }, + + /** + * A focused [`describe`]{@link describe} + * + * If suites or specs are focused, only those that are focused will be executed + * @see fit + * @name fdescribe + * @since 2.1.0 + * @function + * @global + * @param {String} description Textual description of the group + * @param {Function} specDefinitions Function for Jasmine to invoke that will define inner suites and specs + */ + fdescribe: function(description, specDefinitions) { + return env.fdescribe(description, specDefinitions); + }, + + /** + * Define a single spec. A spec should contain one or more {@link expect|expectations} that test the state of the code. + * + * A spec whose expectations all succeed will be passing and a spec with any failures will fail. + * The name `it` is a pronoun for the test target, not an abbreviation of anything. It makes the + * spec more readable by connecting the function name `it` and the argument `description` as a + * complete sentence. + * @name it + * @since 1.3.0 + * @function + * @global + * @param {String} description Textual description of what this spec is checking + * @param {implementationCallback} [testFunction] Function that contains the code of your test. If not provided the test will be `pending`. + * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async spec. + * @see async + */ + it: function() { + return env.it.apply(env, arguments); + }, + + /** + * A temporarily disabled [`it`]{@link it} + * + * The spec will report as `pending` and will not be executed. + * @name xit + * @since 1.3.0 + * @function + * @global + * @param {String} description Textual description of what this spec is checking. + * @param {implementationCallback} [testFunction] Function that contains the code of your test. Will not be executed. + */ + xit: function() { + return env.xit.apply(env, arguments); + }, + + /** + * A focused [`it`]{@link it} + * + * If suites or specs are focused, only those that are focused will be executed. + * @name fit + * @since 2.1.0 + * @function + * @global + * @param {String} description Textual description of what this spec is checking. + * @param {implementationCallback} testFunction Function that contains the code of your test. + * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async spec. + * @see async + */ + fit: function() { + return env.fit.apply(env, arguments); + }, + + /** + * Run some shared setup before each of the specs in the {@link describe} in which it is called. + * @name beforeEach + * @since 1.3.0 + * @function + * @global + * @param {implementationCallback} [function] Function that contains the code to setup your specs. + * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async beforeEach. + * @see async + */ + beforeEach: function() { + return env.beforeEach.apply(env, arguments); + }, + + /** + * Run some shared teardown after each of the specs in the {@link describe} in which it is called. + * @name afterEach + * @since 1.3.0 + * @function + * @global + * @param {implementationCallback} [function] Function that contains the code to teardown your specs. + * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async afterEach. + * @see async + */ + afterEach: function() { + return env.afterEach.apply(env, arguments); + }, + + /** + * Run some shared setup once before all of the specs in the {@link describe} are run. + * + * _Note:_ Be careful, sharing the setup from a beforeAll makes it easy to accidentally leak state between your specs so that they erroneously pass or fail. + * @name beforeAll + * @since 2.1.0 + * @function + * @global + * @param {implementationCallback} [function] Function that contains the code to setup your specs. + * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async beforeAll. + * @see async + */ + beforeAll: function() { + return env.beforeAll.apply(env, arguments); + }, + + /** + * Run some shared teardown once after all of the specs in the {@link describe} are run. + * + * _Note:_ Be careful, sharing the teardown from a afterAll makes it easy to accidentally leak state between your specs so that they erroneously pass or fail. + * @name afterAll + * @since 2.1.0 + * @function + * @global + * @param {implementationCallback} [function] Function that contains the code to teardown your specs. + * @param {Int} [timeout={@link jasmine.DEFAULT_TIMEOUT_INTERVAL}] Custom timeout for an async afterAll. + * @see async + */ + afterAll: function() { + return env.afterAll.apply(env, arguments); + }, + + /** + * Sets a user-defined property that will be provided to reporters as part of the properties field of {@link SpecResult} + * @name setSpecProperty + * @since 3.6.0 + * @function + * @param {String} key The name of the property + * @param {*} value The value of the property + */ + setSpecProperty: function(key, value) { + return env.setSpecProperty(key, value); + }, + + /** + * Sets a user-defined property that will be provided to reporters as part of the properties field of {@link SuiteResult} + * @name setSuiteProperty + * @since 3.6.0 + * @function + * @param {String} key The name of the property + * @param {*} value The value of the property + */ + setSuiteProperty: function(key, value) { + return env.setSuiteProperty(key, value); + }, + + /** + * Create an expectation for a spec. + * @name expect + * @since 1.3.0 + * @function + * @global + * @param {Object} actual - Actual computed value to test expectations against. + * @return {matchers} + */ + expect: function(actual) { + return env.expect(actual); + }, + + /** + * Create an asynchronous expectation for a spec. Note that the matchers + * that are provided by an asynchronous expectation all return promises + * which must be either returned from the spec or waited for using `await` + * in order for Jasmine to associate them with the correct spec. + * @name expectAsync + * @since 3.3.0 + * @function + * @global + * @param {Object} actual - Actual computed value to test expectations against. + * @return {async-matchers} + * @example + * await expectAsync(somePromise).toBeResolved(); + * @example + * return expectAsync(somePromise).toBeResolved(); + */ + expectAsync: function(actual) { + return env.expectAsync(actual); + }, + + /** + * Mark a spec as pending, expectation results will be ignored. + * @name pending + * @since 2.0.0 + * @function + * @global + * @param {String} [message] - Reason the spec is pending. + */ + pending: function() { + return env.pending.apply(env, arguments); + }, + + /** + * Explicitly mark a spec as failed. + * @name fail + * @since 2.1.0 + * @function + * @global + * @param {String|Error} [error] - Reason for the failure. + */ + fail: function() { + return env.fail.apply(env, arguments); + }, + + /** + * Install a spy onto an existing object. + * @name spyOn + * @since 1.3.0 + * @function + * @global + * @param {Object} obj - The object upon which to install the {@link Spy}. + * @param {String} methodName - The name of the method to replace with a {@link Spy}. + * @returns {Spy} + */ + spyOn: function(obj, methodName) { + return env.spyOn(obj, methodName); + }, + + /** + * Install a spy on a property installed with `Object.defineProperty` onto an existing object. + * @name spyOnProperty + * @since 2.6.0 + * @function + * @global + * @param {Object} obj - The object upon which to install the {@link Spy} + * @param {String} propertyName - The name of the property to replace with a {@link Spy}. + * @param {String} [accessType=get] - The access type (get|set) of the property to {@link Spy} on. + * @returns {Spy} + */ + spyOnProperty: function(obj, methodName, accessType) { + return env.spyOnProperty(obj, methodName, accessType); + }, + + /** + * Installs spies on all writable and configurable properties of an object. + * @name spyOnAllFunctions + * @since 3.2.1 + * @function + * @global + * @param {Object} obj - The object upon which to install the {@link Spy}s + * @param {boolean} includeNonEnumerable - Whether or not to add spies to non-enumerable properties + * @returns {Object} the spied object + */ + spyOnAllFunctions: function(obj, includeNonEnumerable) { + return env.spyOnAllFunctions(obj, includeNonEnumerable); + }, + + jsApiReporter: new jasmine.JsApiReporter({ + timer: new jasmine.Timer() + }), + + /** + * @namespace jasmine + */ + jasmine: jasmine + }; + + /** + * Add a custom equality tester for the current scope of specs. + * + * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. + * @name jasmine.addCustomEqualityTester + * @since 2.0.0 + * @function + * @param {Function} tester - A function which takes two arguments to compare and returns a `true` or `false` comparison result if it knows how to compare them, and `undefined` otherwise. + * @see custom_equality + */ + jasmine.addCustomEqualityTester = function(tester) { + env.addCustomEqualityTester(tester); + }; + + /** + * Add custom matchers for the current scope of specs. + * + * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. + * @name jasmine.addMatchers + * @since 2.0.0 + * @function + * @param {Object} matchers - Keys from this object will be the new matcher names. + * @see custom_matcher + */ + jasmine.addMatchers = function(matchers) { + return env.addMatchers(matchers); + }; + + /** + * Add custom async matchers for the current scope of specs. + * + * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. + * @name jasmine.addAsyncMatchers + * @since 3.5.0 + * @function + * @param {Object} matchers - Keys from this object will be the new async matcher names. + * @see custom_matcher + */ + jasmine.addAsyncMatchers = function(matchers) { + return env.addAsyncMatchers(matchers); + }; + + /** + * Add a custom object formatter for the current scope of specs. + * + * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. + * @name jasmine.addCustomObjectFormatter + * @since 3.6.0 + * @function + * @param {Function} formatter - A function which takes a value to format and returns a string if it knows how to format it, and `undefined` otherwise. + * @see custom_object_formatters + */ + jasmine.addCustomObjectFormatter = function(formatter) { + return env.addCustomObjectFormatter(formatter); + }; + + /** + * Get the currently booted mock {Clock} for this Jasmine environment. + * @name jasmine.clock + * @since 2.0.0 + * @function + * @returns {Clock} + */ + jasmine.clock = function() { + return env.clock; + }; + + /** + * Create a bare {@link Spy} object. This won't be installed anywhere and will not have any implementation behind it. + * @name jasmine.createSpy + * @since 1.3.0 + * @function + * @param {String} [name] - Name to give the spy. This will be displayed in failure messages. + * @param {Function} [originalFn] - Function to act as the real implementation. + * @return {Spy} + */ + jasmine.createSpy = function(name, originalFn) { + return env.createSpy(name, originalFn); + }; + + /** + * Create an object with multiple {@link Spy}s as its members. + * @name jasmine.createSpyObj + * @since 1.3.0 + * @function + * @param {String} [baseName] - Base name for the spies in the object. + * @param {String[]|Object} methodNames - Array of method names to create spies for, or Object whose keys will be method names and values the {@link Spy#and#returnValue|returnValue}. + * @param {String[]|Object} [propertyNames] - Array of property names to create spies for, or Object whose keys will be propertynames and values the {@link Spy#and#returnValue|returnValue}. + * @return {Object} + */ + jasmine.createSpyObj = function(baseName, methodNames, propertyNames) { + return env.createSpyObj(baseName, methodNames, propertyNames); + }; + + /** + * Add a custom spy strategy for the current scope of specs. + * + * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. + * @name jasmine.addSpyStrategy + * @since 3.5.0 + * @function + * @param {String} name - The name of the strategy (i.e. what you call from `and`) + * @param {Function} factory - Factory function that returns the plan to be executed. + */ + jasmine.addSpyStrategy = function(name, factory) { + return env.addSpyStrategy(name, factory); + }; + + /** + * Set the default spy strategy for the current scope of specs. + * + * _Note:_ This is only callable from within a {@link beforeEach}, {@link it}, or {@link beforeAll}. + * @name jasmine.setDefaultSpyStrategy + * @function + * @param {Function} defaultStrategyFn - a function that assigns a strategy + * @example + * beforeEach(function() { + * jasmine.setDefaultSpyStrategy(and => and.returnValue(true)); + * }); + */ + jasmine.setDefaultSpyStrategy = function(defaultStrategyFn) { + return env.setDefaultSpyStrategy(defaultStrategyFn); + }; + + return jasmineInterface; +}; + +getJasmineRequireObj().Spy = function(j$) { + var nextOrder = (function() { + var order = 0; + + return function() { + return order++; + }; + })(); + + var matchersUtil = new j$.MatchersUtil({ + customTesters: [], + pp: j$.makePrettyPrinter() + }); + + /** + * @classdesc _Note:_ Do not construct this directly. Use {@link spyOn}, + * {@link spyOnProperty}, {@link jasmine.createSpy}, or + * {@link jasmine.createSpyObj} instead. + * @class Spy + * @hideconstructor + */ + function Spy( + name, + originalFn, + customStrategies, + defaultStrategyFn, + getPromise + ) { + var numArgs = typeof originalFn === 'function' ? originalFn.length : 0, + wrapper = makeFunc(numArgs, function(context, args, invokeNew) { + return spy(context, args, invokeNew); + }), + strategyDispatcher = new SpyStrategyDispatcher({ + name: name, + fn: originalFn, + getSpy: function() { + return wrapper; + }, + customStrategies: customStrategies, + getPromise: getPromise + }), + callTracker = new j$.CallTracker(), + spy = function(context, args, invokeNew) { + /** + * @name Spy.callData + * @property {object} object - `this` context for the invocation. + * @property {number} invocationOrder - Order of the invocation. + * @property {Array} args - The arguments passed for this invocation. + * @property returnValue - The value that was returned from this invocation. + */ + var callData = { + object: context, + invocationOrder: nextOrder(), + args: Array.prototype.slice.apply(args) + }; + + callTracker.track(callData); + var returnValue = strategyDispatcher.exec(context, args, invokeNew); + callData.returnValue = returnValue; + + return returnValue; + }; + + function makeFunc(length, fn) { + switch (length) { + case 1: + return function wrap1(a) { + return fn(this, arguments, this instanceof wrap1); + }; + case 2: + return function wrap2(a, b) { + return fn(this, arguments, this instanceof wrap2); + }; + case 3: + return function wrap3(a, b, c) { + return fn(this, arguments, this instanceof wrap3); + }; + case 4: + return function wrap4(a, b, c, d) { + return fn(this, arguments, this instanceof wrap4); + }; + case 5: + return function wrap5(a, b, c, d, e) { + return fn(this, arguments, this instanceof wrap5); + }; + case 6: + return function wrap6(a, b, c, d, e, f) { + return fn(this, arguments, this instanceof wrap6); + }; + case 7: + return function wrap7(a, b, c, d, e, f, g) { + return fn(this, arguments, this instanceof wrap7); + }; + case 8: + return function wrap8(a, b, c, d, e, f, g, h) { + return fn(this, arguments, this instanceof wrap8); + }; + case 9: + return function wrap9(a, b, c, d, e, f, g, h, i) { + return fn(this, arguments, this instanceof wrap9); + }; + default: + return function wrap() { + return fn(this, arguments, this instanceof wrap); + }; + } + } + + for (var prop in originalFn) { + if (prop === 'and' || prop === 'calls') { + throw new Error( + "Jasmine spies would overwrite the 'and' and 'calls' properties on the object being spied upon" + ); + } + + wrapper[prop] = originalFn[prop]; + } + + /** + * @member {SpyStrategy} - Accesses the default strategy for the spy. This strategy will be used + * whenever the spy is called with arguments that don't match any strategy + * created with {@link Spy#withArgs}. + * @name Spy#and + * @since 2.0.0 + * @example + * spyOn(someObj, 'func').and.returnValue(42); + */ + wrapper.and = strategyDispatcher.and; + /** + * Specifies a strategy to be used for calls to the spy that have the + * specified arguments. + * @name Spy#withArgs + * @since 3.0.0 + * @function + * @param {...*} args - The arguments to match + * @type {SpyStrategy} + * @example + * spyOn(someObj, 'func').withArgs(1, 2, 3).and.returnValue(42); + * someObj.func(1, 2, 3); // returns 42 + */ + wrapper.withArgs = function() { + return strategyDispatcher.withArgs.apply(strategyDispatcher, arguments); + }; + wrapper.calls = callTracker; + + if (defaultStrategyFn) { + defaultStrategyFn(wrapper.and); + } + + return wrapper; + } + + function SpyStrategyDispatcher(strategyArgs) { + var baseStrategy = new j$.SpyStrategy(strategyArgs); + var argsStrategies = new StrategyDict(function() { + return new j$.SpyStrategy(strategyArgs); + }); + + this.and = baseStrategy; + + this.exec = function(spy, args, invokeNew) { + var strategy = argsStrategies.get(args); + + if (!strategy) { + if (argsStrategies.any() && !baseStrategy.isConfigured()) { + throw new Error( + "Spy '" + + strategyArgs.name + + "' received a call with arguments " + + j$.pp(Array.prototype.slice.call(args)) + + ' but all configured strategies specify other arguments.' + ); + } else { + strategy = baseStrategy; + } + } + + return strategy.exec(spy, args, invokeNew); + }; + + this.withArgs = function() { + return { and: argsStrategies.getOrCreate(arguments) }; + }; + } + + function StrategyDict(strategyFactory) { + this.strategies = []; + this.strategyFactory = strategyFactory; + } + + StrategyDict.prototype.any = function() { + return this.strategies.length > 0; + }; + + StrategyDict.prototype.getOrCreate = function(args) { + var strategy = this.get(args); + + if (!strategy) { + strategy = this.strategyFactory(); + this.strategies.push({ + args: args, + strategy: strategy + }); + } + + return strategy; + }; + + StrategyDict.prototype.get = function(args) { + var i; + + for (i = 0; i < this.strategies.length; i++) { + if (matchersUtil.equals(args, this.strategies[i].args)) { + return this.strategies[i].strategy; + } + } + }; + + return Spy; +}; + +getJasmineRequireObj().SpyFactory = function(j$) { + function SpyFactory(getCustomStrategies, getDefaultStrategyFn, getPromise) { + var self = this; + + this.createSpy = function(name, originalFn) { + return j$.Spy( + name, + originalFn, + getCustomStrategies(), + getDefaultStrategyFn(), + getPromise + ); + }; + + this.createSpyObj = function(baseName, methodNames, propertyNames) { + var baseNameIsCollection = + j$.isObject_(baseName) || j$.isArray_(baseName); + + if (baseNameIsCollection) { + propertyNames = methodNames; + methodNames = baseName; + baseName = 'unknown'; + } + + var obj = {}; + var spy, descriptor; + + var methods = normalizeKeyValues(methodNames); + for (var i = 0; i < methods.length; i++) { + spy = obj[methods[i][0]] = self.createSpy( + baseName + '.' + methods[i][0] + ); + if (methods[i].length > 1) { + spy.and.returnValue(methods[i][1]); + } + } + + var properties = normalizeKeyValues(propertyNames); + for (var i = 0; i < properties.length; i++) { + descriptor = { + enumerable: true, + get: self.createSpy(baseName + '.' + properties[i][0] + '.get'), + set: self.createSpy(baseName + '.' + properties[i][0] + '.set') + }; + if (properties[i].length > 1) { + descriptor.get.and.returnValue(properties[i][1]); + descriptor.set.and.returnValue(properties[i][1]); + } + Object.defineProperty(obj, properties[i][0], descriptor); + } + + if (methods.length === 0 && properties.length === 0) { + throw 'createSpyObj requires a non-empty array or object of method names to create spies for'; + } + + return obj; + }; + } + + function normalizeKeyValues(object) { + var result = []; + if (j$.isArray_(object)) { + for (var i = 0; i < object.length; i++) { + result.push([object[i]]); + } + } else if (j$.isObject_(object)) { + for (var key in object) { + if (object.hasOwnProperty(key)) { + result.push([key, object[key]]); + } + } + } + return result; + } + + return SpyFactory; +}; + +getJasmineRequireObj().SpyRegistry = function(j$) { + var spyOnMsg = j$.formatErrorMsg('', 'spyOn(, )'); + var spyOnPropertyMsg = j$.formatErrorMsg( + '', + 'spyOnProperty(, , [accessType])' + ); + + function SpyRegistry(options) { + options = options || {}; + var global = options.global || j$.getGlobal(); + var createSpy = options.createSpy; + var currentSpies = + options.currentSpies || + function() { + return []; + }; + + this.allowRespy = function(allow) { + this.respy = allow; + }; + + this.spyOn = function(obj, methodName) { + var getErrorMsg = spyOnMsg; + + if (j$.util.isUndefined(obj) || obj === null) { + throw new Error( + getErrorMsg( + 'could not find an object to spy upon for ' + methodName + '()' + ) + ); + } + + if (j$.util.isUndefined(methodName) || methodName === null) { + throw new Error(getErrorMsg('No method name supplied')); + } + + if (j$.util.isUndefined(obj[methodName])) { + throw new Error(getErrorMsg(methodName + '() method does not exist')); + } + + if (obj[methodName] && j$.isSpy(obj[methodName])) { + if (this.respy) { + return obj[methodName]; + } else { + throw new Error( + getErrorMsg(methodName + ' has already been spied upon') + ); + } + } + + var descriptor = Object.getOwnPropertyDescriptor(obj, methodName); + + if (descriptor && !(descriptor.writable || descriptor.set)) { + throw new Error( + getErrorMsg(methodName + ' is not declared writable or has no setter') + ); + } + + var originalMethod = obj[methodName], + spiedMethod = createSpy(methodName, originalMethod), + restoreStrategy; + + if ( + Object.prototype.hasOwnProperty.call(obj, methodName) || + (obj === global && methodName === 'onerror') + ) { + restoreStrategy = function() { + obj[methodName] = originalMethod; + }; + } else { + restoreStrategy = function() { + if (!delete obj[methodName]) { + obj[methodName] = originalMethod; + } + }; + } + + currentSpies().push({ + restoreObjectToOriginalState: restoreStrategy + }); + + obj[methodName] = spiedMethod; + + return spiedMethod; + }; + + this.spyOnProperty = function(obj, propertyName, accessType) { + var getErrorMsg = spyOnPropertyMsg; + + accessType = accessType || 'get'; + + if (j$.util.isUndefined(obj)) { + throw new Error( + getErrorMsg( + 'spyOn could not find an object to spy upon for ' + + propertyName + + '' + ) + ); + } + + if (j$.util.isUndefined(propertyName)) { + throw new Error(getErrorMsg('No property name supplied')); + } + + var descriptor = j$.util.getPropertyDescriptor(obj, propertyName); + + if (!descriptor) { + throw new Error(getErrorMsg(propertyName + ' property does not exist')); + } + + if (!descriptor.configurable) { + throw new Error( + getErrorMsg(propertyName + ' is not declared configurable') + ); + } + + if (!descriptor[accessType]) { + throw new Error( + getErrorMsg( + 'Property ' + + propertyName + + ' does not have access type ' + + accessType + ) + ); + } + + if (j$.isSpy(descriptor[accessType])) { + if (this.respy) { + return descriptor[accessType]; + } else { + throw new Error( + getErrorMsg( + propertyName + '#' + accessType + ' has already been spied upon' + ) + ); + } + } + + var originalDescriptor = j$.util.clone(descriptor), + spy = createSpy(propertyName, descriptor[accessType]), + restoreStrategy; + + if (Object.prototype.hasOwnProperty.call(obj, propertyName)) { + restoreStrategy = function() { + Object.defineProperty(obj, propertyName, originalDescriptor); + }; + } else { + restoreStrategy = function() { + delete obj[propertyName]; + }; + } + + currentSpies().push({ + restoreObjectToOriginalState: restoreStrategy + }); + + descriptor[accessType] = spy; + + Object.defineProperty(obj, propertyName, descriptor); + + return spy; + }; + + this.spyOnAllFunctions = function(obj, includeNonEnumerable) { + if (j$.util.isUndefined(obj)) { + throw new Error( + 'spyOnAllFunctions could not find an object to spy upon' + ); + } + + var pointer = obj, + propsToSpyOn = [], + properties, + propertiesToSkip = []; + + while ( + pointer && + (!includeNonEnumerable || pointer !== Object.prototype) + ) { + properties = getProps(pointer, includeNonEnumerable); + properties = properties.filter(function(prop) { + return propertiesToSkip.indexOf(prop) === -1; + }); + propertiesToSkip = propertiesToSkip.concat(properties); + propsToSpyOn = propsToSpyOn.concat( + getSpyableFunctionProps(pointer, properties) + ); + pointer = Object.getPrototypeOf(pointer); + } + + for (var i = 0; i < propsToSpyOn.length; i++) { + this.spyOn(obj, propsToSpyOn[i]); + } + + return obj; + }; + + this.clearSpies = function() { + var spies = currentSpies(); + for (var i = spies.length - 1; i >= 0; i--) { + var spyEntry = spies[i]; + spyEntry.restoreObjectToOriginalState(); + } + }; + } + + function getProps(obj, includeNonEnumerable) { + var enumerableProperties = Object.keys(obj); + + if (!includeNonEnumerable) { + return enumerableProperties; + } + + return Object.getOwnPropertyNames(obj).filter(function(prop) { + return ( + prop !== 'constructor' || + enumerableProperties.indexOf('constructor') > -1 + ); + }); + } + + function getSpyableFunctionProps(obj, propertiesToCheck) { + var props = [], + prop; + for (var i = 0; i < propertiesToCheck.length; i++) { + prop = propertiesToCheck[i]; + if ( + Object.prototype.hasOwnProperty.call(obj, prop) && + isSpyableProp(obj, prop) + ) { + props.push(prop); + } + } + return props; + } + + function isSpyableProp(obj, prop) { + var value, descriptor; + try { + value = obj[prop]; + } catch (e) { + return false; + } + if (value instanceof Function) { + descriptor = Object.getOwnPropertyDescriptor(obj, prop); + return (descriptor.writable || descriptor.set) && descriptor.configurable; + } + return false; + } + + return SpyRegistry; +}; + +getJasmineRequireObj().SpyStrategy = function(j$) { + /** + * @interface SpyStrategy + */ + function SpyStrategy(options) { + options = options || {}; + + var self = this; + + /** + * Get the identifying information for the spy. + * @name SpyStrategy#identity + * @since 3.0.0 + * @member + * @type {String} + */ + this.identity = options.name || 'unknown'; + this.originalFn = options.fn || function() {}; + this.getSpy = options.getSpy || function() {}; + this.plan = this._defaultPlan = function() {}; + + var k, + cs = options.customStrategies || {}; + for (k in cs) { + if (j$.util.has(cs, k) && !this[k]) { + this[k] = createCustomPlan(cs[k]); + } + } + + var getPromise = + typeof options.getPromise === 'function' + ? options.getPromise + : function() {}; + + var requirePromise = function(name) { + var Promise = getPromise(); + + if (!Promise) { + throw new Error( + name + + ' requires global Promise, or `Promise` configured with `jasmine.getEnv().configure()`' + ); + } + + return Promise; + }; + + /** + * Tell the spy to return a promise resolving to the specified value when invoked. + * @name SpyStrategy#resolveTo + * @since 3.5.0 + * @function + * @param {*} value The value to return. + */ + this.resolveTo = function(value) { + var Promise = requirePromise('resolveTo'); + self.plan = function() { + return Promise.resolve(value); + }; + return self.getSpy(); + }; + + /** + * Tell the spy to return a promise rejecting with the specified value when invoked. + * @name SpyStrategy#rejectWith + * @since 3.5.0 + * @function + * @param {*} value The value to return. + */ + this.rejectWith = function(value) { + var Promise = requirePromise('rejectWith'); + + self.plan = function() { + return Promise.reject(value); + }; + return self.getSpy(); + }; + } + + function createCustomPlan(factory) { + return function() { + var plan = factory.apply(null, arguments); + + if (!j$.isFunction_(plan)) { + throw new Error('Spy strategy must return a function'); + } + + this.plan = plan; + return this.getSpy(); + }; + } + + /** + * Execute the current spy strategy. + * @name SpyStrategy#exec + * @since 2.0.0 + * @function + */ + SpyStrategy.prototype.exec = function(context, args, invokeNew) { + var contextArgs = [context].concat( + args ? Array.prototype.slice.call(args) : [] + ); + var target = this.plan.bind.apply(this.plan, contextArgs); + + return invokeNew ? new target() : target(); + }; + + /** + * Tell the spy to call through to the real implementation when invoked. + * @name SpyStrategy#callThrough + * @since 2.0.0 + * @function + */ + SpyStrategy.prototype.callThrough = function() { + this.plan = this.originalFn; + return this.getSpy(); + }; + + /** + * Tell the spy to return the value when invoked. + * @name SpyStrategy#returnValue + * @since 2.0.0 + * @function + * @param {*} value The value to return. + */ + SpyStrategy.prototype.returnValue = function(value) { + this.plan = function() { + return value; + }; + return this.getSpy(); + }; + + /** + * Tell the spy to return one of the specified values (sequentially) each time the spy is invoked. + * @name SpyStrategy#returnValues + * @since 2.1.0 + * @function + * @param {...*} values - Values to be returned on subsequent calls to the spy. + */ + SpyStrategy.prototype.returnValues = function() { + var values = Array.prototype.slice.call(arguments); + this.plan = function() { + return values.shift(); + }; + return this.getSpy(); + }; + + /** + * Tell the spy to throw an error when invoked. + * @name SpyStrategy#throwError + * @since 2.0.0 + * @function + * @param {Error|Object|String} something Thing to throw + */ + SpyStrategy.prototype.throwError = function(something) { + var error = j$.isString_(something) ? new Error(something) : something; + this.plan = function() { + throw error; + }; + return this.getSpy(); + }; + + /** + * Tell the spy to call a fake implementation when invoked. + * @name SpyStrategy#callFake + * @since 2.0.0 + * @function + * @param {Function} fn The function to invoke with the passed parameters. + */ + SpyStrategy.prototype.callFake = function(fn) { + if ( + !( + j$.isFunction_(fn) || + j$.isAsyncFunction_(fn) || + j$.isGeneratorFunction_(fn) + ) + ) { + throw new Error( + 'Argument passed to callFake should be a function, got ' + fn + ); + } + this.plan = fn; + return this.getSpy(); + }; + + /** + * Tell the spy to do nothing when invoked. This is the default. + * @name SpyStrategy#stub + * @since 2.0.0 + * @function + */ + SpyStrategy.prototype.stub = function(fn) { + this.plan = function() {}; + return this.getSpy(); + }; + + SpyStrategy.prototype.isConfigured = function() { + return this.plan !== this._defaultPlan; + }; + + return SpyStrategy; +}; + +getJasmineRequireObj().StackTrace = function(j$) { + function StackTrace(error) { + var lines = error.stack.split('\n').filter(function(line) { + return line !== ''; + }); + + var extractResult = extractMessage(error.message, lines); + + if (extractResult) { + this.message = extractResult.message; + lines = extractResult.remainder; + } + + var parseResult = tryParseFrames(lines); + this.frames = parseResult.frames; + this.style = parseResult.style; + } + + var framePatterns = [ + // PhantomJS on Linux, Node, Chrome, IE, Edge + // e.g. " at QueueRunner.run (http://localhost:8888/__jasmine__/jasmine.js:4320:20)" + // Note that the "function name" can include a surprisingly large set of + // characters, including angle brackets and square brackets. + { + re: /^\s*at ([^\)]+) \(([^\)]+)\)$/, + fnIx: 1, + fileLineColIx: 2, + style: 'v8' + }, + + // NodeJS alternate form, often mixed in with the Chrome style + // e.g. " at /some/path:4320:20 + { re: /\s*at (.+)$/, fileLineColIx: 1, style: 'v8' }, + + // PhantomJS on OS X, Safari, Firefox + // e.g. "run@http://localhost:8888/__jasmine__/jasmine.js:4320:27" + // or "http://localhost:8888/__jasmine__/jasmine.js:4320:27" + { + re: /^(([^@\s]+)@)?([^\s]+)$/, + fnIx: 2, + fileLineColIx: 3, + style: 'webkit' + } + ]; + + // regexes should capture the function name (if any) as group 1 + // and the file, line, and column as group 2. + function tryParseFrames(lines) { + var style = null; + var frames = lines.map(function(line) { + var convertedLine = first(framePatterns, function(pattern) { + var overallMatch = line.match(pattern.re), + fileLineColMatch; + if (!overallMatch) { + return null; + } + + fileLineColMatch = overallMatch[pattern.fileLineColIx].match( + /^(.*):(\d+):\d+$/ + ); + if (!fileLineColMatch) { + return null; + } + + style = style || pattern.style; + return { + raw: line, + file: fileLineColMatch[1], + line: parseInt(fileLineColMatch[2], 10), + func: overallMatch[pattern.fnIx] + }; + }); + + return convertedLine || { raw: line }; + }); + + return { + style: style, + frames: frames + }; + } + + function first(items, fn) { + var i, result; + + for (i = 0; i < items.length; i++) { + result = fn(items[i]); + + if (result) { + return result; + } + } + } + + function extractMessage(message, stackLines) { + var len = messagePrefixLength(message, stackLines); + + if (len > 0) { + return { + message: stackLines.slice(0, len).join('\n'), + remainder: stackLines.slice(len) + }; + } + } + + function messagePrefixLength(message, stackLines) { + if (!stackLines[0].match(/^\w*Error/)) { + return 0; + } + + var messageLines = message.split('\n'); + var i; + + for (i = 1; i < messageLines.length; i++) { + if (messageLines[i] !== stackLines[i]) { + return 0; + } + } + + return messageLines.length; + } + + return StackTrace; +}; + +getJasmineRequireObj().Suite = function(j$) { + /** + * @interface Suite + * @see Env#topSuite + */ + function Suite(attrs) { + this.env = attrs.env; + this.id = attrs.id; + /** + * The parent of this suite, or null if this is the top suite. + * @name Suite#parentSuite + * @readonly + * @type {Suite} + */ + this.parentSuite = attrs.parentSuite; + /** + * The description passed to the {@link describe} that created this suite. + * @name Suite#description + * @readonly + * @type {string} + */ + this.description = attrs.description; + this.expectationFactory = attrs.expectationFactory; + this.asyncExpectationFactory = attrs.asyncExpectationFactory; + this.expectationResultFactory = attrs.expectationResultFactory; + this.throwOnExpectationFailure = !!attrs.throwOnExpectationFailure; + + this.beforeFns = []; + this.afterFns = []; + this.beforeAllFns = []; + this.afterAllFns = []; + + this.timer = attrs.timer || new j$.Timer(); + + /** + * The suite's children. + * @name Suite#children + * @type {Array.<(Spec|Suite)>} + */ + this.children = []; + + /** + * @typedef SuiteResult + * @property {Int} id - The unique id of this suite. + * @property {String} description - The description text passed to the {@link describe} that made this suite. + * @property {String} fullName - The full description including all ancestors of this suite. + * @property {Expectation[]} failedExpectations - The list of expectations that failed in an {@link afterAll} for this suite. + * @property {Expectation[]} deprecationWarnings - The list of deprecation warnings that occurred on this suite. + * @property {String} status - Once the suite has completed, this string represents the pass/fail status of this suite. + * @property {number} duration - The time in ms for Suite execution, including any before/afterAll, before/afterEach. + * @property {Object} properties - User-supplied properties, if any, that were set using {@link Env#setSuiteProperty} + */ + this.result = { + id: this.id, + description: this.description, + fullName: this.getFullName(), + failedExpectations: [], + deprecationWarnings: [], + duration: null, + properties: null + }; + } + + Suite.prototype.setSuiteProperty = function(key, value) { + this.result.properties = this.result.properties || {}; + this.result.properties[key] = value; + }; + + Suite.prototype.expect = function(actual) { + return this.expectationFactory(actual, this); + }; + + Suite.prototype.expectAsync = function(actual) { + return this.asyncExpectationFactory(actual, this); + }; + + /** + * The full description including all ancestors of this suite. + * @name Suite#getFullName + * @function + * @returns {string} + */ + Suite.prototype.getFullName = function() { + var fullName = []; + for ( + var parentSuite = this; + parentSuite; + parentSuite = parentSuite.parentSuite + ) { + if (parentSuite.parentSuite) { + fullName.unshift(parentSuite.description); + } + } + return fullName.join(' '); + }; + + Suite.prototype.pend = function() { + this.markedPending = true; + }; + + Suite.prototype.beforeEach = function(fn) { + this.beforeFns.unshift(fn); + }; + + Suite.prototype.beforeAll = function(fn) { + this.beforeAllFns.push(fn); + }; + + Suite.prototype.afterEach = function(fn) { + this.afterFns.unshift(fn); + }; + + Suite.prototype.afterAll = function(fn) { + this.afterAllFns.unshift(fn); + }; + + Suite.prototype.startTimer = function() { + this.timer.start(); + }; + + Suite.prototype.endTimer = function() { + this.result.duration = this.timer.elapsed(); + }; + + function removeFns(queueableFns) { + for (var i = 0; i < queueableFns.length; i++) { + queueableFns[i].fn = null; + } + } + + Suite.prototype.cleanupBeforeAfter = function() { + removeFns(this.beforeAllFns); + removeFns(this.afterAllFns); + removeFns(this.beforeFns); + removeFns(this.afterFns); + }; + + Suite.prototype.addChild = function(child) { + this.children.push(child); + }; + + Suite.prototype.status = function() { + if (this.markedPending) { + return 'pending'; + } + + if (this.result.failedExpectations.length > 0) { + return 'failed'; + } else { + return 'passed'; + } + }; + + Suite.prototype.canBeReentered = function() { + return this.beforeAllFns.length === 0 && this.afterAllFns.length === 0; + }; + + Suite.prototype.getResult = function() { + this.result.status = this.status(); + return this.result; + }; + + Suite.prototype.sharedUserContext = function() { + if (!this.sharedContext) { + this.sharedContext = this.parentSuite + ? this.parentSuite.clonedSharedUserContext() + : new j$.UserContext(); + } + + return this.sharedContext; + }; + + Suite.prototype.clonedSharedUserContext = function() { + return j$.UserContext.fromExisting(this.sharedUserContext()); + }; + + Suite.prototype.onException = function() { + if (arguments[0] instanceof j$.errors.ExpectationFailed) { + return; + } + + var data = { + matcherName: '', + passed: false, + expected: '', + actual: '', + error: arguments[0] + }; + var failedExpectation = this.expectationResultFactory(data); + + if (!this.parentSuite) { + failedExpectation.globalErrorType = 'afterAll'; + } + + this.result.failedExpectations.push(failedExpectation); + }; + + Suite.prototype.addExpectationResult = function() { + if (isFailure(arguments)) { + var data = arguments[1]; + this.result.failedExpectations.push(this.expectationResultFactory(data)); + if (this.throwOnExpectationFailure) { + throw new j$.errors.ExpectationFailed(); + } + } + }; + + Suite.prototype.addDeprecationWarning = function(deprecation) { + if (typeof deprecation === 'string') { + deprecation = { message: deprecation }; + } + this.result.deprecationWarnings.push( + this.expectationResultFactory(deprecation) + ); + }; + + function isFailure(args) { + return !args[0]; + } + + return Suite; +}; + +if (typeof window == void 0 && typeof exports == 'object') { + /* globals exports */ + exports.Suite = jasmineRequire.Suite; +} + +getJasmineRequireObj().Timer = function() { + var defaultNow = (function(Date) { + return function() { + return new Date().getTime(); + }; + })(Date); + + function Timer(options) { + options = options || {}; + + var now = options.now || defaultNow, + startTime; + + this.start = function() { + startTime = now(); + }; + + this.elapsed = function() { + return now() - startTime; + }; + } + + return Timer; +}; + +getJasmineRequireObj().TreeProcessor = function() { + function TreeProcessor(attrs) { + var tree = attrs.tree, + runnableIds = attrs.runnableIds, + queueRunnerFactory = attrs.queueRunnerFactory, + nodeStart = attrs.nodeStart || function() {}, + nodeComplete = attrs.nodeComplete || function() {}, + failSpecWithNoExpectations = !!attrs.failSpecWithNoExpectations, + orderChildren = + attrs.orderChildren || + function(node) { + return node.children; + }, + excludeNode = + attrs.excludeNode || + function(node) { + return false; + }, + stats = { valid: true }, + processed = false, + defaultMin = Infinity, + defaultMax = 1 - Infinity; + + this.processTree = function() { + processNode(tree, true); + processed = true; + return stats; + }; + + this.execute = function(done) { + if (!processed) { + this.processTree(); + } + + if (!stats.valid) { + throw 'invalid order'; + } + + var childFns = wrapChildren(tree, 0); + + queueRunnerFactory({ + queueableFns: childFns, + userContext: tree.sharedUserContext(), + onException: function() { + tree.onException.apply(tree, arguments); + }, + onComplete: done + }); + }; + + function runnableIndex(id) { + for (var i = 0; i < runnableIds.length; i++) { + if (runnableIds[i] === id) { + return i; + } + } + } + + function processNode(node, parentExcluded) { + var executableIndex = runnableIndex(node.id); + + if (executableIndex !== undefined) { + parentExcluded = false; + } + + if (!node.children) { + var excluded = parentExcluded || excludeNode(node); + stats[node.id] = { + excluded: excluded, + willExecute: !excluded && !node.markedPending, + segments: [ + { + index: 0, + owner: node, + nodes: [node], + min: startingMin(executableIndex), + max: startingMax(executableIndex) + } + ] + }; + } else { + var hasExecutableChild = false; + + var orderedChildren = orderChildren(node); + + for (var i = 0; i < orderedChildren.length; i++) { + var child = orderedChildren[i]; + + processNode(child, parentExcluded); + + if (!stats.valid) { + return; + } + + var childStats = stats[child.id]; + + hasExecutableChild = hasExecutableChild || childStats.willExecute; + } + + stats[node.id] = { + excluded: parentExcluded, + willExecute: hasExecutableChild + }; + + segmentChildren(node, orderedChildren, stats[node.id], executableIndex); + + if (!node.canBeReentered() && stats[node.id].segments.length > 1) { + stats = { valid: false }; + } + } + } + + function startingMin(executableIndex) { + return executableIndex === undefined ? defaultMin : executableIndex; + } + + function startingMax(executableIndex) { + return executableIndex === undefined ? defaultMax : executableIndex; + } + + function segmentChildren( + node, + orderedChildren, + nodeStats, + executableIndex + ) { + var currentSegment = { + index: 0, + owner: node, + nodes: [], + min: startingMin(executableIndex), + max: startingMax(executableIndex) + }, + result = [currentSegment], + lastMax = defaultMax, + orderedChildSegments = orderChildSegments(orderedChildren); + + function isSegmentBoundary(minIndex) { + return ( + lastMax !== defaultMax && + minIndex !== defaultMin && + lastMax < minIndex - 1 + ); + } + + for (var i = 0; i < orderedChildSegments.length; i++) { + var childSegment = orderedChildSegments[i], + maxIndex = childSegment.max, + minIndex = childSegment.min; + + if (isSegmentBoundary(minIndex)) { + currentSegment = { + index: result.length, + owner: node, + nodes: [], + min: defaultMin, + max: defaultMax + }; + result.push(currentSegment); + } + + currentSegment.nodes.push(childSegment); + currentSegment.min = Math.min(currentSegment.min, minIndex); + currentSegment.max = Math.max(currentSegment.max, maxIndex); + lastMax = maxIndex; + } + + nodeStats.segments = result; + } + + function orderChildSegments(children) { + var specifiedOrder = [], + unspecifiedOrder = []; + + for (var i = 0; i < children.length; i++) { + var child = children[i], + segments = stats[child.id].segments; + + for (var j = 0; j < segments.length; j++) { + var seg = segments[j]; + + if (seg.min === defaultMin) { + unspecifiedOrder.push(seg); + } else { + specifiedOrder.push(seg); + } + } + } + + specifiedOrder.sort(function(a, b) { + return a.min - b.min; + }); + + return specifiedOrder.concat(unspecifiedOrder); + } + + function executeNode(node, segmentNumber) { + if (node.children) { + return { + fn: function(done) { + var onStart = { + fn: function(next) { + nodeStart(node, next); + } + }; + + queueRunnerFactory({ + onComplete: function() { + var args = Array.prototype.slice.call(arguments, [0]); + node.cleanupBeforeAfter(); + nodeComplete(node, node.getResult(), function() { + done.apply(undefined, args); + }); + }, + queueableFns: [onStart].concat(wrapChildren(node, segmentNumber)), + userContext: node.sharedUserContext(), + onException: function() { + node.onException.apply(node, arguments); + } + }); + } + }; + } else { + return { + fn: function(done) { + node.execute( + done, + stats[node.id].excluded, + failSpecWithNoExpectations + ); + } + }; + } + } + + function wrapChildren(node, segmentNumber) { + var result = [], + segmentChildren = stats[node.id].segments[segmentNumber].nodes; + + for (var i = 0; i < segmentChildren.length; i++) { + result.push( + executeNode(segmentChildren[i].owner, segmentChildren[i].index) + ); + } + + if (!stats[node.id].willExecute) { + return result; + } + + return node.beforeAllFns.concat(result).concat(node.afterAllFns); + } + } + + return TreeProcessor; +}; + +getJasmineRequireObj().UserContext = function(j$) { + function UserContext() {} + + UserContext.fromExisting = function(oldContext) { + var context = new UserContext(); + + for (var prop in oldContext) { + if (oldContext.hasOwnProperty(prop)) { + context[prop] = oldContext[prop]; + } + } + + return context; + }; + + return UserContext; +}; + +getJasmineRequireObj().version = function() { + return '3.8.0'; +}; diff --git a/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/jasmine_favicon.png b/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/jasmine_favicon.png new file mode 100644 index 0000000..3b84583 Binary files /dev/null and b/Pcb-1-lan9252/EEPROM_generator/lib/jasmine-3.8.0/jasmine_favicon.png differ diff --git a/Pcb-1-lan9252/EEPROM_generator/lib/jszip.min.js b/Pcb-1-lan9252/EEPROM_generator/lib/jszip.min.js new file mode 100644 index 0000000..131b697 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/lib/jszip.min.js @@ -0,0 +1,13 @@ +/*! + +JSZip v3.6.0 - A JavaScript class for generating and reading zip files + + +(c) 2009-2016 Stuart Knightley +Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/master/LICENSE.markdown. + +JSZip uses the library pako released under the MIT license : +https://github.com/nodeca/pako/blob/master/LICENSE +*/ + +!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{("undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this).JSZip=e()}}(function(){return function s(a,o,u){function h(r,e){if(!o[r]){if(!a[r]){var t="function"==typeof require&&require;if(!e&&t)return t(r,!0);if(f)return f(r,!0);var n=new Error("Cannot find module '"+r+"'");throw n.code="MODULE_NOT_FOUND",n}var i=o[r]={exports:{}};a[r][0].call(i.exports,function(e){var t=a[r][1][e];return h(t||e)},i,i.exports,s,a,o,u)}return o[r].exports}for(var f="function"==typeof require&&require,e=0;e>2,s=(3&t)<<4|r>>4,a=1>6:64,o=2>4,r=(15&i)<<4|(s=p.indexOf(e.charAt(o++)))>>2,n=(3&s)<<6|(a=p.indexOf(e.charAt(o++))),h[u++]=t,64!==s&&(h[u++]=r),64!==a&&(h[u++]=n);return h}},{"./support":30,"./utils":32}],2:[function(e,t,r){"use strict";var n=e("./external"),i=e("./stream/DataWorker"),s=e("./stream/Crc32Probe"),a=e("./stream/DataLengthProbe");function o(e,t,r,n,i){this.compressedSize=e,this.uncompressedSize=t,this.crc32=r,this.compression=n,this.compressedContent=i}o.prototype={getContentWorker:function(){var e=new i(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new a("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new i(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(e,t,r){return e.pipe(new s).pipe(new a("uncompressedSize")).pipe(t.compressWorker(r)).pipe(new a("compressedSize")).withStreamInfo("compression",t)},t.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,r){"use strict";var n=e("./stream/GenericWorker");r.STORE={magic:"\0\0",compressWorker:function(e){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},r.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,r){"use strict";var n=e("./utils"),a=function(){for(var e,t=[],r=0;r<256;r++){e=r;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[r]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==n.getTypeOf(e)?function(e,t,r){var n=a,i=0+r;e^=-1;for(var s=0;s>>8^n[255&(e^t[s])];return-1^e}(0|t,e,e.length):function(e,t,r){var n=a,i=0+r;e^=-1;for(var s=0;s>>8^n[255&(e^t.charCodeAt(s))];return-1^e}(0|t,e,e.length):0}},{"./utils":32}],5:[function(e,t,r){"use strict";r.base64=!1,r.binary=!1,r.dir=!1,r.createFolders=!0,r.date=null,r.compression=null,r.compressionOptions=null,r.comment=null,r.unixPermissions=null,r.dosPermissions=null},{}],6:[function(e,t,r){"use strict";var n;n="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:n}},{lie:37}],7:[function(e,t,r){"use strict";var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,i=e("pako"),s=e("./utils"),a=e("./stream/GenericWorker"),o=n?"uint8array":"array";function u(e,t){a.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}r.magic="\b\0",s.inherits(u,a),u.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(s.transformTo(o,e.data),!1)},u.prototype.flush=function(){a.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){a.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new i[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var t=this;this._pako.onData=function(e){t.push({data:e,meta:t.meta})}},r.compressWorker=function(e){return new u("Deflate",e)},r.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,r){"use strict";function I(e,t){var r,n="";for(r=0;r>>=8;return n}function i(e,t,r,n,i,s){var a,o,u=e.file,h=e.compression,f=s!==B.utf8encode,l=O.transformTo("string",s(u.name)),d=O.transformTo("string",B.utf8encode(u.name)),c=u.comment,p=O.transformTo("string",s(c)),m=O.transformTo("string",B.utf8encode(c)),_=d.length!==u.name.length,g=m.length!==c.length,v="",b="",w="",y=u.dir,k=u.date,x={crc32:0,compressedSize:0,uncompressedSize:0};t&&!r||(x.crc32=e.crc32,x.compressedSize=e.compressedSize,x.uncompressedSize=e.uncompressedSize);var S=0;t&&(S|=8),f||!_&&!g||(S|=2048);var z,E=0,C=0;y&&(E|=16),"UNIX"===i?(C=798,E|=((z=u.unixPermissions)||(z=y?16893:33204),(65535&z)<<16)):(C=20,E|=63&(u.dosPermissions||0)),a=k.getUTCHours(),a<<=6,a|=k.getUTCMinutes(),a<<=5,a|=k.getUTCSeconds()/2,o=k.getUTCFullYear()-1980,o<<=4,o|=k.getUTCMonth()+1,o<<=5,o|=k.getUTCDate(),_&&(v+="up"+I((b=I(1,1)+I(T(l),4)+d).length,2)+b),g&&(v+="uc"+I((w=I(1,1)+I(T(p),4)+m).length,2)+w);var A="";return A+="\n\0",A+=I(S,2),A+=h.magic,A+=I(a,2),A+=I(o,2),A+=I(x.crc32,4),A+=I(x.compressedSize,4),A+=I(x.uncompressedSize,4),A+=I(l.length,2),A+=I(v.length,2),{fileRecord:R.LOCAL_FILE_HEADER+A+l+v,dirRecord:R.CENTRAL_FILE_HEADER+I(C,2)+A+I(p.length,2)+"\0\0\0\0"+I(E,4)+I(n,4)+l+v+p}}var O=e("../utils"),s=e("../stream/GenericWorker"),B=e("../utf8"),T=e("../crc32"),R=e("../signature");function n(e,t,r,n){s.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=r,this.encodeFileName=n,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}O.inherits(n,s),n.prototype.push=function(e){var t=e.meta.percent||0,r=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,s.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:r?(t+100*(r-n-1))/r:100}}))},n.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var r=i(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:r.fileRecord,meta:{percent:0}})}else this.accumulate=!0},n.prototype.closedSource=function(e){this.accumulate=!1;var t,r=this.streamFiles&&!e.file.dir,n=i(e,r,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(n.dirRecord),r)this.push({data:(t=e,R.DATA_DESCRIPTOR+I(t.crc32,4)+I(t.compressedSize,4)+I(t.uncompressedSize,4)),meta:{percent:100}});else for(this.push({data:n.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},n.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t=this.index;t--)r=(r<<8)+this.byteAt(t);return this.index+=e,r},readString:function(e){return n.transformTo("string",this.readData(e))},readData:function(e){},lastIndexOfSignature:function(e){},readAndCheckSignature:function(e){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=i},{"../utils":32}],19:[function(e,t,r){"use strict";var n=e("./Uint8ArrayReader");function i(e){n.call(this,e)}e("../utils").inherits(i,n),i.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,r){"use strict";var n=e("./DataReader");function i(e){n.call(this,e)}e("../utils").inherits(i,n),i.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},i.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},i.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},i.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i},{"../utils":32,"./DataReader":18}],21:[function(e,t,r){"use strict";var n=e("./ArrayReader");function i(e){n.call(this,e)}e("../utils").inherits(i,n),i.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=i},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,r){"use strict";var n=e("../utils"),i=e("../support"),s=e("./ArrayReader"),a=e("./StringReader"),o=e("./NodeBufferReader"),u=e("./Uint8ArrayReader");t.exports=function(e){var t=n.getTypeOf(e);return n.checkSupport(t),"string"!==t||i.uint8array?"nodebuffer"===t?new o(e):i.uint8array?new u(n.transformTo("uint8array",e)):new s(n.transformTo("array",e)):new a(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,r){"use strict";r.LOCAL_FILE_HEADER="PK",r.CENTRAL_FILE_HEADER="PK",r.CENTRAL_DIRECTORY_END="PK",r.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",r.ZIP64_CENTRAL_DIRECTORY_END="PK",r.DATA_DESCRIPTOR="PK\b"},{}],24:[function(e,t,r){"use strict";var n=e("./GenericWorker"),i=e("../utils");function s(e){n.call(this,"ConvertWorker to "+e),this.destType=e}i.inherits(s,n),s.prototype.processChunk=function(e){this.push({data:i.transformTo(this.destType,e.data),meta:e.meta})},t.exports=s},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,r){"use strict";var n=e("./GenericWorker"),i=e("../crc32");function s(){n.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(s,n),s.prototype.processChunk=function(e){this.streamInfo.crc32=i(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=s},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,r){"use strict";var n=e("../utils"),i=e("./GenericWorker");function s(e){i.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}n.inherits(s,i),s.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}i.prototype.processChunk.call(this,e)},t.exports=s},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,r){"use strict";var n=e("../utils"),i=e("./GenericWorker");function s(e){i.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=n.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}n.inherits(s,i),s.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this.data=null},s.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,n.delay(this._tickAndRepeat,[],this)),!0)},s.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(n.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},s.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=s},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,r){"use strict";function n(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}n.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var r=0;r "+e:e}},t.exports=n},{}],29:[function(e,t,r){"use strict";var h=e("../utils"),i=e("./ConvertWorker"),s=e("./GenericWorker"),f=e("../base64"),n=e("../support"),a=e("../external"),o=null;if(n.nodestream)try{o=e("../nodejs/NodejsStreamOutputAdapter")}catch(e){}function u(e,t,r){var n=t;switch(t){case"blob":case"arraybuffer":n="uint8array";break;case"base64":n="string"}try{this._internalType=n,this._outputType=t,this._mimeType=r,h.checkSupport(n),this._worker=e.pipe(new i(n)),e.lock()}catch(e){this._worker=new s("error"),this._worker.error(e)}}u.prototype={accumulate:function(e){return o=this,u=e,new a.Promise(function(t,r){var n=[],i=o._internalType,s=o._outputType,a=o._mimeType;o.on("data",function(e,t){n.push(e),u&&u(t)}).on("error",function(e){n=[],r(e)}).on("end",function(){try{var e=function(e,t,r){switch(e){case"blob":return h.newBlob(h.transformTo("arraybuffer",t),r);case"base64":return f.encode(t);default:return h.transformTo(e,t)}}(s,function(e,t){var r,n=0,i=null,s=0;for(r=0;r>>6:(r<65536?t[s++]=224|r>>>12:(t[s++]=240|r>>>18,t[s++]=128|r>>>12&63),t[s++]=128|r>>>6&63),t[s++]=128|63&r);return t}(e)},s.utf8decode=function(e){return u.nodebuffer?o.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,r,n,i,s=e.length,a=new Array(2*s);for(t=r=0;t>10&1023,a[r++]=56320|1023&n)}return a.length!==r&&(a.subarray?a=a.subarray(0,r):a.length=r),o.applyFromCharCode(a)}(e=o.transformTo(u.uint8array?"uint8array":"array",e))},o.inherits(a,n),a.prototype.processChunk=function(e){var t=o.transformTo(u.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(u.uint8array){var r=t;(t=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),t.set(r,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var n=function(e,t){var r;for((t=t||e.length)>e.length&&(t=e.length),r=t-1;0<=r&&128==(192&e[r]);)r--;return r<0?t:0===r?t:r+h[e[r]]>t?r:t}(t),i=t;n!==t.length&&(u.uint8array?(i=t.subarray(0,n),this.leftOver=t.subarray(n,t.length)):(i=t.slice(0,n),this.leftOver=t.slice(n,t.length))),this.push({data:s.utf8decode(i),meta:e.meta})},a.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:s.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},s.Utf8DecodeWorker=a,o.inherits(f,n),f.prototype.processChunk=function(e){this.push({data:s.utf8encode(e.data),meta:e.meta})},s.Utf8EncodeWorker=f},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,o){"use strict";var u=e("./support"),h=e("./base64"),r=e("./nodejsUtils"),n=e("set-immediate-shim"),f=e("./external");function i(e){return e}function l(e,t){for(var r=0;r>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(e){if(this.extraFields[1]){var t=n(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=t.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=t.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=t.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=t.readInt(4))}},readExtraFields:function(e){var t,r,n,i=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4>>6:(r<65536?t[s++]=224|r>>>12:(t[s++]=240|r>>>18,t[s++]=128|r>>>12&63),t[s++]=128|r>>>6&63),t[s++]=128|63&r);return t},r.buf2binstring=function(e){return f(e,e.length)},r.binstring2buf=function(e){for(var t=new u.Buf8(e.length),r=0,n=t.length;r>10&1023,o[n++]=56320|1023&i)}return f(o,n)},r.utf8border=function(e,t){var r;for((t=t||e.length)>e.length&&(t=e.length),r=t-1;0<=r&&128==(192&e[r]);)r--;return r<0?t:0===r?t:r+h[e[r]]>t?r:t}},{"./common":41}],43:[function(e,t,r){"use strict";t.exports=function(e,t,r,n){for(var i=65535&e|0,s=e>>>16&65535|0,a=0;0!==r;){for(r-=a=2e3>>1:e>>>1;t[r]=e}return t}();t.exports=function(e,t,r,n){var i=o,s=n+r;e^=-1;for(var a=n;a>>8^i[255&(e^t[a])];return-1^e}},{}],46:[function(e,t,r){"use strict";var u,d=e("../utils/common"),h=e("./trees"),c=e("./adler32"),p=e("./crc32"),n=e("./messages"),f=0,l=0,m=-2,i=2,_=8,s=286,a=30,o=19,g=2*s+1,v=15,b=3,w=258,y=w+b+1,k=42,x=113;function S(e,t){return e.msg=n[t],t}function z(e){return(e<<1)-(4e.avail_out&&(r=e.avail_out),0!==r&&(d.arraySet(e.output,t.pending_buf,t.pending_out,r,e.next_out),e.next_out+=r,t.pending_out+=r,e.total_out+=r,e.avail_out-=r,t.pending-=r,0===t.pending&&(t.pending_out=0))}function A(e,t){h._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,C(e.strm)}function I(e,t){e.pending_buf[e.pending++]=t}function O(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function B(e,t){var r,n,i=e.max_chain_length,s=e.strstart,a=e.prev_length,o=e.nice_match,u=e.strstart>e.w_size-y?e.strstart-(e.w_size-y):0,h=e.window,f=e.w_mask,l=e.prev,d=e.strstart+w,c=h[s+a-1],p=h[s+a];e.prev_length>=e.good_match&&(i>>=2),o>e.lookahead&&(o=e.lookahead);do{if(h[(r=t)+a]===p&&h[r+a-1]===c&&h[r]===h[s]&&h[++r]===h[s+1]){s+=2,r++;do{}while(h[++s]===h[++r]&&h[++s]===h[++r]&&h[++s]===h[++r]&&h[++s]===h[++r]&&h[++s]===h[++r]&&h[++s]===h[++r]&&h[++s]===h[++r]&&h[++s]===h[++r]&&su&&0!=--i);return a<=e.lookahead?a:e.lookahead}function T(e){var t,r,n,i,s,a,o,u,h,f,l=e.w_size;do{if(i=e.window_size-e.lookahead-e.strstart,e.strstart>=l+(l-y)){for(d.arraySet(e.window,e.window,l,l,0),e.match_start-=l,e.strstart-=l,e.block_start-=l,t=r=e.hash_size;n=e.head[--t],e.head[t]=l<=n?n-l:0,--r;);for(t=r=l;n=e.prev[--t],e.prev[t]=l<=n?n-l:0,--r;);i+=l}if(0===e.strm.avail_in)break;if(a=e.strm,o=e.window,u=e.strstart+e.lookahead,f=void 0,(h=i)<(f=a.avail_in)&&(f=h),r=0===f?0:(a.avail_in-=f,d.arraySet(o,a.input,a.next_in,f,u),1===a.state.wrap?a.adler=c(a.adler,o,f,u):2===a.state.wrap&&(a.adler=p(a.adler,o,f,u)),a.next_in+=f,a.total_in+=f,f),e.lookahead+=r,e.lookahead+e.insert>=b)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=(e.ins_h<=b&&(e.ins_h=(e.ins_h<=b)if(n=h._tr_tally(e,e.strstart-e.match_start,e.match_length-b),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=b){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<=b&&(e.ins_h=(e.ins_h<=b&&e.match_length<=e.prev_length){for(i=e.strstart+e.lookahead-b,n=h._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-b),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=i&&(e.ins_h=(e.ins_h<e.pending_buf_size-5&&(r=e.pending_buf_size-5);;){if(e.lookahead<=1){if(T(e),0===e.lookahead&&t===f)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+r;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,A(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-y&&(A(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(A(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(A(e,!1),e.strm.avail_out),1)}),new F(4,4,8,4,R),new F(4,5,16,8,R),new F(4,6,32,32,R),new F(4,4,16,16,D),new F(8,16,32,32,D),new F(8,16,128,128,D),new F(8,32,128,256,D),new F(32,128,258,1024,D),new F(32,258,258,4096,D)],r.deflateInit=function(e,t){return L(e,t,_,15,8,0)},r.deflateInit2=L,r.deflateReset=P,r.deflateResetKeep=U,r.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?m:(e.state.gzhead=t,l):m},r.deflate=function(e,t){var r,n,i,s;if(!e||!e.state||5>8&255),I(n,n.gzhead.time>>16&255),I(n,n.gzhead.time>>24&255),I(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),I(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(I(n,255&n.gzhead.extra.length),I(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(e.adler=p(e.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(I(n,0),I(n,0),I(n,0),I(n,0),I(n,0),I(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),I(n,3),n.status=x);else{var a=_+(n.w_bits-8<<4)<<8;a|=(2<=n.strategy||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(a|=32),a+=31-a%31,n.status=x,O(n,a),0!==n.strstart&&(O(n,e.adler>>>16),O(n,65535&e.adler)),e.adler=1}if(69===n.status)if(n.gzhead.extra){for(i=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),C(e),i=n.pending,n.pending!==n.pending_buf_size));)I(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),C(e),i=n.pending,n.pending===n.pending_buf_size)){s=1;break}s=n.gzindexi&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),0===s&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){i=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>i&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),C(e),i=n.pending,n.pending===n.pending_buf_size)){s=1;break}s=n.gzindexi&&(e.adler=p(e.adler,n.pending_buf,n.pending-i,i)),0===s&&(n.status=103)}else n.status=103;if(103===n.status&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&C(e),n.pending+2<=n.pending_buf_size&&(I(n,255&e.adler),I(n,e.adler>>8&255),e.adler=0,n.status=x)):n.status=x),0!==n.pending){if(C(e),0===e.avail_out)return n.last_flush=-1,l}else if(0===e.avail_in&&z(t)<=z(r)&&4!==t)return S(e,-5);if(666===n.status&&0!==e.avail_in)return S(e,-5);if(0!==e.avail_in||0!==n.lookahead||t!==f&&666!==n.status){var o=2===n.strategy?function(e,t){for(var r;;){if(0===e.lookahead&&(T(e),0===e.lookahead)){if(t===f)return 1;break}if(e.match_length=0,r=h._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,r&&(A(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(A(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(A(e,!1),0===e.strm.avail_out)?1:2}(n,t):3===n.strategy?function(e,t){for(var r,n,i,s,a=e.window;;){if(e.lookahead<=w){if(T(e),e.lookahead<=w&&t===f)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=b&&0e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=b?(r=h._tr_tally(e,1,e.match_length-b),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(r=h._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),r&&(A(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(A(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(A(e,!1),0===e.strm.avail_out)?1:2}(n,t):u[n.level].func(n,t);if(3!==o&&4!==o||(n.status=666),1===o||3===o)return 0===e.avail_out&&(n.last_flush=-1),l;if(2===o&&(1===t?h._tr_align(n):5!==t&&(h._tr_stored_block(n,0,0,!1),3===t&&(E(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),C(e),0===e.avail_out))return n.last_flush=-1,l}return 4!==t?l:n.wrap<=0?1:(2===n.wrap?(I(n,255&e.adler),I(n,e.adler>>8&255),I(n,e.adler>>16&255),I(n,e.adler>>24&255),I(n,255&e.total_in),I(n,e.total_in>>8&255),I(n,e.total_in>>16&255),I(n,e.total_in>>24&255)):(O(n,e.adler>>>16),O(n,65535&e.adler)),C(e),0=r.w_size&&(0===s&&(E(r.head),r.strstart=0,r.block_start=0,r.insert=0),h=new d.Buf8(r.w_size),d.arraySet(h,t,f-r.w_size,r.w_size,0),t=h,f=r.w_size),a=e.avail_in,o=e.next_in,u=e.input,e.avail_in=f,e.next_in=0,e.input=t,T(r);r.lookahead>=b;){for(n=r.strstart,i=r.lookahead-(b-1);r.ins_h=(r.ins_h<>>=w=b>>>24,p-=w,0==(w=b>>>16&255))E[s++]=65535&b;else{if(!(16&w)){if(0==(64&w)){b=m[(65535&b)+(c&(1<>>=w,p-=w),p<15&&(c+=z[n++]<>>=w=b>>>24,p-=w,!(16&(w=b>>>16&255))){if(0==(64&w)){b=_[(65535&b)+(c&(1<>>=w,p-=w,(w=s-a)>3,c&=(1<<(p-=y<<3))-1,e.next_in=n,e.next_out=s,e.avail_in=n>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function s(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new I.Buf16(320),this.work=new I.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function a(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=P,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new I.Buf32(n),t.distcode=t.distdyn=new I.Buf32(i),t.sane=1,t.back=-1,N):U}function o(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,a(e)):U}function u(e,t){var r,n;return e&&e.state?(n=e.state,t<0?(r=0,t=-t):(r=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15=s.wsize?(I.arraySet(s.window,t,r-s.wsize,s.wsize,0),s.wnext=0,s.whave=s.wsize):(n<(i=s.wsize-s.wnext)&&(i=n),I.arraySet(s.window,t,r-n,i,s.wnext),(n-=i)?(I.arraySet(s.window,t,r-n,n,0),s.wnext=n,s.whave=s.wsize):(s.wnext+=i,s.wnext===s.wsize&&(s.wnext=0),s.whave>>8&255,r.check=B(r.check,C,2,0),f=h=0,r.mode=2;break}if(r.flags=0,r.head&&(r.head.done=!1),!(1&r.wrap)||(((255&h)<<8)+(h>>8))%31){e.msg="incorrect header check",r.mode=30;break}if(8!=(15&h)){e.msg="unknown compression method",r.mode=30;break}if(f-=4,k=8+(15&(h>>>=4)),0===r.wbits)r.wbits=k;else if(k>r.wbits){e.msg="invalid window size",r.mode=30;break}r.dmax=1<>8&1),512&r.flags&&(C[0]=255&h,C[1]=h>>>8&255,r.check=B(r.check,C,2,0)),f=h=0,r.mode=3;case 3:for(;f<32;){if(0===o)break e;o--,h+=n[s++]<>>8&255,C[2]=h>>>16&255,C[3]=h>>>24&255,r.check=B(r.check,C,4,0)),f=h=0,r.mode=4;case 4:for(;f<16;){if(0===o)break e;o--,h+=n[s++]<>8),512&r.flags&&(C[0]=255&h,C[1]=h>>>8&255,r.check=B(r.check,C,2,0)),f=h=0,r.mode=5;case 5:if(1024&r.flags){for(;f<16;){if(0===o)break e;o--,h+=n[s++]<>>8&255,r.check=B(r.check,C,2,0)),f=h=0}else r.head&&(r.head.extra=null);r.mode=6;case 6:if(1024&r.flags&&(o<(c=r.length)&&(c=o),c&&(r.head&&(k=r.head.extra_len-r.length,r.head.extra||(r.head.extra=new Array(r.head.extra_len)),I.arraySet(r.head.extra,n,s,c,k)),512&r.flags&&(r.check=B(r.check,n,c,s)),o-=c,s+=c,r.length-=c),r.length))break e;r.length=0,r.mode=7;case 7:if(2048&r.flags){if(0===o)break e;for(c=0;k=n[s+c++],r.head&&k&&r.length<65536&&(r.head.name+=String.fromCharCode(k)),k&&c>9&1,r.head.done=!0),e.adler=r.check=0,r.mode=12;break;case 10:for(;f<32;){if(0===o)break e;o--,h+=n[s++]<>>=7&f,f-=7&f,r.mode=27;break}for(;f<3;){if(0===o)break e;o--,h+=n[s++]<>>=1)){case 0:r.mode=14;break;case 1:if(j(r),r.mode=20,6!==t)break;h>>>=2,f-=2;break e;case 2:r.mode=17;break;case 3:e.msg="invalid block type",r.mode=30}h>>>=2,f-=2;break;case 14:for(h>>>=7&f,f-=7&f;f<32;){if(0===o)break e;o--,h+=n[s++]<>>16^65535)){e.msg="invalid stored block lengths",r.mode=30;break}if(r.length=65535&h,f=h=0,r.mode=15,6===t)break e;case 15:r.mode=16;case 16:if(c=r.length){if(o>>=5,f-=5,r.ndist=1+(31&h),h>>>=5,f-=5,r.ncode=4+(15&h),h>>>=4,f-=4,286>>=3,f-=3}for(;r.have<19;)r.lens[A[r.have++]]=0;if(r.lencode=r.lendyn,r.lenbits=7,S={bits:r.lenbits},x=R(0,r.lens,0,19,r.lencode,0,r.work,S),r.lenbits=S.bits,x){e.msg="invalid code lengths set",r.mode=30;break}r.have=0,r.mode=19;case 19:for(;r.have>>16&255,v=65535&E,!((_=E>>>24)<=f);){if(0===o)break e;o--,h+=n[s++]<>>=_,f-=_,r.lens[r.have++]=v;else{if(16===v){for(z=_+2;f>>=_,f-=_,0===r.have){e.msg="invalid bit length repeat",r.mode=30;break}k=r.lens[r.have-1],c=3+(3&h),h>>>=2,f-=2}else if(17===v){for(z=_+3;f>>=_)),h>>>=3,f-=3}else{for(z=_+7;f>>=_)),h>>>=7,f-=7}if(r.have+c>r.nlen+r.ndist){e.msg="invalid bit length repeat",r.mode=30;break}for(;c--;)r.lens[r.have++]=k}}if(30===r.mode)break;if(0===r.lens[256]){e.msg="invalid code -- missing end-of-block",r.mode=30;break}if(r.lenbits=9,S={bits:r.lenbits},x=R(D,r.lens,0,r.nlen,r.lencode,0,r.work,S),r.lenbits=S.bits,x){e.msg="invalid literal/lengths set",r.mode=30;break}if(r.distbits=6,r.distcode=r.distdyn,S={bits:r.distbits},x=R(F,r.lens,r.nlen,r.ndist,r.distcode,0,r.work,S),r.distbits=S.bits,x){e.msg="invalid distances set",r.mode=30;break}if(r.mode=20,6===t)break e;case 20:r.mode=21;case 21:if(6<=o&&258<=u){e.next_out=a,e.avail_out=u,e.next_in=s,e.avail_in=o,r.hold=h,r.bits=f,T(e,d),a=e.next_out,i=e.output,u=e.avail_out,s=e.next_in,n=e.input,o=e.avail_in,h=r.hold,f=r.bits,12===r.mode&&(r.back=-1);break}for(r.back=0;g=(E=r.lencode[h&(1<>>16&255,v=65535&E,!((_=E>>>24)<=f);){if(0===o)break e;o--,h+=n[s++]<>b)])>>>16&255,v=65535&E,!(b+(_=E>>>24)<=f);){if(0===o)break e;o--,h+=n[s++]<>>=b,f-=b,r.back+=b}if(h>>>=_,f-=_,r.back+=_,r.length=v,0===g){r.mode=26;break}if(32&g){r.back=-1,r.mode=12;break}if(64&g){e.msg="invalid literal/length code",r.mode=30;break}r.extra=15&g,r.mode=22;case 22:if(r.extra){for(z=r.extra;f>>=r.extra,f-=r.extra,r.back+=r.extra}r.was=r.length,r.mode=23;case 23:for(;g=(E=r.distcode[h&(1<>>16&255,v=65535&E,!((_=E>>>24)<=f);){if(0===o)break e;o--,h+=n[s++]<>b)])>>>16&255,v=65535&E,!(b+(_=E>>>24)<=f);){if(0===o)break e;o--,h+=n[s++]<>>=b,f-=b,r.back+=b}if(h>>>=_,f-=_,r.back+=_,64&g){e.msg="invalid distance code",r.mode=30;break}r.offset=v,r.extra=15&g,r.mode=24;case 24:if(r.extra){for(z=r.extra;f>>=r.extra,f-=r.extra,r.back+=r.extra}if(r.offset>r.dmax){e.msg="invalid distance too far back",r.mode=30;break}r.mode=25;case 25:if(0===u)break e;if(c=d-u,r.offset>c){if((c=r.offset-c)>r.whave&&r.sane){e.msg="invalid distance too far back",r.mode=30;break}p=c>r.wnext?(c-=r.wnext,r.wsize-c):r.wnext-c,c>r.length&&(c=r.length),m=r.window}else m=i,p=a-r.offset,c=r.length;for(uc?(m=T[R+a[b]],A[I+a[b]]):(m=96,0),u=1<>S)+(h-=u)]=p<<24|m<<16|_|0,0!==h;);for(u=1<>=1;if(0!==u?(C&=u-1,C+=u):C=0,b++,0==--O[v]){if(v===y)break;v=t[r+a[b]]}if(k>>7)]}function x(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function S(e,t,r){e.bi_valid>i-r?(e.bi_buf|=t<>i-e.bi_valid,e.bi_valid+=r-i):(e.bi_buf|=t<>>=1,r<<=1,0<--t;);return r>>>1}function C(e,t,r){var n,i,s=new Array(_+1),a=0;for(n=1;n<=_;n++)s[n]=a=a+r[n-1]<<1;for(i=0;i<=t;i++){var o=e[2*i+1];0!==o&&(e[2*i]=E(s[o]++,o))}}function A(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function I(e){8>1;1<=r;r--)B(e,s,r);for(i=u;r=e.heap[1],e.heap[1]=e.heap[e.heap_len--],B(e,s,1),n=e.heap[1],e.heap[--e.heap_max]=r,e.heap[--e.heap_max]=n,s[2*i]=s[2*r]+s[2*n],e.depth[i]=(e.depth[r]>=e.depth[n]?e.depth[r]:e.depth[n])+1,s[2*r+1]=s[2*n+1]=i,e.heap[1]=i++,B(e,s,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var r,n,i,s,a,o,u=t.dyn_tree,h=t.max_code,f=t.stat_desc.static_tree,l=t.stat_desc.has_stree,d=t.stat_desc.extra_bits,c=t.stat_desc.extra_base,p=t.stat_desc.max_length,m=0;for(s=0;s<=_;s++)e.bl_count[s]=0;for(u[2*e.heap[e.heap_max]+1]=0,r=e.heap_max+1;r<573;r++)p<(s=u[2*u[2*(n=e.heap[r])+1]+1]+1)&&(s=p,m++),u[2*n+1]=s,h>=7;n<30;n++)for(w[n]=i<<7,e=0;e<1<>>=1)if(1&r&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),R(e,e.l_desc),R(e,e.d_desc),a=function(e){var t;for(D(e,e.dyn_ltree,e.l_desc.max_code),D(e,e.dyn_dtree,e.d_desc.max_code),R(e,e.bl_desc),t=18;3<=t&&0===e.bl_tree[2*f[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),i=e.opt_len+3+7>>>3,(s=e.static_len+3+7>>>3)<=i&&(i=s)):i=s=r+5,r+4<=i&&-1!==t?U(e,t,r,n):4===e.strategy||s===i?(S(e,2+(n?1:0),3),T(e,l,d)):(S(e,4+(n?1:0),3),function(e,t,r,n){var i;for(S(e,t-257,5),S(e,r-1,5),S(e,n-4,4),i=0;i>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&r,e.last_lit++,0===t?e.dyn_ltree[2*r]++:(e.matches++,t--,e.dyn_ltree[2*(p[r]+256+1)]++,e.dyn_dtree[2*k(t)]++),e.last_lit===e.lit_bufsize-1},r._tr_align=function(e){var t;S(e,2,3),z(e,256,l),16===(t=e).bi_valid?(x(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):8<=t.bi_valid&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}},{"../utils/common":41}],53:[function(e,t,r){"use strict";t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,r){"use strict";t.exports="function"==typeof setImmediate?setImmediate:function(){var e=[].slice.apply(arguments);e.splice(1,0,0),setTimeout.apply(null,e)}},{}]},{},[10])(10)})}).call(this,void 0!==r?r:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[1])(1)})}).call(this,void 0!==r?r:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[1])(1)})}).call(this,void 0!==r?r:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[1])(1)})}).call(this,void 0!==r?r:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[1])(1)})}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[1])(1)}); \ No newline at end of file diff --git a/Pcb-1-lan9252/EEPROM_generator/ref/gen.xml b/Pcb-1-lan9252/EEPROM_generator/ref/gen.xml new file mode 100644 index 0000000..298e84b --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/ref/gen.xml @@ -0,0 +1,282 @@ + + + + 0 + ACME EtherCAT Devices + + + + + DigIn + Digital input + + + + + DigIn2000 + 2-channel Hypergalactic input superimpermanator + DigIn + + 5001 + 0 + + + + DT1018 + 144 + + 0 + Max SubIndex + USINT + 8 + 0 + + ro + + + + 1 + Vendor ID + UDINT + 32 + 16 + + ro + + + + 2 + Product Code + UDINT + 32 + 48 + + ro + + + + 3 + Revision Number + UDINT + 32 + 80 + + ro + + + + 4 + Serial Number + UDINT + 32 + 112 + + ro + + + + + DT1C00ARR + USINT + 32 + + 1 + 4 + + + + DT1C00 + 48 + + 0 + Max SubIndex + USINT + 8 + 0 + + ro + + + + Elements + DT1C00ARR + 32 + 16 + + ro + + + + + UDINT + 32 + + + STRING(47) + 376 + + + STRING(5) + 40 + + + USINT + 8 + + + + + #x1000 + Device Type + UDINT + 32 + + 5001 + + + ro + m + + + + #x1008 + Device Name + STRING(47) + 376 + + 2-channel Hypergalactic input superimpermanator + + + ro + + + + #x1009 + Hardware Version + STRING(5) + 40 + + 0.0.1 + + + ro + o + + + + #x100A + Software Version + STRING(5) + 40 + + 0.0.1 + + + ro + + + + #x1018 + Identity Object + DT1018 + 144 + + + Max SubIndex + + 4 + + + + Vendor ID + + 0 + + + + Product Code + + 700707 + + + + Revision Number + + 2 + + + + Serial Number + + 1 + + + + + ro + + + + #x1C00 + Sync Manager Communication Type + DT1C00 + 48 + + + Max SubIndex + + 4 + + + + Communications Type SM0 + + 1 + + + + Communications Type SM1 + + 2 + + + + Communications Type SM2 + + 3 + + + + Communications Type SM3 + + 4 + + + + + ro + + + + + + Outputs + Inputs + MBoxState + MBoxOut + MBoxIn + Outputs + Inputs + + + + + + + 2048 + 05060344640000 + + + + + \ No newline at end of file diff --git a/Pcb-1-lan9252/EEPROM_generator/ref/start.xml b/Pcb-1-lan9252/EEPROM_generator/ref/start.xml new file mode 100644 index 0000000..8d28a59 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/ref/start.xml @@ -0,0 +1,281 @@ + + + + 600 + oss + + + + + groupType + groupName + + + + + codegentool + slave + groupType + + 5001 + 0 + + + + DT1018 + 144 + + 0 + Max SubIndex + USINT + 8 + 0 + + ro + + + + 1 + Vendor ID + UDINT + 32 + 16 + + ro + + + + 2 + Product Code + UDINT + 32 + 48 + + ro + + + + 3 + Revision Number + UDINT + 32 + 80 + + ro + + + + 4 + Serial Number + UDINT + 32 + 112 + + ro + + + + + DT1C00ARR + USINT + 32 + + 1 + 4 + + + + DT1C00 + 48 + + 0 + Max SubIndex + USINT + 8 + 0 + + ro + + + + Elements + DT1C00ARR + 32 + 16 + + ro + + + + + STRING(3) + 24 + + + STRING(11) + 88 + + + UDINT + 32 + + + USINT + 8 + + + + + #x1000 + Device Type + UDINT + 32 + + #x00001389 + + + ro + m + + + + #x1008 + Device Name + STRING(11) + 88 + + codegentool + + + ro + + + + #x1009 + Hardware Version + STRING(3) + 24 + + 1.0 + + + ro + o + + + + #x100A + Software Version + STRING(3) + 24 + + 1.0 + + + ro + + + + #x1018 + Identity Object + DT1018 + 144 + + + Max SubIndex + + 4 + + + + Vendor ID + + 600 + + + + Product Code + + 0 + + + + Revision Number + + 0 + + + + Serial Number + + #x00000000 + + + + + ro + + + + #x1C00 + Sync Manager Communication Type + DT1C00 + 48 + + + Max SubIndex + + 4 + + + + Communications Type SM0 + + 1 + + + + Communications Type SM1 + + 2 + + + + Communications Type SM2 + + 3 + + + + Communications Type SM3 + + 4 + + + + + ro + + + + + + Outputs + Inputs + MBoxState + MBoxOut + MBoxIn + Outputs + Inputs + + + + + 256 + 0502030000000000 + 0010000200120002 + + + + + \ No newline at end of file diff --git a/Pcb-1-lan9252/EEPROM_generator/spec/backupSpec.js b/Pcb-1-lan9252/EEPROM_generator/spec/backupSpec.js new file mode 100644 index 0000000..1dd382c --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/spec/backupSpec.js @@ -0,0 +1,14 @@ +describe("backup", function() { + + beforeEach(function() { + }); + + it("should return false for button control", function() { + // arrange + const control = { type: 'button' }; + // act + var result = isBackedUp(control); + // assert + expect(result).toEqual(false); + }); +}); diff --git a/Pcb-1-lan9252/EEPROM_generator/spec/generatorsSpec.js b/Pcb-1-lan9252/EEPROM_generator/spec/generatorsSpec.js new file mode 100644 index 0000000..82f8e62 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/spec/generatorsSpec.js @@ -0,0 +1,593 @@ +describe("generators", function() { + + + describe("for default, empty project", function() { + var form; + var od; + var indexes; + + beforeEach(function() { + form = buildMockFormHelper(); + od = buildObjectDictionary(form); + indexes = getUsedIndexes(od); + }); + + it("esi_generator should generate expected code", function() { + // arrange + const dc = []; + // act + var result = esi_generator(form, od, indexes, dc); + + // assert + const expectedesi = +` + + + 0 + ACME EtherCAT Devices + + + + + DigIn + Digital input + + + + + DigIn2000 + 2-channel Hypergalactic input superimpermanator + DigIn + + 5001 + 0 + + + + DT1018 + 144 + + 0 + Max SubIndex + USINT + 8 + 0 + + ro + + + + 1 + Vendor ID + UDINT + 32 + 16 + + ro + + + + 2 + Product Code + UDINT + 32 + 48 + + ro + + + + 3 + Revision Number + UDINT + 32 + 80 + + ro + + + + 4 + Serial Number + UDINT + 32 + 112 + + ro + + + + + DT1C00ARR + USINT + 32 + + 1 + 4 + + + + DT1C00 + 48 + + 0 + Max SubIndex + USINT + 8 + 0 + + ro + + + + Elements + DT1C00ARR + 32 + 16 + + ro + + + + + UDINT + 32 + + + STRING(47) + 376 + + + STRING(5) + 40 + + + USINT + 8 + + + + + #x1000 + Device Type + UDINT + 32 + + 5001 + + + ro + m + + + + #x1008 + Device Name + STRING(47) + 376 + + 2-channel Hypergalactic input superimpermanator + + + ro + + + + #x1009 + Hardware Version + STRING(5) + 40 + + 0.0.1 + + + ro + o + + + + #x100A + Software Version + STRING(5) + 40 + + 0.0.1 + + + ro + + + + #x1018 + Identity Object + DT1018 + 144 + + + Max SubIndex + + 4 + + + + Vendor ID + + 0 + + + + Product Code + + 700707 + + + + Revision Number + + 2 + + + + Serial Number + + 1 + + + + + ro + + + + #x1C00 + Sync Manager Communication Type + DT1C00 + 48 + + + Max SubIndex + + 4 + + + + Communications Type SM0 + + 1 + + + + Communications Type SM1 + + 2 + + + + Communications Type SM2 + + 3 + + + + Communications Type SM3 + + 4 + + + + + ro + + + + + + Outputs + Inputs + MBoxState + MBoxOut + MBoxIn + Outputs + Inputs + + + + + + + 2048 + 05060344640000 + + + + +`; + console.log(result); + debugger; + expect(result.slice(9000)).toEqual(expectedesi.slice(9000)); + }); + + it("hex_generator should generate config data", function() { + // arrange + // act + var result = hex_generator(form, true); + + // assert + const configData = `05060344640000`; + expect(result).toEqual(configData); + }); + + it("ecat_options_generator should generate config data", function() { + // arrange + // act + var result = ecat_options_generator(form, od, indexes); + + // assert + const ecat_options = +`#ifndef __ECAT_OPTIONS_H__ +#define __ECAT_OPTIONS_H__ + +#define USE_FOE 0 +#define USE_EOE 0 + +#define MBXSIZE 512 +#define MBXSIZEBOOT 512 +#define MBXBUFFERS 3 + +#define MBX0_sma 0x1000 +#define MBX0_sml MBXSIZE +#define MBX0_sme MBX0_sma+MBX0_sml-1 +#define MBX0_smc 0x26 +#define MBX1_sma MBX0_sma+MBX0_sml +#define MBX1_sml MBXSIZE +#define MBX1_sme MBX1_sma+MBX1_sml-1 +#define MBX1_smc 0x22 + +#define MBX0_sma_b 0x1000 +#define MBX0_sml_b MBXSIZEBOOT +#define MBX0_sme_b MBX0_sma_b+MBX0_sml_b-1 +#define MBX0_smc_b 0x26 +#define MBX1_sma_b MBX0_sma_b+MBX0_sml_b +#define MBX1_sml_b MBXSIZEBOOT +#define MBX1_sme_b MBX1_sma_b+MBX1_sml_b-1 +#define MBX1_smc_b 0x22 + +#define SM2_sma 0x1600 +#define SM2_smc 0x24 +#define SM2_act 1 +#define SM3_sma 0x1A00 +#define SM3_smc 0x20 +#define SM3_act 1 + +#define MAX_MAPPINGS_SM2 0 +#define MAX_MAPPINGS_SM3 0 + +#define MAX_RXPDO_SIZE 512 +#define MAX_TXPDO_SIZE 512 + +#endif /* __ECAT_OPTIONS_H__ */ +`; + expect(result).toEqual(ecat_options); + }); + + it("objectlist_generator should generate config data", function() { + // arrange + // act + var result = objectlist_generator(form, od, indexes); + + // assert + const objectlist = +`#include "esc_coe.h" +#include "utypes.h" +#include + + +static const char acName1000[] = "Device Type"; +static const char acName1008[] = "Device Name"; +static const char acName1009[] = "Hardware Version"; +static const char acName100A[] = "Software Version"; +static const char acName1018[] = "Identity Object"; +static const char acName1018_00[] = "Max SubIndex"; +static const char acName1018_01[] = "Vendor ID"; +static const char acName1018_02[] = "Product Code"; +static const char acName1018_03[] = "Revision Number"; +static const char acName1018_04[] = "Serial Number"; +static const char acName1C00[] = "Sync Manager Communication Type"; +static const char acName1C00_00[] = "Max SubIndex"; +static const char acName1C00_01[] = "Communications Type SM0"; +static const char acName1C00_02[] = "Communications Type SM1"; +static const char acName1C00_03[] = "Communications Type SM2"; +static const char acName1C00_04[] = "Communications Type SM3"; + +const _objd SDO1000[] = +{ + {0x0, DTYPE_UNSIGNED32, 32, ATYPE_RO, acName1000, 5001, NULL}, +}; +const _objd SDO1008[] = +{ + {0x0, DTYPE_VISIBLE_STRING, 376, ATYPE_RO, acName1008, 0, "2-channel Hypergalactic input superimpermanator"}, +}; +const _objd SDO1009[] = +{ + {0x0, DTYPE_VISIBLE_STRING, 40, ATYPE_RO, acName1009, 0, "0.0.1"}, +}; +const _objd SDO100A[] = +{ + {0x0, DTYPE_VISIBLE_STRING, 40, ATYPE_RO, acName100A, 0, "0.0.1"}, +}; +const _objd SDO1018[] = +{ + {0x00, DTYPE_UNSIGNED8, 8, ATYPE_RO, acName1018_00, 4, NULL}, + {0x01, DTYPE_UNSIGNED32, 32, ATYPE_RO, acName1018_01, 0, NULL}, + {0x02, DTYPE_UNSIGNED32, 32, ATYPE_RO, acName1018_02, 700707, NULL}, + {0x03, DTYPE_UNSIGNED32, 32, ATYPE_RO, acName1018_03, 2, NULL}, + {0x04, DTYPE_UNSIGNED32, 32, ATYPE_RO, acName1018_04, 1, &Obj.serial}, +}; +const _objd SDO1C00[] = +{ + {0x00, DTYPE_UNSIGNED8, 8, ATYPE_RO, acName1C00_00, 4, NULL}, + {0x01, DTYPE_UNSIGNED8, 8, ATYPE_RO, acName1C00_01, 1, NULL}, + {0x02, DTYPE_UNSIGNED8, 8, ATYPE_RO, acName1C00_02, 2, NULL}, + {0x03, DTYPE_UNSIGNED8, 8, ATYPE_RO, acName1C00_03, 3, NULL}, + {0x04, DTYPE_UNSIGNED8, 8, ATYPE_RO, acName1C00_04, 4, NULL}, +}; + +const _objectlist SDOobjects[] = +{ + {0x1000, OTYPE_VAR, 0, 0, acName1000, SDO1000}, + {0x1008, OTYPE_VAR, 0, 0, acName1008, SDO1008}, + {0x1009, OTYPE_VAR, 0, 0, acName1009, SDO1009}, + {0x100A, OTYPE_VAR, 0, 0, acName100A, SDO100A}, + {0x1018, OTYPE_RECORD, 4, 0, acName1018, SDO1018}, + {0x1C00, OTYPE_ARRAY, 4, 0, acName1C00, SDO1C00}, + {0xffff, 0xff, 0xff, 0xff, NULL, NULL} +}; +`; + expect(result).toEqual(objectlist); + }); + + it("utypes_generator should generate expected code", function() { + // arrange + // act + var result = utypes_generator(form, od, indexes); + + // assert + const expectedUtypes = +`#ifndef __UTYPES_H__ +#define __UTYPES_H__ + +#include "cc.h" + +/* Object dictionary storage */ + +typedef struct +{ + /* Identity */ + + uint32_t serial; + +} _Objects; + +extern _Objects Obj; + +#endif /* __UTYPES_H__ */ +`; + expect(result).toEqual(expectedUtypes); + }); + + describe("hex_generator given SPImode", function () { + const testCases = [ + { mode: 0 }, + { mode: 1 }, + { mode: 2 }, + { mode: 3 }, + ]; + + testCases.forEach((test, index) => { + it(`SPImode ${test.mode} should return 05060${test.mode}44640000 (testcase: ${index + 1})`, () => { + // arrange + form.SPImode.value = test.mode; + + // act + var result = hex_generator(form, true); + + // assert + expect(result).toEqual(`05060${test.mode}44640000`); + }); + }); + }); + }); + + describe("for AX58100 project", function() { + var form; + var od; + var indexes; + + beforeEach(function() { + form = buildMockFormHelper(); + form.ESC.value = SupportedESC.AX58100 + od = buildObjectDictionary(form); + indexes = getUsedIndexes(od); + }); + + it("hex_generator should generate config data 050603446400000000001A000000", function() { + // arrange + // act + var result = hex_generator(form, true); + + // assert + const configData = `050603446400000000001A000000`; + expect(result).toEqual(configData); + }); + }); + + describe("for ET1100 project", function() { + var form; + var od; + var indexes; + + beforeEach(function() { + form = buildMockFormHelper(); + form.ESC.value = SupportedESC.ET1100 + od = buildObjectDictionary(form); + indexes = getUsedIndexes(od); + }); + + it("hex_generator should generate config data 05060344640000", function() { + // arrange + // act + var result = hex_generator(form, true); + + // assert + const configData = `05060344640000`; + expect(result).toEqual(configData); + }); + }); + + describe("for LAN9252 project", function() { + var form; + var od; + var indexes; + + beforeEach(function() { + form = buildMockFormHelper(); + form.ESC.value = SupportedESC.LAN9252 + od = buildObjectDictionary(form); + indexes = getUsedIndexes(od); + }); + + it("hex_generator should generate config data 80060344640000", function() { + // arrange + // act + var result = hex_generator(form, true); + + // assert + const configData = `80060344640000`; + expect(result).toEqual(configData); + }); + }); + + describe("for LAN9253_Beckhoff project", function() { + var form; + var od; + var indexes; + + beforeEach(function() { + form = buildMockFormHelper(); + form.ESC.value = SupportedESC.LAN9253_Beckhoff + od = buildObjectDictionary(form); + indexes = getUsedIndexes(od); + }); + + it("hex_generator should generate config data 0506034464000000000040C00000", function() { + // arrange + // act + var result = hex_generator(form, true); + + // assert + const configData = `0506034464000000000040C00000`; + expect(result).toEqual(configData); + }); + }); +}); + \ No newline at end of file diff --git a/Pcb-1-lan9252/EEPROM_generator/spec/helpers/formMockHelper.js b/Pcb-1-lan9252/EEPROM_generator/spec/helpers/formMockHelper.js new file mode 100644 index 0000000..4b6e2c0 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/spec/helpers/formMockHelper.js @@ -0,0 +1,25 @@ +var formMock = {}; + +function buildMockFormHelper(formValues = null) { + const defaultFormValues = getFormDefaultValues().form; + + if (!formValues) { + formValues = defaultFormValues; + } + + formMock = { } + + Object.keys(defaultFormValues).forEach(formControlName => { + const formControl = { + name: formControlName, + }; + setFormControlValue(formControl, formValues[formControlName]); + formMock[formControlName] = formControl; + }); + + return formMock; +} + +function getForm() { + return formMock; +} \ No newline at end of file diff --git a/Pcb-1-lan9252/EEPROM_generator/src/backup.js b/Pcb-1-lan9252/EEPROM_generator/src/backup.js new file mode 100644 index 0000000..fd2dfd9 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/src/backup.js @@ -0,0 +1,127 @@ +/** + * SOES EEPROM generator + * Project backup save and restore + + * This tool serves as: +- EtherCAT Slave Information XML + EEPROM binary generator +- SOES code generator + + * Victor Sluiter 2013-2018 + * Kuba Buda 2020-2021 + */ +'use strict' + +// ####################### Backup serialization + deserialization ####################### // + +function isValidBackup(backup) { + if (!backup || !backup.form || !backup.od ) { + if (!confirm('Backup is incomplete or invalid, proceed anyway?')) { + return false; + } + } + return true; +} + +function prepareBackupObject(form) { + const formValues = {}; + if (form) { + Object.entries(form).forEach(formEntry => { + const formControl = formEntry[1]; // entry[0] is form control order number + if(isBackedUp(formControl) && formControl.value) { + formValues[formControl.name] = formControl.value; + }; + }); + } + + const backup = { + form: formValues, + od: getObjDict(), + dc: _dc, + }; + + return backup; +} + +function isBackedUp(formControl) { + return formControl.type != "button"; +} + +function loadBackup(backupObject, form) { + if (backupObject.od) { + setObjDictSection(sdo, backupObject.od.sdo); + setObjDictSection(txpdo, backupObject.od.txpdo); + setObjDictSection(rxpdo, backupObject.od.rxpdo); + } + + if (backupObject.dc) { + _dc = backupObject.dc; + } + + setFormValues(form, backupObject); +} + +function setFormValues(form, backupObject) { + if (form) { + Object.entries(form).forEach(formEntry => { + const formControl = formEntry[1]; // entry[0] is index + const formControlValue = backupObject.form[formControl.name]; + if (isBackedUp(formControl) && formControlValue) { + setFormControlValue(formControl, formControlValue); + }; + }); + } +} + +function setFormControlValue(formControl, formControlValue) { + if (formControl.name.startsWith('CoeDetailsEnable')) { + if (formControlValue == true) { + formControl.checked = true; + } else { + } + } else { + formControl.value = formControlValue; + } +} + +function prepareBackupFileContent(form) { + var backupObject = prepareBackupObject(form); + var backupFileContent = JSON.stringify(backupObject, null, 2); // pretty print + return backupFileContent; +} + +// ####################### Backup using JSON file from filesystem ####################### // + +// Localstorage limit is usually 5MB, super large object dictionaries on older browsers might be problematic + +function downloadBackupFile(form) { + const backupFileContent = prepareBackupFileContent(form); // pretty print + downloadFile(backupFileContent, 'esi.json', 'text/json'); +} + +function restoreBackup(fileContent, form) { + var backup = JSON.parse(fileContent); + if (isValidBackup(backup)) { + loadBackup(backup, form); + reloadOD_Sections(); + reloadSyncModes() + } +} + +// ####################### Backup using browser localstorage ####################### // + +/** persist OD and settings changes over page reload */ +function saveLocalBackup(form) { + localStorage.etherCATeepromGeneratorBackup = prepareBackupFileContent(form); +} + +function tryRestoreLocalBackup(form) { + if (localStorage.etherCATeepromGeneratorBackup) { + restoreBackup(localStorage.etherCATeepromGeneratorBackup, form); + } +} + +function resetLocalBackup() { + if (localStorage.etherCATeepromGeneratorBackup) { + delete localStorage.etherCATeepromGeneratorBackup; + } +} \ No newline at end of file diff --git a/Pcb-1-lan9252/EEPROM_generator/src/constants.js b/Pcb-1-lan9252/EEPROM_generator/src/constants.js new file mode 100644 index 0000000..109f357 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/src/constants.js @@ -0,0 +1,157 @@ +/** + * SOES EEPROM generator + * Shared constants, data types + + * This tool serves as: +- EtherCAT Slave Information XML + EEPROM binary generator +- SOES code generator + + * Victor Sluiter 2013-2018 + * Kuba Buda 2020-2021 + */ +'use strict' + +const automaticCodegen = true; // code is regenerated on every form change. + // no need to remember to generate before copying or downloading + // app is noticeably slower + +// ####################### Constants, lookup tables ####################### // +/** CoE Object Types */ +const OTYPE = { + VAR : 'VAR', + ARRAY : 'ARRAY', + RECORD: 'RECORD', +}; +/** CoE Data Types */ +const DTYPE = { + BOOLEAN : 'BOOLEAN', + INTEGER8 : 'INTEGER8', + INTEGER16 : 'INTEGER16', + INTEGER32 : 'INTEGER32', + UNSIGNED8 : 'UNSIGNED8', + UNSIGNED16 : 'UNSIGNED16', + UNSIGNED32 : 'UNSIGNED32', + REAL32 : 'REAL32', + VISIBLE_STRING : 'VISIBLE_STRING', + /* TODO implement missing less common types */ + // OCTET_STRING : 'OCTET_STRING', + // UNICODE_STRING : 'UNICODE_STRING', + // INTEGER24 : 'INTEGER24', + // UNSIGNED24 : 'UNSIGNED24', + // INTEGER64 : 'INTEGER64', + // UNSIGNED64 : 'UNSIGNED64', + // REAL64 : 'REAL64', + // PDO_MAPPING : 'PDO_MAPPING', +}; +/** Data types bitsize as used in objectlist.c */ +const dtype_bitsize = { + 'BOOLEAN' : 1, + 'INTEGER8' : 8, + 'INTEGER16' : 16, + 'INTEGER32' : 32, + 'UNSIGNED8' : 8, + 'UNSIGNED16' : 16, + 'UNSIGNED32' : 32, + 'REAL32' : 32, + 'VISIBLE_STRING' : 8, +}; +const booleanPaddingBitsize = 7; +/** ESI XML data type */ +const ESI_DT = { + 'BOOLEAN': { name: 'BOOL', bitsize: 1, ctype: 'uint8_t' }, + 'INTEGER8': { name: 'SINT', bitsize: 8, ctype: 'int8_t' }, + 'INTEGER16': { name: 'INT', bitsize: 16, ctype: 'int16_t' }, + 'INTEGER32': { name: 'DINT', bitsize: 32, ctype: 'int32_t' }, + 'UNSIGNED8': { name: 'USINT', bitsize: 8, ctype: 'uint8_t' }, + 'UNSIGNED16': { name: 'UINT', bitsize: 16, ctype: 'uint16_t' }, + 'UNSIGNED32': { name: 'UDINT', bitsize: 32, ctype: 'uint32_t' }, + 'REAL32': { name: 'REAL', bitsize: 32, ctype: 'float' }, // TODO check C type name + 'VISIBLE_STRING': { name: 'STRING', bitsize: 8, ctype: 'char *' }, // TODO check C type name +}; + +/** These are required by minimal CiA 301 device */ +const SDO_category = { + '1000': 'm', + '1009': 'o', +}; + +// ####################### Object Dictionary building ####################### // +/** + * Returns Object Dictionaty stub with mandatory objects. + * OD index is hexadecimal value without '0x' prefix + */ +function getMandatoryObjects() { + const OD = { + '1000': { otype: OTYPE.VAR, dtype: DTYPE.UNSIGNED32, name: 'Device Type', value: 0x1389 }, + '1008': { otype: OTYPE.VAR, dtype: DTYPE.VISIBLE_STRING, name: 'Device Name', data: '' }, + '1009': { otype: OTYPE.VAR, dtype: DTYPE.VISIBLE_STRING, name: 'Hardware Version', data: '' }, + '100A': { otype: OTYPE.VAR, dtype: DTYPE.VISIBLE_STRING, name: 'Software Version', data: '' }, + '1018': { otype: OTYPE.RECORD, name: 'Identity Object', items: [ + { name: 'Max SubIndex' }, + { name: 'Vendor ID', dtype: DTYPE.UNSIGNED32, value: 600 }, + { name: 'Product Code', dtype: DTYPE.UNSIGNED32 }, + { name: 'Revision Number', dtype: DTYPE.UNSIGNED32 }, + { name: 'Serial Number', dtype: DTYPE.UNSIGNED32, data: '&Obj.serial' }, + ]}, + '1C00': { otype: OTYPE.ARRAY, dtype: DTYPE.UNSIGNED8, name: 'Sync Manager Communication Type', items: [ + { name: 'Max SubIndex' }, + { name: 'Communications Type SM0', value: 1 }, + { name: 'Communications Type SM1', value: 2 }, + { name: 'Communications Type SM2', value: 3 }, + { name: 'Communications Type SM3', value: 4 }, + ]}, + }; + return OD; +}; + +const sdo = 'sdo'; +const txpdo = 'txpdo'; +const rxpdo = 'rxpdo'; + +/** EtherCAT Slave Chips that are supported by this web tool */ +const SupportedESC = { + AX58100: 'AX58100', + ET1100: 'ET1100', + LAN9252: 'LAN9252', + LAN9253_Beckhoff: 'LAN9253 Beckhoff', +}; + +/** ESCs that are using reserved bytes for configuration, for example AX58100 configdata reaches 0x0A byte */ +const configOnReservedBytes = [SupportedESC.AX58100, SupportedESC.LAN9253_Beckhoff]; + +//** Form default values */ +function getFormDefaultValues() { + return {form: { + VendorName: "ACME EtherCAT Devices", + VendorID: "0x000", + ProductCode: "0x00ab123", + ProfileNo: "5001", + RevisionNumber: "0x002", + SerialNumber: "0x001", + HWversion: "0.0.1", + SWversion: "0.0.1", + EEPROMsize: "2048", + RxMailboxOffset: "0x1000", + TxMailboxOffset: "0x1200", + MailboxSize: "512", + SM2Offset: "0x1600", + SM3Offset: "0x1A00", + TextGroupType: "DigIn", + TextGroupName5: "Digital input", + ImageName: "IMGCBY", + TextDeviceType: "DigIn2000", + TextDeviceName: "2-channel Hypergalactic input superimpermanator", + Port0Physical: "Y", + Port1Physical: "Y", + Port2Physical: " ", + Port3Physical: " ", + ESC: SupportedESC.ET1100, + SPImode: "3", + CoeDetailsEnableSDO: true, + CoeDetailsEnableSDOInfo: true, + CoeDetailsEnablePDOAssign: false, + CoeDetailsEnablePDOConfiguration: false, + CoeDetailsEnableUploadAtStartup: true, + CoeDetailsEnableSDOCompleteAccess: false, + }}; +}; diff --git a/Pcb-1-lan9252/EEPROM_generator/src/file_io.js b/Pcb-1-lan9252/EEPROM_generator/src/file_io.js new file mode 100644 index 0000000..a0046e7 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/src/file_io.js @@ -0,0 +1,89 @@ +/** + * SOES EEPROM generator + * Files input and output + + * This tool serves as: +- EtherCAT Slave Information XML + EEPROM binary generator +- SOES code generator + + * Victor Sluiter 2013-2018 + * Kuba Buda 2020-2021 + */ +'use strict' + +// ####################### File operations ####################### // + +/** save file in local filesystem, by downloading from browser */ +function downloadFile(content, fileName, contentType) { + var a = document.createElement("a"); + var file = new Blob([content], {type: contentType}); + a.href = URL.createObjectURL(file); + a.download = fileName; + a.click(); + // a element will be garbage collected, no need to cleanup +} + +/** reads saved project from file user opened */ +function readFile(e) { + var file = e.target.files[0]; + if (!file) return; + var reader = new FileReader(); + reader.onload = function(e) { + onRestoreComplete(e.target.result); + } + reader.readAsText(file); +} + +/** takes bytes array, returns Intel Hex as string */ +function toIntelHex(record) { + var hex = ""; + const bytes_per_rule = 32; + const rulesTotalCount = record.length/bytes_per_rule; + + for (var rulenumber = 0 ; rulenumber < (rulesTotalCount); rulenumber++) + { + const sliceStart = rulenumber*bytes_per_rule; + const sliceEnd = bytes_per_rule + (rulenumber * bytes_per_rule); + const recordSlice = record.slice(sliceStart, sliceEnd); + hex += CreateiHexRule(bytes_per_rule, rulenumber, recordSlice); + } + //end of file marker + hex += ':00000001FF'; + return hex.toUpperCase(); + + function CreateiHexRule(bytes_per_rule, rulenumber, record) + { + var record_type_datarecord = '00'; + var rule = ':'+ bytes_per_rule.toString(16).slice(-2) + generate_hex_address(rulenumber*bytes_per_rule) + record_type_datarecord; + for(var byteposition = 0; byteposition < bytes_per_rule ; byteposition++) + { + var byte = record[byteposition].toString(16).slice(-2); // convert to hexadecimal, crop to last 2 digits + if(byte.length < 2) + byte = '0' + byte; //minimal field width = 2 characters. + rule += byte; + } + var checksum = 0; + for(var rule_pos = 0 ; rule_pos < (rule.length-1)/2 ; rule_pos++) + { + var byte = parseInt(rule.slice(1+(2*rule_pos), 3+(2*rule_pos)),16); + checksum += byte; + } + checksum %= 0x100; //leave last byte + checksum = 0x100-checksum; //two's complement + rule += checksum.toString(16).slice(-2) + '\n'; + return rule; + } + /** takex number, returns its hexadecimal value padded/trimmed to 4 digits */ + function generate_hex_address(number) + { + //convert to hexadecimal string + var output = number.toString(16); + //take care that 4 characters are present + while(output.length<4) + { + output ='0' + output; + } + //return 4 characters, prevents overflow + return output.slice(-4); + } +} diff --git a/Pcb-1-lan9252/EEPROM_generator/src/generators/EEPROM.js b/Pcb-1-lan9252/EEPROM_generator/src/generators/EEPROM.js new file mode 100644 index 0000000..e7534e4 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/src/generators/EEPROM.js @@ -0,0 +1,330 @@ +/** + * SOES EEPROM generator + * EEPROM .bin / .hex code generation logic + +* This tool serves as: +- EtherCAT Slave Information XML + EEPROM binary generator +- SOES code generator + + * Victor Sluiter 2013-2018 + * Kuba Buda 2020-2021 + */ +'use strict' + +// ####################### EEPROM generating ####################### // + +function hex_generator(form, stringOnly=false) +{ + //WORD ADDRESS 0-7 + var record = getConfigDataBytes(form); + if (stringOnly) { return getConfigDataString(record, form.ESC.value); } + + /** Takes form, returns config data: + * first 16 bytes (8 words) with check sum */ + function getConfigDataBytes(form) { + const recordLength = parseInt(form.EEPROMsize.value); + var record = new Uint8Array(recordLength); + record.fill(0xFF); + //Start of EEPROM contents; A lot of information can be found in 5.4 of ETG1000.6 + let pdiControl = 0x05; + const spiMode = parseInt(form.SPImode.value); // valid values ara 0, 1, 2 or 3 + let reserved_0x05 = 0x0000; + + switch(form.ESC.value) { + case SupportedESC.AX58100: + reserved_0x05 = 0x001A; // enable IO for SPI driver on AX58100: + // Write 0x1A value (INT edge pulse length, 8 mA Control + IO 9:0 Drive Select) to 0x0A (Host Interface Extend Setting and Drive Strength + break; + case SupportedESC.LAN9252: + pdiControl = 0x80; + break; + case SupportedESC.LAN9253_Beckhoff: + reserved_0x05 = 0xC040; // enable ERRLED, STATE_RUNLED and MI Write + // in ASIC CONFIGURATION REGISTER: 0142h-0143h (refer to DS00003421A-page 268) + break; + default: + break; + } + + //WORD ADDRESS 0-7 + writeEEPROMbyte_byteaddress(pdiControl, 0, record); //PDI control: SPI slave (mapped to register 0x0140) + writeEEPROMbyte_byteaddress(0x06, 1, record); //ESC configuration: Distributed clocks Sync Out and Latch In enabled (mapped register 0x0141) + writeEEPROMbyte_byteaddress(spiMode, 2, record); //SPI mode (mapped to register 0x0150) + writeEEPROMbyte_byteaddress(0x44, 3, record); //SYNC /LATCH configuration (mapped to 0x0151). Make both Syncs output + writeEEPROMword_wordaddress(0x0064, 2, record); //Syncsignal Pulselenght in 10ns units(mapped to 0x0982:0x0983) + writeEEPROMword_wordaddress(0x00, 3, record); //Extended PDI configuration (none for SPI slave)(0x0152:0x0153) + writeEEPROMword_wordaddress(0x00, 4, record); //Configured Station Alias (0x0012:0x0013) + writeEEPROMword_wordaddress(reserved_0x05, 5, record); //Reserved, 0 (when not AX58100) + writeEEPROMword_wordaddress(0, 6, record); //Reserved, 0 + const crc = FindCRC(record, 14); + writeEEPROMword_wordaddress(crc, 7, record); //CRC + + return record; + } + + //WORD ADDRESS 8-15 + writeEEPROMDword_wordaddress(parseInt(form.VendorID.value),8,record); //CoE 0x1018:01 + writeEEPROMDword_wordaddress(parseInt(form.ProductCode.value),10,record); //CoE 0x1018:02 + writeEEPROMDword_wordaddress(parseInt(form.RevisionNumber.value),12,record);//CoE 0x1018:03 + writeEEPROMDword_wordaddress(parseInt(form.SerialNumber.value),14,record); //CoE 0x1018:04 + //WORD ADDRESS 16-23 + writeEEPROMword_wordaddress(0,16,record); //Execution Delay Time; units? + writeEEPROMword_wordaddress(0,17,record); //Port0 Delay Time; units? + writeEEPROMword_wordaddress(0,18,record); //Port1 Delay Time; units? + writeEEPROMword_wordaddress(0,19,record); //Reserved, zero + writeEEPROMword_wordaddress(0,20,record); //Bootstrap Rx mailbox offset //Bootstrap not supported + writeEEPROMword_wordaddress(0,21,record); //Bootstrap Rx mailbox size + writeEEPROMword_wordaddress(0,22,record); //Bootstrap Tx mailbox offset + writeEEPROMword_wordaddress(0,23,record); //Bootstrap Tx mailbox size + //WORD ADDRESS 24-... + writeEEPROMword_wordaddress(parseInt(form.RxMailboxOffset.value),24,record); //Standard Rx mailbox offset + writeEEPROMword_wordaddress(parseInt(form.MailboxSize.value),25,record); //Standard Rx mailbox size + writeEEPROMword_wordaddress(parseInt(form.TxMailboxOffset.value),26,record); //Standard Tx mailbox offset + writeEEPROMword_wordaddress(parseInt(form.MailboxSize.value),27,record); //Standard Tx mailbox size + writeEEPROMword_wordaddress(0x04,28,record); //CoE protocol, see Table18 in ETG1000.6 + for (var count = 29; count <= 61; count++) { //fill reserved area with zeroes + writeEEPROMword_wordaddress(0,count,record); + } + writeEEPROMword_wordaddress((Math.floor(parseInt(form.EEPROMsize.value)/128))-1,62,record); //EEPROM size + writeEEPROMword_wordaddress(1,63,record); //Version + //////////////////////////////////// + /// Vendor Specific Info // + //////////////////////////////////// + + //Strings + var array_of_strings = [form.TextDeviceType.value, form.TextGroupType.value, form.ImageName.value, form.TextDeviceName.value]; + var offset = 0; + offset = writeEEPROMstrings(record, 0x80, array_of_strings); //See ETG1000.6 Table20 + //General info + offset = writeEEPROMgeneral_settings(form,offset,record); //See ETG1000.6 Table21 + //FMMU + offset = writeFMMU(form,offset, record); //see Table 22 ETG1000.6 + //SyncManagers + offset = writeSyncManagers(form, offset, record); //See Table 23 ETG1000.6 + //End of EEPROM contents + const eepromSize = getForm().EEPROMsize.value; + + return record; + + /** See ETG1000.6 Table20 for Category string */ + function writeEEPROMstrings(record, offset, a_strings) + { + var number_of_strings = a_strings.length; + var total_string_data_length = 0; + var length_is_even; + for(var strcounter = 0; strcounter < number_of_strings ; strcounter++) + { + total_string_data_length += a_strings[strcounter].length //add length of strings + } + total_string_data_length += number_of_strings; //for each string a byte is needed to indicate the length + total_string_data_length += 1; //for byte to give 'number of strings' + if(total_string_data_length %2) //if length is even (ends at word boundary) + length_is_even = false; + else + length_is_even = true; + writeEEPROMword_wordaddress(0x000A, offset/2, record); //Type: STRING + writeEEPROMword_wordaddress(Math.ceil(total_string_data_length/2), (offset/2) + 1, record); //write length of complete package + offset += 4; //2 words written + writeEEPROMbyte_byteaddress(number_of_strings, offset++, record); + for(var strcounter = 0; strcounter < number_of_strings ; strcounter++) + { + writeEEPROMbyte_byteaddress(a_strings[strcounter].length, offset++, record); + for(var charcounter = 0 ; charcounter < a_strings[strcounter].length ; charcounter++) + { + writeEEPROMbyte_byteaddress(a_strings[strcounter].charCodeAt(charcounter), offset++, record); + } + } + if(length_is_even == false) + { + writeEEPROMbyte_byteaddress(0, offset++, record); + } + return offset; + } + /** See ETG1000.6 Table21 */ + function writeEEPROMgeneral_settings(form,offset,record) + { + const General_category = 0x1E; // value: 30d + const categorysize = 0x10; + //Clear memory region + for(let wordcount = 0; wordcount < categorysize + 2; wordcount++) { + writeEEPROMword_wordaddress(0, (offset/2) + wordcount, record); + } + //write code 30, 'General type'. See ETG1000.6, Table 19 + writeEEPROMword_wordaddress(General_category, offset/2, record); + //write length of General Category data + writeEEPROMword_wordaddress(categorysize, 1+(offset/2), record); + offset +=4; + writeEEPROMbyte_byteaddress(2,offset++,record);//index to string for Group Info + writeEEPROMbyte_byteaddress(3,offset++,record);//index to string for Image Name + writeEEPROMbyte_byteaddress(1,offset++,record);//index to string for Device Order Number + writeEEPROMbyte_byteaddress(4,offset++,record);//index to string for Device Name Information + offset++; //byte 4 is reserved + writeEEPROMbyte_byteaddress(getCOEdetails(form),offset++,record);//CoE Details + writeEEPROMbyte_byteaddress(0,offset++,record); //Enable FoE + writeEEPROMbyte_byteaddress(0,offset++,record); //Enable EoE + writeEEPROMbyte_byteaddress(0,offset++,record); //reserved + writeEEPROMbyte_byteaddress(0,offset++,record); //reserved + writeEEPROMbyte_byteaddress(0,offset++,record); //reserved + writeEEPROMbyte_byteaddress(0,offset++,record); //flags (Bit0: Enable SafeOp, Bit1: Enable notLRW + writeEEPROMword_wordaddress(0x0000, offset/2, record); //current consumption in mA + offset += 2; + writeEEPROMword_wordaddress(0x0000, offset/2, record); //2 pad bytes + offset += 2; + writeEEPROMword_wordaddress(getPhysicalPort(form), offset/2, record); + offset += 2; + offset += 14; //14 pad bytes + return offset; + } + /** See ETG1000.6 Table 22 */ + function writeFMMU(form, offset, record) + { + const FMMU_category = 0x28 // 40d + writeEEPROMword_wordaddress(FMMU_category,offset/2,record); + offset += 2; + const length = 2 //length = 2 word = 4bytes: 3 FMMU's + padding + //length = 1 word = 2bytes: 2 FMMU's. + writeEEPROMword_wordaddress(length, offset/2, record); + offset += 2; + writeEEPROMbyte_byteaddress(1, offset++, record); //FMMU0 used for Outputs; see Table 22 ETG1000.6 + writeEEPROMbyte_byteaddress(2, offset++, record); //FMMU1 used for Inputs; see Table 22 ETG1000.6 + writeEEPROMbyte_byteaddress(3, offset++, record); //FMMU2 used for Mailbox State + writeEEPROMbyte_byteaddress(0, offset++, record); //padding, disable FMMU4 if exists + + return offset; + } + /** See Table 23 ETG1000.6 */ + function writeSyncManagers(form, offset, record) + { + const SyncManager_category = 0x29 // 41d + writeEEPROMword_wordaddress(SyncManager_category, offset/2, record); //SyncManager + offset += 2; + writeEEPROMword_wordaddress(0x10, offset/2, record); //size of structure category + offset += 2; + //SM0 + writeEEPROMword_wordaddress(parseInt(form.RxMailboxOffset.value),offset/2, record); //Physical start address + offset += 2; + writeEEPROMword_wordaddress(parseInt(form.MailboxSize.value),offset/2, record); //Physical size + offset += 2; + writeEEPROMbyte_byteaddress(0x26,offset++, record); //Mode of operation + writeEEPROMbyte_byteaddress(0,offset++, record); //don't care + writeEEPROMbyte_byteaddress(1,offset++, record); //Enable Syncmanager; bit0: enable, bit 1: fixed content, bit 2: virtual SyncManager, bit 3: Op Only + writeEEPROMbyte_byteaddress(1,offset++, record); //SyncManagerType; 0: not used, 1: Mbx out, 2: Mbx In, 3: PDO, 4: PDI + //SM1 + writeEEPROMword_wordaddress(parseInt(form.TxMailboxOffset.value),offset/2, record); //Physical start address + offset += 2; + writeEEPROMword_wordaddress(parseInt(form.MailboxSize.value),offset/2, record); //Physical size + offset += 2; + writeEEPROMbyte_byteaddress(0x22,offset++, record); //Mode of operation + writeEEPROMbyte_byteaddress(0,offset++, record); //don't care + writeEEPROMbyte_byteaddress(1,offset++, record); //Enable Syncmanager; bit0: enable, bit 1: fixed content, bit 2: virtual SyncManager, bit 3: Op Only + writeEEPROMbyte_byteaddress(2,offset++, record); //SyncManagerType; 0: not used, 1: Mbx out, 2: Mbx In, 3: PDO, 4: PDI + //SM2 + writeEEPROMword_wordaddress(parseInt(form.SM2Offset.value),offset/2, record); //Physical start address + offset += 2; + writeEEPROMword_wordaddress(0,offset/2, record); //Physical size + offset += 2; + writeEEPROMbyte_byteaddress(0x24,offset++, record); //Mode of operation + writeEEPROMbyte_byteaddress(0,offset++, record); //don't care + writeEEPROMbyte_byteaddress(1,offset++, record); //Enable Syncmanager; bit0: enable, bit 1: fixed content, bit 2: virtual SyncManager, bit 3: Op Only + writeEEPROMbyte_byteaddress(3,offset++, record); //SyncManagerType; 0: not used, 1: Mbx out, 2: Mbx In, 3: PDO, 4: PDI + //SM3 + writeEEPROMword_wordaddress(parseInt(form.SM3Offset.value),offset/2, record); //Physical start address + offset += 2; + writeEEPROMword_wordaddress(0,offset/2, record); //Physical size + offset += 2; + writeEEPROMbyte_byteaddress(0x20,offset++, record); //Mode of operation + writeEEPROMbyte_byteaddress(0,offset++, record); //don't care + writeEEPROMbyte_byteaddress(1,offset++, record); //Enable Syncmanager; bit0: enable, bit 1: fixed content, bit 2: virtual SyncManager, bit 3: Op Only + writeEEPROMbyte_byteaddress(4,offset++, record); //SyncManagerType; 0: not used, 1: Mbx out, 2: Mbx In, 3: PDO, 4: PDI + return offset; + } + function getCOEdetails(form) + { + let coedetails = 0; + if(form.CoeDetailsEnableSDO.checked) coedetails |= 0x01; //Enable SDO + if(form.CoeDetailsEnableSDOInfo.checked) coedetails |= 0x02; //Enable SDO Info + if(form.CoeDetailsEnablePDOAssign.checked) coedetails |= 0x04; //Enable PDO Assign + if(form.CoeDetailsEnablePDOConfiguration.checked) coedetails |= 0x08; //Enable PDO Configuration + if(form.CoeDetailsEnableUploadAtStartup.checked) coedetails |= 0x10; //Enable Upload at startup + if(form.CoeDetailsEnableSDOCompleteAccess.checked) coedetails |= 0x20; //Enable SDO complete access + return coedetails; + } + /** ETG1000.6 Table 21 */ + function getPhysicalPort(form) + { + let portinfo = 0; + let physicals = [form.Port3Physical.value, form.Port2Physical.value, form.Port1Physical.value, form.Port0Physical.value]; + for (var physicalcounter = 0; physicalcounter < physicals.length ; physicalcounter++) + { + portinfo = (portinfo << 4); //shift previous result + switch(physicals[physicalcounter]) + { + case 'Y': + case 'H': + portinfo |= 0x01; //MII + break; + case 'K': + portinfo |= 0x03; //EBUS + break; + default: + portinfo |= 0; //No connection + } + } + return portinfo; + } + + /** computes crc value */ + function FindCRC(data,datalen) { + var i,j; + var c; + var CRC=0xFF; + var genPoly = 0x07; + for (j=0; j>8) & 0xFF; + } + + function writeEEPROMDword_wordaddress(word, address, record) + {//little endian word storage! + record[ address*2 ] = word&0xFF; + record[1 + (address*2)] = (word>>8) & 0xFF; + record[2 + (address*2)] = (word>>16) & 0xFF; + record[3 + (address*2)] = (word>>24) & 0xFF; + } + + /** takes bytes array and count, returns ConfigData string */ + function getConfigDataString(record, esc) { + const configdata_bytecount = new Set(configOnReservedBytes).has(esc) ? 14 : 7; + + var configdata = ''; + for (var bytecount = 0; bytecount < configdata_bytecount; bytecount++) { + configdata += (record[bytecount] + 0x100).toString(16).slice(-2).toUpperCase(); + } + return configdata; + } +} diff --git a/Pcb-1-lan9252/EEPROM_generator/src/generators/ecat_options.js b/Pcb-1-lan9252/EEPROM_generator/src/generators/ecat_options.js new file mode 100644 index 0000000..a0031cd --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/src/generators/ecat_options.js @@ -0,0 +1,95 @@ +/** + * SOES EEPROM generator + * ecat_options.h code generation logic + +* This tool serves as: +- EtherCAT Slave Information XML + EEPROM binary generator +- SOES code generator + + * Victor Sluiter 2013-2018 + * Kuba Buda 2020-2021 + */ +'use strict' + +// ####################### ecat_options.h generation ####################### // + +function ecat_options_generator(form, od, indexes) +{ + let ecat_options = '#ifndef __ECAT_OPTIONS_H__\n#define __ECAT_OPTIONS_H__\n\n#define USE_FOE 0\n#define USE_EOE 0\n\n'; + + //Mailbox size + ecat_options += '#define MBXSIZE ' + parseInt(form.MailboxSize.value).toString() + + '\n#define MBXSIZEBOOT ' + parseInt(form.MailboxSize.value).toString() + + '\n#define MBXBUFFERS 3\n\n'; + //Mailbox 0 Config + ecat_options += `#define MBX0_sma 0x${indexToString(form.RxMailboxOffset.value)}` + + '\n#define MBX0_sml MBXSIZE' + + '\n#define MBX0_sme MBX0_sma+MBX0_sml-1' + + '\n#define MBX0_smc 0x26\n'; + //Mailbox 1 Config + ecat_options += `#define MBX1_sma MBX0_sma+MBX0_sml` //'0x${indexToString(form.TxMailboxOffset.value)}`; + + '\n#define MBX1_sml MBXSIZE' + + '\n#define MBX1_sme MBX1_sma+MBX1_sml-1' + + '\n#define MBX1_smc 0x22\n\n'; + // Mailbox boot configuration + ecat_options += `#define MBX0_sma_b 0x${indexToString(form.RxMailboxOffset.value)}` + + '\n#define MBX0_sml_b MBXSIZEBOOT' + + '\n#define MBX0_sme_b MBX0_sma_b+MBX0_sml_b-1' + + '\n#define MBX0_smc_b 0x26\n'; + ecat_options += `#define MBX1_sma_b MBX0_sma_b+MBX0_sml_b` //'0x${indexToString(form.TxMailboxOffset.value)}`; + + '\n#define MBX1_sml_b MBXSIZEBOOT' + + '\n#define MBX1_sme_b MBX1_sma_b+MBX1_sml_b-1' + + '\n#define MBX1_smc_b 0x22\n\n'; + //SyncManager2 Config + ecat_options += `#define SM2_sma 0x${indexToString(form.SM2Offset.value)}` + + '\n#define SM2_smc 0x24' + + '\n#define SM2_act 1\n'; + //SyncManager3 Config + ecat_options += `#define SM3_sma 0x${indexToString(form.SM3Offset.value)}` + + '\n#define SM3_smc 0x20' + + '\n#define SM3_act 1\n\n'; + // Mappings config + const MAX_MAPPINGS_SM2 = getMaxMappings(od, indexes, rxpdo); + const MAX_MAPPINGS_SM3 = getMaxMappings(od, indexes, txpdo); + ecat_options += `#define MAX_MAPPINGS_SM2 ${MAX_MAPPINGS_SM2}` + + `\n#define MAX_MAPPINGS_SM3 ${MAX_MAPPINGS_SM3}\n\n` + // PDO buffer config + ecat_options += '#define MAX_RXPDO_SIZE 512' // TODO calculate based on offset, size + + '\n#define MAX_TXPDO_SIZE 512\n\n' + + '#endif /* __ECAT_OPTIONS_H__ */\n'; + + return ecat_options; + + function getMaxMappings(od, indexes, pdoName) { + let result = 0; + + indexes.forEach(index => { + const objd = od[index]; + if(objd.pdo_mappings) { + if(objd.items) { + objd.items.slice(1).forEach(subitem => { + objd.pdo_mappings.forEach(mapping => { + if (mapping == pdoName) { + ++result; + if (subitem.dtype == DTYPE.BOOLEAN) { + ++result; // boolean padding is mapping too + // TODO handle array of booleans + } + } + }); + }); + } else if(objd.pdo_mappings) { + objd.pdo_mappings.forEach(mapping => { + if (mapping == pdoName) { + ++result; + if (objd.dtype == DTYPE.BOOLEAN) { + ++result; // boolean padding is mapping too + } + } + }); + }; + }; + }); + return result; + } +} diff --git a/Pcb-1-lan9252/EEPROM_generator/src/generators/esi_xml.js b/Pcb-1-lan9252/EEPROM_generator/src/generators/esi_xml.js new file mode 100644 index 0000000..7881d28 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/src/generators/esi_xml.js @@ -0,0 +1,410 @@ +/** + * SOES EEPROM generator + * ESI XML code generation logic + +* This tool serves as: +- EtherCAT Slave Information XML + EEPROM binary generator +- SOES code generator + + * Victor Sluiter 2013-2018 + * Kuba Buda 2020-2021 + */ +'use strict' + +// ####################### ESI.xml generating ####################### // + +function esiDTbitsize(dtype) { + return ESI_DT[dtype].bitsize; +} + +//See ETG2000 for ESI format +function esi_generator(form, od, indexes, dc) +{ + //VendorID + var esi =`\n\n \n ${parseInt(form.VendorID.value).toString()}\n`; + //VendorName + esi += ` ${form.VendorName.value}\n \n \n`; + //Groups + esi += ` \n \n ${form.TextGroupType.value}\n ${form.TextGroupName5.value}\n \n \n \n`; + //Physics + esi += ` \n ${form.TextDeviceType.value}\n`; + //Add Name info + esi += ` ${form.TextDeviceName.value}\n`; + //Add in between + esi += ` ${form.TextGroupType.value}\n`; + //Add profile + esi += ` \n ${form.ProfileNo.value}\n 0\n \n `; + const customTypes = {}; + const variableTypes = {}; + + function addVariableType(element) { + if (element && element.otype && (element.otype != OTYPE.VAR && element.otype != OTYPE.ARRAY)) { + alert(`${element.name} is not OTYPE VAR, cannot treat is as variable type`); return; + } + if (!element || !element.dtype) { + alert(`${element.name} has no DTYPE, cannot treat is as variable type`); return; + } + let el_name = esiVariableTypeName(element); + if (!variableTypes[el_name]) { + const bitsize = (element.dtype == DTYPE.VISIBLE_STRING) ? esiBitsize(element) : esiDTbitsize(element.dtype); + variableTypes[el_name] = bitsize; + } + } + function addObjectDictionaryDataType(od, index) { + const objd = od[index]; + const dtName = esiDtName(objd, index); + var result = ''; + + if (objd.otype == OTYPE.VAR) { + addVariableType(objd); // variable types will have to be be done later anyway, add to that queue + } else if (!customTypes[dtName]) { + // generate data types code for complex objects + const bitsize = esiBitsize(objd); + customTypes[dtName] = true; + result += `\n `; + + let flags = `\n ro`; // PDO assign flags for variables are set in dictionary objects section + if (objd.otype == OTYPE.ARRAY) { + addVariableType(objd); // queue variable type to add after array code is generated + let esi_type = ESI_DT[objd.dtype]; + let arr_bitsize = (objd.items.length - 1) * esi_type.bitsize + result += `\n ${dtName}ARR\n ${esi_type.name}\n ${arr_bitsize}`; + result += `\n \n 1\n ${objd.items.length - 1}\n `; + result += `\n `; + result += `\n `; + } + result += `\n ${dtName}\n ${bitsize}`; + result += `\n \n 0\n Max SubIndex\n USINT` + + `\n 8\n 0\n ${flags}\n \n `; + + flags += getPdoMappingFlags(objd); // PDO assign flags for composite type + + switch (objd.otype) { + case OTYPE.ARRAY: { + let arr_bitsize = (objd.items.length - 1) * esiDTbitsize(objd.dtype); + result += `\n \n Elements\n ${dtName}ARR\n ${arr_bitsize}` + +`\n 16\n ${flags}\n \n `; + break; + } case OTYPE.RECORD: { + let subindex = 0; + let bits_offset = 16; + objd.items.forEach(subitem => { + if (subindex > 0) { // skipped Max Subindex + addVariableType(subitem); // cannot add variable type now that record code is being generated + let subitem_dtype = ESI_DT[subitem.dtype]; + let subitem_bitsize = subitem_dtype.bitsize + const subitemFlags = getSubitemFlags(objd, subitem); + result += `\n \n ${subindex}\n ${subitem.name}` + + `\n ${subitem_dtype.name}\n ${subitem_bitsize}\n ${bits_offset}` + + `\n ${subitemFlags}\n ` + + `\n `; + bits_offset += subitem_bitsize; + } + subindex++; + }); + break; + } default: { + alert(`Object ${index} "${objd.name}" has unexpected OTYPE ${objd.otype}`); + alert; + }} + result += `\n `; + } + + return result; + + function getSubitemFlags(objd, subitem) { + let access = 'ro'; + let modifier = ''; + if (subitem.access) { + access = subitem.access.slice(0,2).toLowerCase(); + modifier = ' WriteRestrictions="PreOP"'; + } + let flags = `\n ${access}`; // PDO assign flags for variables are set in dictionary objects section + flags += getPdoMappingFlags(objd); // PDO assign flags for composite type + return flags; + } + } + // Add objects dictionary data types + indexes.forEach(index => { esi += addObjectDictionaryDataType(od, index); }); + // Add variable type + Object.entries(variableTypes).forEach(variableType => { + esi += `\n `; + esi += `\n ${variableType[0]}\n ${variableType[1]}`; + esi += `\n `; + }); + esi += `\n \n `; + // Add objects dictionary + function addDictionaryObject(od, index) { + const objd = od[index]; + const el_dtype = esiDtName(objd, index); + const bitsize = esiBitsize(objd); + let result = `\n \n #x${index}\n ${objd.name}\n ${el_dtype}\n ${bitsize}\n `; + if (objd.data) { + if (objd.dtype == DTYPE.VISIBLE_STRING) { + result += `\n ${objd.data}`; + } + } + if (objd.value) { + result += `\n ${toEsiHexValue(objd.value)}`; + } + //Add object subitems for complex types + if (objd.items) { + result += addDictionaryObjectSubitems(objd.items); + } + + var flags = `\n ro`; + if (objd.otype == OTYPE.VAR) { + flags += getPdoMappingFlags(objd); + } + if (SDO_category[index]) { + flags += `\n ${SDO_category[index]}`; + } + result += `\n \n ${flags}\n \n `; + return result; + + function addDictionaryObjectSubitems(element_items) { + const max_subindex_value = element_items.length - 1; + var result = "" + let subindex = 0; + element_items.forEach(subitem => { + var defaultValue = (subindex > 0) ? subitem.value : max_subindex_value; + result += `\n \n ${subitem.name}\n \n ${toEsiHexValue(defaultValue)}\n \n `; + subindex++; + }); + return result; + } + } + indexes.forEach(index => { esi += addDictionaryObject(od, index); }); + const is_rxpdo = isPdoWithVariables(od, indexes, rxpdo); + const is_txpdo = isPdoWithVariables(od, indexes, txpdo); + + esi += `\n \n \n \n Outputs\n Inputs\n MBoxState\n`; + //Add Rxmailbox sizes + esi += ` MBoxOut\n`; + //Add Txmailbox sizes + esi += ` MBoxIn\n`; + //Add SM2 + esi += ` Outputs\n`; + //Add SM3 + esi += ` Inputs\n`; + if (is_rxpdo) { + var memOffset = getSM2_MappingOffset(form); + indexes.forEach(index => { + const objd = od[index]; + + if (isInArray(objd.pdo_mappings, rxpdo)) { + esi += addEsiDevicePDO(objd, index, rxpdo, memOffset); + ++memOffset; + } + }); + } + if (is_txpdo) { + var memOffset = form.SM3Offset.value; + indexes.forEach(index => { + const objd = od[index]; + if (isInArray(objd.pdo_mappings, txpdo)) { + esi += addEsiDevicePDO(objd, index, txpdo, memOffset); + ++memOffset; + } + }); + } + + //Add Mailbox DLL + esi += ` \n \n \n`; + //Add DCs + esi += getEsiDCsection(dc); + //Add EEPROM + const configdata = hex_generator(form, true); + esi +=` \n ${parseInt(form.EEPROMsize.value)}\n ${configdata}\n \n`; + //Close all items + esi +=` \n \n \n`; + + return esi; + + function addEsiDevicePDO(objd, index, pdo, memOffset) { + var esi = ''; + const PdoName = pdo[0].toUpperCase(); + const SmNo = (pdo == txpdo) ? 3 : 2; + const memoryOffset = indexToString(memOffset); + esi += ` <${PdoName}xPdo Fixed="true" Mandatory="true" Sm="${SmNo}">\n #x${memoryOffset}\n ${objd.name}`; + var subindex = 0; + switch (objd.otype) { + case OTYPE.VAR: { + const esiType = esiVariableTypeName(objd); + const bitsize = esiDTbitsize(objd.dtype); + esi += `\n \n #x${index}\n #x${subindex.toString(16)}\n ${bitsize}\n ${objd.name}\n ${esiType}\n `; + esi += pdoBooleanPadding(objd); + break; + } + case OTYPE.ARRAY: { + const esiType = esiVariableTypeName(objd); + const bitsize = esiDTbitsize(objd.dtype); + subindex = 1; // skip 'Max subindex' + objd.items.slice(subindex).forEach(subitem => { + esi += `\n \n #x${index}\n #x${subindex.toString(16)}\n ${bitsize}\n ${subitem.name}\n ${esiType}\n `; + // TODO handle padding for array of booleans + ++subindex; + }); + break; + } + case OTYPE.RECORD: { + subindex = 1; // skip 'Max subindex' + objd.items.slice(subindex).forEach(subitem => { + const esiType = esiVariableTypeName(subitem); + const bitsize = esiDTbitsize(subitem.dtype); + esi += `\n \n #x${index}\n #x${subindex.toString(16)}\n ${bitsize}\n ${subitem.name}\n ${esiType}\n `; + esi += pdoBooleanPadding(subitem); + ++subindex; + }); + break; + } + default: { + alert(`Unexpected OTYPE ${objd.otype} for ${index} ${objd.name} in ESI ${PdoName}PDOs`); + break; + }} + esi += `\n \n`; + + return esi; + + function pdoBooleanPadding(item) { + if (item.dtype == DTYPE.BOOLEAN) { + return `\n \n ${0}\n ${0}\n ${7}\n `; + } + return ``; + } + } + + function toEsiHexValue(value) { + if (!value) { + return 0; + } + if (value.startsWith && value.startsWith('0x')) { + value = `#x${value.slice(2)}`; + } + return value; + } + + function getPdoMappingFlags(item) { + var flags = ''; + if (item.pdo_mappings) { + if (item.pdo_mappings.length > 1) { + alert(`Object ${index} "${objd.name}" has multiple PDO mappings, that is not supported by this version of tool` + + `, only first ${pdoMappingFlag}XPDO will be used`); + } + const pdoMappingFlag = item.pdo_mappings[0].slice(0,1).toUpperCase(); + flags += `\n ${pdoMappingFlag}`; + } + return flags; + } + + function getEsiDCsection(dc) { + if (!dc) { + return ''; + } + var dcSection = ' '; + dc.forEach(opMode => { + dcSection += `\n \n ${opMode.Name}\n ${opMode.Description}\n ${opMode.AssignActivate}`; + if (opMode.Sync0cycleTime && opMode.Sync0cycleTime != 0) { + dcSection += `\n ${opMode.Sync0cycleTime}`; + } + if (opMode.Sync0shiftTime && opMode.Sync0shiftTime != 0) { + dcSection += `\n ${opMode.Sync0shiftTime}`; + } + if (opMode.Sync1cycleTime && opMode.Sync1cycleTime != 0) { + dcSection += `\n ${opMode.Sync1cycleTime}`; + } + if (opMode.Sync1shiftTime && opMode.Sync1shiftTime != 0) { + dcSection += `\n ${opMode.Sync1shiftTime}`; + } + dcSection += `\n `; + }); + dcSection += `\n \n`; + + return dcSection; + } + + //See Table 40 ETG2000 + function getCoEString(form) + { + var result = "" + // if(form.CoeDetailsEnableSDO.checked) + // result += 'SdoInfo="true" '; + // else + // result += 'SdoInfo="false" '; + if(form.CoeDetailsEnableSDOInfo.checked) + result += 'SdoInfo="true" '; + else + result += 'SdoInfo="false" '; + if(form.CoeDetailsEnablePDOAssign.checked) + result += 'PdoAssign="true" '; + else + result += 'PdoAssign="false" '; + if(form.CoeDetailsEnablePDOConfiguration.checked) + result += 'PdoConfig="true" '; + else + result += 'PdoConfig="false" '; + if(form.CoeDetailsEnableUploadAtStartup.checked) + result += 'PdoUpload="true" '; + else + result += 'PdoUpload="false" '; + if(form.CoeDetailsEnableSDOCompleteAccess.checked) + result += 'CompleteAccess="true" '; + else + result +='CompleteAccess="false" '; + return result; + } + + function esiVariableTypeName(element) { + let el_name = ESI_DT[element.dtype].name; + if (element.dtype == DTYPE.VISIBLE_STRING) { + return `${el_name}(${element.data.length})`; + } + return el_name; + } + + function esiDtName(element, index) { + switch (element.otype) { + case OTYPE.VAR: + return esiVariableTypeName(element); + case OTYPE.ARRAY: + case OTYPE.RECORD: + return `DT${index}`; + default: + alert(`Element 0x${index} has unexpected OTYPE ${element.otype}`); + break; + } + } + + function esiBitsize(element) { + switch (element.otype) { + case OTYPE.VAR: { + let bitsize = esiDTbitsize(element.dtype); + if (element.dtype == DTYPE.VISIBLE_STRING) { + return bitsize * element.data.length; + } + return bitsize; + } + case OTYPE.ARRAY: { + const maxsubindex_bitsize = esiDTbitsize(DTYPE.UNSIGNED8); + let bitsize = esiDTbitsize(element.dtype); + let elements = element.items.length - 1; // skip max subindex + return maxsubindex_bitsize * 2 + elements * bitsize; + } + case OTYPE.RECORD: { + const maxsubindex_bitsize = esiDTbitsize(DTYPE.UNSIGNED8); + let bitsize = maxsubindex_bitsize * 2; + for (let subindex = 1; subindex < element.items.length; subindex++) { + const subitem = element.items[subindex]; + bitsize += esiDTbitsize(subitem.dtype); + if(subitem.dtype == DTYPE.BOOLEAN) { + bitsize += booleanPaddingBitsize; + } + } + return bitsize; + } + default: + alert(`Element ${element} has unexpected OTYPE ${element.otype}`); + break; + } + } +} diff --git a/Pcb-1-lan9252/EEPROM_generator/src/generators/objectlist.js b/Pcb-1-lan9252/EEPROM_generator/src/generators/objectlist.js new file mode 100644 index 0000000..ee14e96 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/src/generators/objectlist.js @@ -0,0 +1,233 @@ +/** + * SOES EEPROM generator + * objectlist.c code generation logic + +* This tool serves as: +- EtherCAT Slave Information XML + EEPROM binary generator +- SOES code generator + + * Victor Sluiter 2013-2018 + * Kuba Buda 2020-2021 + */ +'use strict' + +// ####################### Objectlist.c generating ####################### // + +function get_objdBitsize(element) { + let bitsize = dtype_bitsize[element.dtype]; + if (element.dtype == DTYPE.VISIBLE_STRING) { + bitsize = bitsize * element.data.length; + } + return bitsize; +} + + +/** Takes object dictionary item from sdo, rxpdo or txpdo section + * Adds objd.data that is displayed in objectlist.c + * and links to OD variable declared on OD struct in utypes.h + */ +function objectlist_link_utypes(objd) { + switch (objd.otype) { + case OTYPE.VAR: { + objd.data = objectlist_VAR_data(objd); + break; + } + case OTYPE.ARRAY: { + var subindex = 1; + objd.items.slice(subindex).forEach(subitem => { + subitem.data = objectlist_ARRAY_data(objd, subindex); + ++subindex; + }); + break; + } + case OTYPE.RECORD: { + var subindex = 1; + objd.items.slice(subindex).forEach(subitem => { + subitem.data = objectlist_RECORD_data(objd, subitem); + ++subindex; + }); + break; + } + } + + function objectlist_VAR_data(objd) { + return `&Obj.${variableName(objd.name)}`; + } + + function objectlist_ARRAY_data(objd, subindex) { + return `&Obj.${variableName(objd.name)}[${subindex - 1}]`; + } + + function objectlist_RECORD_data(objd, subitem) { + return `&Obj.${variableName(objd.name)}.${variableName(subitem.name)}`; + } +} + +function objectlist_generator(form, od, indexes) +{ + var objectlist = '#include "esc_coe.h"\n#include "utypes.h"\n#include \n\n'; + + //Variable names + indexes.forEach(index => { + const objd = od[index]; + objectlist += objectlist_variableName(index, objd); + + }); + objectlist += '\n'; + //SDO objects declaration + indexes.forEach(index => { + const objd = od[index]; + objectlist += objectlist_SdoObjectDeclaration(index, objd); + }) + + objectlist += '\n\nconst _objectlist SDOobjects[] =\n{'; + //SDO object dictionary declaration + indexes.forEach(index => { + const objd = od[index]; + objectlist += objectlist_DictionaryDeclaration(index, objd); + }) + objectlist += '\n {0xffff, 0xff, 0xff, 0xff, NULL, NULL}\n};\n'; + + return objectlist; + + function objectlist_variableName(index, objd) { + var objectlist = `\nstatic const char acName${index}[] = "${objd.name}";`; + switch (objd.otype) { + case OTYPE.VAR: + break; + case OTYPE.ARRAY: + case OTYPE.RECORD: + for (let subindex = 0; subindex < objd.items.length; subindex++) { + const item = objd.items[subindex]; + objectlist += `\nstatic const char acName${index}_${subindex_padded(subindex)}[] = "${item.name}";`; + } + break; + default: + alert("Unexpected object type in object dictionary: ", objd) + break; + }; + return objectlist; + } + + function objectlist_SdoObjectDeclaration(index, objd) { + var objectlist = `\nconst _objd SDO${index}[] =\n{`; + + switch (objd.otype) { + case OTYPE.VAR: { + const value = objectlist_getItemValue(objd, objd.dtype); + objectlist += `\n {0x0, DTYPE_${objd.dtype}, ${get_objdBitsize(objd)}, ${objectlist_objdFlags(objd)}, acName${index}, ${value}, ${objeclist_objdData(objd)}},`; + break; + } + case OTYPE.ARRAY: { + objectlist += `\n {0x00, DTYPE_${DTYPE.UNSIGNED8}, ${8}, ATYPE_RO, acName${index}_00, ${objd.items.length - 1}, NULL},`; // max subindex + const bitsize = dtype_bitsize[objd.dtype]; /* TODO what if it is array of strings? */ + let subindex = 1; + objd.items.slice(subindex).forEach(subitem => { + var subi = subindex_padded(subindex); + const value = objectlist_getItemValue(subitem, objd.dtype); + objectlist += `\n {0x${subi}, DTYPE_${objd.dtype}, ${bitsize}, ${objectlist_objdFlags(objd)}, acName${index}_${subi}, ${value}, ${subitem.data || 'NULL'}},`; + subindex++; + }); + break; + } + case OTYPE.RECORD: { + objectlist += `\n {0x00, DTYPE_${DTYPE.UNSIGNED8}, ${8}, ATYPE_RO, acName${index}_00, ${objd.items.length - 1}, NULL},`; // max subindex + let subindex = 1; + objd.items.slice(subindex).forEach(subitem => { + var subi = subindex_padded(subindex); + const bitsize = dtype_bitsize[subitem.dtype]; + const value = objectlist_getItemValue(subitem, subitem.dtype); + const atypeflag = objectlist_objdFlags(subitem); + objectlist += `\n {0x${subi}, DTYPE_${subitem.dtype}, ${bitsize}, ${atypeflag}, acName${index}_${subi}, ${value}, ${subitem.data || 'NULL'}},`; + subindex++; + }); + + break; + } + default: + alert("Unexpected object type om object dictionary"); + break; + }; + objectlist += '\n};'; + + return objectlist; + } + + function objectlist_DictionaryDeclaration(index, objd) { + var objectlist = ``; + switch (objd.otype) { + case OTYPE.VAR: + case OTYPE.ARRAY: + case OTYPE.RECORD: + let maxsubindex = 0; + if (objd.items) { + maxsubindex = objd.items.length - 1; + } + objectlist += `\n {0x${index}, OTYPE_${objd.otype}, ${maxsubindex}, ${objd.pad1 || 0}, acName${index}, SDO${index}},`; + break; + default: + alert("Unexpected object type om object dictionary") + break; + }; + return objectlist; + } + + function float32ToHex(float32) { + // made by: Jozo132 (https://github.com/Jozo132) + const getHex = i => ('00' + i.toString(16)).slice(-2); + var view = new DataView(new ArrayBuffer(4)) + view.setFloat32(0, float32); + return Array.apply(null, { length: 4 }).map((_, i) => getHex(view.getUint8(i))).join(''); + } + + function objectlist_getItemValue(item, dtype) { + let value = '0'; + if (item.value) { + value = `${item.value}`; + if (dtype == DTYPE.REAL32) { + return `0x${float32ToHex(value)}`; + } + } + return value; + } + + function subindex_padded(subindex) { + // pad with 0 if single digit + if (subindex > 9) { + return `${subindex}`; + } + return `0${subindex}`; + } + + /** Gets flags for objectlist item: + * + * ATYPE: access type (RO/RW/WO/RWpre) + * + * PDO mappings */ + function objectlist_objdFlags(element) { + let flags = "ATYPE_RO"; // RO by default + if (element.access) { + flags = `ATYPE_${element.access}`; + } + + if (element.pdo_mappings) { + element.pdo_mappings .forEach(mapping => { + flags = `${flags} | ATYPE_${mapping.toUpperCase()}`; + }); + } + return flags; + } + + function objeclist_objdData(element) { + let el_data = 'NULL'; + + if (element.data) { + el_data = element.data; + if (element.dtype == DTYPE.VISIBLE_STRING) { + el_data = `"${element.data}"`; + } + } + /* TODO el_data is assigned also for PDO mapped variables */ + return el_data; + } +} diff --git a/Pcb-1-lan9252/EEPROM_generator/src/generators/utypes.js b/Pcb-1-lan9252/EEPROM_generator/src/generators/utypes.js new file mode 100644 index 0000000..0a7019e --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/src/generators/utypes.js @@ -0,0 +1,88 @@ +/** + * SOES EEPROM generator + * utypes.h code generation logic + +* This tool serves as: +- EtherCAT Slave Information XML + EEPROM binary generator +- SOES code generator + + * Victor Sluiter 2013-2018 + * Kuba Buda 2020-2021 + */ +'use strict' + +// ####################### utypes.h generation ####################### // + +function utypes_generator(form, od, indexes) { + var utypes = '#ifndef __UTYPES_H__\n#define __UTYPES_H__\n\n#include "cc.h"\n\n/* Object dictionary storage */\n\ntypedef struct\n{\n /* Identity */\n' + utypes += '\n uint32_t serial;\n'; + + var utypesInputs = '\n /* Inputs */\n'; + var utypesOutputs = '\n /* Outputs */\n'; + var hasInputs = isPdoWithVariables(od, indexes, txpdo); + var hasOutputs = isPdoWithVariables(od, indexes, rxpdo); + + indexes.forEach(index => { + const objd = od[index]; + if (objd.pdo_mappings) { + if(objd.pdo_mappings.length > 1) { alert(`${index} ${objd.name} Generating utypes.h for objects with multiple PDO mappings is not yet supported`); } + + const line = getUtypesDeclaration(objd); + + if (objd.pdo_mappings[0] == txpdo) { + utypesInputs += line; + } else { + utypesOutputs += line; + } + } + }); + + if (hasInputs) { utypes += utypesInputs + '\n'; } + if (hasOutputs) { utypes += utypesOutputs + '\n'; } + + var utypesOutputs = '\n /* Parameters */\n'; + var anyParameters = false; + indexes.forEach(index => { + const objd = od[index]; + if (objd.isSDOitem) { + utypesOutputs += getUtypesDeclaration(objd); + anyParameters = true; + } + }); + if (anyParameters) { + utypes += utypesOutputs; + } + + utypes += '\n} _Objects;\n\nextern _Objects Obj;\n\n#endif /* __UTYPES_H__ */\n'; + + return utypes; + + function getUtypesDeclaration(objd) { + const varName = variableName(objd.name); + switch (objd.otype) { + case OTYPE.VAR: { + const ctype = ESI_DT[objd.dtype].ctype; + return `\n ${ctype} ${varName};` + } + case OTYPE.ARRAY: { + const ctype = ESI_DT[objd.dtype].ctype; + return `\n ${ctype} ${varName}[${objd.items.length - 1}];` + } + case OTYPE.RECORD: { + var section = `\n struct\n {`; + /* TODO test */ + objd.items.slice(1).forEach(subitem => { + const subitemCType = ESI_DT[subitem.dtype].ctype; + const subitemName = variableName(subitem.name); + section += `\n ${subitemCType} ${subitemName};` + }); + section += `\n } ${varName};` + return section; + } + default: { + alert(`Cannot generate utypes.h for object ${objd?.name} with has unexpected OTYPE ${objd?.otype}`); + return ''; + } + } + } +} diff --git a/Pcb-1-lan9252/EEPROM_generator/src/od.js b/Pcb-1-lan9252/EEPROM_generator/src/od.js new file mode 100644 index 0000000..5b1f344 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/src/od.js @@ -0,0 +1,363 @@ +/** + * SOES EEPROM generator + * Object Dictionary edition logic + +* This tool serves as: +- EtherCAT Slave Information XML + EEPROM binary generator +- SOES code generator + + * Victor Sluiter 2013-2018 + * Kuba Buda 2020-2021 + */ +'use strict' + +/** Object Dictionary sections edited by UI + * Assumption: single non dynamic PDO */ +const _odSections = { + sdo : {}, + txpdo : {}, // addding PDO requires matching SDO in Sync Manager, and PDO mapping + rxpdo : {}, // this will be done when stitching sections during code generation +}; + +function getObjDict() { + return _odSections; +} + +function getObjDictSection(odSectionName) { + return _odSections[odSectionName]; +} + +function setObjDictSection(odSectionName, backupValue) { + _odSections[odSectionName] = backupValue; +} + +function objectExists(odSectionName, index) { + var odSection = getObjDictSection(odSectionName); + return index && odSection[index]; +} + +function checkObjectType(expected, objd) { + if (objd.otype != expected) { + var msg = `Object ${objd.name} was expected to be OTYPE ${expected} but is ${objd.otype}`; + alert(msg); + throw new Exception(msg); + } +} + +function addObject(od, objd, index) { + if (od[index]) { + alert(`Object ${objd.name} duplicates 0x${index}: ${od[index].name} !`); + } + od[index] = objd; +} + +function removeObject(od, index) { + if (index) { + if (od[index]) { + delete od[index]; + } else { + alert(`Cannot remove object 0x${index}: it does not exist`); + } + } +} + +function isInArray(array, seekValue) { + return array && (array[0] == seekValue + || array.find(currentValue => currentValue == seekValue)); +} + +function variableName(objectName) { + const charsToReplace = [ ' ', '.', ',', ';', ':', '/' ]; + const charsToRemove = [ '+', '-', '*', '=', '!', '@' ]; + + var variableName = objectName; + charsToReplace.forEach(c => { + variableName = variableName.replaceAll(c, '_'); + }); + charsToRemove.forEach(c => { + variableName = variableName.replaceAll(c, ''); + }); + return variableName; +} + +// ####################### Building Object Dictionary model ####################### // + +/** Takes OD entries from UI SDO section and adds to given OD */ +function addSDOitems(od) { + const sdoSection = getObjDictSection(sdo); + const indexes = getUsedIndexes(sdoSection); + + indexes.forEach(index => { + const item = sdoSection[index]; + item.isSDOitem = true; + objectlist_link_utypes(item); + + addObject(od, item, index); + }); +} +/** Returns true if any object in given Object Dictionary has mapping to PDO with given name */ +function isPdoWithVariables(od, indexes, pdoName) { + for (let i = 0; i < indexes.length; i++) { + const index = indexes[i]; + const objd = od[index]; + if (isInArray(objd.pdo_mappings, pdoName)) { + return true; + } + } + return false; +} +/** Regardles of value set, SDK was generating RXPDO mappings as SDO1600 + * This offset _can_ be changed, not sure why one would need it + */ +function getSM2_MappingOffset(form) { + return parseInt(form.SM2Offset.value); +} +/** Takes OD entries from UI RXPDO section and adds to given OD */ +function addRXPDOitems(od) { + const rxpdoSection = getObjDictSection(rxpdo); + const form = getForm(); + const pdo = { + name : rxpdo, + SMassignmentIndex : '1C12', + smOffset : getSM2_MappingOffset(form), // usually 0x1600 + }; + addPdoObjectsSection(od, rxpdoSection, pdo); +} +/** Takes OD entries from UI TXPDO section and adds to given OD */ +function addTXPDOitems(od) { + const txpdoSection = getObjDictSection(txpdo); + const form = getForm(); + const pdo = { + name : txpdo, + SMassignmentIndex : '1C13', + smOffset : parseInt(form.SM3Offset.value), // usually 0x1A00 + }; + addPdoObjectsSection(od, txpdoSection, pdo); +} + +var _booleanPaddingCount = 0; +/** + * Takes OD entries from given UI SDO/PDO section and adds to given OD + * using provided SM offset, and SM assignment address. + + * Available sections are 'sdo', 'txpdo', 'rxpdo' + */ +function addPdoObjectsSection(od, odSection, pdo){ + var currentSMoffsetValue = pdo.smOffset; + const indexes = getUsedIndexes(odSection); + + if (indexes.length) { + const pdoAssignments = ensurePDOAssignmentExists(od, pdo.SMassignmentIndex); + + indexes.forEach(index => { + const objd = odSection[index]; + const currentOffset = indexToString(currentSMoffsetValue) + + const pdoMappingObj = { otype: OTYPE.RECORD, name: objd.name, items: [ + { name: 'Max SubIndex' }, + ]}; + // create PDO assignment to SM + const pdoAssignment = { name: "PDO Mapping", value: `0x${currentOffset}` }; + addPdoMapping(objd, pdo.name); + + objectlist_link_utypes(objd); + + switch (objd.otype) { + case OTYPE.VAR: { + // create PDO mapping + pdoMappingObj.items.push({ name: objd.name, dtype: DTYPE.UNSIGNED32, value: getPdoMappingValue(index, 0, objd.dtype) }); + if (objd.dtype == DTYPE.BOOLEAN) { + addBooleanPadding(pdoMappingObj.items, ++_booleanPaddingCount); + } + break; + } + case OTYPE.ARRAY: { + var subindex = 1; + objd.items.slice(subindex).forEach(subitem => { + // create PDO mappings + pdoMappingObj.items.push({ name: subitem.name, dtype: DTYPE.UNSIGNED32, value: getPdoMappingValue(index, subindex , objd.dtype) }); + // TODO handle padding on array of booleans + ++subindex; + }); + break; + } + case OTYPE.RECORD: { + var subindex = 1; + objd.items.slice(subindex).forEach(subitem => { + // create PDO mappings + pdoMappingObj.items.push({ name: subitem.name, dtype: DTYPE.UNSIGNED32, value: getPdoMappingValue(index, subindex , subitem.dtype) }); + if (subitem.dtype == DTYPE.BOOLEAN) { + addBooleanPadding(pdoMappingObj.items, ++_booleanPaddingCount); + } + ++subindex; + }); + break; + } + default: { + alert(`${pdoMappingValue} object ${index} ${objd.name} has unexpected object type ${objd.otype}!`); + break; + }} + + addObject(od, pdoMappingObj, currentOffset); + pdoAssignments.items.push(pdoAssignment); + + addObject(od, objd, index); + + ++currentSMoffsetValue; + }); + + function addBooleanPadding(mappingOjbItems, paddingCount) { + mappingOjbItems.push({ name: `Padding ${paddingCount}`, dtype: DTYPE.UNSIGNED32, value: `0x0000000${booleanPaddingBitsize}` }); + } + } + + function addPdoMapping(objd, pdoName) { + // make sure there is space + if (!objd.pdo_mappings) { + objd.pdo_mappings = []; + } + // mark object as PDO mapped, if it is not already + if(!isInArray(objd.pdo_mappings, pdoName)) { + objd.pdo_mappings.push(pdoName); + } + } + + function ensurePDOAssignmentExists(od, index) { + var pdoAssignments = od[index]; + if (!pdoAssignments) { + pdoAssignments = { otype: OTYPE.ARRAY, dtype: DTYPE.UNSIGNED16, name: `Sync Manager ${index[3]} PDO Assignment`, items: [ + { name: 'Max SubIndex' }, + ]}; + od[index] = pdoAssignments; + } + return pdoAssignments; + } + + function getPdoMappingValue(index, subindex, dtype) { + function toByte(value) { + var result = value.toString(16).slice(0, 2); + while (result.length < 2) { + result = `0${result}`; + } + return result; + } + var bitsize = esiDTbitsize(dtype); + + return `0x${index}${toByte(subindex)}${toByte(bitsize)}`; + } +} +/** populates mandatory objects with values from UI */ +function populateMandatoryObjectValues(form, od) { + if (form) { + od['1008'].data = form.TextDeviceName.value; + od['1009'].data = form.HWversion.value; + od['100A'].data = form.SWversion.value; + od['1018'].items[1].value = parseInt(form.VendorID.value); + od['1018'].items[2].value = parseInt(form.ProductCode.value); + od['1018'].items[3].value = parseInt(form.RevisionNumber.value); + od['1018'].items[4].value = parseInt(form.SerialNumber.value); + } +} +/** builds complete object dictionary, with values from UI */ +function buildObjectDictionary(form) { + const od = getMandatoryObjects(); + populateMandatoryObjectValues(form, od); + // populate custom objects + addSDOitems(od); + addTXPDOitems(od); + addRXPDOitems(od); + _booleanPaddingCount = 0; + + return od; +} + +// ####################### Object Dictionary index manipulation ####################### // + +function indexToString(index) { + var indexValue = parseInt(index); + return indexValue.toString(16).toUpperCase(); +} +/** returns list of indexes that are used in given OD, as array of integer values */ +function getUsedIndexes(od) { + const index_min = 0x1000; + const index_max = 0xFFFF; + const usedIndexes = []; + // scan index address space for ones used + for (let i = index_min; i <= index_max; i++) { + const index = indexToString(i); + const element = od[index]; + if (element) { + usedIndexes.push(index); + } + } + return usedIndexes; +} + +// ####################### Object Dictionary edition ####################### // + +function getFirstFreeIndex(odSectionName) { + var addressRangeStart = { + "sdo": 0x2000, + "txpdo": 0x6000, + "rxpdo": 0x7000, + } + var result = addressRangeStart[odSectionName]; + var odSection = getObjDictSection(odSectionName); + while (odSection[indexToString(result)]) { + result++; + } + + return indexToString(result); +} +/** returns new object description for given PDO section */ +function getNewObjd(odSectionName, otype) { + const readableNames = { + VAR: 'Variable', + ARRAY: 'Array', + RECORD: 'Record' + } + const objd = { + otype: otype, + name: `New ${readableNames[otype]}`, + access: 'RO', + }; + switch(otype) { + case OTYPE.ARRAY: { + objd.items = [ + { name: 'Max SubIndex' }, + ]; + addArraySubitem(objd); + break; + } + case OTYPE.RECORD: { + objd.items = [ + { name: 'Max SubIndex' }, + ]; + addRecordSubitem(objd); + break; + }} + if (odSectionName == txpdo || odSectionName == rxpdo) { + objd.pdo_mappings = [ odSectionName ]; + } + return objd; +} + +function addArraySubitem(objd) { + if (objd.otype != OTYPE.ARRAY) { alert(`${objd} is not ARRAY, cannot add subitem`); return; } + if (!objd.items) { alert(`${objd} does not have items list, cannot add subitem`); return; } + const newSubitem = { name: 'New array subitem' } + objd.items.push(newSubitem); + + return newSubitem; +} + +function addRecordSubitem(objd) { + if (objd.otype != OTYPE.RECORD) { alert(`${objd} is not RECORD, cannot add subitem`); return; } + if (!objd.items) { alert(`${objd} does not have items list, cannot add subitem`); return; } + + const default_subitemDT = DTYPE.UNSIGNED8; // first from list + const newSubitem = { name: 'New record subitem', dtype: default_subitemDT } + objd.items.push(newSubitem); + + return newSubitem; +} diff --git a/Pcb-1-lan9252/EEPROM_generator/src/ui.js b/Pcb-1-lan9252/EEPROM_generator/src/ui.js new file mode 100644 index 0000000..33b5421 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/src/ui.js @@ -0,0 +1,627 @@ +/** + * SOES EEPROM generator + * UI behavior logic + +* This tool serves as: +- EtherCAT Slave Information XML + EEPROM binary generator +- SOES code generator + + * Victor Sluiter 2013-2018 + * Kuba Buda 2020-2021 + */ +'use strict' + +// ####################### UI changes handlers ####################### // + +function getForm() { + return document.getElementById("SlaveForm"); +} + +function getOutputForm() { + return document.getElementById("outCodeForm"); +} + +function onFormChanged() { + const form = getForm(); + saveLocalBackup(form); + processForm(form); +} + +/** Shortcuts: + * Ctrl + S to save project + * Ctrl + O to load save file + * Shortcuts start to work after user clicked on page + */ +document.onkeydown = function(e) { + const S_keyCode = 83; + const O_keyCode = 79; + if (e.ctrlKey){ + if (e.keyCode === S_keyCode) { + event.preventDefault(); + onSaveClick(); + return false; + } + else if (e.keyCode == O_keyCode) { + event.preventDefault(); + onRestoreClick(); + return false; + } + } +}; + +// When the user clicks anywhere outside of the modal, close it +window.onclick = function(event) { + if (event.target == odModal) { + odModalClose(); + } +} + +window.onload = (event) => { + odModalSetup(); + syncModalSetup(); + const form = getForm(); + setFormValues(form, getFormDefaultValues()); + tryRestoreLocalBackup(form); + // for convinience during tool development, trigger codegen on page refresh + processForm(form); + + const _isComputerFast = automaticCodegen; + + if (_isComputerFast) { + // code is regenerated on every form change. + // no need to remember to generate before copying or downloading + // app is noticeably slower + + processForm(form); // make sure displayed code is up to date at startup, e.g redo, if it came from backup + + document.getElementById('GenerateFilesButton').style.display = 'none'; // 'generate' button no longer needed + form.addEventListener('change', function() { + onFormChanged(); + }); + } + setupDarkMode(); +} + + +// ####################### dark mode logic ####################### // +function setupDarkMode() { + if (!localStorage.darkMode) { + localStorage.darkMode = 'dark'; // dark mode by default + } + document.documentElement.setAttribute("data-theme", localStorage.darkMode); +} + +function toggleDarkMode() { + var newMode = (localStorage.darkMode == 'dark') ? "light" : "dark" + localStorage.darkMode = newMode; + document.documentElement.setAttribute("data-theme", localStorage.darkMode); +} + +// ####################### code generation UI logic ####################### // + +/** Code generation method, triggered by UI */ +function processForm(form) +{ + const od = buildObjectDictionary(form); + const indexes = getUsedIndexes(od); + var outputCtl = getOutputForm(); + + outputCtl.objectlist.value = objectlist_generator(form, od, indexes); + outputCtl.ecat_options.value = ecat_options_generator(form, od, indexes); + outputCtl.utypes.value = utypes_generator(form, od, indexes); + outputCtl.HEX.hexData = hex_generator(form); + outputCtl.HEX.value = toIntelHex(outputCtl.HEX.hexData); + outputCtl.ESI.value = esi_generator(form, od, indexes, _dc); + + saveLocalBackup(form); + + return outputCtl; +} + +// ####################### Button handlers ####################### // +function getProjectName(form) { + return variableName(form.TextDeviceName.value); +} + +function onGenerateDownloadClick() +{ + const form = getForm(); + var result = processForm(form); + downloadGeneratedFilesZipped(form, result); + + function downloadGeneratedFilesZipped(form, result) { + var zip = new JSZip(); + const projectName = getProjectName(form); + zip.file(`${projectName}.xml`, result.ESI.value); + zip.file('eeprom.hex', result.HEX.value); + zip.file('eeprom.bin', result.HEX.hexData); + zip.file('ecat_options.h', result.ecat_options.value); + zip.file('objectlist.c', result.objectlist.value); + zip.file('utypes.h', result.utypes.value); + zip.file('esi.json', prepareBackupFileContent(form)); + + zip.generateAsync({type:"blob"}).then(function (blob) { // generate the zip file + downloadFile(blob, "esi.zip", "application/zip"); // trigger the download + }, function (err) { + console.log(err); + }); + } + + function downloadGeneratedFiles(form, result) { + const projectName = getProjectName(form); + downloadFile(result.ESI.value, `${projectName}.xml`, 'text/html'); + downloadFile(result.HEX.value, 'eeprom.hex', 'application/octet-stream'); + downloadFile(result.ecat_options.value, 'ecat_options.h', 'text/plain'); + downloadFile(result.objectlist.value, 'objectlist.c', 'text/plain'); + downloadFile(result.utypes.value, 'utypes.h', 'text/plain'); + downloadBackupFile(form); + + } +} + +function onGenerateClick() { + processForm(getForm()); +} + +function onSaveClick() { + const form = getForm(); + downloadBackupFile(form); + saveLocalBackup(form); +} + +function onRestoreClick() { + // trigger file input dialog window + document.getElementById('restoreFileInput').click(); +} + +function onRestoreComplete(fileContent) { + const form = getForm(); + restoreBackup(fileContent, form); + processForm(form); +} + +function onResetClick() { + if (confirm("Are you sure you want to reset project to default values?")){ + resetLocalBackup(); + location.reload(true); + } +} + +function onDownloadEsiXmlClick() { + const form = getForm(); + const projectName = getProjectName(form); + downloadFile(getOutputForm().ESI.value, `${projectName}.xml`, 'text/html'); +} + +function onDownloadBinClick() { + const record = getOutputForm().HEX.hexData; + if (!record) { alert("Generate code before you can download it"); return; } + downloadFile(record, 'eeprom.bin', 'application/octet-stream'); +} + +// ####################### Handle modal dialog ####################### // + +var odModal = {}; + +function odModalSetup() { + // Get the modal + odModal = document.getElementById("editObjectModal"); + if (odModal) { + odModal.form = document.getElementById('EditObjectForm'); + } + else { + alert("Element required to edit Object Dictionary not found!"); + } +} + +// When the user clicks the button, open the modal +function odModalOpen() { + odModal.style.display = "block"; +} + +function odModalClose() { + odModal.style.display = "none"; +} + +/** update control values on OD modal */ +function odModalUpdate(index, objd) { + odModal.form.Index.value = `0x${index}`; + odModal.form.ObjectName.value = objd.name; + odModal.form.DTYPE.value = objd.dtype || DTYPE.UNSIGNED8; + odModal.form.Access.value = objd.access || 'RO'; + odModal.objd = objd; +} + +function odModalHideControls() { + document.getElementById('dialogRowIndex').style.display = 'none'; + document.getElementById('dialogRowDtype').style.display = 'none'; + document.getElementById('dialogRowValue').style.display = 'none'; + document.getElementById('dialogRowAccess').style.display = 'none'; +} + +// ####################### Modal dialogs for OD edition ####################### // + +function editExistingOD_ObjectDialog(odSectionName, index, otype) { + const od = getObjDictSection(odSectionName); + var objd = od[index]; + odModal.index_initial_value = index; + checkObjectType(otype, objd); + odModalUpdate(index, objd); +} + +function addNewOD_ObjectDialog(odSectionName, otype) { + var objd = getNewObjd(odSectionName, otype); + var index = getFirstFreeIndex(odSectionName); + delete odModal.index_initial_value; // add new object, not replace edited one + odModalUpdate(index, objd); +} + +function odModalOpenForObject(otype) { + odModalHideControls(); + document.getElementById('dialogRowIndex').style.display = ''; + document.getElementById('dialogRowAccess').style.display = ''; + + switch (otype) { + case OTYPE.VAR: { + document.getElementById('dialogRowDtype').style.display = ''; + document.getElementById('dialogRowValue').style.display = ''; + break; + } + case OTYPE.ARRAY: { + document.getElementById('dialogRowDtype').style.display = ""; + break; + } + case OTYPE.RECORD: { + break; + } + default: { + alert(`Unknown object type ${otype}, cannot open modal for it!`); + return; + } + } + odModalOpen(); + document.getElementById('modalInputIndex').focus(); +} + +function odModalSetTitle(message) { + document.getElementById('editObjectTitle').innerHTML = `${message}`; +} + +// ####################### Edit Object Dictionary UI logic ####################### // + +function editVAR_Click(odSectionName, indexValue = null) { + const otype = OTYPE.VAR; + const index = indexToString(indexValue); + var actionName = "Edit"; + odModal.odSectionName = odSectionName; + + if (objectExists(odSectionName, index)) { + editExistingOD_ObjectDialog(odSectionName, index, otype); + odModal.form.DTYPE.value = odModal.objd.dtype; + } else { + addNewOD_ObjectDialog(odSectionName, otype); + actionName = "Add" + } + odModalSetTitle(`${actionName} ${odSectionName.toUpperCase()} variable`); + odModalOpenForObject(otype); +} + +function editARRAY_Click(odSectionName, indexValue = null) { + const otype = OTYPE.ARRAY; + const index = indexToString(indexValue); + var actionName = "Edit"; + odModal.odSectionName = odSectionName; + odModal.form.Access + + if (objectExists(odSectionName, index)) { + editExistingOD_ObjectDialog(odSectionName, index, otype); + odModal.form.DTYPE.value = odModal.objd.dtype; + } else { + addNewOD_ObjectDialog(odSectionName, otype); + actionName = "Add" + } + odModalSetTitle(`${actionName} ${odSectionName.toUpperCase()} array`); + odModalOpenForObject(otype); +} + +function editRECORD_Click(odSectionName, indexValue = null) { + const otype = OTYPE.RECORD; + const index = indexToString(indexValue); + var actionName = "Edit"; + odModal.odSectionName = odSectionName; + + if (objectExists(odSectionName, index)) { + editExistingOD_ObjectDialog(odSectionName, index, otype); + } else { + addNewOD_ObjectDialog(odSectionName, otype); + actionName = "Add" + } + odModalSetTitle(`${actionName} ${odSectionName.toUpperCase()} record`); + odModalOpenForObject(otype); +} + +function onEditObjectSubmit(modalform) { + if (odModal.subitem) { + onEditSubitemSubmit(odModal.subitem); + delete odModal.subitem; + return; + } + const objd = odModal.objd; + const objectType = objd.otype; + const index = indexToString(modalform.Index.value); + + objd.name = modalform.ObjectName.value; + + switch (objectType) { + case OTYPE.VAR: + objd.dtype = modalform.DTYPE.value; + + if (objd.dtype == DTYPE.VISIBLE_STRING) { + objd.data = '' + } else { + objd.value = modalform.InitalValue.value; + } + break; + case OTYPE.ARRAY: + objd.dtype = modalform.DTYPE.value; + + break; + case OTYPE.RECORD: + + break; + default: + alert(`Unexpected type ${objectType} on object ${modalform.ObjectName} being edited!`); + break; + } + const odSection = getObjDictSection(odModal.odSectionName); + if (odModal.index_initial_value) { + removeObject(odSection, odModal.index_initial_value); // detach from OD, to avoid duplicate if index changed + } + addObject(odSection, objd, index); // attach updated object + odModalClose(); + reloadOD_Section(odModal.odSectionName); + delete odModal.odSectionName; + odModal.objd = {}; + + onFormChanged(); +} + +function onRemoveClick(odSectionName, indexValue, subindex = null) { + const index = indexToString(indexValue); + const odSection = getObjDictSection(odSectionName); + const objd = odSection[index]; + if(!objd) { alert(`${odSectionName.toUpperCase()} object ${index} does not exist!`); return; } + + if(subindex) { + if(!objd.items) { alert(`Object 0x${index} "${objd.name}" does not have any items!`); return; } + if(objd.items.length < subindex) { alert(`Object 0x${index} "${objd.name}" does not have enough items!`); return; } + if(objd.items.length < 3) { // only max subindex and one more subitem + alert(`Object 0x${index} "${objd.name}" has only 1 subitem, it should not be empty. Remove entire object instead.`); return; } + } + + if (confirm(getConfirmMessage(objd, index, subindex))) { + + if (subindex) { + const subitemsToRemove = 1; + objd.items.splice(subindex, subitemsToRemove); + } else { + removeObject(odSection, index); + } + reloadOD_Section(odSectionName); + onFormChanged(); + } + + function getConfirmMessage(objd, index, subindex) { + if (subindex) { + return `Are you sure you want to remove subitem ${subindex} "${objd.items[subindex].name }" from object 0x${index} "${objd.name}"?` + } + return `Are you sure you want to remove object 0x${index} "${objd.name}"?` + } +} + +function addSubitemClick(odSectionName, indexValue) { + const index = indexToString(indexValue); + const odSection = getObjDictSection(odSectionName); + const objd = odSection[index]; + + // we expect objd to have items array with at least [{ name: 'Max SubIndex' }] + if(!objd.items || !objd.items.length ) { alert(`Object ${index} "${objd.name}" has no subitems!`); return; } + + switch(objd.otype) { + case OTYPE.ARRAY: { + addArraySubitem(objd); + break; + } + case OTYPE.RECORD: { + addRecordSubitem(objd); + break; + } + default: { + alert(`Object ${index} "${objd.name}" has OTYPE ${objd.otype} so cannot add subitems`); + } + } + const subindex = objd.items.length - 1; // subitem is added to end of items list + editSubitemClick(odSectionName, indexValue, subindex, "Add"); +} + +function editSubitemClick(odSectionName, indexValue, subindex, actionName = "Edit") { + const index = indexToString(indexValue); + const odSection = getObjDictSection(odSectionName); + const objd = odSection[index]; + + if(!objd.items || objd.items.length <= subindex ) { alert(`Object ${index} "${objd.name}" does not have ${subindex} subitems!`); return; } + + odModalSetTitle(`${actionName} ${odSectionName.toUpperCase()} object 0x${index} "${objd.name}" subitem 0x${indexToString(subindex)}`); + + const subitem = objd.items[subindex]; + + odModalHideControls(); + + document.getElementById('dialogRowValue').style.display = ""; + odModal.form.InitalValue.value = subitem.value ?? 0; + + if (objd.otype == OTYPE.RECORD) { + document.getElementById('dialogRowDtype').style.display = ""; + odModal.form.DTYPE.value = subitem.dtype; + document.getElementById('dialogRowAccess').style.display = ''; // access for record subitems can differ + odModal.form.Access.value = subitem.access || 'RO'; + } + odModal.form.ObjectName.value = subitem.name; + odModal.subitem = { odSectionName: odSectionName, index: index, subindex: subindex }; + odModalOpen(); + document.getElementById('modalInputObjectName').focus(); +} + +function onEditSubitemSubmit(modalSubitem) { + const odSection = getObjDictSection(modalSubitem.odSectionName); + const objd = odSection[modalSubitem.index]; + const subitem = objd.items[modalSubitem.subindex]; + + subitem.name = odModal.form.ObjectName.value; + subitem.value = odModal.form.InitalValue.value; + if (objd.otype == OTYPE.RECORD) { + subitem.dtype = odModal.form.DTYPE.value; + subitem.access = odModal.form.Access.value; + } + odModalClose(); + onFormChanged(); + reloadOD_Section(modalSubitem.odSectionName); +} + +// ####################### Display Object Dictionary state ####################### // + +function reloadOD_Sections() { + reloadOD_Section(sdo); + reloadOD_Section(txpdo); + reloadOD_Section(rxpdo); +} + +function reloadOD_Section(odSectionName) { + const odSection = getObjDictSection(odSectionName); + var indexes = getUsedIndexes(odSection); + var section = ''; + indexes.forEach(index => { + const objd = odSection[index]; + section += `
0x${index}     "${objd.name}" ${objd.otype} ${objd.dtype ?? ''}`; + if (objd.otype == OTYPE.ARRAY || objd.otype == OTYPE.RECORD) { + section += ``; + } + section += ``; + section += ``; + section += `
`; + if (objd.items) { + var subindex = 1; // skip Max Subindex + objd.items.slice(subindex).forEach(subitem => { + var subindexHex = subindex < 16 ? `0${subindex.toString(16)}` : subindex.toString(16); + section += `
:0x${subindexHex}   "${subitem.name}" ${subitem.dtype ?? ''}`; + section += ``; + section += ``; + section += `
`; + ++subindex; + }); + } + }); + const odSectionElement = document.getElementById(`tr_${odSectionName}`); + if (odSectionElement) { + odSectionElement.innerHTML = section; + } +} + +// ####################### Synchronization settings UI ####################### // + +var syncModal = {}; +var _dc = [] + +function syncModalSetup() { + // Get the modal + syncModal = document.getElementById("syncModal"); + if (syncModal) { + syncModal.form = document.getElementById('syncModalForm'); + } + else { + alert("Element required to edit Object Dictionary not found!"); + } +} + +function syncModalClose() { + syncModal.style.display = "none"; + delete syncModal.edited; + reloadSyncModes(); +} + +function syncModalOpen() { + syncModal.style.display = "block"; +} + +function syncModeEdit(sync) { + syncModal.edited = sync; + + syncModal.form.Name.value = sync.Name; + syncModal.form.Description.value = sync.Description; + syncModal.form.AssignActivate.value = sync.AssignActivate; + syncModal.form.Sync0cycleTime.value = sync.Sync0cycleTime; + syncModal.form.Sync0shiftTime.value = sync.Sync0shiftTime; + syncModal.form.Sync1cycleTime.value = sync.Sync1cycleTime; + syncModal.form.Sync1shiftTime.value = sync.Sync1shiftTime; + + syncModalOpen(); +} + +function onSyncSubmit(syncForm) { + + syncModal.edited.Name = syncForm.Name.value; + syncModal.edited.Description = syncForm.Description.value; + syncModal.edited.AssignActivate = syncForm.AssignActivate.value; + syncModal.edited.Sync0cycleTime = syncForm.Sync0cycleTime.value; + syncModal.edited.Sync0shiftTime = syncForm.Sync0shiftTime.value; + syncModal.edited.Sync1cycleTime = syncForm.Sync1cycleTime.value; + syncModal.edited.Sync1shiftTime = syncForm.Sync1shiftTime.value; + + syncModalClose(); + onFormChanged(); +} + +// ####################### Synchronization settings button handlers ####################### // + +function addSyncClick() { + const newSyncMode = { + Name: "DcOff", + Description: "DC unused", + AssignActivate: "#x000", + Sync0cycleTime: 0, + Sync0shiftTime: 0, + Sync1cycleTime: 0, + Sync1shiftTime: 0, + } + _dc.push(newSyncMode); + syncModeEdit(newSyncMode); +} + +function onEditSyncClick(i) { + const syncMode = _dc[i]; + syncModeEdit(syncMode); +} + +function onRemoveSyncClick(i) { + _dc.splice(i, 1); + reloadSyncModes(); + onFormChanged(); +} + +// ####################### Synchronization settings UI ####################### // + +function reloadSyncModes() { + var section = ''; + var i = 0; + _dc.forEach(sync => { + section += `
${sync.Name}     ${sync.Description}   [${sync.AssignActivate}]`; + section += ``; + section += ``; + section += `
`; + ++i; + }); + const sectionElement = document.getElementById(`dcSyncModes`); + if (sectionElement) { + sectionElement.innerHTML = section; + } +} \ No newline at end of file diff --git a/Pcb-1-lan9252/EEPROM_generator/styles/styles.css b/Pcb-1-lan9252/EEPROM_generator/styles/styles.css new file mode 100644 index 0000000..4800409 --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/styles/styles.css @@ -0,0 +1,195 @@ +:root { + --background-color: #fff; + --text-color: #000; + --input-color: #ffffff; + --display-dark: none; + --display-light: block; +} + +/* dark mode */ +[data-theme="dark"] { +/* body, .modal-content { */ + --background-color: #2D2D2D; /* #4D4D4D; */ + --text-color: white; + --input-color: #3D3D3D; + --display-dark: block; + --display-light: none; +} + +tr td:nth-child(3) { + text-align: center; +} +tr td:nth-child(4) { + text-align: center; +} +tr td:nth-child(5) { + text-align: center; +} +tr td:nth-child(6) { + text-align: center; +} +/* The Modal (background) */ +.modal { + display: none; /* Hidden by default */ + position: fixed; /* Stay in place */ + z-index: 1; /* Sit on top */ + padding-top: 18%; /* Location of the box */ + left: 0; + top: 0; + width: 100%; /* Full width */ + height: 100%; /* Full height */ + overflow: auto; /* Enable scroll if needed */ + background-color: rgb(0,0,0); /* Fallback color */ + background-color: rgba(0,0,0,0.4); /* Black w/ opacity */ +} + +/* Modal Content */ +.modal-content { + background-color: var(--background-color); + margin: auto; + padding: 20px; + border: 1px solid #888; + width: 450px; +} + +#editObjectTitle { + margin-bottom: 25px; +} + +/* The Close Button */ +.close { + color: #aaaaaa; + float: right; + font-size: 28px; + font-weight: bold; +} + +.close:hover, +.close:focus { + color: #000; + text-decoration: none; + cursor: pointer; +} + +/* Dropdown Button */ +.dropbtn { + padding: 6px 16px; + } + + /* The container
- needed to position the dropdown content */ + .dropdown { + position: relative; + display: inline-block; + } + + /* Dropdown Content (Hidden by Default) */ + .dropdown-content { + display: none; + position: absolute; + background-color: var(--background-color); + box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2); + z-index: 1; + } + + /* Links inside the dropdown */ + .dropdown-content a { + /* width: 100; */ + text-decoration: none; + margin: 10px 4px; + } + + /* Change color of dropdown links on hover */ + .dropdown-content a:hover {background-color: #ddd;} + + /* Show the dropdown menu on hover */ + .dropdown:hover .dropdown-content {display: block;} + + /* Change the background color of the dropdown button when the dropdown content is shown */ + .dropdown:hover .dropbtn {background-color: var(--background-color);} + +/* main content layout */ + +body { + font-family: Arial, Helvetica, sans-serif; + font-size: large; +} + +div.main-wrapper { + margin: auto; + max-width: 960px; +} + +h1, h2, h3 { + text-align: center; +} + +table, textarea { + width: 100%; +} + +button { + margin-left: 5px; + margin-right: 5px; +} + +div.settings-menu { + display: flex; + justify-content: space-between; + /* align-items: right; */ + /* background-color: red; */ +} + +.odSectionHeading, .odItem, .odSubitem { + display: flex; + align-items: center; + justify-content: space-between; +} + +div.odItem, div.odSubitem { + padding-top: 4px; + padding-bottom: 4px; + width: 100%; + border-top: 1px dotted; + border-bottom: 1px dotted; +} + +h3.odSectionHeading { + text-align: left; +} + +span.odSectionTitle { + font-weight: 800; + margin-top: 10px; + margin-right: -5px; +} + +span.odSubitemContent { + margin-left: 15px; +} + +body { + background-color: var(--background-color); + color: var(--text-color); +} + +input, textarea, select, button { + background-color: var(--input-color); + color: var(--text-color); +} + +.display-dark { + display: var(--display-dark); +} + +.display-light { + display: var(--display-light); +} + +a { + color: var(--text-color); + font-weight: 600; +} + +button { + font-size: 16px; +} \ No newline at end of file diff --git a/Pcb-1-lan9252/EEPROM_generator/tests.html b/Pcb-1-lan9252/EEPROM_generator/tests.html new file mode 100644 index 0000000..2b7f09c --- /dev/null +++ b/Pcb-1-lan9252/EEPROM_generator/tests.html @@ -0,0 +1,37 @@ + + + + + SOES EEPROM Generator spec runner + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +