Input: Function that calls Solium object s linter based on user settings . If not given we lint the entire directory s ( and sub - directories ) solidity files . [CODESPLIT] function lint ( userConfig , input , ignore , errorReporter ) { let filesToLint , errorCount ; //If filename is provided, lint it. Otherwise, lint over current directory & sub-directories if ( input . file ) { if ( ! fsUtils . isFile ( input . file ) ) { errorReporter . reportFatal ( ` ${ input . file } ` ) ; process . exit ( errorCodes . INVALID_PARAMS ) ; } filesToLint = [ input . file ] ; } else if ( input . dir ) { if ( ! fsUtils . isDirectory ( input . dir ) ) { errorReporter . reportFatal ( ` ${ input . dir } ` ) ; process . exit ( errorCodes . INVALID_PARAMS ) ; } filesToLint = traverse ( input . dir , ignore ) ; } if ( filesToLint ) { errorCount = sum ( filesToLint . map ( function ( file , index ) { userConfig . options . returnInternalIssues = ( index === 0 ) ; return lintFile ( file , userConfig , errorReporter ) ; } ) ) ; } else if ( input . stdin ) { // This only works on *nix. Need to fix to enable stdin input in windows. let sourceCode = fs . readFileSync ( "/dev/stdin" , "utf-8" ) ; userConfig . options . returnInternalIssues = true ; errorCount = lintString ( sourceCode , userConfig , errorReporter , "[stdin]" ) ; } else { errorReporter . reportFatal ( "Must specify input for linter using --file, --dir or --stdin" ) ; process . exit ( errorCodes . INVALID_PARAMS ) ; } errorReporter . finalize && errorReporter . finalize ( ) ; return errorCount ; }


Input: Function responsible for defining all the available commandline options & version information [CODESPLIT] function createCliOptions ( cliObject ) { function collect ( val , memo ) { memo . push ( val ) ; return memo ; } cliObject . version ( ` ${ version } ` ) . description ( "Linter to find & fix style and security issues in Solidity smart contracts." ) . usage ( "[options] <keyword>" ) . option ( "-i, --init" , "Create default rule configuration files" ) . option ( "-f, --file [filepath::String]" , "Solidity file to lint" ) . option ( "-d, --dir [dirpath::String]" , "Directory containing Solidity files to lint" ) . option ( "-R, --reporter [name::String]" , "Format to report lint issues in (pretty | gcc)" , "pretty" ) . option ( "-c, --config [filepath::String]" , "Path to the .soliumrc configuration file" ) . option ( "-, --stdin" , "Read input file from stdin" ) . option ( "--fix" , "Fix Lint issues where possible" ) . option ( "--fix-dry-run" , "Output fix diff without applying it" ) . option ( "--debug" , "Display debug information" ) . option ( "--watch" , "Watch for file changes" ) . option ( "--hot" , "(Deprecated) Same as --watch" ) . option ( "--no-soliumignore" , "Do not look for .soliumignore file" ) . option ( "--no-soliumrc" , "Do not look for soliumrc configuration file" ) . option ( "--rule [rule]" , "Rule to execute. This overrides the specified rule's configuration in soliumrc if present" , collect , [ ] ) . option ( "--plugin [plugin]" , "Plugin to execute. This overrides the specified plugin's configuration in soliumrc if present" , collect , [ ] ) ; }


Input:
Entry point to the CLI reponsible for initiating linting process based on command - line arguments [CODESPLIT] function execute ( programArgs ) { let userConfig = { } , ignore , errorReporter ; createCliOptions ( cli ) ; programArgs . length === 2 ? cli . help ( ) : cli . parse ( programArgs ) ; if ( cli . init ) { return setupDefaultUserConfig ( ) ; } try { errorReporter = getErrorReporter ( cli . reporter ) ; } catch ( e ) { process . stderr . write ( ` ${ e . message } ${ EOL } ` ) ; process . exit ( errorCodes . INVALID_PARAMS ) ; } if ( cli . soliumrc ) { /**
         * If cli.config option is NOT specified, then resort to .soliumrc in current dir.
         * Else,
         *   If path is absolute, assign as-it-is.
         *   Else (relative pathing) join path with current dir.
         */ const soliumrcAbsPath = cli . config ? ( path . isAbsolute ( cli . config ) ? cli . config : path . join ( CWD , cli . config ) ) : SOLIUMRC_FILENAME_ABSOLUTE ; try { userConfig = require ( soliumrcAbsPath ) ; } catch ( e ) { // Check if soliumrc file exists. If yes, then the file is in an invalid format. if ( fs . existsSync ( soliumrcAbsPath ) ) { errorReporter . reportFatal ( ` ${ SOLIUMRC_FILENAME } ${ e . message } ` ) ; } else { if ( cli . config ) { errorReporter . reportFatal ( ` ${ soliumrcAbsPath } ` ) ; } else { errorReporter . reportFatal ( ` ${ SOLIUMRC_FILENAME } ` ) ; } } process . exit ( errorCodes . NO_SOLIUMRC ) ; } } //if custom rules' file is set, make sure we have its absolute path if ( userConfig [ "custom-rules-filename" ] && ! path . isAbsolute ( userConfig [ "custom-rules-filename" ] ) ) { userConfig [ "custom-rules-filename" ] = path . join ( CWD , userConfig [ "custom-rules-filename" ] ) ; } // Pass cli arguments that modify the behaviour of upstream functions. userConfig . options = { autofix : Boolean ( cli . fix ) , autofixDryrun : Boolean ( cli . fixDryRun ) , debug : Boolean ( cli . debug ) } ; if ( userConfig . options . autofixDryrun ) { if ( userConfig . options . autofix ) { return errorReporter . reportFatal ( "Cannot use both --fix and --fix-dry-run" ) ; } if ( cli . reporter != "pretty" ) { return errorReporter . reportFatal ( "Option --fix-dry-run is only supported with pretty reporter" ) ; } } userConfig . plugins = userConfig . plugins || [ ] ; userConfig . rules = userConfig . rules || { } ; for ( const plugin of cli . plugin ) { userConfig . plugins . push ( plugin ) ; } for ( const rule of cli . rule ) { // If no ":" was found, it means only the rule's name was specified. // Treat it as an error and adopt its default configuration options. if ( ! rule . includes ( ":" ) ) { userConfig . rules [ rule ] = "error" ; continue ; } let [ key , value ] = rule . split ( ":" ) . map ( i => i . trim ( ) ) ; try { value = JSON . parse ( value ) ; } catch ( e ) { errorReporter . reportFatal ( ` ${ rule } ${ e . message } ` ) ; process . exit ( errorCodes . INVALID_PARAMS ) ; } userConfig . rules [ key ] = value ; } //get all files & folders to ignore from .soliumignore if ( cli . soliumignore ) { try { ignore = fs . readFileSync ( SOLIUMIGNORE_FILENAME_ABSOLUTE , "utf8" ) . split ( EOL ) ; } catch ( e ) { if ( e . code === "ENOENT" ) { errorReporter . reportInternal ( "No '.soliumignore' found. Use --no-soliumignore to make this warning go away." ) ; } else { errorReporter . reportInternal ( ` ${ e . message } ` ) ; } } } if ( cli . hot ) { // --hot is equivalent to --watch in functionality, is a legacy option cli . watch = true ; } if ( cli . watch ) { if ( cli . stdin ) { return errorReporter . reportFatal ( "Cannot watch files when reading from stdin" ) ; } if ( cli . fix ) { return errorReporter . reportFatal ( "Automatic code formatting is not supported in watch mode." ) ; } } let errorCount = lint ( userConfig , { file : cli . file , dir : cli . dir , stdin : cli . stdin } , ignore , errorReporter ) ; if ( cli . watch ) { let spy = chokidar . watch ( CWD ) ; spy . on ( "change" , function ( ) { console . log ( "\x1Bc" ) ; // clear the console console . log ( ` ${ EOL } ` ) ; lint ( userConfig , { file : cli . file , dir : cli . dir } , ignore , errorReporter ) ; //lint on subsequent changes (hot) console . log ( ` ${ EOL } ` ) ; } ) ; } else if ( errorCount > 0 ) { process . exit ( errorCodes . ERRORS_FOUND ) ; } }


Input: Determine whether the options object supplied is valid according to the schema passed . [CODESPLIT] function ( options , listItemsSchema ) { let validateOptionsList = SchemaValidator . compile ( { type : "array" , minItems : listItemsSchema . length , additionalItems : false , items : listItemsSchema } ) ; return validateOptionsList ( options ) ; }


Input: Find index of the first visibility modifier in declaration . Find the first non - VM before this first VM found above . If non - VM found report the VM . [CODESPLIT] function inspectFD ( emitted ) { const { node } = emitted , visibilityModifiers = [ "public" , "external" , "internal" , "private" ] ; const modifiers = ( node . modifiers || [ ] ) , firstVisibilityModifierIndex = modifiers . findIndex ( m => visibilityModifiers . includes ( m . name ) ) ; // If no visibility modifiers exist in function declaration, exit now if ( emitted . exit || firstVisibilityModifierIndex === - 1 ) { return ; } const firstNonVisModifBeforeFirstVisModif = modifiers . slice ( 0 , firstVisibilityModifierIndex ) . find ( m => ! visibilityModifiers . includes ( m . name ) ) ; // TODO: Add fix() for this rule if ( firstNonVisModifBeforeFirstVisModif ) { const issue = { node : modifiers [ firstVisibilityModifierIndex ] , message : ` ${ modifiers [ firstVisibilityModifierIndex ] . name } ` } ; context . report ( issue ) ; } }


Input: function params ( if on multiple lines ) [CODESPLIT] function inspectFunctionDeclaration ( emitted ) { let node = emitted . node , params = node . params || [ ] ; let startLine = sourceCode . getLine ( node ) , lastArgLine = params . length ? sourceCode . getEndingLine ( params . slice ( - 1 ) [ 0 ] ) : startLine ; if ( emitted . exit ) { return ; } if ( startLine === lastArgLine ) { if ( params . length > MAX_IN_SINGLE_LINE ) { context . report ( { node : node , message : "In case of more than " + MAX_IN_SINGLE_LINE + " parameters, drop each into its own line." } ) ; } return ; } }


Input: Determine whether the provided literal is in Hex Notation [CODESPLIT] function isHex ( literal ) { let reg = / ^[0-9a-f]+$ / i ; //test for '0x' separately because hex notation should not be a part of the standard RegExp if ( literal . slice ( 0 , 2 ) !== "0x" ) { return false ; } return reg . test ( literal . slice ( 2 ) ) ; }


Input: Create a Soundfont object [CODESPLIT] function Soundfont ( ctx , nameToUrl ) { console . warn ( 'new Soundfont() is deprected' ) console . log ( 'Please use Soundfont.instrument() instead of new Soundfont().instrument()' ) if ( ! ( this instanceof Soundfont ) ) return new Soundfont ( ctx ) this . nameToUrl = nameToUrl || Soundfont . nameToUrl this . ctx = ctx this . instruments = { } this . promises = [ ] }


Input: / * Load the buffers of a given instrument name . It returns a promise that resolves to a hash with midi note numbers as keys and audio buffers as values . [CODESPLIT] function loadBuffers ( ac , name , options ) { console . warn ( 'Soundfont.loadBuffers is deprecate.' ) console . log ( 'Use Soundfont.instrument(..) and get buffers properties from the result.' ) return Soundfont . instrument ( ac , name , options ) . then ( function ( inst ) { return inst . buffers } ) }


Input: Returns a function that plays an oscillator [CODESPLIT] function oscillatorPlayer ( ctx , defaultOptions ) { defaultOptions = defaultOptions || { } return function ( note , time , duration , options ) { console . warn ( 'The oscillator player is deprecated.' ) console . log ( 'Starting with version 0.9.0 you will have to wait until the soundfont is loaded to play sounds.' ) var midi = note > 0 && note < 129 ? + note : parser . midi ( note ) var freq = midi ? parser . midiToFreq ( midi , 440 ) : null if ( ! freq ) return duration = duration || 0.2 options = options || { } var destination = options . destination || defaultOptions . destination || ctx . destination var vcoType = options . vcoType || defaultOptions . vcoType || 'sine' var gain = options . gain || defaultOptions . gain || 0.4 var vco = ctx . createOscillator ( ) vco . type = vcoType vco . frequency . value = freq /* VCA */ var vca = ctx . createGain ( ) vca . gain . value = gain /* Connections */ vco . connect ( vca ) vca . connect ( destination ) vco . start ( time ) if ( duration > 0 ) vco . stop ( time + duration ) return vco } }


Input: Load a soundfont instrument . It returns a promise that resolves to a instrument object . [CODESPLIT] function instrument ( ac , name , options ) { if ( arguments . length === 1 ) return function ( n , o ) { return instrument ( ac , n , o ) } var opts = options || { } var isUrl = opts . isSoundfontURL || isSoundfontURL var toUrl = opts . nameToUrl || nameToUrl var url = isUrl ( name ) ? name : toUrl ( name , opts . soundfont , opts . format ) return load ( ac , url , { only : opts . only || opts . notes } ) . then ( function ( buffers ) { var p = player ( ac , buffers , opts ) . connect ( opts . destination ? opts . destination : ac . destination ) p . url = url p . name = name return p } ) }


Input: Given an instrument name returns a URL to to the Benjamin Gleitzman s package of [ pre - rendered sound fonts ] ( https : // github . com / gleitz / midi - js - soundfonts ) [CODESPLIT] function nameToUrl ( name , sf , format ) { format = format === 'ogg' ? format : 'mp3' sf = sf === 'FluidR3_GM' ? sf : 'MusyngKite' return 'https://gleitz.github.io/midi-js-soundfonts/' + sf + '/' + name + '-' + format + '.js' }


Input: Checks for lib using ldconfig if present or searching SYSTEM_PATHS otherwise . [CODESPLIT] function hasSystemLib ( lib ) { var libName = 'lib' + lib + '.+(so|dylib)' var libNameRegex = new RegExp ( libName ) // Try using ldconfig on linux systems if ( hasLdconfig ( ) ) { try { if ( childProcess . execSync ( 'ldconfig -p 2>/dev/null | grep -E "' + libName + '"' ) . length ) { return true } } catch ( err ) { // noop -- proceed to other search methods } } // Try checking common library locations return SYSTEM_PATHS . some ( function ( systemPath ) { try { var dirListing = fs . readdirSync ( systemPath ) return dirListing . some ( function ( file ) { return libNameRegex . test ( file ) } ) } catch ( err ) { return false } } ) }


Input: Checks for ldconfig on the path and / sbin [CODESPLIT] function hasLdconfig ( ) { try { // Add /sbin to path as ldconfig is located there on some systems -- e.g. // Debian (and it can still be used by unprivileged users): childProcess . execSync ( 'export PATH="$PATH:/sbin"' ) process . env . PATH = '...' // execSync throws on nonzero exit childProcess . execSync ( 'hash ldconfig 2>/dev/null' ) return true } catch ( err ) { return false } }


Input: Helper function to convert a callback to a Promise . [CODESPLIT] async function thenify ( fn ) { return await new Promise ( function ( resolve , reject ) { function callback ( err , res ) { if ( err ) return reject ( err ) ; return resolve ( res ) ; } fn ( callback ) ; } ) ; }


Input: Estimates spent working hours based on commit dates [CODESPLIT] function startWatching ( opts ) { var chokidarOpts = createChokidarOpts ( opts ) ; var watcher = chokidar . watch ( opts . patterns , chokidarOpts ) ; var throttledRun = _ . throttle ( run , opts . throttle ) ; var debouncedRun = _ . debounce ( throttledRun , opts . debounce ) ; watcher . on ( 'all' , function ( event , path ) { var description = EVENT_DESCRIPTIONS [ event ] + ':' ; if ( opts . verbose ) { console . error ( description , path ) ; } else { if ( ! opts . silent ) { console . log ( event + ':' + path ) ; } } // XXX: commands might be still run concurrently if ( opts . command ) { debouncedRun ( opts . command . replace ( / \{path\} / ig , path ) . replace ( / \{event\} / ig , event ) ) ; } } ) ; watcher . on ( 'error' , function ( error ) { console . error ( 'Error:' , error ) ; console . error ( error . stack ) ; } ) ; watcher . once ( 'ready' , function ( ) { var list = opts . patterns . join ( '", "' ) ; if ( ! opts . silent ) { console . error ( 'Watching' , '"' + list + '" ..' ) ; } } ) ; }


Input: Takes string or array of strings [CODESPLIT] function _resolveIgnoreOpt ( ignoreOpt ) { if ( ! ignoreOpt ) { return ignoreOpt ; } var ignores = ! _ . isArray ( ignoreOpt ) ? [ ignoreOpt ] : ignoreOpt ; return _ . map ( ignores , function ( ignore ) { var isRegex = ignore [ 0 ] === '/' && ignore [ ignore . length - 1 ] === '/' ; if ( isRegex ) { // Convert user input to regex object var match = ignore . match ( new RegExp ( '^/(.*)/(.*?)$' ) ) ; return new RegExp ( match [ 1 ] , match [ 2 ] ) ; } return ignore ; } ) ; }


Input: XXX : Wrapping tos to a promise is a bit wrong abstraction . Maybe RX suits better? [CODESPLIT] function run ( cmd , opts ) { if ( ! SHELL_PATH ) { // If we cannot resolve shell, better to just crash throw new Error ( '$SHELL environment variable is not set.' ) ; } opts = _ . merge ( { pipe : true , cwd : undefined , callback : function ( child ) { // Since we return promise, we need to provide // this callback if one wants to access the child // process reference // Called immediately after successful child process // spawn } } , opts ) ; return new Promise ( function ( resolve , reject ) { var child ; try { child = childProcess . spawn ( SHELL_PATH , [ EXECUTE_OPTION , cmd ] , { cwd : opts . cwd , stdio : opts . pipe ? 'inherit' : null } ) ; } catch ( e ) { return Promise . reject ( e ) ; } opts . callback ( child ) ; function errorHandler ( err ) { child . removeListener ( 'close' , closeHandler ) ; reject ( err ) ; } function closeHandler ( exitCode ) { child . removeListener ( 'error' , errorHandler ) ; resolve ( exitCode ) ; } child . once ( 'error' , errorHandler ) ; child . once ( 'close' , closeHandler ) ; } ) ; }


Input: Require a prop to not be empty [CODESPLIT] function requireProp ( props , propName , componentName ) { return isEmpty ( props [ propName ] ) ? new Error ( ` \` ${ propName } \` \` ${ componentName } \` ` ) : null }


Input: Accept any number in the 0 = > 1 range [CODESPLIT] function _0to1 ( props , propName , componentName ) { if ( isEmpty ( props [ propName ] ) ) { return null } if ( typeof props [ propName ] === 'number' && props [ propName ] >= 0 && props [ propName ] <= 1 ) { return null } return new Error ( ` \` ${ propName } \` \` ${ componentName } \` ` ) }


Input: The thread - loader parallelizes code compilation useful with babel since it transpiles both application javascript and node_modules javascript [CODESPLIT] function babel ( options = { } ) { return ( context , { addLoader } ) => addLoader ( { // setting `test` defaults here, in case there is no `context.match` data test : / \.(js|jsx)$ / , use : [ { loader : 'thread-loader' , options : { // Keep workers alive for more effective watch mode ... ( process . env . NODE_ENV === 'development' && { poolTimeout : Infinity } ) , } , } , { loader : 'babel-loader' , options : Object . assign ( babelLoaderOptions , options ) , } , ] , ... context . match , } ) }


Input: Extracts the css and puts it in the <head > [CODESPLIT] function extractCss ( ) { return ( context , { addLoader } ) => addLoader ( { test : / \.css$ / , use : [ { loader : MiniCssExtractPlugin . loader , } , ] , ... context . match , } ) }


Input: Images smaller than 10kb are loaded as a base64 encoded url instead of file url [CODESPLIT] function imageLoader ( ) { return ( context , { addLoader } ) => addLoader ( { test : / \.(gif|ico|jpg|jpeg|png|webp)$ / , loader : 'url-loader' , options : { limit : 10000 , name : fileNameTemplate , } , } ) }


Input: Parse . csv files with PapaParse and return it in a JSON format [CODESPLIT] function csvLoader ( ) { return ( context , { addLoader } ) => addLoader ( { test : / \.csv$ / , loader : 'csv-loader' , options : { dynamicTyping : true , header : true , skipEmptyLines : true , } , } ) }


Input: Allows you to use two kinds of imports for SVG : import logoUrl from . / logo . svg ; gives you the URL . import { ReactComponent as Logo } from . / logo . svg ; gives you a component . [CODESPLIT] function reactSvgLoader ( ) { return ( context , { addLoader } ) => addLoader ( { test : / \.svg$ / , issuer : { test : / \.(js|jsx|ts|tsx)$ / , } , use : [ // TODO this is probably not needed // { //   loader: 'babel-loader', //   options: babelLoaderOptions, // }, { loader : '@svgr/webpack' , options : { svgProps : { fill : 'currentColor' , } , titleProp : true , svgoConfig : { multipass : true , pretty : process . env . NODE_ENV === 'development' , indent : 2 , plugins : [ { sortAttrs : true } , { removeViewBox : false } , { removeDimensions : true } , { convertColors : { currentColor : true } } , { cleanupIDs : { minify : false } } , ] , } , } , } , { loader : 'url-loader' , options : { limit : 10000 , name : fileNameTemplate , } , } , ] , } ) }


Input: Url - loader for svgs in css [CODESPLIT] function cssSvgLoader ( ) { return ( context , { addLoader } ) => addLoader ( { // This needs to be different form the reactSvgLoader, otherwise it will merge test : / (.*)\.svg$ / , issuer : { test : / \.css$ / , } , loader : 'url-loader' , options : { limit : 10000 , name : fileNameTemplate , } , } ) }


Input: Add entryPoint at beginning of entry array [CODESPLIT] function prependEntry ( entry ) { const blockFunction = ( context , util ) => { if ( ! context . entriesToPrepend ) context . entriesToPrepend = [ ] context . entriesToPrepend . unshift ( entry ) return config => config } return Object . assign ( blockFunction , { post : prependEntryPostHook , } ) }


Input: Create the production build and print the deployment instructions . [CODESPLIT] function build ( ) { log . info ( ` ` ) const compiler = createWebpackCompiler ( ( ) => { log . ok ( ` ${ chalk . cyan ( relativeAppBuildPath ) } ` ) } , ( ) => { log . err ( ` ` ) process . exit ( 2 ) } ) return new Promise ( ( resolve , reject ) => { compiler . run ( ( err , stats ) => { if ( err ) { return reject ( err ) } return resolve ( stats ) } ) } ) }


Input: / * The webpack compiler is a low - level interface to Webpack that lets us listen to some events and provide our own custom messages . [CODESPLIT] function createWebpackCompiler ( onFirstReadyCallback = ( ) => { } , onError = ( ) => { } ) { let compiler try { const config = readWebpackConfig ( ) compiler = webpack ( config ) } catch ( err ) { log . err ( ` \n ${ err . message || err } ` ) process . exit ( 1 ) } const useTypeScript = fs . existsSync ( ` ${ appDir } ` ) // You have changed a file, bundle is now "invalidated", and Webpack is recompiling a bundle. compiler . hooks . invalid . tap ( 'invalid' , filePath => { const filePathRelative = path . relative ( appDir , filePath ) console . log ( ) log . info ( ` ${ chalk . cyan ( filePathRelative ) } ` ) } ) let isFirstCompile = true let tsMessagesPromise // used to wait for the typechecking let tsMessagesResolver // used to trigger the messages after the typechecking if ( useTypeScript ) { // reset the promise compiler . hooks . beforeCompile . tap ( 'beforeCompile' , ( ) => { tsMessagesPromise = new Promise ( resolve => { tsMessagesResolver = msgs => resolve ( msgs ) } ) } ) // trigger the rest of done function ForkTsCheckerWebpackPlugin . getCompilerHooks ( compiler ) . receive . tap ( 'afterTypeScriptCheck' , ( diagnostics , lints ) => { const allMsgs = [ ... diagnostics , ... lints ] const format = message => ` ${ message . file } \n ${ typescriptFormatter ( message , true ) } ` tsMessagesResolver ( { errors : allMsgs . filter ( msg => msg . severity === 'error' ) . map ( format ) , warnings : allMsgs . filter ( msg => msg . severity === 'warning' ) . map ( format ) , } ) } ) } // Webpack has finished recompiling the bundle (whether or not you have warnings or errors) compiler . hooks . done . tap ( 'done' , async stats => { const statsJson = stats . toJson ( { all : false , warnings : true , errors : true , timings : true , } ) if ( useTypeScript && statsJson . errors . length === 0 ) { // push typescript errors and warnings const messages = await tsMessagesPromise statsJson . errors . push ( ... messages . errors ) statsJson . warnings . push ( ... messages . warnings ) // Push errors and warnings into compilation result // to show them after page refresh triggered by user. stats . compilation . errors . push ( ... messages . errors ) stats . compilation . warnings . push ( ... messages . warnings ) // if (messages.errors.length > 0) { //   devSocket.errors(messages.errors); // } else if (messages.warnings.length > 0) { //   devSocket.warnings(messages.warnings); // } } const messages = formatWebpackMessages ( statsJson ) const time = prettyMs ( statsJson . time ) const isSuccessful = messages . errors . length + messages . warnings . length === 0 if ( isSuccessful ) { log . ok ( ` ${ chalk . cyan ( time ) } ` ) } else if ( messages . errors . length > 0 ) { log . err ( 'Errors in compiling:' ) // Only log the first error. Others are often indicative // of the same problem, but confuse the reader with noise console . log ( listLine ( messages . errors [ 0 ] , chalk . red ) ) onError ( ) } else if ( messages . warnings . length > 0 ) { log . warn ( ` ${ chalk . cyan ( time ) } ` ) messages . warnings . forEach ( message => { console . log ( listLine ( message , chalk . yellow ) ) } ) } // If the first time compiles, also with warnings, // call the onFirstReadyCallback if ( isFirstCompile && messages . errors . length === 0 ) { onFirstReadyCallback ( ) isFirstCompile = false } } ) return compiler }


Input: Helper that recursively merges two data objects together . [CODESPLIT] function mergeData ( to , from ) { if ( ! from ) { return to } var key , toVal , fromVal ; var keys = Object . keys ( from ) ; for ( var i = 0 ; i < keys . length ; i ++ ) { key = keys [ i ] ; toVal = to [ key ] ; fromVal = from [ key ] ; if ( ! hasOwn ( to , key ) ) { set ( to , key , fromVal ) ; } else if ( toVal !== fromVal && isPlainObject ( toVal ) && isPlainObject ( fromVal ) ) { mergeData ( toVal , fromVal ) ; } } return to }


Input: Wrap a function so that if any code inside triggers state change the changes are queued using a ( macro ) task instead of a microtask . [CODESPLIT] function withMacroTask ( fn ) { return fn . _withTask || ( fn . _withTask = function ( ) { useMacroTask = true ; try { return fn . apply ( null , arguments ) } finally { useMacroTask = false ; } } ) }


Input: / * [CODESPLIT] function transformNode ( el , options ) { var warn = options . warn || baseWarn ; var staticClass = getAndRemoveAttr ( el , 'class' ) ; if ( staticClass ) { var res = parseText ( staticClass , options . delimiters ) ; if ( res ) { warn ( "class=\"" + staticClass + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div class="{{ val }}">, use <div :class="val">.' ) ; } } if ( staticClass ) { el . staticClass = JSON . stringify ( staticClass ) ; } var classBinding = getBindingAttr ( el , 'class' , false /* getStatic */ ) ; if ( classBinding ) { el . classBinding = classBinding ; } }


Input: / * [CODESPLIT] function transformNode$1 ( el , options ) { var warn = options . warn || baseWarn ; var staticStyle = getAndRemoveAttr ( el , 'style' ) ; if ( staticStyle ) { /* istanbul ignore if */ { var res = parseText ( staticStyle , options . delimiters ) ; if ( res ) { warn ( "style=\"" + staticStyle + "\": " + 'Interpolation inside attributes has been removed. ' + 'Use v-bind or the colon shorthand instead. For example, ' + 'instead of <div style="{{ val }}">, use <div :style="val">.' ) ; } } el . staticStyle = JSON . stringify ( parseStyleText ( staticStyle ) ) ; } var styleBinding = getBindingAttr ( el , 'style' , false /* getStatic */ ) ; if ( styleBinding ) { el . styleBinding = styleBinding ; } }


Input: Checks if value is a plain object that is an object created by the Object constructor or one with a [[ Prototype ]] of null . [CODESPLIT] function isPlainObject ( value ) { if ( ! isObjectLike_1 ( value ) || _baseGetTag ( value ) != objectTag ) { return false ; } var proto = _getPrototype ( value ) ; if ( proto === null ) { return true ; } var Ctor = hasOwnProperty$1 . call ( proto , 'constructor' ) && proto . constructor ; return typeof Ctor == 'function' && Ctor instanceof Ctor && funcToString . call ( Ctor ) == objectCtorString ; }


Input: https : // github . com / vuejs / vue / blob / dev / src / core / util / props . js#L177 [CODESPLIT] function getType ( fn ) { var type = fn !== null && fn !== undefined ? fn . type ? fn . type : fn : null ; var match = type && type . toString ( ) . match ( FN_MATCH_REGEXP ) ; return match && match [ 1 ] ; }


Input: Adds a def method to the object returning a new object with passed in argument as default property [CODESPLIT] function withDefault ( type ) { return Object . defineProperty ( type , 'def' , { value : function value ( def ) { if ( def === undefined && ! this . default ) { return this ; } if ( ! isFunction ( def ) && ! validateType ( this , def ) ) { warn ( this . _vueTypes_name + " - invalid default value: \"" + def + "\"" , def ) ; return this ; } if ( isArray ( def ) ) { this . default = function ( ) { return [ ] . concat ( def ) ; } ; } else if ( isPlainObject_1 ( def ) ) { this . default = function ( ) { return Object . assign ( { } , def ) ; } ; } else { this . default = def ; } return this ; } , enumerable : false , writable : false } ) ; }


Input: Adds a isRequired getter returning a new object with required : true key - value [CODESPLIT] function withRequired ( type ) { return Object . defineProperty ( type , 'isRequired' , { get : function get ( ) { this . required = true ; return this ; } , enumerable : false } ) ; }


Input: Adds a validate method useful to set the prop validator function . [CODESPLIT] function withValidate ( type ) { return Object . defineProperty ( type , 'validate' , { value : function value ( fn ) { this . validator = fn . bind ( this ) ; return this ; } , enumerable : false } ) ; }


Input: Adds isRequired and def modifiers to an object [CODESPLIT] function toType ( name , obj , validateFn ) { if ( validateFn === void 0 ) { validateFn = false ; } Object . defineProperty ( obj , '_vueTypes_name' , { enumerable : false , writable : false , value : name } ) ; withDefault ( withRequired ( obj ) ) ; if ( validateFn ) { withValidate ( obj ) ; } if ( isFunction ( obj . validator ) ) { obj . validator = obj . validator . bind ( obj ) ; } return obj ; }


Input: Validates a given value against a prop type object [CODESPLIT] function validateType ( type , value , silent ) { if ( silent === void 0 ) { silent = false ; } var typeToCheck = type ; var valid = true ; var expectedType ; if ( ! isPlainObject_1 ( type ) ) { typeToCheck = { type : type } ; } var namePrefix = typeToCheck . _vueTypes_name ? typeToCheck . _vueTypes_name + ' - ' : '' ; if ( hasOwn . call ( typeToCheck , 'type' ) && typeToCheck . type !== null ) { if ( isArray ( typeToCheck . type ) ) { valid = typeToCheck . type . some ( function ( type ) { return validateType ( type , value , true ) ; } ) ; expectedType = typeToCheck . type . map ( function ( type ) { return getType ( type ) ; } ) . join ( ' or ' ) ; } else { expectedType = getType ( typeToCheck ) ; if ( expectedType === 'Array' ) { valid = isArray ( value ) ; } else if ( expectedType === 'Object' ) { valid = isPlainObject_1 ( value ) ; } else if ( expectedType === 'String' || expectedType === 'Number' || expectedType === 'Boolean' || expectedType === 'Function' ) { valid = getNativeType ( value ) === expectedType ; } else { valid = value instanceof typeToCheck . type ; } } } if ( ! valid ) { silent === false && warn ( namePrefix + "value \"" + value + "\" should be of type \"" + expectedType + "\"" ) ; return false ; } if ( hasOwn . call ( typeToCheck , 'validator' ) && isFunction ( typeToCheck . validator ) ) { // swallow warn var oldWarn ; if ( silent ) { oldWarn = warn ; warn = noop ; } valid = typeToCheck . validator ( value ) ; oldWarn && ( warn = oldWarn ) ; if ( ! valid && silent === false ) warn ( namePrefix + "custom validation failed" ) ; return valid ; } return valid ; }


Input: the infamous substitute [CODESPLIT] function CustomEvent ( type , eventInitDict ) { /*jshint eqnull:true */ var event = document . createEvent ( eventName ) ; if ( typeof type != 'string' ) { throw new Error ( 'An event name must be provided' ) ; } if ( eventName == 'Event' ) { event . initCustomEvent = initCustomEvent ; } if ( eventInitDict == null ) { eventInitDict = defaultInitDict ; } event . initCustomEvent ( type , eventInitDict . bubbles , eventInitDict . cancelable , eventInitDict . detail ) ; return event ; }


Input: attached at runtime [CODESPLIT] function initCustomEvent ( type , bubbles , cancelable , detail ) { /*jshint validthis:true*/ this . initEvent ( type , bubbles , cancelable ) ; this . detail = detail ; }


Input: https : // dom . spec . whatwg . org / #interface - eventtarget [CODESPLIT] function createEventListener ( type , callback , options ) { function eventListener ( e ) { if ( eventListener . once ) { e . currentTarget . removeEventListener ( e . type , callback , eventListener ) ; eventListener . removed = true ; } if ( eventListener . passive ) { e . preventDefault = createEventListener . preventDefault ; } if ( typeof eventListener . callback === 'function' ) { /* jshint validthis: true */ eventListener . callback . call ( this , e ) ; } else if ( eventListener . callback ) { eventListener . callback . handleEvent ( e ) ; } if ( eventListener . passive ) { delete e . preventDefault ; } } eventListener . type = type ; eventListener . callback = callback ; eventListener . capture = ! ! options . capture ; eventListener . passive = ! ! options . passive ; eventListener . once = ! ! options . once ; // currently pointless but specs say to use it, so ... eventListener . removed = false ; return eventListener ; }


Input: Removes all events set by this instance during runtime [CODESPLIT] function cleanUpRuntimeEvents ( ) { // Remove all touch events added during 'onDown' as well. document . removeEventListener ( 'touchmove' , onMove , getPassiveSupported ( ) ? { passive : false } : false ) ; document . removeEventListener ( 'touchend' , onUp ) ; document . removeEventListener ( 'touchcancel' , stopTracking ) ; document . removeEventListener ( 'mousemove' , onMove , getPassiveSupported ( ) ? { passive : false } : false ) ; document . removeEventListener ( 'mouseup' , onUp ) ; }


Input: Add all required runtime events [CODESPLIT] function addRuntimeEvents ( ) { cleanUpRuntimeEvents ( ) ; // @see https://developers.google.com/web/updates/2017/01/scrolling-intervention document . addEventListener ( 'touchmove' , onMove , getPassiveSupported ( ) ? { passive : false } : false ) ; document . addEventListener ( 'touchend' , onUp ) ; document . addEventListener ( 'touchcancel' , stopTracking ) ; document . addEventListener ( 'mousemove' , onMove , getPassiveSupported ( ) ? { passive : false } : false ) ; document . addEventListener ( 'mouseup' , onUp ) ; }


Input: Creates a custom normalized event object from touch and mouse events [CODESPLIT] function normalizeEvent ( ev ) { if ( ev . type === 'touchmove' || ev . type === 'touchstart' || ev . type === 'touchend' ) { var touch = ev . targetTouches [ 0 ] || ev . changedTouches [ 0 ] ; return { x : touch . clientX , y : touch . clientY , id : touch . identifier } ; } else { // mouse events return { x : ev . clientX , y : ev . clientY , id : null } ; } }


Input: Initializes movement tracking [CODESPLIT] function onDown ( ev ) { var event = normalizeEvent ( ev ) ; if ( ! pointerActive && ! paused ) { pointerActive = true ; decelerating = false ; pointerId = event . id ; pointerLastX = pointerCurrentX = event . x ; pointerLastY = pointerCurrentY = event . y ; trackingPoints = [ ] ; addTrackingPoint ( pointerLastX , pointerLastY ) ; addRuntimeEvents ( ) ; } }


Input: Handles move events [CODESPLIT] function onMove ( ev ) { ev . preventDefault ( ) ; var event = normalizeEvent ( ev ) ; if ( pointerActive && event . id === pointerId ) { pointerCurrentX = event . x ; pointerCurrentY = event . y ; addTrackingPoint ( pointerLastX , pointerLastY ) ; requestTick ( ) ; } }


Input: Handles up / end events [CODESPLIT] function onUp ( ev ) { var event = normalizeEvent ( ev ) ; if ( pointerActive && event . id === pointerId ) { stopTracking ( ) ; } }


Input: Records movement for the last 100ms [CODESPLIT] function addTrackingPoint ( x , y ) { var time = Date . now ( ) ; while ( trackingPoints . length > 0 ) { if ( time - trackingPoints [ 0 ] . time <= 100 ) { break ; } trackingPoints . shift ( ) ; } trackingPoints . push ( { x : x , y : y , time : time } ) ; }


Input: Calculate new values call update function [CODESPLIT] function updateAndRender ( ) { var pointerChangeX = pointerCurrentX - pointerLastX ; var pointerChangeY = pointerCurrentY - pointerLastY ; targetX += pointerChangeX * multiplier ; targetY += pointerChangeY * multiplier ; if ( bounce ) { var diff = checkBounds ( ) ; if ( diff . x !== 0 ) { targetX -= pointerChangeX * dragOutOfBoundsMultiplier ( diff . x ) * multiplier ; } if ( diff . y !== 0 ) { targetY -= pointerChangeY * dragOutOfBoundsMultiplier ( diff . y ) * multiplier ; } } else { checkBounds ( true ) ; } callUpdateCallback ( ) ; pointerLastX = pointerCurrentX ; pointerLastY = pointerCurrentY ; ticking = false ; }


Input: Initialize animation of values coming to a stop [CODESPLIT] function startDecelAnim ( ) { var firstPoint = trackingPoints [ 0 ] ; var lastPoint = trackingPoints [ trackingPoints . length - 1 ] ; var xOffset = lastPoint . x - firstPoint . x ; var yOffset = lastPoint . y - firstPoint . y ; var timeOffset = lastPoint . time - firstPoint . time ; var D = timeOffset / 15 / multiplier ; decVelX = xOffset / D || 0 ; // prevent NaN decVelY = yOffset / D || 0 ; var diff = checkBounds ( ) ; if ( Math . abs ( decVelX ) > 1 || Math . abs ( decVelY ) > 1 || ! diff . inBounds ) { decelerating = true ; requestAnimFrame ( stepDecelAnim ) ; } }


Input: Animates values slowing down [CODESPLIT] function stepDecelAnim ( ) { if ( ! decelerating ) { return ; } decVelX *= friction ; decVelY *= friction ; targetX += decVelX ; targetY += decVelY ; var diff = checkBounds ( ) ; if ( Math . abs ( decVelX ) > stopThreshold || Math . abs ( decVelY ) > stopThreshold || ! diff . inBounds ) { if ( bounce ) { var reboundAdjust = 2.5 ; if ( diff . x !== 0 ) { if ( diff . x * decVelX <= 0 ) { decVelX += diff . x * bounceDeceleration ; } else { var adjust = diff . x > 0 ? reboundAdjust : - reboundAdjust ; decVelX = ( diff . x + adjust ) * bounceAcceleration ; } } if ( diff . y !== 0 ) { if ( diff . y * decVelY <= 0 ) { decVelY += diff . y * bounceDeceleration ; } else { var adjust = diff . y > 0 ? reboundAdjust : - reboundAdjust ; decVelY = ( diff . y + adjust ) * bounceAcceleration ; } } } else { if ( diff . x !== 0 ) { if ( diff . x > 0 ) { targetX = boundXmin ; } else { targetX = boundXmax ; } decVelX = 0 ; } if ( diff . y !== 0 ) { if ( diff . y > 0 ) { targetY = boundYmin ; } else { targetY = boundYmax ; } decVelY = 0 ; } } callUpdateCallback ( ) ; requestAnimFrame ( stepDecelAnim ) ; } else { decelerating = false ; } }


Input: Determine position relative to bounds [CODESPLIT] function checkBounds ( restrict ) { var xDiff = 0 ; var yDiff = 0 ; if ( boundXmin !== undefined && targetX < boundXmin ) { xDiff = boundXmin - targetX ; } else if ( boundXmax !== undefined && targetX > boundXmax ) { xDiff = boundXmax - targetX ; } if ( boundYmin !== undefined && targetY < boundYmin ) { yDiff = boundYmin - targetY ; } else if ( boundYmax !== undefined && targetY > boundYmax ) { yDiff = boundYmax - targetY ; } if ( restrict ) { if ( xDiff !== 0 ) { targetX = ( xDiff > 0 ) ? boundXmin : boundXmax ; } if ( yDiff !== 0 ) { targetY = ( yDiff > 0 ) ? boundYmin : boundYmax ; } } return { x : xDiff , y : yDiff , inBounds : xDiff === 0 && yDiff === 0 } ; }


Input: Borrowing from underscorejs https : // github . com / jashkenas / underscore [CODESPLIT] function values ( obj ) { var keys = Object . keys ( obj ) ; var length = keys . length ; var vals = new Array ( length ) ; for ( var i = 0 ; i < length ; i ++ ) { vals [ i ] = obj [ keys [ i ] ] ; } return vals ; }


Input: The default is to save screenshots to the root of your project even though there is a screenshots path in the config object above! ... so we need a function that returns the correct path for storing our screenshots . While we re at it we are adding some meta - data to the filename specifically the Platform / Browser where the test was run and the test ( file ) name . [CODESPLIT] function imgpath ( browser ) { var a = browser . options . desiredCapabilities ; var meta = [ a . platform ] ; meta . push ( a . browserName ? a . browserName : 'any' ) ; meta . push ( a . version ? a . version : 'any' ) ; meta . push ( a . name ) ; // this is the test filename so always exists. var metadata = meta . join ( '~' ) . toLowerCase ( ) . replace ( /   / g , '' ) ; return SCREENSHOT_PATH + metadata + '_' + padLeft ( FILECOUNT ++ ) + '_' ; }


Input: This route returns the editor page as HTML [CODESPLIT] function ( req , res , next ) { var filePath = req . originalUrl . replace ( '/abe/editor' , '' ) if ( filePath === '' || filePath === '/' ) { filePath = null } if ( filePath != null && path . extname ( filePath ) != ` ${ config . files . templates . extension } ` && path . extname ( filePath ) != '.json' ) { next ( ) return } if ( filePath != null ) { var testXSS = xss ( filePath , { whiteList : [ ] , stripIgnoreTag : true } ) if ( testXSS !== filePath ) { filePath = testXSS } } abeExtend . hooks . instance . trigger ( 'beforeRoute' , req , res , next ) if ( typeof res . _header !== 'undefined' && res . _header !== null ) return var isHome = true var jsonPath = null var template = null var fileName = null var folderPath = null var EditorVariables = { user : res . user , slugs : Manager . instance . getSlugs ( ) , express : { res : res , req : req } , filename : fileName , folderPath : folderPath , abeUrl : '/abe/editor/' , isHome : isHome , config : config , Locales : coreUtils . locales . instance . i18n , abeVersion : pkg . version } let p = new Promise ( resolve => { if ( filePath != null ) { fileName = path . basename ( filePath ) folderPath = path . dirname ( filePath ) EditorVariables . isHome = false EditorVariables . isEditor = true var filePathTest = cmsData . revision . getDocumentRevision ( filePath ) if ( typeof filePathTest !== 'undefined' && filePathTest !== null ) { jsonPath = filePathTest . path template = filePathTest . abe_meta . template } if ( jsonPath === null || ! coreUtils . file . exist ( jsonPath ) ) { res . redirect ( '/abe/editor' ) return } var json = { } if ( coreUtils . file . exist ( jsonPath ) ) { json = cmsData . file . get ( jsonPath , 'utf8' ) } var text = cmsTemplates . template . getTemplate ( template , json ) cmsEditor . editor . create ( text , json ) . then ( result => { resolve ( result ) } ) . catch ( function ( e ) { console . error ( e ) } ) } else { resolve ( { json : { } , manager : { } } ) } } ) . catch ( function ( e ) { console . error ( e ) // "oh, no!" } ) p . then ( obj => { var precontribs = Manager . instance . getPrecontribution ( ) var promises = [ ] EditorVariables . resultPrecontrib = [ ] if ( precontribs != null ) { Array . prototype . forEach . call ( precontribs , precontrib => { var p = cmsEditor . editor . create ( precontrib , obj . json , true ) . then ( resultPrecontrib => { EditorVariables . resultPrecontrib . push ( resultPrecontrib ) } ) . catch ( function ( e ) { console . error ( e ) } ) promises . push ( p ) } ) Promise . all ( promises ) . then ( ( ) => { renderAbeAdmin ( EditorVariables , obj , filePath , isHome , template ) } ) . catch ( function ( e ) { console . error ( 'get-main.js getDataList' , e . stack ) } ) } } ) . catch ( e => { console . log ( 'error' , e ) } ) }


Input: stringify () and serizlier () from https : // github . com / moll / json - stringify - safe [CODESPLIT] function stringify ( obj , replacer , spaces , cycleReplacer ) { if ( typeof replacer !== 'function' ) { replacer = null ; } return JSON . stringify ( obj , serializer ( replacer , cycleReplacer ) , spaces ) ; }


Input: ie10以及以下，对某些样式支持有问题，需要降级 [CODESPLIT] function getIEVersion ( ) { var agent = navigator . userAgent var reg = / MSIE\s?(\d+)(?:\.(\d+))? / i var matches = agent . match ( reg ) if ( matches != null ) { return { major : matches [ 1 ] , minor : matches [ 2 ] } } return { major : '-1' , minor : '-1' } }


Input: get all components dirs [CODESPLIT] function initCompDirs ( ) { var compRoot = path . resolve ( process . cwd ( ) , 'src/components' ) , compReg = / ^[A-Z]\w+$ / ; //['Button', 'Select'] compDirs = fs . readdirSync ( compRoot ) . filter ( function ( filename ) { return compReg . test ( filename ) } ) return compDirs }


Input: Writes a log to a file [CODESPLIT] function appendLogToFileStream ( fileName , newLog , headerLineCount ) { const filePath = path . join ( __dirname , '../../' , fileName ) const oldChangelog = grunt . file . read ( filePath ) . toString ( ) . split ( '\n' ) ; let wStr = fs . createWriteStream ( filePath ) /** lines used by the default header */ let logHeader = oldChangelog . slice ( 0 , headerLineCount ) ; /** previous changelog entries */ let prevLogs = oldChangelog . slice ( headerLineCount ) ; var s = new Readable ; s . pipe ( wStr ) ; s . push ( logHeader . join ( '\n' ) + '\n' ) ; s . push ( newLog ) ; s . push ( prevLogs . join ( '\n' ) ) ; s . push ( null ) ; // indicates end-of-file basically - the end of the stream) return wStr ; }


Input: maximum bit length of any code [CODESPLIT] function InfTree ( ) { var that = this ; var hn ; // hufts used in space var v ; // work area for huft_build var c ; // bit length count table var r ; // table entry for structure assignment var u ; // table stack var x ; // bit offsets, then code stack function huft_build ( b , // code lengths in bits (all assumed <= // BMAX) bindex , n , // number of codes (assumed <= 288) s , // number of simple-valued codes (0..s-1) d , // list of base values for non-simple codes e , // list of extra bits for non-simple codes t , // result: starting table m , // maximum lookup bits, returns actual hp , // space for trees hn , // hufts used in space v // working area: values in order of bit length ) { // Given a list of code lengths and a maximum table size, make a set of // tables to decode that set of codes. Return Z_OK on success, // Z_BUF_ERROR // if the given code set is incomplete (the tables are still built in // this // case), Z_DATA_ERROR if the input is invalid (an over-subscribed set // of // lengths), or Z_MEM_ERROR if not enough memory. var a ; // counter for codes of length k var f ; // i repeats in table every f entries var g ; // maximum code length var h ; // table level var i ; // counter, current code var j ; // counter var k ; // number of bits in current code var l ; // bits per table (returned in m) var mask ; // (1 << w) - 1, to avoid cc -O bug on HP var p ; // pointer into c[], b[], or v[] var q ; // points to current table var w ; // bits before this table == (l * h) var xp ; // pointer into x var y ; // number of dummy codes added var z ; // number of entries in current table // Generate counts for each bit length p = 0 ; i = n ; do { c [ b [ bindex + p ] ] ++ ; p ++ ; i -- ; // assume all entries <= BMAX } while ( i !== 0 ) ; if ( c [ 0 ] == n ) { // null input--all zero length codes t [ 0 ] = - 1 ; m [ 0 ] = 0 ; return Z_OK ; } // Find minimum and maximum length, bound *m by those l = m [ 0 ] ; for ( j = 1 ; j <= BMAX ; j ++ ) if ( c [ j ] !== 0 ) break ; k = j ; // minimum code length if ( l < j ) { l = j ; } for ( i = BMAX ; i !== 0 ; i -- ) { if ( c [ i ] !== 0 ) break ; } g = i ; // maximum code length if ( l > i ) { l = i ; } m [ 0 ] = l ; // Adjust last length count to fill out codes, if needed for ( y = 1 << j ; j < i ; j ++ , y <<= 1 ) { if ( ( y -= c [ j ] ) < 0 ) { return Z_DATA_ERROR ; } } if ( ( y -= c [ i ] ) < 0 ) { return Z_DATA_ERROR ; } c [ i ] += y ; // Generate starting offsets into the value table for each length x [ 1 ] = j = 0 ; p = 1 ; xp = 2 ; while ( -- i !== 0 ) { // note that i == g from above x [ xp ] = ( j += c [ p ] ) ; xp ++ ; p ++ ; } // Make a table of values in order of bit lengths i = 0 ; p = 0 ; do { if ( ( j = b [ bindex + p ] ) !== 0 ) { v [ x [ j ] ++ ] = i ; } p ++ ; } while ( ++ i < n ) ; n = x [ g ] ; // set n to length of v // Generate the Huffman codes and for each, make the table entries x [ 0 ] = i = 0 ; // first Huffman code is zero p = 0 ; // grab values in bit order h = - 1 ; // no tables yet--level -1 w = - l ; // bits decoded == (l * h) u [ 0 ] = 0 ; // just to keep compilers happy q = 0 ; // ditto z = 0 ; // ditto // go through the bit lengths (k already is bits in shortest code) for ( ; k <= g ; k ++ ) { a = c [ k ] ; while ( a -- !== 0 ) { // here i is the Huffman code of length k bits for value *p // make tables up to required level while ( k > w + l ) { h ++ ; w += l ; // previous table always l bits // compute minimum size table less than or equal to l bits z = g - w ; z = ( z > l ) ? l : z ; // table size upper limit if ( ( f = 1 << ( j = k - w ) ) > a + 1 ) { // try a k-w bit table // too few codes for // k-w bit table f -= a + 1 ; // deduct codes from patterns left xp = k ; if ( j < z ) { while ( ++ j < z ) { // try smaller tables up to z bits if ( ( f <<= 1 ) <= c [ ++ xp ] ) break ; // enough codes to use up j bits f -= c [ xp ] ; // else deduct codes from patterns } } } z = 1 << j ; // table entries for j-bit table // allocate new table if ( hn [ 0 ] + z > MANY ) { // (note: doesn't matter for fixed) return Z_DATA_ERROR ; // overflow of MANY } u [ h ] = q = /* hp+ */ hn [ 0 ] ; // DEBUG hn [ 0 ] += z ; // connect to last table, if there is one if ( h !== 0 ) { x [ h ] = i ; // save pattern for backing up r [ 0 ] = /* (byte) */ j ; // bits in this table r [ 1 ] = /* (byte) */ l ; // bits to dump before this table j = i >>> ( w - l ) ; r [ 2 ] = /* (int) */ ( q - u [ h - 1 ] - j ) ; // offset to this table hp . set ( r , ( u [ h - 1 ] + j ) * 3 ) ; // to // last // table } else { t [ 0 ] = q ; // first table is returned result } } // set up table entry in r r [ 1 ] = /* (byte) */ ( k - w ) ; if ( p >= n ) { r [ 0 ] = 128 + 64 ; // out of values--invalid code } else if ( v [ p ] < s ) { r [ 0 ] = /* (byte) */ ( v [ p ] < 256 ? 0 : 32 + 64 ) ; // 256 is // end-of-block r [ 2 ] = v [ p ++ ] ; // simple code is just the value } else { r [ 0 ] = /* (byte) */ ( e [ v [ p ] - s ] + 16 + 64 ) ; // non-simple--look // up in lists r [ 2 ] = d [ v [ p ++ ] - s ] ; } // fill code-like entries with r f = 1 << ( k - w ) ; for ( j = i >>> w ; j < z ; j += f ) { hp . set ( r , ( q + j ) * 3 ) ; } // backwards increment the k-bit code i for ( j = 1 << ( k - 1 ) ; ( i & j ) !== 0 ; j >>>= 1 ) { i ^= j ; } i ^= j ; // backup over finished tables mask = ( 1 << w ) - 1 ; // needed on HP, cc -O bug while ( ( i & mask ) != x [ h ] ) { h -- ; // don't need to update q w -= l ; mask = ( 1 << w ) - 1 ; } } } // Return Z_BUF_ERROR if we were given an incomplete table return y !== 0 && g != 1 ? Z_BUF_ERROR : Z_OK ; } function initWorkArea ( vsize ) { var i ; if ( ! hn ) { hn = [ ] ; // []; //new Array(1); v = [ ] ; // new Array(vsize); c = new Int32Array ( BMAX + 1 ) ; // new Array(BMAX + 1); r = [ ] ; // new Array(3); u = new Int32Array ( BMAX ) ; // new Array(BMAX); x = new Int32Array ( BMAX + 1 ) ; // new Array(BMAX + 1); } if ( v . length < vsize ) { v = [ ] ; // new Array(vsize); } for ( i = 0 ; i < vsize ; i ++ ) { v [ i ] = 0 ; } for ( i = 0 ; i < BMAX + 1 ; i ++ ) { c [ i ] = 0 ; } for ( i = 0 ; i < 3 ; i ++ ) { r [ i ] = 0 ; } // for(int i=0; i<BMAX; i++){u[i]=0;} u . set ( c . subarray ( 0 , BMAX ) , 0 ) ; // for(int i=0; i<BMAX+1; i++){x[i]=0;} x . set ( c . subarray ( 0 , BMAX + 1 ) , 0 ) ; } that . inflate_trees_bits = function ( c , // 19 code lengths bb , // bits tree desired/actual depth tb , // bits tree result hp , // space for trees z // for messages ) { var result ; initWorkArea ( 19 ) ; hn [ 0 ] = 0 ; result = huft_build ( c , 0 , 19 , 19 , null , null , tb , bb , hp , hn , v ) ; if ( result == Z_DATA_ERROR ) { z . msg = "oversubscribed dynamic bit lengths tree" ; } else if ( result == Z_BUF_ERROR || bb [ 0 ] === 0 ) { z . msg = "incomplete dynamic bit lengths tree" ; result = Z_DATA_ERROR ; } return result ; } ; that . inflate_trees_dynamic = function ( nl , // number of literal/length codes nd , // number of distance codes c , // that many (total) code lengths bl , // literal desired/actual bit depth bd , // distance desired/actual bit depth tl , // literal/length tree result td , // distance tree result hp , // space for trees z // for messages ) { var result ; // build literal/length tree initWorkArea ( 288 ) ; hn [ 0 ] = 0 ; result = huft_build ( c , 0 , nl , 257 , cplens , cplext , tl , bl , hp , hn , v ) ; if ( result != Z_OK || bl [ 0 ] === 0 ) { if ( result == Z_DATA_ERROR ) { z . msg = "oversubscribed literal/length tree" ; } else if ( result != Z_MEM_ERROR ) { z . msg = "incomplete literal/length tree" ; result = Z_DATA_ERROR ; } return result ; } // build distance tree initWorkArea ( 288 ) ; result = huft_build ( c , nl , nd , 0 , cpdist , cpdext , td , bd , hp , hn , v ) ; if ( result != Z_OK || ( bd [ 0 ] === 0 && nl > 257 ) ) { if ( result == Z_DATA_ERROR ) { z . msg = "oversubscribed distance tree" ; } else if ( result == Z_BUF_ERROR ) { z . msg = "incomplete distance tree" ; result = Z_DATA_ERROR ; } else if ( result != Z_MEM_ERROR ) { z . msg = "empty distance tree with lengths" ; result = Z_DATA_ERROR ; } return result ; } return Z_OK ; } ; }


Input: x : got error [CODESPLIT] function InfCodes ( ) { var that = this ; var mode ; // current inflate_codes mode // mode dependent information var len = 0 ; var tree ; // pointer into tree var tree_index = 0 ; var need = 0 ; // bits needed var lit = 0 ; // if EXT or COPY, where and how much var get = 0 ; // bits to get for extra var dist = 0 ; // distance back to copy from var lbits = 0 ; // ltree bits decoded per branch var dbits = 0 ; // dtree bits decoder per branch var ltree ; // literal/length/eob tree var ltree_index = 0 ; // literal/length/eob tree var dtree ; // distance tree var dtree_index = 0 ; // distance tree // Called with number of bytes left to write in window at least 258 // (the maximum string length) and number of input bytes available // at least ten. The ten bytes are six bytes for the longest length/ // distance pair plus four bytes for overloading the bit buffer. function inflate_fast ( bl , bd , tl , tl_index , td , td_index , s , z ) { var t ; // temporary pointer var tp ; // temporary pointer var tp_index ; // temporary pointer var e ; // extra bits or operation var b ; // bit buffer var k ; // bits in bit buffer var p ; // input data pointer var n ; // bytes available there var q ; // output window write pointer var m ; // bytes to end of window or read pointer var ml ; // mask for literal/length tree var md ; // mask for distance tree var c ; // bytes to copy var d ; // distance back to copy from var r ; // copy source pointer var tp_index_t_3 ; // (tp_index+t)*3 // load input, output, bit values p = z . next_in_index ; n = z . avail_in ; b = s . bitb ; k = s . bitk ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; // initialize masks ml = inflate_mask [ bl ] ; md = inflate_mask [ bd ] ; // do until not enough input or output space for fast loop do { // assume called with m >= 258 && n >= 10 // get literal/length code while ( k < ( 20 ) ) { // max bits for literal/length code n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } t = b & ml ; tp = tl ; tp_index = tl_index ; tp_index_t_3 = ( tp_index + t ) * 3 ; if ( ( e = tp [ tp_index_t_3 ] ) === 0 ) { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; s . window [ q ++ ] = /* (byte) */ tp [ tp_index_t_3 + 2 ] ; m -- ; continue ; } do { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; if ( ( e & 16 ) !== 0 ) { e &= 15 ; c = tp [ tp_index_t_3 + 2 ] + ( /* (int) */ b & inflate_mask [ e ] ) ; b >>= e ; k -= e ; // decode distance base of block to copy while ( k < ( 15 ) ) { // max bits for distance code n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } t = b & md ; tp = td ; tp_index = td_index ; tp_index_t_3 = ( tp_index + t ) * 3 ; e = tp [ tp_index_t_3 ] ; do { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; if ( ( e & 16 ) !== 0 ) { // get extra bits to add to distance base e &= 15 ; while ( k < ( e ) ) { // get extra bits (up to 13) n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } d = tp [ tp_index_t_3 + 2 ] + ( b & inflate_mask [ e ] ) ; b >>= ( e ) ; k -= ( e ) ; // do the copy m -= c ; if ( q >= d ) { // offset before dest // just copy r = q - d ; if ( q - r > 0 && 2 > ( q - r ) ) { s . window [ q ++ ] = s . window [ r ++ ] ; // minimum // count is // three, s . window [ q ++ ] = s . window [ r ++ ] ; // so unroll // loop a // little c -= 2 ; } else { s . window . set ( s . window . subarray ( r , r + 2 ) , q ) ; q += 2 ; r += 2 ; c -= 2 ; } } else { // else offset after destination r = q - d ; do { r += s . end ; // force pointer in window } while ( r < 0 ) ; // covers invalid distances e = s . end - r ; if ( c > e ) { // if source crosses, c -= e ; // wrapped copy if ( q - r > 0 && e > ( q - r ) ) { do { s . window [ q ++ ] = s . window [ r ++ ] ; } while ( -- e !== 0 ) ; } else { s . window . set ( s . window . subarray ( r , r + e ) , q ) ; q += e ; r += e ; e = 0 ; } r = 0 ; // copy rest from start of window } } // copy all or what's left if ( q - r > 0 && c > ( q - r ) ) { do { s . window [ q ++ ] = s . window [ r ++ ] ; } while ( -- c !== 0 ) ; } else { s . window . set ( s . window . subarray ( r , r + c ) , q ) ; q += c ; r += c ; c = 0 ; } break ; } else if ( ( e & 64 ) === 0 ) { t += tp [ tp_index_t_3 + 2 ] ; t += ( b & inflate_mask [ e ] ) ; tp_index_t_3 = ( tp_index + t ) * 3 ; e = tp [ tp_index_t_3 ] ; } else { z . msg = "invalid distance code" ; c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_DATA_ERROR ; } } while ( true ) ; break ; } if ( ( e & 64 ) === 0 ) { t += tp [ tp_index_t_3 + 2 ] ; t += ( b & inflate_mask [ e ] ) ; tp_index_t_3 = ( tp_index + t ) * 3 ; if ( ( e = tp [ tp_index_t_3 ] ) === 0 ) { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; s . window [ q ++ ] = /* (byte) */ tp [ tp_index_t_3 + 2 ] ; m -- ; break ; } } else if ( ( e & 32 ) !== 0 ) { c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_STREAM_END ; } else { z . msg = "invalid literal/length code" ; c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_DATA_ERROR ; } } while ( true ) ; } while ( m >= 258 && n >= 10 ) ; // not enough input or output--restore pointers and return c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_OK ; } that . init = function ( bl , bd , tl , tl_index , td , td_index ) { mode = START ; lbits = /* (byte) */ bl ; dbits = /* (byte) */ bd ; ltree = tl ; ltree_index = tl_index ; dtree = td ; dtree_index = td_index ; tree = null ; } ; that . proc = function ( s , z , r ) { var j ; // temporary storage var tindex ; // temporary pointer var e ; // extra bits or operation var b = 0 ; // bit buffer var k = 0 ; // bits in bit buffer var p = 0 ; // input data pointer var n ; // bytes available there var q ; // output window write pointer var m ; // bytes to end of window or read pointer var f ; // pointer to copy strings from // copy input/output information to locals (UPDATE macro restores) p = z . next_in_index ; n = z . avail_in ; b = s . bitb ; k = s . bitk ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; // process input and output based on current state while ( true ) { switch ( mode ) { // waiting for "i:"=input, "o:"=output, "x:"=nothing case START : // x: set up for LEN if ( m >= 258 && n >= 10 ) { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; r = inflate_fast ( lbits , dbits , ltree , ltree_index , dtree , dtree_index , s , z ) ; p = z . next_in_index ; n = z . avail_in ; b = s . bitb ; k = s . bitk ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; if ( r != Z_OK ) { mode = r == Z_STREAM_END ? WASH : BADCODE ; break ; } } need = lbits ; tree = ltree ; tree_index = ltree_index ; mode = LEN ; /* falls through */ case LEN : // i: get length/literal/eob next j = need ; while ( k < ( j ) ) { if ( n !== 0 ) r = Z_OK ; else { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } tindex = ( tree_index + ( b & inflate_mask [ j ] ) ) * 3 ; b >>>= ( tree [ tindex + 1 ] ) ; k -= ( tree [ tindex + 1 ] ) ; e = tree [ tindex ] ; if ( e === 0 ) { // literal lit = tree [ tindex + 2 ] ; mode = LIT ; break ; } if ( ( e & 16 ) !== 0 ) { // length get = e & 15 ; len = tree [ tindex + 2 ] ; mode = LENEXT ; break ; } if ( ( e & 64 ) === 0 ) { // next table need = e ; tree_index = tindex / 3 + tree [ tindex + 2 ] ; break ; } if ( ( e & 32 ) !== 0 ) { // end of block mode = WASH ; break ; } mode = BADCODE ; // invalid code z . msg = "invalid literal/length code" ; r = Z_DATA_ERROR ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; case LENEXT : // i: getting length extra (have base) j = get ; while ( k < ( j ) ) { if ( n !== 0 ) r = Z_OK ; else { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } len += ( b & inflate_mask [ j ] ) ; b >>= j ; k -= j ; need = dbits ; tree = dtree ; tree_index = dtree_index ; mode = DIST ; /* falls through */ case DIST : // i: get distance next j = need ; while ( k < ( j ) ) { if ( n !== 0 ) r = Z_OK ; else { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } tindex = ( tree_index + ( b & inflate_mask [ j ] ) ) * 3 ; b >>= tree [ tindex + 1 ] ; k -= tree [ tindex + 1 ] ; e = ( tree [ tindex ] ) ; if ( ( e & 16 ) !== 0 ) { // distance get = e & 15 ; dist = tree [ tindex + 2 ] ; mode = DISTEXT ; break ; } if ( ( e & 64 ) === 0 ) { // next table need = e ; tree_index = tindex / 3 + tree [ tindex + 2 ] ; break ; } mode = BADCODE ; // invalid code z . msg = "invalid distance code" ; r = Z_DATA_ERROR ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; case DISTEXT : // i: getting distance extra j = get ; while ( k < ( j ) ) { if ( n !== 0 ) r = Z_OK ; else { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } dist += ( b & inflate_mask [ j ] ) ; b >>= j ; k -= j ; mode = COPY ; /* falls through */ case COPY : // o: copying bytes in window, waiting for space f = q - dist ; while ( f < 0 ) { // modulo window size-"while" instead f += s . end ; // of "if" handles invalid distances } while ( len !== 0 ) { if ( m === 0 ) { if ( q == s . end && s . read !== 0 ) { q = 0 ; m = q < s . read ? s . read - q - 1 : s . end - q ; } if ( m === 0 ) { s . write = q ; r = s . inflate_flush ( z , r ) ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; if ( q == s . end && s . read !== 0 ) { q = 0 ; m = q < s . read ? s . read - q - 1 : s . end - q ; } if ( m === 0 ) { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } } } s . window [ q ++ ] = s . window [ f ++ ] ; m -- ; if ( f == s . end ) f = 0 ; len -- ; } mode = START ; break ; case LIT : // o: got literal, waiting for output space if ( m === 0 ) { if ( q == s . end && s . read !== 0 ) { q = 0 ; m = q < s . read ? s . read - q - 1 : s . end - q ; } if ( m === 0 ) { s . write = q ; r = s . inflate_flush ( z , r ) ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; if ( q == s . end && s . read !== 0 ) { q = 0 ; m = q < s . read ? s . read - q - 1 : s . end - q ; } if ( m === 0 ) { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } } } r = Z_OK ; s . window [ q ++ ] = /* (byte) */ lit ; m -- ; mode = START ; break ; case WASH : // o: got eob, possibly more output if ( k > 7 ) { // return unused byte, if any k -= 8 ; n ++ ; p -- ; // can always return one } s . write = q ; r = s . inflate_flush ( z , r ) ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; if ( s . read != s . write ) { s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } mode = END ; /* falls through */ case END : r = Z_STREAM_END ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; case BADCODE : // x: got error r = Z_DATA_ERROR ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; default : r = Z_STREAM_ERROR ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return s . inflate_flush ( z , r ) ; } } } ; that . free = function ( ) { // ZFREE(z, c); } ; }


Input: Called with number of bytes left to write in window at least 258 ( the maximum string length ) and number of input bytes available at least ten . The ten bytes are six bytes for the longest length / distance pair plus four bytes for overloading the bit buffer . [CODESPLIT] function inflate_fast ( bl , bd , tl , tl_index , td , td_index , s , z ) { var t ; // temporary pointer var tp ; // temporary pointer var tp_index ; // temporary pointer var e ; // extra bits or operation var b ; // bit buffer var k ; // bits in bit buffer var p ; // input data pointer var n ; // bytes available there var q ; // output window write pointer var m ; // bytes to end of window or read pointer var ml ; // mask for literal/length tree var md ; // mask for distance tree var c ; // bytes to copy var d ; // distance back to copy from var r ; // copy source pointer var tp_index_t_3 ; // (tp_index+t)*3 // load input, output, bit values p = z . next_in_index ; n = z . avail_in ; b = s . bitb ; k = s . bitk ; q = s . write ; m = q < s . read ? s . read - q - 1 : s . end - q ; // initialize masks ml = inflate_mask [ bl ] ; md = inflate_mask [ bd ] ; // do until not enough input or output space for fast loop do { // assume called with m >= 258 && n >= 10 // get literal/length code while ( k < ( 20 ) ) { // max bits for literal/length code n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } t = b & ml ; tp = tl ; tp_index = tl_index ; tp_index_t_3 = ( tp_index + t ) * 3 ; if ( ( e = tp [ tp_index_t_3 ] ) === 0 ) { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; s . window [ q ++ ] = /* (byte) */ tp [ tp_index_t_3 + 2 ] ; m -- ; continue ; } do { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; if ( ( e & 16 ) !== 0 ) { e &= 15 ; c = tp [ tp_index_t_3 + 2 ] + ( /* (int) */ b & inflate_mask [ e ] ) ; b >>= e ; k -= e ; // decode distance base of block to copy while ( k < ( 15 ) ) { // max bits for distance code n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } t = b & md ; tp = td ; tp_index = td_index ; tp_index_t_3 = ( tp_index + t ) * 3 ; e = tp [ tp_index_t_3 ] ; do { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; if ( ( e & 16 ) !== 0 ) { // get extra bits to add to distance base e &= 15 ; while ( k < ( e ) ) { // get extra bits (up to 13) n -- ; b |= ( z . read_byte ( p ++ ) & 0xff ) << k ; k += 8 ; } d = tp [ tp_index_t_3 + 2 ] + ( b & inflate_mask [ e ] ) ; b >>= ( e ) ; k -= ( e ) ; // do the copy m -= c ; if ( q >= d ) { // offset before dest // just copy r = q - d ; if ( q - r > 0 && 2 > ( q - r ) ) { s . window [ q ++ ] = s . window [ r ++ ] ; // minimum // count is // three, s . window [ q ++ ] = s . window [ r ++ ] ; // so unroll // loop a // little c -= 2 ; } else { s . window . set ( s . window . subarray ( r , r + 2 ) , q ) ; q += 2 ; r += 2 ; c -= 2 ; } } else { // else offset after destination r = q - d ; do { r += s . end ; // force pointer in window } while ( r < 0 ) ; // covers invalid distances e = s . end - r ; if ( c > e ) { // if source crosses, c -= e ; // wrapped copy if ( q - r > 0 && e > ( q - r ) ) { do { s . window [ q ++ ] = s . window [ r ++ ] ; } while ( -- e !== 0 ) ; } else { s . window . set ( s . window . subarray ( r , r + e ) , q ) ; q += e ; r += e ; e = 0 ; } r = 0 ; // copy rest from start of window } } // copy all or what's left if ( q - r > 0 && c > ( q - r ) ) { do { s . window [ q ++ ] = s . window [ r ++ ] ; } while ( -- c !== 0 ) ; } else { s . window . set ( s . window . subarray ( r , r + c ) , q ) ; q += c ; r += c ; c = 0 ; } break ; } else if ( ( e & 64 ) === 0 ) { t += tp [ tp_index_t_3 + 2 ] ; t += ( b & inflate_mask [ e ] ) ; tp_index_t_3 = ( tp_index + t ) * 3 ; e = tp [ tp_index_t_3 ] ; } else { z . msg = "invalid distance code" ; c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_DATA_ERROR ; } } while ( true ) ; break ; } if ( ( e & 64 ) === 0 ) { t += tp [ tp_index_t_3 + 2 ] ; t += ( b & inflate_mask [ e ] ) ; tp_index_t_3 = ( tp_index + t ) * 3 ; if ( ( e = tp [ tp_index_t_3 ] ) === 0 ) { b >>= ( tp [ tp_index_t_3 + 1 ] ) ; k -= ( tp [ tp_index_t_3 + 1 ] ) ; s . window [ q ++ ] = /* (byte) */ tp [ tp_index_t_3 + 2 ] ; m -- ; break ; } } else if ( ( e & 32 ) !== 0 ) { c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_STREAM_END ; } else { z . msg = "invalid literal/length code" ; c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_DATA_ERROR ; } } while ( true ) ; } while ( m >= 258 && n >= 10 ) ; // not enough input or output--restore pointers and return c = z . avail_in - n ; c = ( k >> 3 ) < c ? k >> 3 : c ; n += c ; p -= c ; k -= c << 3 ; s . bitb = b ; s . bitk = k ; z . avail_in = n ; z . total_in += p - z . next_in_index ; z . next_in_index = p ; s . write = q ; return Z_OK ; }


Input: Inflater [CODESPLIT] function Inflater ( ) { var that = this ; var z = new ZStream ( ) ; var bufsize = 512 ; var flush = Z_NO_FLUSH ; var buf = new Uint8Array ( bufsize ) ; var nomoreinput = false ; z . inflateInit ( ) ; z . next_out = buf ; that . append = function ( data , onprogress ) { var err , buffers = [ ] , lastIndex = 0 , bufferIndex = 0 , bufferSize = 0 , array ; if ( data . length === 0 ) return ; z . next_in_index = 0 ; z . next_in = data ; z . avail_in = data . length ; do { z . next_out_index = 0 ; z . avail_out = bufsize ; if ( ( z . avail_in === 0 ) && ( ! nomoreinput ) ) { // if buffer is empty and more input is available, refill it z . next_in_index = 0 ; nomoreinput = true ; } err = z . inflate ( flush ) ; if ( nomoreinput && ( err === Z_BUF_ERROR ) ) { if ( z . avail_in !== 0 ) throw new Error ( "inflating: bad input" ) ; } else if ( err !== Z_OK && err !== Z_STREAM_END ) throw new Error ( "inflating: " + z . msg ) ; if ( ( nomoreinput || err === Z_STREAM_END ) && ( z . avail_in === data . length ) ) throw new Error ( "inflating: bad input" ) ; if ( z . next_out_index ) if ( z . next_out_index === bufsize ) buffers . push ( new Uint8Array ( buf ) ) ; else buffers . push ( new Uint8Array ( buf . subarray ( 0 , z . next_out_index ) ) ) ; bufferSize += z . next_out_index ; if ( onprogress && z . next_in_index > 0 && z . next_in_index != lastIndex ) { onprogress ( z . next_in_index ) ; lastIndex = z . next_in_index ; } } while ( z . avail_in > 0 || z . avail_out === 0 ) ; array = new Uint8Array ( bufferSize ) ; buffers . forEach ( function ( chunk ) { array . set ( chunk , bufferIndex ) ; bufferIndex += chunk . length ; } ) ; return array ; } ; that . flush = function ( ) { z . inflateEnd ( ) ; } ; }


Input: inflate / deflate core functions [CODESPLIT] function launchWorkerProcess ( worker , initialMessage , reader , writer , offset , size , onprogress , onend , onreaderror , onwriteerror ) { var chunkIndex = 0 , index , outputSize , sn = initialMessage . sn , crc ; function onflush ( ) { worker . removeEventListener ( 'message' , onmessage , false ) ; onend ( outputSize , crc ) ; } function onmessage ( event ) { var message = event . data , data = message . data , err = message . error ; if ( err ) { err . toString = function ( ) { return 'Error: ' + this . message ; } ; onreaderror ( err ) ; return ; } if ( message . sn !== sn ) return ; if ( typeof message . codecTime === 'number' ) worker . codecTime += message . codecTime ; // should be before onflush() if ( typeof message . crcTime === 'number' ) worker . crcTime += message . crcTime ; switch ( message . type ) { case 'append' : if ( data ) { outputSize += data . length ; writer . writeUint8Array ( data , function ( ) { step ( ) ; } , onwriteerror ) ; } else step ( ) ; break ; case 'flush' : crc = message . crc ; if ( data ) { outputSize += data . length ; writer . writeUint8Array ( data , function ( ) { onflush ( ) ; } , onwriteerror ) ; } else onflush ( ) ; break ; case 'progress' : if ( onprogress ) onprogress ( index + message . loaded , size ) ; break ; case 'importScripts' : //no need to handle here case 'newTask' : case 'echo' : break ; default : console . warn ( 'zip.js:launchWorkerProcess: unknown message: ' , message ) ; } } function step ( ) { index = chunkIndex * CHUNK_SIZE ; // use `<=` instead of `<`, because `size` may be 0. if ( index <= size ) { reader . readUint8Array ( offset + index , Math . min ( CHUNK_SIZE , size - index ) , function ( array ) { if ( onprogress ) onprogress ( index , size ) ; var msg = index === 0 ? initialMessage : { sn : sn } ; msg . type = 'append' ; msg . data = array ; // posting a message with transferables will fail on IE10 try { worker . postMessage ( msg , [ array . buffer ] ) ; } catch ( ex ) { worker . postMessage ( msg ) ; // retry without transferables } chunkIndex ++ ; } , onreaderror ) ; } else { worker . postMessage ( { sn : sn , type : 'flush' } ) ; } } outputSize = 0 ; worker . addEventListener ( 'message' , onmessage , false ) ; step ( ) ; }


Input: ZipReader [CODESPLIT] function decodeASCII ( str ) { var i , out = "" , charCode , extendedASCII = [ '\u00C7' , '\u00FC' , '\u00E9' , '\u00E2' , '\u00E4' , '\u00E0' , '\u00E5' , '\u00E7' , '\u00EA' , '\u00EB' , '\u00E8' , '\u00EF' , '\u00EE' , '\u00EC' , '\u00C4' , '\u00C5' , '\u00C9' , '\u00E6' , '\u00C6' , '\u00F4' , '\u00F6' , '\u00F2' , '\u00FB' , '\u00F9' , '\u00FF' , '\u00D6' , '\u00DC' , '\u00F8' , '\u00A3' , '\u00D8' , '\u00D7' , '\u0192' , '\u00E1' , '\u00ED' , '\u00F3' , '\u00FA' , '\u00F1' , '\u00D1' , '\u00AA' , '\u00BA' , '\u00BF' , '\u00AE' , '\u00AC' , '\u00BD' , '\u00BC' , '\u00A1' , '\u00AB' , '\u00BB' , '_' , '_' , '_' , '\u00A6' , '\u00A6' , '\u00C1' , '\u00C2' , '\u00C0' , '\u00A9' , '\u00A6' , '\u00A6' , '+' , '+' , '\u00A2' , '\u00A5' , '+' , '+' , '-' , '-' , '+' , '-' , '+' , '\u00E3' , '\u00C3' , '+' , '+' , '-' , '-' , '\u00A6' , '-' , '+' , '\u00A4' , '\u00F0' , '\u00D0' , '\u00CA' , '\u00CB' , '\u00C8' , 'i' , '\u00CD' , '\u00CE' , '\u00CF' , '+' , '+' , '_' , '_' , '\u00A6' , '\u00CC' , '_' , '\u00D3' , '\u00DF' , '\u00D4' , '\u00D2' , '\u00F5' , '\u00D5' , '\u00B5' , '\u00FE' , '\u00DE' , '\u00DA' , '\u00DB' , '\u00D9' , '\u00FD' , '\u00DD' , '\u00AF' , '\u00B4' , '\u00AD' , '\u00B1' , '_' , '\u00BE' , '\u00B6' , '\u00A7' , '\u00F7' , '\u00B8' , '\u00B0' , '\u00A8' , '\u00B7' , '\u00B9' , '\u00B3' , '\u00B2' , '_' , ' ' ] ; for ( i = 0 ; i < str . length ; i ++ ) { charCode = str . charCodeAt ( i ) & 0xFF ; if ( charCode > 127 ) out += extendedASCII [ charCode - 128 ] ; else out += String . fromCharCode ( charCode ) ; } return out ; }


Input: seek last length bytes of file for EOCDR [CODESPLIT] function doSeek ( length , eocdrNotFoundCallback ) { reader . readUint8Array ( reader . size - length , length , function ( bytes ) { for ( var i = bytes . length - EOCDR_MIN ; i >= 0 ; i -- ) { if ( bytes [ i ] === 0x50 && bytes [ i + 1 ] === 0x4b && bytes [ i + 2 ] === 0x05 && bytes [ i + 3 ] === 0x06 ) { eocdrCallback ( new DataView ( bytes . buffer , i , EOCDR_MIN ) ) ; return ; } } eocdrNotFoundCallback ( ) ; } , function ( ) { onerror ( ERR_READ ) ; } ) ; }


Input: @class CardJs [CODESPLIT] function CardJs ( elem ) { this . elem = jQuery ( elem ) ; this . captureName = this . elem . data ( "capture-name" ) ? this . elem . data ( "capture-name" ) : false ; this . iconColour = this . elem . data ( "icon-colour" ) ? this . elem . data ( "icon-colour" ) : false ; this . stripe = this . elem . data ( "stripe" ) ? this . elem . data ( "stripe" ) : false ; if ( this . stripe ) { this . captureName = false ; } // Initialise this . initCardNumberInput ( ) ; this . initNameInput ( ) ; this . initExpiryMonthInput ( ) ; this . initExpiryYearInput ( ) ; this . initCvcInput ( ) ; this . elem . empty ( ) ; // Setup display this . setupCardNumberInput ( ) ; this . setupNameInput ( ) ; this . setupExpiryInput ( ) ; this . setupCvcInput ( ) ; // Set icon colour if ( this . iconColour ) { this . setIconColour ( this . iconColour ) ; } // --- --- --- --- --- --- --- --- --- --- this . refreshCreditCardTypeIcon ( ) ; }


Input: console . log ( ! -------------- Starting Test options . name ) ; data . push ( { name : Starting test + options . name } ) ; [CODESPLIT] function ( err , inData ) { //console.log("!--------------  Checking Results", options.name, "Error: ", err, "Data:", inData); var passed = true ; if ( err ) { console . log ( "!------------ Error" , err . toString ( ) ) ; data . push ( { name : options . name + " test failed with: " , css : 'one' } ) ; data . push ( { name : "  " + err . toString ( ) , css : 'one' } ) ; return callback ( false ) ; } if ( ! inData || inData . length !== options . results . length ) { console . dir ( inData ) ; console . log ( "!----------- No Data" ) ; data . push ( { name : options . name + " test failed with different results length" , css : 'one' } ) ; return callback ( false ) ; } if ( inData . length === 0 ) { console . log ( "!-------- No Data Returned" ) ; return callback ( passed ) ; } //console.log("!------------ Data Returned", inData.length, inData); for ( var i = 0 ; i < inData . length ; i ++ ) { var result = checkRowOfData ( inData [ i ] , options . results [ i ] ) ; if ( ! result . status ) { passed = false ; data . push ( { name : options . name + " test failed on row: " + i + ", field: " + result . field , css : 'one' } ) ; console . log ( "$$$$$ Failure:" , inData [ i ] , options . results [ i ] , typeof inData [ i ] [ result . field ] , typeof options . results [ i ] [ result . field ] ) ; break ; } } callback ( passed ) ; }


Input: * Parses a Row of data into a JS Array ( as Native ) [CODESPLIT] function DBGetRowArrayNative ( cursor ) { //noinspection JSUnresolvedFunction let count = cursor . getColumnCount ( ) ; let results = [ ] ; for ( let i = 0 ; i < count ; i ++ ) { const type = cursor . getType ( i ) ; switch ( type ) { case 0 : // NULL results . push ( null ) ; break ; case 1 : // Integer //noinspection JSUnresolvedFunction results . push ( cursor . getLong ( i ) ) ; break ; case 2 : // Float //noinspection JSUnresolvedFunction results . push ( cursor . getFloat ( i ) ) ; break ; case 3 : // String //noinspection JSUnresolvedFunction results . push ( cursor . getString ( i ) ) ; break ; case 4 : // Blob // noinspection JSCheckFunctionSignatures results . push ( cursor . getBlob ( i ) ) ; break ; default : throw new Error ( 'SQLITE - Unknown Field Type ' + type ) ; } } return results ; }


Input: * Parses a Row of data into a JS Array ( as String ) [CODESPLIT] function DBGetRowArrayString ( cursor ) { //noinspection JSUnresolvedFunction let count = cursor . getColumnCount ( ) ; let results = [ ] ; for ( let i = 0 ; i < count ; i ++ ) { const type = cursor . getType ( i ) ; switch ( type ) { case 0 : // NULL results . push ( null ) ; break ; case 1 : // Integer //noinspection JSUnresolvedFunction results . push ( cursor . getString ( i ) ) ; break ; case 2 : // Float //noinspection JSUnresolvedFunction results . push ( cursor . getString ( i ) ) ; break ; case 3 : // String //noinspection JSUnresolvedFunction results . push ( cursor . getString ( i ) ) ; break ; case 4 : // Blob // noinspection JSCheckFunctionSignatures results . push ( cursor . getBlob ( i ) ) ; break ; default : throw new Error ( 'SQLITE - Unknown Field Type ' + type ) ; } } return results ; }


Input: * Parses a Row of data into a JS Object ( as String ) [CODESPLIT] function DBGetRowObjectString ( cursor ) { //noinspection JSUnresolvedFunction const count = cursor . getColumnCount ( ) ; let results = { } ; for ( let i = 0 ; i < count ; i ++ ) { const type = cursor . getType ( i ) ; //noinspection JSUnresolvedFunction const name = cursor . getColumnName ( i ) ; switch ( type ) { case 0 : // NULL results [ name ] = null ; break ; case 1 : // Integer //noinspection JSUnresolvedFunction results [ name ] = cursor . getString ( i ) ; break ; case 2 : // Float //noinspection JSUnresolvedFunction results [ name ] = cursor . getString ( i ) ; break ; case 3 : // String //noinspection JSUnresolvedFunction results [ name ] = cursor . getString ( i ) ; break ; case 4 : // Blob // noinspection JSCheckFunctionSignatures results [ name ] = cursor . getBlob ( i ) ; break ; default : throw new Error ( 'SQLITE - Unknown Field Type ' + type ) ; } } return results ; }


Input: * Database Constructor [CODESPLIT] function Database ( dbname , options , callback ) { if ( ! this instanceof Database ) { // jshint ignore:line //noinspection JSValidateTypes return new Database ( dbname , options , callback ) ; } this . _isOpen = false ; this . _resultType = Database . RESULTSASARRAY ; this . _valuesType = Database . VALUESARENATIVE ; if ( typeof options === 'function' ) { callback = options ; //noinspection JSUnusedAssignment options = { } ; } else { //noinspection JSUnusedAssignment options = options || { } ; } //noinspection JSUnresolvedVariable if ( options && options . multithreading && typeof global . Worker === 'function' ) { // We don't want this passed into the worker; to try and start another worker (which would fail). delete options . multithreading ; if ( ! Database . HAS_COMMERCIAL ) { throw new Error ( "Commercial only feature; see http://nativescript.tools/product/10" ) ; } return new Database . _multiSQL ( dbname , options , callback ) ; } // Check to see if it has a path, or if it is a relative dbname // dbname = "" - Temporary Database // dbname = ":memory:" = memory database if ( dbname !== "" && dbname !== ":memory:" ) { //var pkgName = appModule.android.context.getPackageName(); //noinspection JSUnresolvedFunction dbname = _getContext ( ) . getDatabasePath ( dbname ) . getAbsolutePath ( ) . toString ( ) ; let path = dbname . substr ( 0 , dbname . lastIndexOf ( '/' ) + 1 ) ; // Create "databases" folder if it is missing.  This causes issues on Emulators if it is missing // So we create it if it is missing try { //noinspection JSUnresolvedFunction,JSUnresolvedVariable let javaFile = new java . io . File ( path ) ; if ( ! javaFile . exists ( ) ) { //noinspection JSUnresolvedFunction javaFile . mkdirs ( ) ; //noinspection JSUnresolvedFunction javaFile . setReadable ( true ) ; //noinspection JSUnresolvedFunction javaFile . setWritable ( true ) ; } } catch ( err ) { console . info ( "SQLITE.CONSTRUCTOR - Creating DB Folder Error" , err ) ; } } const self = this ; return new Promise ( function ( resolve , reject ) { try { let flags = 0 ; if ( typeof options . androidFlags !== 'undefined' ) { flags = options . androidFlags ; } self . _db = self . _openDatabase ( dbname , flags , options , _getContext ( ) ) ; } catch ( err ) { console . error ( "SQLITE.CONSTRUCTOR -  Open DB Error" , err ) ; if ( callback ) { callback ( err , null ) ; } reject ( err ) ; return ; } self . _isOpen = true ; let doneCnt = _DatabasePluginInits . length , doneHandled = 0 ; const done = function ( err ) { if ( err ) { doneHandled = doneCnt ; // We don't want any more triggers after this if ( callback ) { callback ( err , null ) ; } reject ( err ) ; return ; } doneHandled ++ ; if ( doneHandled === doneCnt ) { if ( callback ) { callback ( null , self ) ; } resolve ( self ) ; } } ; if ( doneCnt ) { try { for ( let i = 0 ; i < doneCnt ; i ++ ) { _DatabasePluginInits [ i ] . call ( self , options , done ) ; } } catch ( err ) { done ( err ) ; } } else { if ( callback ) { callback ( null , self ) ; } resolve ( self ) ; } } ) ; }


Input: * Converts a string to a UTF - 8 char array and wraps it in an adopted pointer ( which is GC managed and kept alive until it s referenced by a variable ) . The reason for doing it is that iOS runtime marshals JS string arguments via temporary buffers which are deallocated immediately after the call returns . In some cases however we need them to stay alive for subsequent native calls because otherwise attempts to read the freed memory may lead to unpredictable app crashes . E . g . sqlite3_step function happens to use the stored char * passed as dbname to sqlite3_open_v2 . [CODESPLIT] function toCharPtr ( str ) { const objcStr = NSString . stringWithString ( str ) ; const bufferSize = strlen ( objcStr . UTF8String ) + 1 ; const buffer = interop . alloc ( bufferSize ) ; objcStr . getCStringMaxLengthEncoding ( buffer , bufferSize , NSUTF8StringEncoding ) ; return buffer ; }


Input: * Creates a Cursor Tracking Statement for reading result sets [CODESPLIT] function CursorStatement ( statement , resultType , valuesType ) { this . statement = statement ; this . resultType = resultType ; this . valuesType = valuesType ; this . built = false ; this . columns = [ ] ; }


Input: noinspection JSValidateJSDoc * Database Constructor [CODESPLIT] function Database ( dbname , options , callback ) { if ( ! this instanceof Database ) { // jshint ignore:line //noinspection JSValidateTypes return new Database ( dbname , options , callback ) ; } this . _isOpen = false ; this . _resultType = Database . RESULTSASARRAY ; this . _valuesType = Database . VALUESARENATIVE ; if ( typeof options === 'function' ) { callback = options ; options = { } ; } else { options = options || { } ; } if ( options && options . multithreading && typeof global . Worker === 'function' ) { delete options . multithreading ; if ( ! Database . HAS_COMMERCIAL ) { throw new Error ( "Commercial only feature; see http://nativescript.tools/product/10" ) ; } return new Database . _multiSQL ( dbname , options , callback ) ; } // Check to see if it has a path, or if it is a relative dbname // DBNAME = "" - is a Temporary Database // DBNAME = ":memory:" - is a Memory only database if ( dbname !== "" && dbname !== ":memory:" ) { let path ; if ( dbname . indexOf ( '/' ) === - 1 ) { // noinspection JSUnresolvedVariable, JSUnresolvedFunction path = fs . knownFolders . documents ( ) . path ; dbname = path + '/' + dbname ; } else { path = dbname . substr ( 0 , dbname . lastIndexOf ( '/' ) + 1 ) ; } // Create "databases" folder if it is missing.  This causes issues on Emulators if it is missing // So we create it if it is missing try { // noinspection JSUnresolvedVariable if ( ! fs . File . exists ( path ) ) { //noinspection JSUnresolvedFunction const fileManager = iosProperty ( NSFileManager , NSFileManager . defaultManager ) ; //noinspection JSUnresolvedFunction if ( ! fileManager . createDirectoryAtPathWithIntermediateDirectoriesAttributesError ( path , true , null , null ) ) { console . warn ( "SQLITE.CONSTRUCTOR - Creating DB Folder Error" ) ; } } } catch ( err ) { console . warn ( "SQLITE.CONSTRUCTOR - Creating DB Folder Error" , err ) ; } } this . _dbnamePtr = toCharPtr ( dbname ) ; const self = this ; //noinspection JSUnresolvedFunction return new Promise ( function ( resolve , reject ) { let error ; try { let flags = 0 ; if ( typeof options . iosFlags !== 'undefined' ) { flags = options . iosFlags ; } self . _db = new interop . Reference ( ) ; if ( options && options . readOnly ) { // SQLITE_OPEN_FULLMUTEX = 65536, SQLITE_OPEN_READONLY = 1 ---- 1 | 65536 = 65537 error = sqlite3_open_v2 ( self . _dbnamePtr , self . _db , 65537 | flags , null ) ; } else { // SQLITE_OPEN_FULLMUTEX = 65536, SQLITE_OPEN_CREATE = 4, SQLITE_OPEN_READWRITE = 2 --- 4 | 2 | 65536 = 65542 error = sqlite3_open_v2 ( self . _dbnamePtr , self . _db , 65542 | flags , null ) ; } self . _db = self . _db . value ; } catch ( err ) { if ( callback ) { callback ( err , null ) ; } reject ( err ) ; return ; } if ( error ) { if ( callback ) { callback ( error , null ) ; } reject ( error ) ; return ; } self . _isOpen = true ; let doneCnt = _DatabasePluginInits . length , doneHandled = 0 ; const done = function ( err ) { if ( err ) { doneHandled = doneCnt ; // We don't want any more triggers after this if ( callback ) { callback ( err , null ) ; } reject ( err ) ; return ; } doneHandled ++ ; if ( doneHandled === doneCnt ) { if ( callback ) { callback ( null , self ) ; } resolve ( self ) ; } } ; if ( doneCnt ) { try { for ( let i = 0 ; i < doneCnt ; i ++ ) { _DatabasePluginInits [ i ] . call ( self , options , done ) ; } } catch ( err ) { done ( err ) ; } } else { if ( callback ) { callback ( null , self ) ; } resolve ( self ) ; } } ) ; }


Input:
Creates an object representing a CronJob [CODESPLIT] function CronJob ( sandbox , job ) { /**
     * @property name - The name of the cron job
     * @property schedule - The cron schedule of the job
     * @property next_scheduled_at - The next time this job is scheduled
     */ assign ( this , job ) ; /**
     * @property claims - The claims embedded in the Webtask's token
     */ if ( job . token ) { this . claims = Decode ( job . token ) ; } else { this . claims = { jtn : job . name , ten : this . container , } ; } /**
     * @property sandbox - The {@see Sandbox} instance used to create this Webtask instance
     */ this . sandbox = sandbox ; /**
     * @property url - The public url that can be used to invoke webtask that the cron job runs
     */ Object . defineProperty ( this , 'url' , { enumerable : true , get : function ( ) { return this . sandbox . url + '/api/run/' + this . container + '/' + this . name ; } } ) ; }


Input: Creates an object representing a user s webtask . io credentials [CODESPLIT] function Sandbox ( options ) { var securityVersion = 'v1' ; this . url = options . url ; this . container = options . container ; this . token = options . token ; this . onBeforeRequest = [ ] . concat ( options . onBeforeRequest ) . filter ( hook => typeof hook === 'function' ) ; try { var typ = Decode ( options . token , { header : true } ) . typ ; if ( typ && typ . toLowerCase ( ) === 'jwt' ) { securityVersion = 'v2' ; } } catch ( _ ) { // Ignore jwt decoding failures and assume v1 opaque token } this . securityVersion = securityVersion ; }


Input:
Creates an object representing a Webtask [CODESPLIT] function Webtask ( sandbox , token , options ) { if ( ! options ) options = { } ; if ( sandbox . securityVersion === 'v1' ) { try { /**
             * @property claims - The claims embedded in the Webtask's token
             */ this . claims = Decode ( token ) ; /**
             * @property token - The token associated with this webtask
             */ this . token = token ; } catch ( _ ) { throw new Error ( 'token must be a valid JWT' ) ; } } if ( sandbox . securityVersion === 'v2' ) { if ( typeof options . name !== 'string' ) { throw new Error ( 'name must be a valid string' ) ; } this . claims = { jtn : options . name , ten : options . container || sandbox . container , } } /**
     * @property sandbox - The {@see Sandbox} instance used to create this Webtask instance
     */ this . sandbox = sandbox ; /**
     * @property meta - The metadata associated with this webtask
     */ this . meta = options . meta || { } ; /**
     * @property secrets - The secrets associated with this webtask if `decrypt=true`
     */ this . secrets = options . secrets ; /**
     * @property code - The code associated with this webtask if `fetch_code=true`
     */ this . code = options . code ; /**
     * @property container - The container name in which the webtask will run
     */ Object . defineProperty ( this , 'container' , { enumerable : true , get : function ( ) { return options . container || this . sandbox . container ; } } ) ; /**
     * @property url - The public url that can be used to invoke this webtask
     */ Object . defineProperty ( this , 'url' , { enumerable : true , get : function ( ) { var url = options . webtask_url ; if ( ! url ) { if ( this . claims . host ) { var surl = Url . parse ( this . sandbox . url ) ; url = surl . protocol + '//' + this . claims . host + ( surl . port ? ( ':' + surl . port ) : '' ) + '/' + this . sandbox . container ; } else { url = this . sandbox . url + '/api/run/' + this . sandbox . container ; } if ( this . claims . jtn ) url += '/' + this . claims . jtn ; else url += '?key=' + this . token ; } return url ; } } ) ; }


Input: ********************************************************************************************** * CcZnp Class ** ********************************************************************************************** [CODESPLIT] function CcZnp ( ) { EventEmitter . call ( this ) ; var self = this ; this . MT = MT ; // export constant this . _init = false ; this . _resetting = false ; this . _sp = null ; this . _unpi = null ; this . _spinLock = false ; this . _txQueue = [ ] ; this . on ( '_ready' , function ( ) { self . _init = true ; self . emit ( 'ready' ) ; } ) ; this . _innerListeners = { spOpen : function ( ) { debug ( 'The serialport ' + self . _sp . path + ' is opened.' ) ; self . emit ( '_ready' ) ; } , spErr : function ( err ) { self . _sp . close ( ) ; } , spClose : function ( ) { debug ( 'The serialport ' + self . _sp . path + ' is closed.' ) ; self . _txQueue = null ; self . _txQueue = [ ] ; self . _sp = null ; self . _unpi = null ; self . _init = false ; self . emit ( 'close' ) ; } , parseMtIncomingData : function ( result ) { self . _parseMtIncomingData ( result ) ; } } ; }


Input: ********************************************************************************************** * ZpiObject Class ** * 1 . Provides command framer ( SREQ ) ** * 2 . Provides parser ( SRSP AREQ ) ** ********************************************************************************************** [CODESPLIT] function ZpiObject ( subsys , cmd , args ) { // args is optional, and can be an array or a value-object if given var subsystem = zmeta . Subsys . get ( subsys ) , command , reqParams ; this . type = undefined ; // string after assgined this . subsys = undefined ; // string after assigned this . cmd = undefined ; // string after assigned this . cmdId = undefined ; // number after assigned this . args = undefined ; // array after assigned: [ { name, type, value }, ... ] if ( ! subsystem ) throw new Error ( 'Unrecognized subsystem' ) ; this . subsys = subsystem . key ; command = zmeta [ this . subsys ] . get ( cmd ) ; if ( ! command ) throw new Error ( 'Unrecognized command' ) ; this . cmd = command . key ; this . cmdId = command . value ; this . type = zmeta . getType ( this . subsys , this . cmd ) ; if ( ! this . type ) throw new Error ( 'Unrecognized type' ) ; // if args is given, this is for REQ transmission // otherwise, maybe just for parsing RSP packet if ( args ) reqParams = zmeta . getReqParams ( this . subsys , this . cmd ) ; // [ { name, type }, ... ] if ( reqParams ) { if ( Array . isArray ( args ) ) { // arg: { name, type } -> { name, type, value } reqParams . forEach ( function ( arg , idx ) { arg . value = args [ idx ] ; } ) ; } else if ( typeof args === 'object' ) { reqParams . forEach ( function ( arg , idx ) { if ( ! args . hasOwnProperty ( arg . name ) ) throw new Error ( 'The argument object has incorrect properties' ) ; else arg . value = args [ arg . name ] ; } ) ; } this . args = reqParams ; // [ { name, type, value }, ... ] } }


Input: Updates to this class should also be applied to the the ES6 version in es6 - wrapped - promise . js . [CODESPLIT] function wrappedPromise ( executor ) { if ( ! ( this instanceof wrappedPromise ) ) { return Promise ( executor ) ; } if ( typeof executor !== 'function' ) { return new Promise ( executor ) ; } var context , args ; var promise = new Promise ( wrappedExecutor ) ; promise . __proto__ = wrappedPromise . prototype ; try { executor . apply ( context , args ) ; } catch ( err ) { args [ 1 ] ( err ) ; } return promise ; function wrappedExecutor ( resolve , reject ) { context = this ; args = [ wrappedResolve , wrappedReject ] ; // These wrappers create a function that can be passed a function and an argument to // call as a continuation from the resolve or reject. function wrappedResolve ( val ) { ensureAslWrapper ( promise , false ) ; return resolve ( val ) ; } function wrappedReject ( val ) { ensureAslWrapper ( promise , false ) ; return reject ( val ) ; } } }


Input: wrap callbacks ( success error ) so that the callbacks will be called as a continuations of the resolve or reject call using the __asl_wrapper created above . [CODESPLIT] function bind ( fn ) { if ( typeof fn !== 'function' ) return fn ; return wrapCallback ( function ( val ) { var result = ( promise . __asl_wrapper || propagateAslWrapper ) ( this , fn , val , next ) ; if ( result . error ) { throw result . errorVal } else { return result . returnVal } } ) ; }