Input:
! This is a private undocumented service ! [CODESPLIT] function Browser ( window , document , $log , $sniffer ) { var self = this , rawDocument = document [ 0 ] , location = window . location , history = window . history , setTimeout = window . setTimeout , clearTimeout = window . clearTimeout , pendingDeferIds = { } ; self . isMock = false ; var outstandingRequestCount = 0 ; var outstandingRequestCallbacks = [ ] ; // TODO(vojta): remove this temporary api self . $$completeOutstandingRequest = completeOutstandingRequest ; self . $$incOutstandingRequestCount = function ( ) { outstandingRequestCount ++ ; } ; /**
   * Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
   * counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
   */ function completeOutstandingRequest ( fn ) { try { fn . apply ( null , sliceArgs ( arguments , 1 ) ) ; } finally { outstandingRequestCount -- ; if ( outstandingRequestCount === 0 ) { while ( outstandingRequestCallbacks . length ) { try { outstandingRequestCallbacks . pop ( ) ( ) ; } catch ( e ) { $log . error ( e ) ; } } } } } /**
   * @private
   * Note: this method is used only by scenario runner
   * TODO(vojta): prefix this method with $$ ?
   * @param {function()} callback Function that will be called when no outstanding request
   */ self . notifyWhenNoOutstandingRequests = function ( callback ) { // force browser to execute all pollFns - this is needed so that cookies and other pollers fire // at some deterministic time in respect to the test runner's actions. Leaving things up to the // regular poller would result in flaky tests. forEach ( pollFns , function ( pollFn ) { pollFn ( ) ; } ) ; if ( outstandingRequestCount === 0 ) { callback ( ) ; } else { outstandingRequestCallbacks . push ( callback ) ; } } ; ////////////////////////////////////////////////////////////// // Poll Watcher API ////////////////////////////////////////////////////////////// var pollFns = [ ] , pollTimeout ; /**
   * @name ng.$browser#addPollFn
   * @methodOf ng.$browser
   *
   * @param {function()} fn Poll function to add
   *
   * @description
   * Adds a function to the list of functions that poller periodically executes,
   * and starts polling if not started yet.
   *
   * @returns {function()} the added function
   */ self . addPollFn = function ( fn ) { if ( isUndefined ( pollTimeout ) ) startPoller ( 100 , setTimeout ) ; pollFns . push ( fn ) ; return fn ; } ; /**
   * @param {number} interval How often should browser call poll functions (ms)
   * @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
   *
   * @description
   * Configures the poller to run in the specified intervals, using the specified
   * setTimeout fn and kicks it off.
   */ function startPoller ( interval , setTimeout ) { ( function check ( ) { forEach ( pollFns , function ( pollFn ) { pollFn ( ) ; } ) ; pollTimeout = setTimeout ( check , interval ) ; } ) ( ) ; } ////////////////////////////////////////////////////////////// // URL API ////////////////////////////////////////////////////////////// var lastBrowserUrl = location . href , baseElement = document . find ( 'base' ) , replacedUrl = null ; /**
   * @name ng.$browser#url
   * @methodOf ng.$browser
   *
   * @description
   * GETTER:
   * Without any argument, this method just returns current value of location.href.
   *
   * SETTER:
   * With at least one argument, this method sets url to new value.
   * If html5 history api supported, pushState/replaceState is used, otherwise
   * location.href/location.replace is used.
   * Returns its own instance to allow chaining
   *
   * NOTE: this api is intended for use only by the $location service. Please use the
   * {@link ng.$location $location service} to change url.
   *
   * @param {string} url New url (when used as setter)
   * @param {boolean=} replace Should new url replace current history record ?
   */ self . url = function ( url , replace ) { // setter if ( url ) { if ( lastBrowserUrl == url ) return ; lastBrowserUrl = url ; if ( $sniffer . history ) { if ( replace ) history . replaceState ( null , '' , url ) ; else { history . pushState ( null , '' , url ) ; // Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462 baseElement . attr ( 'href' , baseElement . attr ( 'href' ) ) ; } } else { if ( replace ) { location . replace ( url ) ; replacedUrl = url ; } else { location . href = url ; replacedUrl = null ; } } return self ; // getter } else { // - the replacedUrl is a workaround for an IE8-9 issue with location.replace method that doesn't update //   location.href synchronously // - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172 return replacedUrl || location . href . replace ( / %27 / g , "'" ) ; } } ; var urlChangeListeners = [ ] , urlChangeInit = false ; function fireUrlChange ( ) { if ( lastBrowserUrl == self . url ( ) ) return ; lastBrowserUrl = self . url ( ) ; forEach ( urlChangeListeners , function ( listener ) { listener ( self . url ( ) ) ; } ) ; } /**
   * @name ng.$browser#onUrlChange
   * @methodOf ng.$browser
   * @TODO(vojta): refactor to use node's syntax for events
   *
   * @description
   * Register callback function that will be called, when url changes.
   *
   * It's only called when the url is changed by outside of angular:
   * - user types different url into address bar
   * - user clicks on history (forward/back) button
   * - user clicks on a link
   *
   * It's not called when url is changed by $browser.url() method
   *
   * The listener gets called with new url as parameter.
   *
   * NOTE: this api is intended for use only by the $location service. Please use the
   * {@link ng.$location $location service} to monitor url changes in angular apps.
   *
   * @param {function(string)} listener Listener function to be called when url changes.
   * @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
   */ self . onUrlChange = function ( callback ) { if ( ! urlChangeInit ) { // We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera) // don't fire popstate when user change the address bar and don't fire hashchange when url // changed by push/replaceState // html5 history api - popstate event if ( $sniffer . history ) jqLite ( window ) . on ( 'popstate' , fireUrlChange ) ; // hashchange event if ( $sniffer . hashchange ) jqLite ( window ) . on ( 'hashchange' , fireUrlChange ) ; // polling else self . addPollFn ( fireUrlChange ) ; urlChangeInit = true ; } urlChangeListeners . push ( callback ) ; return callback ; } ; ////////////////////////////////////////////////////////////// // Misc API ////////////////////////////////////////////////////////////// /**
   * @name ng.$browser#baseHref
   * @methodOf ng.$browser
   *
   * @description
   * Returns current <base href>
   * (always relative - without domain)
   *
   * @returns {string=} current <base href>
   */ self . baseHref = function ( ) { var href = baseElement . attr ( 'href' ) ; return href ? href . replace ( / ^https?\:\/\/[^\/]* / , '' ) : '' ; } ; ////////////////////////////////////////////////////////////// // Cookies API ////////////////////////////////////////////////////////////// var lastCookies = { } ; var lastCookieString = '' ; var cookiePath = self . baseHref ( ) ; /**
   * @name ng.$browser#cookies
   * @methodOf ng.$browser
   *
   * @param {string=} name Cookie name
   * @param {string=} value Cookie value
   *
   * @description
   * The cookies method provides a 'private' low level access to browser cookies.
   * It is not meant to be used directly, use the $cookie service instead.
   *
   * The return values vary depending on the arguments that the method was called with as follows:
   *

   *
cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify it

   *
cookies(name, value) -> set name to value, if value is undefined delete the cookie

   *
cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that way)

   *

   *
   * @returns {Object} Hash of all cookies (if called without any parameter)
   */ self . cookies = function ( name , value ) { var cookieLength , cookieArray , cookie , i , index ; if ( name ) { if ( value === undefined ) { rawDocument . cookie = escape ( name ) + "=;path=" + cookiePath + ";expires=Thu, 01 Jan 1970 00:00:00 GMT" ; } else { if ( isString ( value ) ) { cookieLength = ( rawDocument . cookie = escape ( name ) + '=' + escape ( value ) + ';path=' + cookiePath ) . length + 1 ; // per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum: // - 300 cookies // - 20 cookies per unique domain // - 4096 bytes per cookie if ( cookieLength > 4096 ) { $log . warn ( "Cookie '" + name + "' possibly not set or overflowed because it was too large (" + cookieLength + " > 4096 bytes)!" ) ; } } } } else { if ( rawDocument . cookie !== lastCookieString ) { lastCookieString = rawDocument . cookie ; cookieArray = lastCookieString . split ( "; " ) ; lastCookies = { } ; for ( i = 0 ; i < cookieArray . length ; i ++ ) { cookie = cookieArray [ i ] ; index = cookie . indexOf ( '=' ) ; if ( index > 0 ) { //ignore nameless cookies var name = unescape ( cookie . substring ( 0 , index ) ) ; // the first value that is seen for a cookie is the most // specific one.  values for the same cookie name that // follow are for less specific paths. if ( lastCookies [ name ] === undefined ) { lastCookies [ name ] = unescape ( cookie . substring ( index + 1 ) ) ; } } } } return lastCookies ; } } ; /**
   * @name ng.$browser#defer
   * @methodOf ng.$browser
   * @param {function()} fn A function, who's execution should be deferred.
   * @param {number=} [delay=0] of milliseconds to defer the function execution.
   * @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
   *
   * @description
   * Executes a fn asynchronously via `setTimeout(fn, delay)`.
   *
   * Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
   * `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
   * via `$browser.defer.flush()`.
   *
   */ self . defer = function ( fn , delay ) { var timeoutId ; outstandingRequestCount ++ ; timeoutId = setTimeout ( function ( ) { delete pendingDeferIds [ timeoutId ] ; completeOutstandingRequest ( fn ) ; } , delay || 0 ) ; pendingDeferIds [ timeoutId ] = true ; return timeoutId ; } ; /**
   * @name ng.$browser#defer.cancel
   * @methodOf ng.$browser.defer
   *
   * @description
   * Cancels a deferred task identified with `deferId`.
   *
   * @param {*} deferId Token returned by the `$browser.defer` function.
   * @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully canceled.
   */ self . defer . cancel = function ( deferId ) { if ( pendingDeferIds [ deferId ] ) { delete pendingDeferIds [ deferId ] ; clearTimeout ( deferId ) ; completeOutstandingRequest ( noop ) ; return true ; } return false ; } ; }


Input: Set a normalized attribute on the element in a way such that all directives can share the attribute . This function properly handles boolean attributes . [CODESPLIT] function ( key , value , writeAttr , attrName ) { //special case for class attribute addition + removal //so that class changes can tap into the animation //hooks provided by the $animate service if ( key == 'class' ) { value = value || '' ; var current = this . $$element . attr ( 'class' ) || '' ; this . $removeClass ( tokenDifference ( current , value ) . join ( ' ' ) ) ; this . $addClass ( tokenDifference ( value , current ) . join ( ' ' ) ) ; } else { var booleanKey = getBooleanAttrName ( this . $$element [ 0 ] , key ) , normalizedVal , nodeName ; if ( booleanKey ) { this . $$element . prop ( key , value ) ; attrName = booleanKey ; } this [ key ] = value ; // translate normalized key to actual key if ( attrName ) { this . $attr [ key ] = attrName ; } else { attrName = this . $attr [ key ] ; if ( ! attrName ) { this . $attr [ key ] = attrName = snake_case ( key , '-' ) ; } } nodeName = nodeName_ ( this . $$element ) ; // sanitize a[href] and img[src] values if ( ( nodeName === 'A' && key === 'href' ) || ( nodeName === 'IMG' && key === 'src' ) ) { // NOTE: $$urlUtils.resolve() doesn't support IE < 8 so we don't sanitize for that case. if ( ! msie || msie >= 8 ) { normalizedVal = $$urlUtils . resolve ( value ) ; if ( normalizedVal !== '' ) { if ( ( key === 'href' && ! normalizedVal . match ( aHrefSanitizationWhitelist ) ) || ( key === 'src' && ! normalizedVal . match ( imgSrcSanitizationWhitelist ) ) ) { this [ key ] = value = 'unsafe:' + normalizedVal ; } } } } if ( writeAttr !== false ) { if ( value === null || value === undefined ) { this . $$element . removeAttr ( attrName ) ; } else { this . $$element . attr ( attrName , value ) ; } } } // fire observers var $$observers = this . $$observers ; $$observers && forEach ( $$observers [ key ] , function ( fn ) { try { fn ( value ) ; } catch ( e ) { $exceptionHandler ( e ) ; } } ) ; function tokenDifference ( str1 , str2 ) { var values = [ ] , tokens1 = str1 . split ( / \s+ / ) , tokens2 = str2 . split ( / \s+ / ) ; outer : for ( var i = 0 ; i < tokens1 . length ; i ++ ) { var token = tokens1 [ i ] ; for ( var j = 0 ; j < tokens2 . length ; j ++ ) { if ( token == tokens2 [ j ] ) continue outer ; } values . push ( token ) ; } return values ; } ; }


Input: Compile function matches each node in nodeList against the directives . Once all directives for a particular node are collected their compile functions are executed . The compile functions return values - the linking functions - are combined into a composite linking function which is the a linking function for the node . [CODESPLIT] function compileNodes ( nodeList , transcludeFn , $rootElement , maxPriority , ignoreDirective ) { var linkFns = [ ] , nodeLinkFn , childLinkFn , directives , attrs , linkFnFound ; for ( var i = 0 ; i < nodeList . length ; i ++ ) { attrs = new Attributes ( ) ; // we must always refer to nodeList[i] since the nodes can be replaced underneath us. directives = collectDirectives ( nodeList [ i ] , [ ] , attrs , i == 0 ? maxPriority : undefined , ignoreDirective ) ; nodeLinkFn = ( directives . length ) ? applyDirectivesToNode ( directives , nodeList [ i ] , attrs , transcludeFn , $rootElement ) : null ; childLinkFn = ( nodeLinkFn && nodeLinkFn . terminal || ! nodeList [ i ] . childNodes || ! nodeList [ i ] . childNodes . length ) ? null : compileNodes ( nodeList [ i ] . childNodes , nodeLinkFn ? nodeLinkFn . transclude : transcludeFn ) ; linkFns . push ( nodeLinkFn ) ; linkFns . push ( childLinkFn ) ; linkFnFound = ( linkFnFound || nodeLinkFn || childLinkFn ) ; } // return a linking function if we have found anything, null otherwise return linkFnFound ? compositeLinkFn : null ; function compositeLinkFn ( scope , nodeList , $rootElement , boundTranscludeFn ) { var nodeLinkFn , childLinkFn , node , childScope , childTranscludeFn , i , ii , n ; // copy nodeList so that linking doesn't break due to live list updates. var stableNodeList = [ ] ; for ( i = 0 , ii = nodeList . length ; i < ii ; i ++ ) { stableNodeList . push ( nodeList [ i ] ) ; } for ( i = 0 , n = 0 , ii = linkFns . length ; i < ii ; n ++ ) { node = stableNodeList [ n ] ; nodeLinkFn = linkFns [ i ++ ] ; childLinkFn = linkFns [ i ++ ] ; if ( nodeLinkFn ) { if ( nodeLinkFn . scope ) { childScope = scope . $new ( isObject ( nodeLinkFn . scope ) ) ; jqLite ( node ) . data ( '$scope' , childScope ) ; } else { childScope = scope ; } childTranscludeFn = nodeLinkFn . transclude ; if ( childTranscludeFn || ( ! boundTranscludeFn && transcludeFn ) ) { nodeLinkFn ( childLinkFn , childScope , node , $rootElement , ( function ( transcludeFn ) { return function ( cloneFn ) { var transcludeScope = scope . $new ( ) ; transcludeScope . $$transcluded = true ; return transcludeFn ( transcludeScope , cloneFn ) . on ( '$destroy' , bind ( transcludeScope , transcludeScope . $destroy ) ) ; } ; } ) ( childTranscludeFn || transcludeFn ) ) ; } else { nodeLinkFn ( childLinkFn , childScope , node , undefined , boundTranscludeFn ) ; } } else if ( childLinkFn ) { childLinkFn ( scope , node . childNodes , undefined , boundTranscludeFn ) ; } } } }


Input: Wrapper for linking function which converts normal linking function into a grouped linking function . [CODESPLIT] function groupElementsLinkFnWrapper ( linkFn , attrStart , attrEnd ) { return function ( scope , element , attrs , controllers ) { element = groupScan ( element [ 0 ] , attrStart , attrEnd ) ; return linkFn ( scope , element , attrs , controllers ) ; } }


Input: ////////////////// [CODESPLIT] function addLinkFns ( pre , post , attrStart , attrEnd ) { if ( pre ) { if ( attrStart ) pre = groupElementsLinkFnWrapper ( pre , attrStart , attrEnd ) ; pre . require = directive . require ; preLinkFns . push ( pre ) ; } if ( post ) { if ( attrStart ) post = groupElementsLinkFnWrapper ( post , attrStart , attrEnd ) ; post . require = directive . require ; postLinkFns . push ( post ) ; } }


Input: This is a special jqLite . replaceWith which can replace items which have no parents provided that the containing jqLite collection is provided . [CODESPLIT] function replaceWith ( $rootElement , elementsToRemove , newNode ) { var firstElementToRemove = elementsToRemove [ 0 ] , removeCount = elementsToRemove . length , parent = firstElementToRemove . parentNode , i , ii ; if ( $rootElement ) { for ( i = 0 , ii = $rootElement . length ; i < ii ; i ++ ) { if ( $rootElement [ i ] == firstElementToRemove ) { $rootElement [ i ++ ] = newNode ; for ( var j = i , j2 = j + removeCount - 1 , jj = $rootElement . length ; j < jj ; j ++ , j2 ++ ) { if ( j2 < jj ) { $rootElement [ j ] = $rootElement [ j2 ] ; } else { delete $rootElement [ j ] ; } } $rootElement . length -= removeCount - 1 ; break ; } } } if ( parent ) { parent . replaceChild ( newNode , firstElementToRemove ) ; } var fragment = document . createDocumentFragment ( ) ; fragment . appendChild ( firstElementToRemove ) ; newNode [ jqLite . expando ] = firstElementToRemove [ jqLite . expando ] ; for ( var k = 1 , kk = elementsToRemove . length ; k < kk ; k ++ ) { var element = elementsToRemove [ k ] ; jqLite ( element ) . remove ( ) ; // must do this way to clean up expando fragment . appendChild ( element ) ; delete elementsToRemove [ k ] ; } elementsToRemove [ 0 ] = newNode ; elementsToRemove . length = 1 }


Input:
@ngdoc object @name ng . $controllerProvider @description The { @link ng . $controller $controller service } is used by Angular to create new controllers . [CODESPLIT] function $ControllerProvider ( ) { var controllers = { } , CNTRL_REG = / ^(\S+)(\s+as\s+(\w+))?$ / ; /**
   * @ngdoc function
   * @name ng.$controllerProvider#register
   * @methodOf ng.$controllerProvider
   * @param {string|Object} name Controller name, or an object map of controllers where the keys are
   *    the names and the values are the constructors.
   * @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
   *    annotations in the array notation).
   */ this . register = function ( name , constructor ) { if ( isObject ( name ) ) { extend ( controllers , name ) } else { controllers [ name ] = constructor ; } } ; this . $get = [ '$injector' , '$window' , function ( $injector , $window ) { /**
     * @ngdoc function
     * @name ng.$controller
     * @requires $injector
     *
     * @param {Function|string} constructor If called with a function then it's considered to be the
     *    controller constructor function. Otherwise it's considered to be a string which is used
     *    to retrieve the controller constructor using the following steps:
     *
     *    * check if a controller with given name is registered via `$controllerProvider`
     *    * check if evaluating the string on the current scope returns a constructor
     *    * check `window[constructor]` on the global `window` object
     *
     * @param {Object} locals Injection locals for Controller.
     * @return {Object} Instance of given controller.
     *
     * @description
     * `$controller` service is responsible for instantiating controllers.
     *
     * It's just a simple call to {@link AUTO.$injector $injector}, but extracted into
     * a service, so that one can override this service with {@link https://gist.github.com/1649788
     * BC version}.
     */ return function ( expression , locals ) { var instance , match , constructor , identifier ; if ( isString ( expression ) ) { match = expression . match ( CNTRL_REG ) , constructor = match [ 1 ] , identifier = match [ 3 ] ; expression = controllers . hasOwnProperty ( constructor ) ? controllers [ constructor ] : getter ( locals . $scope , constructor , true ) || getter ( $window , constructor , true ) ; assertArgFn ( expression , constructor , true ) ; } instance = $injector . instantiate ( expression , locals ) ; if ( identifier ) { if ( ! ( locals && typeof locals . $scope == 'object' ) ) { throw minErr ( '$controller' ) ( 'noscp' , "Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`." , constructor || expression . name , identifier ) ; } locals . $scope [ identifier ] = instance ; } return instance ; } ; } ] ; }


Input:
LocationHtml5Url represents an url This object is exposed as $location service when HTML5 mode is enabled and supported [CODESPLIT] function LocationHtml5Url ( appBase , basePrefix ) { this . $$html5 = true ; basePrefix = basePrefix || '' ; var appBaseNoFile = stripFile ( appBase ) ; /**
   * Parse given html5 (regular) url string into properties
   * @param {string} newAbsoluteUrl HTML5 url
   * @private
   */ this . $$parse = function ( url ) { var parsed = { } matchUrl ( url , parsed ) ; var pathUrl = beginsWith ( appBaseNoFile , url ) ; if ( ! isString ( pathUrl ) ) { throw $locationMinErr ( 'ipthprfx' , 'Invalid url "{0}", missing path prefix "{1}".' , url , appBaseNoFile ) ; } matchAppUrl ( pathUrl , parsed ) ; extend ( this , parsed ) ; if ( ! this . $$path ) { this . $$path = '/' ; } this . $$compose ( ) ; } ; /**
   * Compose url and update `absUrl` property
   * @private
   */ this . $$compose = function ( ) { var search = toKeyValue ( this . $$search ) , hash = this . $$hash ? '#' + encodeUriSegment ( this . $$hash ) : '' ; this . $$url = encodePath ( this . $$path ) + ( search ? '?' + search : '' ) + hash ; this . $$absUrl = appBaseNoFile + this . $$url . substr ( 1 ) ; // first char is always '/' } ; this . $$rewrite = function ( url ) { var appUrl , prevAppUrl ; if ( ( appUrl = beginsWith ( appBase , url ) ) !== undefined ) { prevAppUrl = appUrl ; if ( ( appUrl = beginsWith ( basePrefix , appUrl ) ) !== undefined ) { return appBaseNoFile + ( beginsWith ( '/' , appUrl ) || appUrl ) ; } else { return appBase + prevAppUrl ; } } else if ( ( appUrl = beginsWith ( appBaseNoFile , url ) ) !== undefined ) { return appBaseNoFile + appUrl ; } else if ( appBaseNoFile == url + '/' ) { return appBaseNoFile ; } } }


Input:
LocationHashbangUrl represents url This object is exposed as $location service when developer doesn t opt into html5 mode . It also serves as the base class for html5 mode fallback on legacy browsers . [CODESPLIT] function LocationHashbangUrl ( appBase , hashPrefix ) { var appBaseNoFile = stripFile ( appBase ) ; matchUrl ( appBase , this ) ; /**
   * Parse given hashbang url into properties
   * @param {string} url Hashbang url
   * @private
   */ this . $$parse = function ( url ) { var withoutBaseUrl = beginsWith ( appBase , url ) || beginsWith ( appBaseNoFile , url ) ; var withoutHashUrl = withoutBaseUrl . charAt ( 0 ) == '#' ? beginsWith ( hashPrefix , withoutBaseUrl ) : ( this . $$html5 ) ? withoutBaseUrl : '' ; if ( ! isString ( withoutHashUrl ) ) { throw $locationMinErr ( 'ihshprfx' , 'Invalid url "{0}", missing hash prefix "{1}".' , url , hashPrefix ) ; } matchAppUrl ( withoutHashUrl , this ) ; this . $$compose ( ) ; } ; /**
   * Compose hashbang url and update `absUrl` property
   * @private
   */ this . $$compose = function ( ) { var search = toKeyValue ( this . $$search ) , hash = this . $$hash ? '#' + encodeUriSegment ( this . $$hash ) : '' ; this . $$url = encodePath ( this . $$path ) + ( search ? '?' + search : '' ) + hash ; this . $$absUrl = appBase + ( this . $$url ? hashPrefix + this . $$url : '' ) ; } ; this . $$rewrite = function ( url ) { if ( stripHash ( appBase ) == stripHash ( url ) ) { return url ; } } }


Input: LocationHashbangUrl represents url This object is exposed as $location service when html5 history api is enabled but the browser does not support it . [CODESPLIT] function LocationHashbangInHtml5Url ( appBase , hashPrefix ) { this . $$html5 = true ; LocationHashbangUrl . apply ( this , arguments ) ; var appBaseNoFile = stripFile ( appBase ) ; this . $$rewrite = function ( url ) { var appUrl ; if ( appBase == stripHash ( url ) ) { return url ; } else if ( ( appUrl = beginsWith ( appBaseNoFile , url ) ) ) { return appBase + hashPrefix + appUrl ; } else if ( appBaseNoFile === url + '/' ) { return appBaseNoFile ; } } }


Input: @ngdoc method @name ng . $location#search @methodOf ng . $location [CODESPLIT] function ( search , paramValue ) { switch ( arguments . length ) { case 0 : return this . $$search ; case 1 : if ( isString ( search ) ) { this . $$search = parseKeyValue ( search ) ; } else if ( isObject ( search ) ) { this . $$search = search ; } else { throw $locationMinErr ( 'isrcharg' , 'The first argument of the `$location#search()` call must be a string or an object.' ) ; } break ; default : if ( paramValue == undefined || paramValue == null ) { delete this . $$search [ search ] ; } else { this . $$search [ search ] = paramValue ; } } this . $$compose ( ) ; return this ; }


Input: This is used with json array declaration [CODESPLIT] function arrayDeclaration ( ) { var elementFns = [ ] ; var allConstant = true ; if ( peekToken ( ) . text != ']' ) { do { var elementFn = expression ( ) ; elementFns . push ( elementFn ) ; if ( ! elementFn . constant ) { allConstant = false ; } } while ( expect ( ',' ) ) ; } consume ( ']' ) ; return extend ( function ( self , locals ) { var array = [ ] ; for ( var i = 0 ; i < elementFns . length ; i ++ ) { array . push ( elementFns [ i ] ( self , locals ) ) ; } return array ; } , { literal : true , constant : allConstant } ) ; }


Input: //////////////////////////////////////////////// Parser helper functions //////////////////////////////////////////////// [CODESPLIT] function setter ( obj , path , setValue , fullExp ) { var element = path . split ( '.' ) , key ; for ( var i = 0 ; element . length > 1 ; i ++ ) { key = ensureSafeMemberName ( element . shift ( ) , fullExp ) ; var propertyObj = obj [ key ] ; if ( ! propertyObj ) { propertyObj = { } ; obj [ key ] = propertyObj ; } obj = propertyObj ; if ( obj . then ) { if ( ! ( "$$v" in obj ) ) { ( function ( promise ) { promise . then ( function ( val ) { promise . $$v = val ; } ) ; } ) ( obj ) ; } if ( obj . $$v === undefined ) { obj . $$v = { } ; } obj = obj . $$v ; } } key = ensureSafeMemberName ( element . shift ( ) , fullExp ) ; obj [ key ] = setValue ; return setValue ; }


Input: @ngdoc @name ng . $q#reject @methodOf ng . $q @description Creates a promise that is resolved as rejected with the specified reason . This api should be used to forward rejection in a chain of promises . If you are dealing with the last promise in a promise chain you don t need to worry about it . [CODESPLIT] function ( reason ) { return { then : function ( callback , errback ) { var result = defer ( ) ; nextTick ( function ( ) { try { result . resolve ( ( isFunction ( errback ) ? errback : defaultErrback ) ( reason ) ) ; } catch ( e ) { result . reject ( e ) ; exceptionHandler ( e ) ; } } ) ; return result . promise ; } } ; }


Input: @ngdoc @name ng . $q#when @methodOf ng . $q @description Wraps an object that might be a value or a ( 3rd party ) then - able promise into a $q promise . This is useful when you are dealing with an object that might or might not be a promise or if the promise comes from a source that can t be trusted . [CODESPLIT] function ( value , callback , errback , progressback ) { var result = defer ( ) , done ; var wrappedCallback = function ( value ) { try { return ( isFunction ( callback ) ? callback : defaultCallback ) ( value ) ; } catch ( e ) { exceptionHandler ( e ) ; return reject ( e ) ; } } ; var wrappedErrback = function ( reason ) { try { return ( isFunction ( errback ) ? errback : defaultErrback ) ( reason ) ; } catch ( e ) { exceptionHandler ( e ) ; return reject ( e ) ; } } ; var wrappedProgressback = function ( progress ) { try { return ( isFunction ( progressback ) ? progressback : defaultCallback ) ( progress ) ; } catch ( e ) { exceptionHandler ( e ) ; } } ; nextTick ( function ( ) { ref ( value ) . then ( function ( value ) { if ( done ) return ; done = true ; result . resolve ( ref ( value ) . then ( wrappedCallback , wrappedErrback , wrappedProgressback ) ) ; } , function ( reason ) { if ( done ) return ; done = true ; result . resolve ( wrappedErrback ( reason ) ) ; } , function ( progress ) { if ( done ) return ; result . notify ( wrappedProgressback ( progress ) ) ; } ) ; } ) ; return result . promise ; }


Input: @ngdoc function @name ng . $rootScope . Scope#$new @methodOf ng . $rootScope . Scope @function [CODESPLIT] function ( isolate ) { var Child , child ; if ( isolate ) { child = new Scope ( ) ; child . $root = this . $root ; // ensure that there is just one async queue per $rootScope and its children child . $$asyncQueue = this . $$asyncQueue ; child . $$postDigestQueue = this . $$postDigestQueue ; } else { Child = function ( ) { } ; // should be anonymous; This is so that when the minifier munges // the name it does not become random set of chars. This will then show up as class // name in the debugger. Child . prototype = this ; child = new Child ( ) ; child . $id = nextUid ( ) ; } child [ 'this' ] = child ; child . $$listeners = { } ; child . $parent = this ; child . $$watchers = child . $$nextSibling = child . $$childHead = child . $$childTail = null ; child . $$prevSibling = this . $$childTail ; if ( this . $$childHead ) { this . $$childTail . $$nextSibling = child ; this . $$childTail = child ; } else { this . $$childHead = this . $$childTail = child ; } return child ; }


Input: @ngdoc function @name ng . $rootScope . Scope#$watch @methodOf ng . $rootScope . Scope @function [CODESPLIT] function ( watchExp , listener , objectEquality ) { var scope = this , get = compileToFn ( watchExp , 'watch' ) , array = scope . $$watchers , watcher = { fn : listener , last : initWatchVal , get : get , exp : watchExp , eq : ! ! objectEquality } ; // in the case user pass string, we need to compile it, do we really need this ? if ( ! isFunction ( listener ) ) { var listenFn = compileToFn ( listener || noop , 'listener' ) ; watcher . fn = function ( newVal , oldVal , scope ) { listenFn ( scope ) ; } ; } if ( typeof watchExp == 'string' && get . constant ) { var originalFn = watcher . fn ; watcher . fn = function ( newVal , oldVal , scope ) { originalFn . call ( this , newVal , oldVal , scope ) ; arrayRemove ( array , watcher ) ; } ; } if ( ! array ) { array = scope . $$watchers = [ ] ; } // we use unshift since we use a while loop in $digest for speed. // the while loop reads in reverse order. array . unshift ( watcher ) ; return function ( ) { arrayRemove ( array , watcher ) ; } ; }


Input: @ngdoc function @name ng . $rootScope . Scope#$watchCollection @methodOf ng . $rootScope . Scope @function [CODESPLIT] function ( obj , listener ) { var self = this ; var oldValue ; var newValue ; var changeDetected = 0 ; var objGetter = $parse ( obj ) ; var internalArray = [ ] ; var internalObject = { } ; var oldLength = 0 ; function $watchCollectionWatch ( ) { newValue = objGetter ( self ) ; var newLength , key ; if ( ! isObject ( newValue ) ) { if ( oldValue !== newValue ) { oldValue = newValue ; changeDetected ++ ; } } else if ( isArrayLike ( newValue ) ) { if ( oldValue !== internalArray ) { // we are transitioning from something which was not an array into array. oldValue = internalArray ; oldLength = oldValue . length = 0 ; changeDetected ++ ; } newLength = newValue . length ; if ( oldLength !== newLength ) { // if lengths do not match we need to trigger change notification changeDetected ++ ; oldValue . length = oldLength = newLength ; } // copy the items to oldValue and look for changes. for ( var i = 0 ; i < newLength ; i ++ ) { if ( oldValue [ i ] !== newValue [ i ] ) { changeDetected ++ ; oldValue [ i ] = newValue [ i ] ; } } } else { if ( oldValue !== internalObject ) { // we are transitioning from something which was not an object into object. oldValue = internalObject = { } ; oldLength = 0 ; changeDetected ++ ; } // copy the items to oldValue and look for changes. newLength = 0 ; for ( key in newValue ) { if ( newValue . hasOwnProperty ( key ) ) { newLength ++ ; if ( oldValue . hasOwnProperty ( key ) ) { if ( oldValue [ key ] !== newValue [ key ] ) { changeDetected ++ ; oldValue [ key ] = newValue [ key ] ; } } else { oldLength ++ ; oldValue [ key ] = newValue [ key ] ; changeDetected ++ ; } } } if ( oldLength > newLength ) { // we used to have more keys, need to find them and destroy them. changeDetected ++ ; for ( key in oldValue ) { if ( oldValue . hasOwnProperty ( key ) && ! newValue . hasOwnProperty ( key ) ) { oldLength -- ; delete oldValue [ key ] ; } } } } return changeDetected ; } function $watchCollectionAction ( ) { listener ( newValue , oldValue , self ) ; } return this . $watch ( $watchCollectionWatch , $watchCollectionAction ) ; }


Input: @ngdoc function @name ng . $rootScope . Scope#$on @methodOf ng . $rootScope . Scope @function [CODESPLIT] function ( name , listener ) { var namedListeners = this . $$listeners [ name ] ; if ( ! namedListeners ) { this . $$listeners [ name ] = namedListeners = [ ] ; } namedListeners . push ( listener ) ; return function ( ) { namedListeners [ indexOf ( namedListeners , listener ) ] = null ; } ; }


Input: @ngdoc function @name ng . $rootScope . Scope#$emit @methodOf ng . $rootScope . Scope @function [CODESPLIT] function ( name , args ) { var empty = [ ] , namedListeners , scope = this , stopPropagation = false , event = { name : name , targetScope : scope , stopPropagation : function ( ) { stopPropagation = true ; } , preventDefault : function ( ) { event . defaultPrevented = true ; } , defaultPrevented : false } , listenerArgs = concat ( [ event ] , arguments , 1 ) , i , length ; do { namedListeners = scope . $$listeners [ name ] || empty ; event . currentScope = scope ; for ( i = 0 , length = namedListeners . length ; i < length ; i ++ ) { // if listeners were deregistered, defragment the array if ( ! namedListeners [ i ] ) { namedListeners . splice ( i , 1 ) ; i -- ; length -- ; continue ; } try { namedListeners [ i ] . apply ( null , listenerArgs ) ; if ( stopPropagation ) return event ; } catch ( e ) { $exceptionHandler ( e ) ; } } //traverse upwards scope = scope . $parent ; } while ( scope ) ; return event ; }


Input: @ngdoc method @name ng . $sceDelegate#trustAs @methodOf ng . $sceDelegate [CODESPLIT] function trustAs ( type , trustedValue ) { var constructor = ( byType . hasOwnProperty ( type ) ? byType [ type ] : null ) ; if ( ! constructor ) { throw $sceMinErr ( 'icontext' , 'Attempted to trust a value in invalid context. Context: {0}; Value: {1}' , type , trustedValue ) ; } if ( trustedValue === null || trustedValue === undefined || trustedValue === '' ) { return trustedValue ; } // All the current contexts in SCE_CONTEXTS happen to be strings.  In order to avoid trusting // mutable objects, we ensure here that the value passed in is actually a string. if ( typeof trustedValue !== 'string' ) { throw $sceMinErr ( 'itype' , 'Attempted to trust a non-string value in a content requiring a string: Context: {0}' , type ) ; } return new constructor ( trustedValue ) ; }


Input: @description Normalizes and optionally parses a URL . [CODESPLIT] function resolve ( url , parse ) { var href = url ; if ( msie <= 11 ) { // Normalize before parse.  Refer Implementation Notes on why this is // done in two steps on IE. urlParsingNode . setAttribute ( "href" , href ) ; href = urlParsingNode . href ; } urlParsingNode . setAttribute ( 'href' , href ) ; if ( ! parse ) { return urlParsingNode . href ; } // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils return { href : urlParsingNode . href , protocol : urlParsingNode . protocol , host : urlParsingNode . host // Currently unused and hence commented out. // hostname: urlParsingNode.hostname, // port: urlParsingNode.port, // pathname: urlParsingNode.pathname, // hash: urlParsingNode.hash, // search: urlParsingNode.search } ; }


Input: Parse a request URL and determine whether this is a same - origin request as the application document . [CODESPLIT] function isSameOrigin ( requestUrl ) { var parsed = ( typeof requestUrl === 'string' ) ? resolve ( requestUrl , true ) : requestUrl ; return ( parsed . protocol === originUrl . protocol && parsed . host === originUrl . host ) ; }


Input: TODO : Make promise agnostic [CODESPLIT] function ConsumingMatcher ( matchers ) { return _ . create ( { } , { unmatchedMatchers : _ . clone ( matchers ) , matches : function ( actual ) { let matched = false ; _ . forEach ( this . unmatchedMatchers , ( matcher , index ) => { if ( matcher . matches ( actual ) ) { matched = true ; this . unmatchedMatchers . splice ( index , 1 ) ; return false ; } } , this ) ; return matched ; } } ) ; }


Input: Traverse the specified AST . [CODESPLIT] function traverse ( node , opt_onEnter , opt_onLeave ) { if ( opt_onEnter ) opt_onEnter ( node ) ; var childNodes = _collectChildNodes ( node ) ; childNodes . forEach ( function ( childNode ) { traverse ( childNode , opt_onEnter , opt_onLeave ) ; } ) ; if ( opt_onLeave ) opt_onLeave ( node ) ; }


Input: json - rpc - ws client [CODESPLIT] function Client ( ) { logger ( 'new Client' ) ; this . type = 'client' ; this . id = uuid ( ) ; this . browser = ( WebSocket . Server === undefined ) ; Base . call ( this ) ; }


Input: Quarantined JSON . parse try / catch block in its own function [CODESPLIT] function jsonParse ( data ) { var payload ; try { payload = JSON . parse ( data ) ; } catch ( error ) { logger ( error ) ; payload = null ; } return payload ; }


Input: json - rpc - ws connection [CODESPLIT] function Connection ( socket , parent ) { logger ( 'new Connection to %s' , parent . type ) ; this . id = uuid ( ) ; this . socket = socket ; this . parent = parent ; this . responseHandlers = { } ; if ( this . parent . browser ) { this . socket . onmessage = this . message . bind ( this ) ; this . socket . onclose = socketClosed . bind ( this ) ; this . socket . onerror = socketError . bind ( this ) ; } else { this . socket . on ( 'message' , this . message . bind ( this ) ) ; this . socket . once ( 'close' , this . close . bind ( this ) ) ; this . socket . once ( 'error' , this . close . bind ( this ) ) ; } }


Input: / * Javascript Diff Algorithm By John Resig ( http : // ejohn . org / ) Modified by Chu Alan sprite [CODESPLIT] function escapeJSDiff ( s ) { var n = s ; n = n . replace ( / & / g , "&" ) ; n = n . replace ( / < / g , "<" ) ; n = n . replace ( / > / g , ">" ) ; n = n . replace ( / " / g , """ ) ; return n ; }


Input: The Dialog class represents a modal dialog . The dialog class can be invoked by providing an options object containing at lest template or templateUrl and controller : var d = new Dialog ( { templateUrl : foo . html controller : BarController } ) ; Dialogs can also be created using templateUrl and controller as distinct arguments : var d = new Dialog ( path / to / dialog . html MyDialogController ) ; [CODESPLIT] function Dialog ( opts ) { var self = this , options = this . options = angular . extend ( { } , defaults , globalOptions , opts ) ; this . _open = false ; this . backdropEl = createElement ( options . backdropClass ) ; if ( options . backdropFade ) { this . backdropEl . addClass ( options . transitionClass ) ; this . backdropEl . removeClass ( options . triggerClass ) ; } this . modalEl = createElement ( options . dialogClass ) ; if ( options . dialogFade ) { this . modalEl . addClass ( options . transitionClass ) ; this . modalEl . removeClass ( options . triggerClass ) ; } this . handledEscapeKey = function ( e ) { if ( e . which === 27 ) { self . close ( ) ; e . preventDefault ( ) ; self . $scope . $apply ( ) ; } } ; this . handleBackDropClick = function ( e ) { self . close ( ) ; e . preventDefault ( ) ; self . $scope . $apply ( ) ; } ; this . handleLocationChange = function ( ) { self . close ( ) ; } ; }


Input: creates a new Dialog tied to the default message box template and controller . Arguments title and message are rendered in the modal header and body sections respectively . The buttons array holds an object with the following members for each button to include in the modal footer section : * result : the result to pass to the close method of the dialog when the button is clicked * label : the label of the button * cssClass : additional css class ( es ) to apply to the button for styling [CODESPLIT] function ( title , message , buttons ) { return new Dialog ( { templateUrl : 'plugins/ui-bootstrap/html/message.html' , controller : 'MessageBoxController' , resolve : { model : function ( ) { return { title : title , message : message , buttons : buttons } ; } } } ) ; }


Input: : ( string ?Object ) → ( ... content : [ union<string Node > ] ) → Node Create a builder function for nodes with content . [CODESPLIT] function block ( type , attrs ) { let result = function ( ... args ) { let myAttrs = takeAttrs ( attrs , args ) let { nodes , tag } = flatten ( type . schema , args , id ) let node = type . create ( myAttrs , nodes ) if ( tag != noTag ) node . tag = tag return node } if ( type . isLeaf ) try { result . flat = [ type . create ( attrs ) ] } catch ( _ ) { } return result }


Input: Create a builder function for marks . [CODESPLIT] function mark ( type , attrs ) { return function ( ... args ) { let mark = type . create ( takeAttrs ( attrs , args ) ) let { nodes , tag } = flatten ( type . schema , args , n => mark . type . isInSet ( n . marks ) ? n : n . mark ( mark . addToSet ( n . marks ) ) ) return { flat : nodes , tag } } }


Input: create store [CODESPLIT] function _createStore ( ) { //start to create store const rootEpic = combineEpics ( ... _epics ) ; const _trueReducers = combineReducers ( _reducersObj ) ; //TODO extra epic inject plugin const epicMiddleware = getEpicMiddleware ( rootEpic , _plugins ) ; _middlewares . push ( epicMiddleware ) ; return _configureStore ( _trueReducers , _middlewares ) ; }


Input: Send the request using the socket [CODESPLIT] function serverRequest ( config ) { var defer = $q . defer ( ) ; if ( provider . debug ) $log . info ( '$sails ' + config . method + ' ' + config . url , config . data || '' ) ; if ( config . timeout > 0 ) { $timeout ( timeoutRequest , config . timeout ) ; } else if ( isPromiseLike ( config . timeout ) ) { config . timeout . then ( timeoutRequest ) ; } socket [ 'legacy_' + config . method . toLowerCase ( ) ] ( config . url , config . data , serverResponse ) ; function timeoutRequest ( ) { serverResponse ( null ) ; } function serverResponse ( result , jwr ) { if ( ! jwr ) { jwr = { body : result , headers : result . headers || { } , statusCode : result . statusCode || result . status || 0 , error : ( function ( ) { if ( this . statusCode < 200 || this . statusCode >= 400 ) { return this . body || this . statusCode ; } } ) ( ) } ; } jwr . data = jwr . body ; // $http compat jwr . status = jwr . statusCode ; // $http compat jwr . socket = socket ; jwr . url = config . url ; jwr . method = config . method ; jwr . config = config . config ; if ( jwr . error ) { if ( provider . debug ) $log . warn ( '$sails response ' + jwr . statusCode + ' ' + config . url , jwr ) ; defer . reject ( jwr ) ; } else { if ( provider . debug ) $log . info ( '$sails response ' + config . url , jwr ) ; defer . resolve ( jwr ) ; } } return defer . promise ; }


Input: Searches for the bootstrap file until it finds one .... [CODESPLIT] function figureOutRootComponent ( ) { var rootComponents = [ '../../../src/app/app.module.ts' , '../../../src/app.ts' , '../../../boot.ts' , '../../../src/main.ts' ] ; for ( var i = 0 ; i < rootComponents . length ; i ++ ) { if ( fs . existsSync ( rootComponents [ i ] ) ) { var result = processBootStrap ( rootComponents [ i ] ) ; if ( result ) { return result ; } } } // Return a default component, if we can't find one... return { name : 'AppComponent' , path : './client/components/app.component' } ; }


Input: Parses the bootstrap to figure out the default bootstrap component [CODESPLIT] function processBootStrap ( file ) { var data = fs . readFileSync ( file ) . toString ( ) ; var idx = data . indexOf ( 'bootstrap(' ) ; if ( idx === - 1 ) { return null ; } else { idx += 10 ; } var odx1 = data . indexOf ( ',' , idx ) ; var odx2 = data . indexOf ( ')' , idx ) ; if ( odx2 < odx1 && odx2 !== - 1 || odx1 === - 1 ) { odx1 = odx2 ; } if ( odx1 === - 1 ) { return null ; } var componentRef = data . substring ( idx , odx1 ) ; var exp = "import\\s+\\{(" + componentRef + ")\\}\\s+from+\\s+[\'|\"](\\S+)[\'|\"][;?]" ; if ( debugging ) { console . log ( "Searching for" , exp ) ; } var result = function ( r ) { return { name : r [ 1 ] , path : r [ r . length - 1 ] } ; } ; //noinspection JSPotentiallyInvalidConstructorUsage var r = RegExp ( exp , 'i' ) . exec ( data ) ; if ( r === null || r . length <= 1 ) { // check if using current style guide with spaces exp = "import\\s+\\{\\s+(" + componentRef + ")\\,\\s+([A-Z]{0,300})\\w+\\s+\\}\\s+from+\\s+[\'|\"](\\S+)[\'|\"][;?]" ; if ( debugging ) { console . log ( "Searching for" , exp ) ; } r = RegExp ( exp , 'i' ) . exec ( data ) ; if ( r === null || r . length <= 1 ) { // try just spaces with no angular cli style (, environment) etc. exp = "import\\s+\\{\\s+(" + componentRef + ")\\s+\\}\\s+from+\\s+[\'|\"](\\S+)[\'|\"][;?]" ; if ( debugging ) { console . log ( "Searching for" , exp ) ; } r = RegExp ( exp , 'i' ) . exec ( data ) ; if ( r !== null && r . length > 1 ) { return result ( r ) ; } } else { // angular cli return result ( r ) ; } return null ; } return result ( r ) ; }


Input: Create Symlink [CODESPLIT] function createSymLink ( ) { if ( debugging ) { console . log ( "Attempting to Symlink" , angularSeedPath , nativescriptClientPath ) ; } fs . symlinkSync ( resolve ( angularSeedPath ) , resolve ( nativescriptClientPath ) , 'junction' ) ; }


Input: This fixes the TS Config file in the nativescript folder [CODESPLIT] function fixTsConfig ( ) { var tsConfig = { } , tsFile = '../../tsconfig.json' ; if ( fs . existsSync ( tsFile ) ) { tsConfig = require ( tsFile ) ; } if ( ! tsConfig . compilerOptions || ! tsConfig . compilerOptions . typeRoots ) { tsConfig . compilerOptions = { target : "es5" , module : "commonjs" , declaration : false , removeComments : true , noLib : false , emitDecoratorMetadata : true , experimentalDecorators : true , lib : [ "dom" ] , sourceMap : true , pretty : true , allowUnreachableCode : false , allowUnusedLabels : false , noImplicitAny : false , noImplicitReturns : true , noImplicitUseStrict : false , noFallthroughCasesInSwitch : true , typeRoots : [ "node_modules/@types" , "node_modules" ] , types : [ "jasmine" ] } ; } // See: https://github.com/NativeScript/nativescript-angular/issues/205 // tsConfig.compilerOptions.noEmitHelpers = false; // tsConfig.compilerOptions.noEmitOnError = false; if ( ! tsConfig . exclude ) { tsConfig . exclude = [ ] ; } if ( tsConfig . exclude . indexOf ( 'node_modules' ) === - 1 ) { tsConfig . exclude . push ( 'node_modules' ) ; } if ( tsConfig . exclude . indexOf ( 'platforms' ) === - 1 ) { tsConfig . exclude . push ( 'platforms' ) ; } fs . writeFileSync ( tsFile , JSON . stringify ( tsConfig , null , 4 ) , 'utf8' ) ; }


Input: This fixes the references file to work with TS 2 . 0 in the nativescript folder [CODESPLIT] function fixRefFile ( ) { var existingRef = '' , refFile = '../../references.d.ts' ; if ( fs . existsSync ( refFile ) ) { existingRef = fs . readFileSync ( refFile ) . toString ( ) ; } if ( existingRef . indexOf ( 'typescript/lib/lib.d.ts' ) === - 1 ) { // has not been previously modified var fix = '/// <reference path="./node_modules/tns-core-modules/tns-core-modules.d.ts" />\n' + '/// <reference path="./node_modules/typescript/lib/lib.d.ts" />\n' ; fs . writeFileSync ( refFile , fix , 'utf8' ) ; } }


Input: Fix the NativeScript Package file [CODESPLIT] function fixNativeScriptPackage ( ) { var packageJSON = { } , packageFile = '../../package.json' ; packageJSON . name = "NativeScriptApp" ; packageJSON . version = "0.0.0" ; // var AngularJSON = {}; if ( fs . existsSync ( packageFile ) ) { packageJSON = require ( packageFile ) ; } else { console . log ( "This should not happen, your are missing your package.json file!" ) ; return ; } // if (fs.existsSync('../angular2/package.json')) { //     AngularJSON = require('../angular2/package.json'); // } else { //     // Copied from the Angular2.0.0-beta-16 package.json, this is a fall back //     AngularJSON.peerDependencies = { //         "es6-shim": "^0.35.0", //         "reflect-metadata": "0.1.2", //         "rxjs": "5.0.0-beta.6", //         "zone.js": "^0.6.12" //     }; // } packageJSON . nativescript [ 'tns-ios' ] = { version : "2.3.0" } ; packageJSON . nativescript [ 'tns-android' ] = { version : "2.3.0" } ; // Copy over all the Peer Dependencies // for (var key in AngularJSON.peerDependencies) { //     if (AngularJSON.peerDependencies.hasOwnProperty(key)) { //         packageJSON.dependencies[key] = AngularJSON.peerDependencies[key]; //     } // } // TODO: Can we get these from somewhere rather than hardcoding them, maybe need to pull/download the package.json from the default template? if ( ! packageJSON . devDependencies ) { packageJSON . devDependencies = { } ; } packageJSON . devDependencies [ "@types/jasmine" ] = "^2.5.35" ; packageJSON . devDependencies [ "babel-traverse" ] = "6.12.0" ; packageJSON . devDependencies [ "babel-types" ] = "6.11.1" ; packageJSON . devDependencies . babylon = "6.8.4" ; packageJSON . devDependencies . filewalker = "0.1.2" ; packageJSON . devDependencies . lazy = "1.0.11" ; // packageJSON.devDependencies["nativescript-dev-typescript"] = "^0.3.2"; packageJSON . devDependencies . typescript = "^2.0.2" ; fs . writeFileSync ( packageFile , JSON . stringify ( packageJSON , null , 4 ) , 'utf8' ) ; }


Input: Fix the Angular Package [CODESPLIT] function fixAngularPackage ( ) { var packageJSON = { } , packageFile = '../../../package.json' ; if ( fs . existsSync ( packageFile ) ) { packageJSON = require ( packageFile ) ; } else { console . log ( "This should not happen, your are missing your main package.json file!" ) ; return ; } if ( ! packageJSON . scripts ) { packageJSON . scripts = { } ; } packageJSON . scripts [ "start.ios" ] = "cd nativescript && tns emulate ios" ; packageJSON . scripts [ "start.livesync.ios" ] = "cd nativescript && tns livesync ios --emulator --watch" ; packageJSON . scripts [ "start.android" ] = "cd nativescript && tns emulate android" ; packageJSON . scripts [ "start.livesync.android" ] = "cd nativescript && tns livesync android --emulator --watch" ; fs . writeFileSync ( packageFile , JSON . stringify ( packageJSON , null , 4 ) , 'utf8' ) ; }


Input: Fix the Main NativeScript File [CODESPLIT] function fixMainFile ( component ) { var mainTS = '' , mainFile = '../../app/main.ts' ; if ( fs . existsSync ( mainFile ) ) { mainTS = fs . readFileSync ( mainFile ) . toString ( ) ; } if ( mainTS . indexOf ( 'MagicService' ) === - 1 ) { // has not been previously modified var fix = '// this import should be first in order to load some required settings (like globals and reflect-metadata)\n' + 'import { platformNativeScriptDynamic, NativeScriptModule } from "nativescript-angular/platform";\n' + 'import { NgModule } from "@angular/core";\n' + 'import { AppComponent } from "./app/app.component";\n' + '\n' + '@NgModule({\n' + '  declarations: [AppComponent],\n' + '  bootstrap: [AppComponent],\n' + '   imports: [NativeScriptModule],\n' + '})\n' + 'class AppComponentModule {}\n\n' + 'platformNativeScriptDynamic().bootstrapModule(AppComponentModule);' ; fs . writeFileSync ( mainFile , fix , 'utf8' ) ; } }


Input: Fix . gitignore [CODESPLIT] function fixGitIgnore ( ignorePattern ) { var fileString = '' , ignoreFile = '../../../.gitignore' ; if ( fs . existsSync ( ignoreFile ) ) { fileString = fs . readFileSync ( ignoreFile ) . toString ( ) ; } if ( fileString . indexOf ( ignorePattern ) === - 1 ) { // has not been previously modified var fix = fileString + '\n' + ignorePattern ; fs . writeFileSync ( ignoreFile , fix , 'utf8' ) ; } }


Input: Display final help screen! [CODESPLIT] function displayFinalHelp ( ) { console . log ( "-------------- Welcome to the Magical World of NativeScript -----------------------------" ) ; console . log ( "To finish, follow this guide https://github.com/NathanWalker/nativescript-ng2-magic#usage" ) ; console . log ( "After you have completed the steps in the usage guide, you can then:" ) ; console . log ( "" ) ; console . log ( "Run your app in the iOS Simulator with these options:" ) ; console . log ( "  npm run start.ios" ) ; console . log ( "  npm run start.livesync.ios" ) ; console . log ( "" ) ; console . log ( "Run your app in an Android emulator with these options:" ) ; console . log ( "  npm run start.android" ) ; console . log ( "  npm run start.livesync.android" ) ; console . log ( "-----------------------------------------------------------------------------------------" ) ; console . log ( "" ) ; }


Input:
Please use this bind not the one from Function . prototype [CODESPLIT] function bind ( func , thisObject , var_args ) { var args = slice ( arguments , 2 ) ; /**
     * @param {...} var_args
     */ function bound ( var_args ) { return InjectedScriptHost . callFunction ( func , thisObject , concat ( args , slice ( arguments ) ) ) ; } bound . toString = function ( ) { return "bound: " + toString ( func ) ; } ; return bound ; }


Input: This method cannot throw . [CODESPLIT] function ( object , objectGroupName , forceValueType , generatePreview , columnNames , isTable , doNotBind , customObjectConfig ) { try { return new InjectedScript . RemoteObject ( object , objectGroupName , doNotBind , forceValueType , generatePreview , columnNames , isTable , undefined , customObjectConfig ) ; } catch ( e ) { try { var description = injectedScript . _describe ( e ) ; } catch ( ex ) { var description = "<failed to convert exception to string>" ; } return new InjectedScript . RemoteObject ( description ) ; } }


Input: Resolves a value from CallArgument description . [CODESPLIT] function ( callArgumentJson ) { callArgumentJson = nullifyObjectProto ( callArgumentJson ) ; var objectId = callArgumentJson . objectId ; if ( objectId ) { var parsedArgId = this . _parseObjectId ( objectId ) ; if ( ! parsedArgId || parsedArgId [ "injectedScriptId" ] !== injectedScriptId ) throw "Arguments should belong to the same JavaScript world as the target object." ; var resolvedArg = this . _objectForId ( parsedArgId ) ; if ( ! this . _isDefined ( resolvedArg ) ) throw "Could not find object with given id" ; return resolvedArg ; } else if ( "value" in callArgumentJson ) { var value = callArgumentJson . value ; if ( callArgumentJson . type === "number" && typeof value !== "number" ) value = Number ( value ) ; return value ; } return undefined ; }


Input: Either callFrameId or functionObjectId must be specified . [CODESPLIT] function ( topCallFrame , callFrameId , functionObjectId , scopeNumber , variableName , newValueJsonString ) { try { var newValueJson = /** @type {!RuntimeAgent.CallArgument} */ ( InjectedScriptHost . eval ( "(" + newValueJsonString + ")" ) ) ; var resolvedValue = this . _resolveCallArgument ( newValueJson ) ; if ( typeof callFrameId === "string" ) { var callFrame = this . _callFrameForId ( topCallFrame , callFrameId ) ; if ( ! callFrame ) return "Could not find call frame with given id" ; callFrame . setVariableValue ( scopeNumber , variableName , resolvedValue ) } else { var parsedFunctionId = this . _parseObjectId ( /** @type {string} */ ( functionObjectId ) ) ; var func = this . _objectForId ( parsedFunctionId ) ; if ( typeof func !== "function" ) return "Could not resolve function by id" ; InjectedScriptHost . setFunctionVariableValue ( func , scopeNumber , variableName , resolvedValue ) ; } } catch ( e ) { return toString ( e ) ; } return undefined ; }


Input: Validates a TileJSON Object [CODESPLIT] function validate ( tj ) { if ( Object . prototype . hasOwnProperty . call ( tj , 'tilejson' ) ) { if ( tj . tilejson !== '2.2.0' ) { return false ; } } else { return false ; } if ( Object . prototype . hasOwnProperty . call ( tj , 'name' ) ) { if ( typeof tj . name !== 'string' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'description' ) ) { if ( typeof tj . description !== 'string' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'version' ) ) { if ( typeof tj . version !== 'string' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'attribution' ) ) { if ( typeof tj . attribution !== 'string' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'template' ) ) { if ( typeof tj . template !== 'string' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'legend' ) ) { if ( typeof tj . legend !== 'string' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'scheme' ) ) { if ( typeof tj . scheme !== 'string' ) { return false ; } if ( tj . scheme !== 'xyz' && tj . scheme !== 'tms' ) { return false ; } } if ( Object . prototype . hasOwnProperty . call ( tj , 'tiles' ) ) { if ( tj . tiles . constructor !== Array ) { return false ; } if ( tj . tiles . length < 1 ) { return false ; } for ( let i = 0 ; i < tj . tiles . length ; i += 1 ) { if ( typeof tj . tiles [ i ] !== 'string' ) { return false ; } } } else { return false ; } if ( Object . prototype . hasOwnProperty . call ( tj , 'grids' ) ) { if ( tj . grids . constructor !== Array ) { return false ; } for ( let i = 0 ; i < tj . grids . length ; i += 1 ) { if ( typeof tj . grids [ i ] !== 'string' ) { return false ; } } } if ( Object . prototype . hasOwnProperty . call ( tj , 'data' ) ) { if ( tj . data . constructor !== Array ) { return false ; } for ( let i = 0 ; i < tj . data . length ; i += 1 ) { if ( typeof tj . data [ i ] !== 'string' ) { return false ; } } } let minzoom = 0 ; if ( Object . prototype . hasOwnProperty . call ( tj , 'minzoom' ) ) { if ( typeof tj . minzoom !== 'number' ) { return false ; } if ( ! Number . isInteger ( tj . minzoom ) ) { return false ; } if ( tj . minzoom < 0 || tj . minzoom > 30 ) { return false ; } minzoom = tj . minzoom ; } let maxzoom = 30 ; if ( Object . prototype . hasOwnProperty . call ( tj , 'maxzoom' ) ) { if ( typeof tj . maxzoom !== 'number' ) { return false ; } if ( ! Number . isInteger ( tj . maxzoom ) ) { return false ; } if ( tj . maxzoom < 0 || tj . maxzoom > 30 ) { return false ; } maxzoom = tj . maxzoom ; } if ( minzoom > maxzoom ) { return false ; } if ( Object . prototype . hasOwnProperty . call ( tj , 'bounds' ) ) { if ( tj . bounds . constructor !== Array ) { return false ; } for ( let i = 0 ; i < tj . bounds . length ; i += 1 ) { if ( typeof tj . bounds [ i ] !== 'number' ) { return false ; } } } if ( Object . prototype . hasOwnProperty . call ( tj , 'center' ) ) { if ( tj . center . constructor !== Array ) { return false ; } for ( let i = 0 ; i < tj . center . length ; i += 1 ) { if ( typeof tj . center [ i ] !== 'number' ) { return false ; } } } return true ; }


Input: Validates a TileJSON [CODESPLIT] function validate ( str ) { let tj ; if ( typeof str === 'object' ) { tj = str ; } else if ( typeof str === 'string' ) { try { tj = jsonlint . parse ( str ) ; } catch ( err ) { return false ; } } else { return false ; } return tilejsonValidateObject . validate ( tj ) ; }


Input: Public : Adds a validator to the model that checks to make sure the given attributes are valid numbers . ... names - One or more attribute names . opts - An optional object containing zero or more of the following options : nonnegative - Ensure that the number is not negative . maximum - Ensure that the number is not greater than this value . minimum - Ensure that the number is not less than this value . Returns the receiver . [CODESPLIT] function validatesNumber ( ) { var names = Array . from ( arguments ) , opts = util . type ( names [ names . length - 1 ] ) === 'object' ? names . pop ( ) : { } ; names . forEach ( function ( name ) { this . validate ( name , function ( ) { this . validateNumber ( name , opts ) ; } ) ; } , this ) ; return this ; }


Input: Public : Adds a validator to the model that checks to make sure the given attributes are valid dates . ... names - One or more attribute names . Returns the receiver . [CODESPLIT] function validatesDate ( ) { Array . from ( arguments ) . forEach ( function ( name ) { this . validate ( name , function ( ) { this . validateDate ( name ) ; } ) ; } , this ) ; }


Input: Public : Adds a validator to the model that checks to make sure the given attributes are valid emails . ... names - One or more attribute names . Returns the receiver . [CODESPLIT] function validatesEmail ( ) { Array . from ( arguments ) . forEach ( function ( name ) { this . validate ( name , function ( ) { this . validateEmail ( name ) ; } ) ; } , this ) ; return this ; }


Input: Public : Adds a validator to the model that checks to make sure the given attributes are valid phone numbers . ... names - One or more attribute names . Returns the receiver . [CODESPLIT] function validatesPhone ( ) { Array . from ( arguments ) . forEach ( function ( name ) { this . validate ( name , function ( ) { this . validatePhone ( name ) ; } ) ; } , this ) ; return this ; }


Input: Public : Adds a validator to the model that checks to make sure the given attributes are valid durations . ... names - One or more attribute names . Returns the receiver . [CODESPLIT] function validatesDuration ( ) { Array . from ( arguments ) . forEach ( function ( name ) { this . validate ( name , function ( ) { this . validateDuration ( name ) ; } ) ; } , this ) ; return this ; }


Input: Public : Parses a string containing a number . s - The string to parse . Returns a number or null if parsing fails . [CODESPLIT] function parseNumber ( s ) { s = String ( s ) . replace ( / [^\d-.] / g , '' ) . replace ( / \.$ / , '' ) ; if ( ! s . match ( NUMBER_RE ) ) { return null ; } return parseFloat ( s , 10 ) ; }


Input: Public : Parses a string containing a percent . s - The string to parse . Returns a number or null if parsing fails . [CODESPLIT] function parsePercent ( s ) { var n = parseNumber ( String ( s ) . replace ( '%' , '' ) ) ; return n == null ? null : n / 100 ; }


Input: Public : Parses a string containing a date in the following formats : - YYYY - MM - DD ( ISO8601 ) - MM / DD - MM?DD?YY where ? is a non - digit character - MM?DD?YYYY where ? is a non - digit character - MMDDYY - MMDDYYYY s - The string to parse . Returns a Date or null if parsing fails . [CODESPLIT] function parseDate ( s ) { var m , d , y , date , parts ; s = String ( s ) . replace ( / \s / g , '' ) ; if ( parts = s . match ( ISO8601_DATE_RE ) ) { y = parseInt ( parts [ 1 ] , 10 ) ; m = parseInt ( parts [ 2 ] , 10 ) - 1 ; d = parseInt ( parts [ 3 ] , 10 ) ; date = new Date ( y , m , d ) ; return date . getMonth ( ) === m ? date : null ; } else if ( parts = s . match ( MDY_DATE_RE ) ) { m = parseInt ( parts [ 1 ] , 10 ) - 1 ; d = parseInt ( parts [ 2 ] , 10 ) ; y = parts [ 3 ] ? parseInt ( parts [ 3 ] , 10 ) : new Date ( ) . getFullYear ( ) ; if ( 0 <= y && y <= 68 ) { y += 2000 ; } if ( 69 <= y && y <= 99 ) { y += 1900 ; } date = new Date ( y , m , d ) ; return date . getMonth ( ) === m ? date : null ; } else { return null ; } }


Input: Public : Parses a string containing an ISO8601 formatted date and time . s - The string to parse . Returns a Date or null if parsing fails . [CODESPLIT] function parseDateTime ( s ) { var n ; s = String ( s ) ; if ( s . match ( NO_TZ_RE ) ) { s += 'Z' ; } return ( n = Date . parse ( s ) ) ? new Date ( n ) : null ; }


Input: Public : Parses a string containing an email . s - The string to parse . Returns the email string . [CODESPLIT] function parseEmail ( s ) { s = String ( s ) ; return EMAIL_FORMAT . test ( s ) ? s : null ; }


Input: Public : Parses a string containing an phone number . s - The string to parse . Returns the phone string . [CODESPLIT] function parsePhone ( s ) { s = String ( s ) ; return PHONE_FORMAT . test ( s . replace ( PHONE_CHARS , '' ) ) ? s : null ; }


Input: Public : Parses a string containing a time duration . The format is : HH : MM : SS where hours and minutes are optional . s - The string to parse . Returns the number of seconds or null if parsing fails . [CODESPLIT] function parseDuration ( s ) { s = String ( s ) ; if ( ! DURATION_RE . test ( s ) ) { return null ; } var parts = s . split ( ':' ) . map ( function ( p ) { return + p ; } ) ; if ( parts . length === 3 ) { return parts [ 0 ] * 3600 + parts [ 1 ] * 60 + parts [ 2 ] ; } else if ( parts . length === 2 ) { return parts [ 0 ] * 60 + parts [ 1 ] ; } else { return parts [ 0 ] ; } }


Input: Internal : Used by detectRecursion to check to see if the given pair of objects has been encountered yet on a previous recursive call . o1 - The first object to check for recursion . o2 - The paired object to check for recursion . Returns true if the pair has been seen previously and false otherwise . [CODESPLIT] function seen ( o1 , o2 ) { var i , len ; for ( i = 0 , len = seenObjects . length ; i < len ; i ++ ) { if ( seenObjects [ i ] [ 0 ] === o1 && seenObjects [ i ] [ 1 ] === o2 ) { return true ; } } return false ; }


Input: Internal : Used by detectRecursion to unmark the given pair of objects after a recursive call has completed . o1 - The first object to unmark . o2 - The paired object to unmark . Returns nothing . [CODESPLIT] function unmark ( o1 , o2 ) { var i , n ; for ( i = 0 , n = seenObjects . length ; i < n ; i ++ ) { if ( seenObjects [ i ] [ 0 ] === o1 && seenObjects [ i ] [ 1 ] === o2 ) { seenObjects . splice ( i , 1 ) ; return ; } } }


Input: Internal : Used by getPath to resolve a path into a value . o - The object to resolve the path from . pathSegments - An array of strings representing segments of the path to resolve . Returns the resolved value or undefined if some segment of the path does not exist . [CODESPLIT] function _getPath ( o , pathSegments ) { if ( o == null ) { return undefined ; } var head = pathSegments [ 0 ] , tail = pathSegments . slice ( 1 ) ; if ( Array . isArray ( o ) && ! ( head in o ) ) { o = o . reduce ( function ( acc , x ) { if ( ! x ) { return acc ; } var y = x [ head ] ; if ( Array . isArray ( y ) ) { acc . push . apply ( acc , y ) ; } else { acc . push ( y ) ; } return acc ; } , [ ] ) ; } else { o = o [ head ] ; } if ( ! tail . length ) { return o ; } else { return o ? _getPath ( o , tail ) : undefined ; } }


Input: Internal : Used to detect cases of recursion on the same pair of objects . Returns true if the given objects have already been seen . Otherwise the given function is called and false is returned . This function is used internally when traversing objects and arrays to avoid getting stuck in infinite loops when circular objects are encountered . It should be wrapped around all recursive function calls where a circular object may be encountered . See Transis . eq for an example . o1 - The first object to check for recursion . o2 - The paired object to check for recursion ( default : undefined ) . f - A function that make the recursive funciton call . Returns true if recursion on the given objects has been detected . If the given pair of objects has yet to be seen calls f and returns false . [CODESPLIT] function detectRecursion ( o1 , o2 , f ) { if ( arguments . length === 2 ) { f = o2 ; o2 = undefined ; } if ( seen ( o1 , o2 ) ) { return true ; } else { mark ( o1 , o2 ) ; try { f ( ) ; } finally { unmark ( o1 , o2 ) ; } return false ; } }


Input: Public : Returns a string indicating the type of the given object . This can be considered an enhanced version of the javascript typeof operator . Examples Transis . type ( [] ) // = > array Transis . type ( {} ) // = > object Transis . type ( 9 ) // = > number Transis . type ( / fo * / ) // = > regexp Transis . type ( new Date ) // = > date o - The object to get the type of . Returns a string indicating the object s type . [CODESPLIT] function type ( o ) { if ( o === null ) { return 'null' ; } if ( o === undefined ) { return 'undefined' ; } switch ( toString . call ( o ) ) { case '[object Array]' : return 'array' ; case '[object Arguments]' : return 'arguments' ; case '[object Function]' : return 'function' ; case '[object String]' : return 'string' ; case '[object Number]' : return 'number' ; case '[object Boolean]' : return 'boolean' ; case '[object Date]' : return 'date' ; case '[object RegExp]' : return 'regexp' ; case '[object Object]' : if ( o . hasOwnProperty ( 'callee' ) ) { return 'arguments' ; } // ie fallback else { return 'object' ; } } return 'unknown' ; }


Input: Public : Performs an object equality test . If the first argument is a Transis . Object then it is sent the eq method otherwise custom equality code is run based on the object type . a - Any object . b - Any object . Returns true if the objects are equal and false otherwise . [CODESPLIT] function eq ( a , b ) { var atype , btype ; // identical objects are equal if ( a === b ) { return true ; } // if the first argument is a Transis.Object, delegate to its `eq` method if ( a && a . objectId && typeof a . eq === 'function' ) { return a . eq ( b ) ; } atype = type ( a ) ; btype = type ( b ) ; // native objects that are not of the same type are not equal if ( atype !== btype ) { return false ; } switch ( atype ) { case 'boolean' : case 'string' : case 'date' : case 'number' : return a . valueOf ( ) === b . valueOf ( ) ; case 'regexp' : return a . source === b . source && a . global === b . global && a . multiline === b . multiline && a . ignoreCase === b . ignoreCase ; case 'array' : return arrayEq ( a , b ) ; case 'object' : return objectEq ( a , b ) ; default : return false ; } }


Input: Public : Performs a a deep array equality test . a - An Array object . b - An Array object . Returns true if the objects are equal and false otherwise . [CODESPLIT] function arrayEq ( a , b ) { var r ; if ( ! Array . isArray ( a ) || ! Array . isArray ( b ) ) { return false ; } if ( a . length !== b . length ) { return false ; } r = true ; detectRecursion ( a , b , function ( ) { var i , len ; for ( i = 0 , len = a . length ; i < len ; i ++ ) { if ( ! eq ( a [ i ] , b [ i ] ) ) { r = false ; break ; } } } ) ; return r ; }


Input: Public : Performs a a deep object equality test . a - Any object . b - Any object . Returns true if the objects are equal and false otherwise . [CODESPLIT] function objectEq ( a , b ) { var akeys = Object . keys ( a ) , bkeys = Object . keys ( b ) , r ; if ( akeys . length !== bkeys . length ) { return false ; } r = true ; detectRecursion ( a , b , function ( ) { var i , len , key ; for ( i = 0 , len = akeys . length ; i < len ; i ++ ) { key = akeys [ i ] ; if ( ! b . hasOwnProperty ( key ) ) { r = false ; break ; } if ( ! eq ( a [ key ] , b [ key ] ) ) { r = false ; break ; } } } ) ; return r ; }


Input: Public : Converts the given string to CamelCase . [CODESPLIT] function camelize ( s ) { return typeof s === 'string' ? s . replace ( / (?:[-_])(\w) / g , function ( _ , c ) { return c ? c . toUpperCase ( ) : '' ; } ) : s ; }


Input: Public : Converts the given string to under_score_case . [CODESPLIT] function underscore ( s ) { return typeof s === 'string' ? s . replace ( / ([a-z\d])([A-Z]+) / g , '$1_$2' ) . replace ( / [-\s]+ / g , '_' ) . toLowerCase ( ) : s ; }


Input: Public : Capitalizes the first letter of the given string . [CODESPLIT] function capitalize ( s ) { return typeof s === 'string' && s . length ? s [ 0 ] . toUpperCase ( ) + s . slice ( 1 ) : s ; }


Input: Internal : Returns the Transis . Model subclass with the given name . name - A string representing the name of a Transis . Model subclass . raise - A boolean indicating whether an exception should be raised if the name can t be resolved ( default : true ) . Returns the resolved subclass constructor function or undefined if a class with the given name is not known . Throws Error if the raise argument is true and the name cannot not be resolved . [CODESPLIT] function resolve ( name ) { var raise = arguments . length > 1 && arguments [ 1 ] !== undefined ? arguments [ 1 ] : true ; var klass = typeof name === 'function' ? name : subclasses [ name ] ; if ( ! klass && raise ) { throw new Error ( "Transis.Model.resolve: could not resolve subclass: `" + name + "`" ) ; } return klass ; }


Input: Internal : Checks to make sure the given object is of the type specified in the given association descriptor . Returns nothing . Throws Error if the given object isn t of the type specified in the association descriptor . [CODESPLIT] function checkAssociatedType ( desc , o ) { var klass = resolve ( desc . klass ) ; if ( o && ! ( o instanceof klass ) ) { throw new Error ( desc . debugName + ": expected an object of type `" + desc . klass + "` but received `" + o + "` instead" ) ; } }


Input: Internal : Wraps the given promise so that subsequent chained promises are called after the next flush cycle has been run . [CODESPLIT] function wrapPromise ( promise ) { return promise . then ( function ( value ) { return new Promise ( function ( resolve , reject ) { _object2 . default . delay ( function ( ) { resolve ( value ) ; } ) ; _object2 . default . _queueFlush ( ) ; } ) ; } , function ( reason ) { return new Promise ( function ( resolve , reject ) { _object2 . default . delay ( function ( ) { reject ( reason ) ; } ) ; _object2 . default . _queueFlush ( ) ; } ) ; } ) ; }


Input: Internal : The overridden _splice method used on hasMany arrays . This method syncs changes to the array to the inverse side of the association and maintains a list of changes made . [CODESPLIT] function hasManySplice ( i , n , added ) { var owner = this . __owner__ , desc = this . __desc__ , inverse = desc . inverse , name = desc . name , removed , changes , i ; added . forEach ( function ( o ) { return checkAssociatedType ( desc , o ) ; } ) ; removed = _array2 . default . prototype . _splice . call ( this , i , n , added ) ; if ( inverse && ! this . __handlingInverse__ ) { removed . forEach ( function ( model ) { model . _inverseRemoved ( inverse , owner ) ; } , this ) ; added . forEach ( function ( model ) { model . _inverseAdded ( inverse , owner ) ; } , this ) ; } if ( desc . owner && ! loads . length ) { changes = owner . ownChanges [ name ] = owner . ownChanges [ name ] || { added : [ ] , removed : [ ] } ; removed . forEach ( function ( m ) { if ( ( i = changes . added . indexOf ( m ) ) !== - 1 ) { changes . added . splice ( i , 1 ) ; } else if ( changes . removed . indexOf ( m ) === - 1 ) { changes . removed . push ( m ) ; } } ) ; added . forEach ( function ( m ) { if ( ( i = changes . removed . indexOf ( m ) ) !== - 1 ) { changes . removed . splice ( i , 1 ) ; } else if ( changes . added . indexOf ( m ) === - 1 ) { changes . added . push ( m ) ; } } ) ; if ( ! changes . added . length && ! changes . removed . length ) { owner . _clearChange ( name ) ; } else { owner . _setChange ( name , changes ) ; } } return removed ; }


Input: Internal : Called when a model is removed from the inverse side of a hasMany association in order to sync the change to the hasMany side . [CODESPLIT] function hasManyInverseRemove ( model ) { var i = this . indexOf ( model ) ; if ( i >= 0 ) { this . __handlingInverse__ = true ; this . splice ( i , 1 ) ; this . __handlingInverse__ = false ; } }


Input: Internal : Builds an array that manages a hasMany association . A hasMany array is a Transis . Array that overrides the _splice method in order to handle syncing the inverse side of the association . [CODESPLIT] function hasManyArray ( owner , desc ) { var a = _array2 . default . of ( ) ; a . proxy ( owner , desc . name ) ; a . __owner__ = owner ; a . __desc__ = desc ; a . _splice = hasManySplice ; a . _inverseAdd = hasManyInverseAdd ; a . _inverseRemove = hasManyInverseRemove ; return a ; }


Input: Internal : Provides the implementation of the query array s query method . [CODESPLIT] function queryArrayQuery ( ) { var _this = this ; var queryOpts = arguments . length > 0 && arguments [ 0 ] !== undefined ? arguments [ 0 ] : { } ; var opts = Object . assign ( { } , this . baseOpts , queryOpts ) ; if ( this . isPaged ) { opts . page = opts . page || 1 ; } if ( this . isBusy ) { if ( util . eq ( opts , this . currentOpts ) ) { return this ; } if ( ! this . __queued__ ) { this . __promise__ = this . __promise__ . then ( function ( ) { _this . query ( _this . __queued__ ) ; _this . __queued__ = undefined ; return _this . __promise__ ; } ) ; } this . __queued__ = opts ; } else { this . isBusy = true ; this . currentOpts = opts ; this . __promise__ = wrapPromise ( this . __modelClass__ . _callMapper ( 'query' , [ opts ] ) . then ( function ( result ) { var results = Array . isArray ( result ) ? result : result . results ; var meta = Array . isArray ( result ) ? { } : result . meta ; _this . isBusy = false ; _this . meta = meta ; _this . error = undefined ; if ( ! results ) { throw new Error ( _this + "#query: mapper failed to return any results" ) ; } if ( _this . isPaged && typeof meta . totalCount !== 'number' ) { throw new Error ( _this + "#query: mapper failed to return total count for paged query" ) ; } try { var models = _this . __modelClass__ . loadAll ( results ) ; if ( _this . isPaged ) { _this . length = meta . totalCount ; _this . splice . apply ( _this , [ ( opts . page - 1 ) * _this . baseOpts . pageSize , models . length ] . concat ( models ) ) ; } else { _this . replace ( models ) ; } } catch ( e ) { console . error ( e ) ; throw e ; } } , function ( e ) { _this . isBusy = false ; _this . error = e ; return Promise . reject ( e ) ; } ) ) ; } return this ; }


Input: Internal : Provides the implementation of the query array s at method . [CODESPLIT] function queryArrayAt ( i ) { var r = _array2 . default . prototype . at . apply ( this , arguments ) ; var pageSize = this . baseOpts && this . baseOpts . pageSize ; if ( arguments . length === 1 && ! r && pageSize ) { this . query ( { page : Math . floor ( i / pageSize ) + 1 } ) ; } return r ; }


Input: Internal : Callback for a successful model deletion . Updates the model s state removes it from the identity map and removes removes it from any associations its currently participating in . [CODESPLIT] function mapperDeleteSuccess ( ) { var _this2 = this ; _id_map2 . default . delete ( this ) ; this . isBusy = false ; this . sourceState = DELETED ; this . _clearErrors ( ) ; var _loop = function _loop ( name ) { var desc = _this2 . associations [ name ] ; if ( ! desc . inverse ) { return "continue" ; } if ( desc . type === 'hasOne' ) { var m = void 0 ; if ( m = _this2 [ name ] ) { m . _inverseRemoved ( desc . inverse , _this2 ) ; } } else if ( desc . type === 'hasMany' ) { _this2 [ name ] . slice ( 0 ) . forEach ( function ( m ) { m . _inverseRemoved ( desc . inverse , _this2 ) ; } ) ; } } ; for ( var name in this . associations ) { var _ret = _loop ( name ) ; if ( _ret === "continue" ) continue ; } }


Input: load and set each association [CODESPLIT] function _loop2 ( _name ) { var klass = resolve ( associations [ _name ] . klass ) ; var data = associated [ _name ] ; // clear association if ( ! data ) { model [ _name ] = null ; return "continue" ; } if ( associations [ _name ] . type === 'hasOne' ) { var other = ( typeof data === "undefined" ? "undefined" : _typeof ( data ) ) === 'object' ? klass . load ( data ) : klass . local ( data ) ; model [ _name ] = other ; } else if ( associations [ _name ] . type === 'hasMany' ) { var others = [ ] ; data . forEach ( function ( o ) { others . push ( ( typeof o === "undefined" ? "undefined" : _typeof ( o ) ) === 'object' ? klass . load ( o ) : klass . local ( o ) ) ; } ) ; model [ _name ] = others ; } }


Input: Internal : Processes recorded property changes by traversing the property dependency graph and forwarding changes to proxy objects . [CODESPLIT] function propagateChanges ( ) { var seen = { } ; var head = void 0 ; for ( var id in changedObjects ) { var _changedObjects$id = changedObjects [ id ] , object = _changedObjects$id . object , props = _changedObjects$id . props ; for ( var k in props ) { head = { object : object , name : k , next : head } ; seen [ id + k ] = true ; } } while ( head ) { var _head = head , name = _head . name , object = _head . object , _head$object = _head . object , _objectId = _head$object . objectId , __deps__ = _head$object . __deps__ , __proxies__ = _head$object . __proxies__ ; var deps = __deps__ && __deps__ [ name ] ; head = head . next ; registerChange ( object , name ) ; if ( object . __cache__ ) { var val = object . __cache__ [ name ] ; if ( val && typeof val . unproxy === 'function' ) { val . unproxy ( object , name ) ; } delete object . __cache__ [ name ] ; } if ( deps ) { for ( var i = 0 , n = deps . length ; i < n ; i ++ ) { var seenKey = _objectId + deps [ i ] ; if ( ! seen [ seenKey ] ) { head = { object : object , name : deps [ i ] , next : head } ; seen [ seenKey ] = true ; } } } if ( __proxies__ && name . indexOf ( '.' ) === - 1 ) { for ( var _k in __proxies__ ) { var proxy = __proxies__ [ _k ] ; var proxyObject = proxy . object ; var proxyName = proxy . name + '.' + name ; var proxySeenKey = proxyObject . objectId + proxyName ; if ( ! seen [ proxySeenKey ] ) { head = { object : proxyObject , name : proxyName , next : head } ; seen [ proxySeenKey ] = true ; } } } } }


Input: Internal : Flushes the current change queue . This notifies observers of the changed props as well as observers of any props that depend on the changed props . Observers are only invoked once per flush regardless of how many of their dependent props have changed . Additionaly cached values are cleared where appropriate . [CODESPLIT] function flush ( ) { var f = void 0 ; while ( f = delayPreFlushCallbacks . shift ( ) ) { f ( ) ; } propagateChanges ( ) ; var curChangedObjects = changedObjects ; changedObjects = { } ; flushTimer = null ; for ( var id in curChangedObjects ) { var _curChangedObjects$id = curChangedObjects [ id ] , object = _curChangedObjects$id . object , props = _curChangedObjects$id . props ; var star = false ; for ( var k in props ) { if ( k . indexOf ( '.' ) === - 1 ) { star = true ; } object . notify ( // strip '@' suffix if present k . length > 1 && k . endsWith ( '@' ) && ! k . endsWith ( '.@' ) ? k . slice ( 0 , k . length - 1 ) : k ) ; } if ( star ) { object . notify ( '*' ) ; } } while ( f = delayPostFlushCallbacks . shift ( ) ) { f ( ) ; } }


Input: Internal : Defines a property on the given object . See the docs for Transis . prop . Returns nothing . [CODESPLIT] function defineProp ( object , name , opts = { } ) { validateOptions ( opts ) ; var descriptor = Object . assign ( { name : name , get : null , set : null , default : undefined , on : [ ] , cache : false , pure : ! ! ( opts . get && opts . on && ! opts . set ) , } , opts , { readonly : opts . get && ! opts . set } ) ; if ( ! object . hasOwnProperty ( '__props__' ) ) { object . __props__ = Object . create ( object . __props__ || null ) ; } object . __props__ [ name ] = descriptor ; if ( ! object . hasOwnProperty ( '__deps__' ) ) { object . __deps__ = Object . create ( object . __deps__ || null ) ; } descriptor . on . forEach ( function ( prop ) { ( object . __deps__ [ prop ] = object . __deps__ [ prop ] || [ ] ) . push ( name ) ; if ( prop . indexOf ( '.' ) !== - 1 ) { let segments = prop . split ( '.' ) , first = segments [ 0 ] , last = segments [ 1 ] ; if ( segments . length > 2 ) { throw new Error ( ` \` ${ prop } \` ` ) ; } ( object . __deps__ [ first ] = object . __deps__ [ first ] || [ ] ) . push ( name ) ; ( object . __deps__ [ ` ${ first } ` ] = object . __deps__ [ ` ${ first } ` ] || [ ] ) . push ( name ) ; ( object . __deps__ [ ` ${ first } ${ last } ` ] = object . __deps__ [ ` ${ first } ${ last } ` ] || [ ] ) . push ( name ) ; } else { ( object . __deps__ [ ` ${ prop } ` ] = object . __deps__ [ ` ${ prop } ` ] || [ ] ) . push ( name ) ; } } ) ; Object . defineProperty ( object , name , { get : function ( ) { return this . _getProp ( name ) ; } , set : descriptor . readonly ? undefined : function ( value ) { this . _setProp ( name , value ) ; } , configurable : false , enumerable : true } ) ; }


Input: Internal : Returns the Transis . Model subclass with the given name . name - A string representing the name of a Transis . Model subclass . raise - A boolean indicating whether an exception should be raised if the name can t be resolved ( default : true ) . Returns the resolved subclass constructor function or undefined if a class with the given name is not known . Throws Error if the raise argument is true and the name cannot not be resolved . [CODESPLIT] function resolve ( name , raise = true ) { var klass = ( typeof name === 'function' ) ? name : subclasses [ name ] ; if ( ! klass && raise ) { throw new Error ( ` \` ${ name } \` ` ) ; } return klass ; }


Input: Internal : Sets the given object on a hasOne property . desc - An association descriptor . v - The value to set . sync - Set to true to notify the inverse side of the association so that it can update itself . Returns nothing . Throws Error if the given object isn t of the type specified in the association descriptor . [CODESPLIT] function hasOneSet ( desc , v , sync ) { var name = desc . name , k = ` ${ name } ` , prev = this [ k ] , inv = desc . inverse ; checkAssociatedType ( desc , v ) ; this [ k ] = v ; if ( sync && inv && prev ) { prev . _inverseRemoved ( inv , this ) ; } if ( sync && inv && v ) { v . _inverseAdded ( inv , this ) ; } if ( prev ) { prev . unproxy ( this , name ) ; } if ( v ) { v . proxy ( this , name ) ; } }


Input: Internal : Callback for a successful model deletion . Updates the model s state removes it from the identity map and removes removes it from any associations its currently participating in . [CODESPLIT] function mapperDeleteSuccess ( ) { IdMap . delete ( this ) ; this . isBusy = false ; this . sourceState = DELETED ; this . _clearErrors ( ) ; for ( let name in this . associations ) { let desc = this . associations [ name ] ; if ( ! desc . inverse ) { continue ; } if ( desc . type === 'hasOne' ) { let m ; if ( m = this [ name ] ) { m . _inverseRemoved ( desc . inverse , this ) ; } } else if ( desc . type === 'hasMany' ) { this [ name ] . slice ( 0 ) . forEach ( ( m ) => { m . _inverseRemoved ( desc . inverse , this ) ; } ) ; } } }


Input: Build a fake File from fixture path to be used by .. / __mocks__ / readFile . js [CODESPLIT] function file ( relpath ) { return { name : basename ( relpath ) , path : ` ${ relpath } ` , size : 123 , type : vcard . FILE_TYPES [ 0 ] } }


Input: the default error handler [CODESPLIT] function handleErrors ( errors , data ) { const message = errors [ 0 ] . message ; const error = new Error ( ` ${ message } ` ) ; error . rawError = errors ; error . rawData = data ; throw error ; }


Input: Zips a list of files or directories [CODESPLIT] function zip ( zipFile , srcList , dstPath ) { if ( ! dstPath ) { dstPath = false ; } const output = fs . createWriteStream ( zipFile ) ; const archive = archiver ( 'zip' , { zlib : { level : 9 } // Sets the compression level. } ) ; return new Promise ( ( resolve , reject ) => { output . on ( 'close' , function ( ) { return resolve ( ) ; } ) ; archive . on ( 'warning' , function ( err ) { if ( err . code === 'ENOENT' ) { console . log ( err ) ; } else { return reject ( err ) ; } } ) ; archive . on ( 'error' , function ( err ) { return reject ( err ) ; } ) ; archive . pipe ( output ) ; srcList . forEach ( ( src ) => { const stat = fs . lstatSync ( src ) ; if ( stat . isFile ( ) ) { archive . file ( src ) ; } else if ( stat . isDirectory ( ) || stat . isSymbolicLink ( ) ) { archive . directory ( src , dstPath ) ; } else { return reject ( new Error ( 'Invalid path' ) ) ; } } ) ; archive . finalize ( ) ; } ) ; }


Input: Executes shell commands synchronously and logs the stdout to console . [CODESPLIT] function exec ( cmd , verbose ) { verbose = verbose === false ? verbose : true ; const stdout = execSync ( cmd ) ; if ( verbose ) { console . log ( stdout . toString ( ) ) ; } return stdout ; }


Input: Updates region of an AWS configuration and point to the correct of profile on ~ / . aws / credentials file if necessary [CODESPLIT] function configureAws ( region , profile , role ) { if ( region ) { AWS . config . update ( { region } ) ; } if ( profile ) { AWS . config . credentials = new AWS . SharedIniFileCredentials ( { profile } ) ; } if ( role ) { AWS . config . credentials = new AWS . TemporaryCredentials ( { RoleArn : role } ) ; } }


Input: Checks if the input is a file if it is a file it reads it and return the content otherwise just pass the input as an output [CODESPLIT] function fileToString ( file ) { try { const stat = fs . lstatSync ( file ) ; if ( stat . isFile ( ) ) { const content = fs . readFileSync ( file , 'utf8' ) ; return content . toString ( ) ; } } catch ( e ) { if ( ! e . message . includes ( 'ENOENT' ) && ! e . message . includes ( 'name too long, lstat' ) ) { throw e ; } } return file ; }


Input: Merges two yaml files . The merge is done using lodash . merge and it happens recursively . Meaning that values of file2 will replace values of file 1 if they have the same key . [CODESPLIT] function mergeYamls ( file1 , file2 ) { const obj1 = yaml . safeLoad ( fileToString ( file1 ) , { schema : yamlfiles . YAML_FILES_SCHEMA } ) ; const obj2 = yaml . safeLoad ( fileToString ( file2 ) , { schema : yamlfiles . YAML_FILES_SCHEMA } ) ; return yaml . safeDump ( merge ( { } , obj1 , obj2 ) ) ; }


Input: Attempt to load a Kes override class . [CODESPLIT] function loadKesOverride ( kesFolder , kesClass = 'kes.js' ) { let kesOverridePath = path . resolve ( kesFolder , kesClass ) ; let KesOverride ; try { KesOverride = require ( kesOverridePath ) ; } catch ( e ) { // If the Kes override file exists, then the error occured when // trying to parse the file, so re-throw and prevent Kes from // going further. const fileExists = fs . existsSync ( kesOverridePath ) ; if ( fileExists ) { throw e ; } console . log ( ` ${ kesOverridePath } ` ) ; } return KesOverride ; }


Input: Based on the information passed from the CLI by the commander module this function determines whether to use the default Kes class or use the override class provided by the user [CODESPLIT] function determineKesClass ( options , Kes ) { let KesOverride ; // If there is a kes class specified, use that const kesClass = get ( options , 'kesClass' ) ; if ( kesClass ) { KesOverride = loadKesOverride ( process . cwd ( ) , kesClass ) ; } else { let kesFolder ; // Check if there is kes.js in the kes folder if ( options . kesFolder ) { kesFolder = options . kesFolder ; } else { kesFolder = path . join ( process . cwd ( ) , '.kes' ) ; } KesOverride = loadKesOverride ( kesFolder ) ; // If the first Kes override didn't load, check if there is // a kes.js in the template folder. if ( ! KesOverride ) { const template = get ( options , 'template' , '/path/to/nowhere' ) ; kesFolder = path . join ( process . cwd ( ) , template ) ; KesOverride = loadKesOverride ( kesFolder ) ; } } return KesOverride || Kes ; }


Input: In case of error logs the error and exit with error 1 [CODESPLIT] function failure ( e ) { if ( e . message ) { console . log ( e . message ) ; } else { console . log ( e ) ; } process . exit ( 1 ) ; }


Input: Discover and returns the system bucket used for deployment [CODESPLIT] function getSystemBucket ( config ) { let bucket = get ( config , 'buckets.internal' ) ; if ( bucket && typeof bucket === 'string' ) { return bucket ; } bucket = get ( config , 'system_bucket' ) ; if ( bucket && typeof bucket === 'string' ) { return bucket ; } return undefined ; }


Input: Builds templates nested in the main template using the specified config and cf file paths [CODESPLIT] function buildNestedCfs ( config , KesClass , options ) { const limit = pLimit ( 1 ) ; if ( config . nested_templates ) { const nested = config . nested_templates ; console . log ( 'Nested templates are found!' ) ; const ps = Object . keys ( nested ) . map ( ( name ) => limit ( ( ) => { console . log ( ` ${ name } ` ) ; const newOptions = Object . assign ( { } , options ) ; newOptions . cfFile = nested [ name ] . cfFile ; newOptions . configFile = nested [ name ] . configFile ; // no templates are used in nested stacks delete newOptions . template ; delete newOptions . deployment ; // use the parent stackname newOptions . stack = config . stack ; newOptions . parent = config ; const nestedConfig = new Config ( newOptions ) ; // get the bucket name from the parent if ( ! nestedConfig . bucket ) { nestedConfig . bucket = utils . getSystemBucket ( config ) ; } // add nested deployment name nestedConfig . nested_cf_name = name ; const kes = new KesClass ( nestedConfig ) ; return kes . uploadCF ( ) . then ( ( uri ) => { config . nested_templates [ name ] . url = uri ; } ) ; } ) ) ; return Promise . all ( ps ) . then ( ( ) => config ) . catch ( utils . failure ) ; } return Promise . resolve ( config ) ; }


Input: Builds uploads and deploy a Cloudformation based on options passed from the commander library [CODESPLIT] function buildCf ( options , cmd ) { const KesClass = utils . determineKesClass ( options , Kes ) ; let parentConfig ; try { parentConfig = new Config ( options ) ; } catch ( e ) { return Promise . reject ( e ) ; } return buildNestedCfs ( parentConfig , KesClass , options ) . then ( ( config ) => { const kes = new KesClass ( config ) ; switch ( cmd ) { case 'create' : deprecate ( '"kes cf create" command is deprecated. Use "kes cf deploy" instead' ) ; return kes . createStack ( ) ; case 'update' : deprecate ( '"kes cf update" command is deprecated. Use "kes cf deploy" instead' ) ; return kes . updateStack ( ) ; case 'upsert' : deprecate ( '"kes cf upsert" command is deprecated. Use "kes cf deploy" instead' ) ; return kes . upsertStack ( ) ; case 'deploy' : return kes . deployStack ( ) ; case 'validate' : return kes . validateTemplate ( ) ; case 'compile' : return kes . compileCF ( ) ; case 'delete' : return kes . deleteStack ( ) ; default : console . log ( 'Wrong choice. Accepted arguments: [create|update|upsert|deploy|validate|compile]' ) ; } } ) ; }


Input: Builds and uploads a lambda function based on the options passed by the commander [CODESPLIT] function buildLambda ( options , cmd ) { if ( cmd ) { const KesClass = utils . determineKesClass ( options , Kes ) ; const config = new Config ( options ) ; const kes = new KesClass ( config ) ; kes . updateSingleLambda ( cmd ) . then ( r => utils . success ( r ) ) . catch ( e => utils . failure ( e ) ) ; } else { utils . failure ( new Error ( 'Lambda name is missing' ) ) ; } }


Input: Send response to the pre - signed S3 URL [CODESPLIT] function sendResponse ( event , context , responseStatus , responseData ) { const responseBody = JSON . stringify ( { Status : responseStatus , Reason : 'See the details in CloudWatch Log Stream: ' + context . logStreamName , PhysicalResourceId : context . logStreamName , StackId : event . StackId , RequestId : event . RequestId , LogicalResourceId : event . LogicalResourceId , Data : responseData } ) ; console . log ( 'RESPONSE BODY:\n' , responseBody ) ; const https = require ( 'https' ) ; const url = require ( 'url' ) ; const parsedUrl = url . parse ( event . ResponseURL ) ; const options = { hostname : parsedUrl . hostname , port : 443 , path : parsedUrl . path , method : 'PUT' , headers : { 'content-type' : '' , 'content-length' : responseBody . length } } ; console . log ( 'SENDING RESPONSE...\n' ) ; const request = https . request ( options , function ( response ) { console . log ( 'STATUS: ' + response . statusCode ) ; console . log ( 'HEADERS: ' + JSON . stringify ( response . headers ) ) ; // Tell AWS Lambda that the function execution is done context . done ( ) ; } ) ; request . on ( 'error' , function ( error ) { console . log ( 'sendResponse Error:' + error ) ; // Tell AWS Lambda that the function execution is done context . done ( ) ; } ) ; // write data to request body request . write ( responseBody ) ; request . end ( ) ; }


Input: Return options converted to a string [CODESPLIT] function optionsToString ( options ) { return Object . keys ( options ) . map ( function processOption ( key ) { return key + "=" + options [ key ] ; } ) . join ( "," ) ; }


Input: Convert centered : true key into concrete left and top arguments Both can be overwritten [CODESPLIT] function optionsResolveCentered ( options ) { var result = options ; var width = window . outerWidth - options . width ; var height = window . outerHeight - options . height ; if ( options . centered ) { result . left = options . left || Math . round ( window . screenX + width / 2 ) ; result . top = options . top || Math . round ( window . screenY + height / 2.5 ) ; delete result . centered ; } return result ; }


Input: Polyfill Object . assign [CODESPLIT] function assign ( target ) { var sources = Array . prototype . slice . call ( arguments , 1 ) ; function assignArgument ( previous , source ) { Object . keys ( source ) . forEach ( function assignItem ( key ) { previous [ key ] = source [ key ] ; // eslint-disable-line no-param-reassign } ) ; return previous ; } return sources . reduce ( assignArgument , target ) ; }


Input: Create a form element add hidden inputs for all the post data and post it into a newly opened popup [CODESPLIT] function openPopupWithPost ( url , postData , name , options ) { var form = document . createElement ( "form" ) ; var win ; form . setAttribute ( "method" , "post" ) ; form . setAttribute ( "action" , url ) ; form . setAttribute ( "target" , name ) ; Object . keys ( postData ) . forEach ( function addFormItem ( key ) { var input = document . createElement ( "input" ) ; input . type = "hidden" ; input . name = key ; input . value = postData [ key ] ; form . appendChild ( input ) ; } ) ; document . body . appendChild ( form ) ; win = window . open ( "/" , name , options ) ; win . document . write ( "Loading..." ) ; form . submit ( ) ; document . body . removeChild ( form ) ; return win ; }