/*
Standard linker that also outputs a manifest file based on the public
resources
778620
@Override
  public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts)
      throws UnableToCompleteException {
    ArtifactSet toReturn = super.link(logger, context, artifacts);

    // Create the general cache-manifest resource for the landing page:
    toReturn.add(emitLandingPageCacheManifest(context, logger, toReturn, staticCachedFiles()));

    return toReturn;
  }
802856
function mapSources (sourceMap, mapCallback) {
  let chain = Promise.resolve()
  function pushChain (path, index, arr) {
    chain = chain
      .then(() => mapCallback(path))
      .then(replacement => {
        arr[index] = replacement || path
      })
  }
  if (sourceMap.sources) {
    sourceMap.sources.forEach(pushChain)
  }
  if (sourceMap.sections) {
    sourceMap.sections.forEach(section => {
      if (section.map && section.map.sources) {
        section.map.sources.forEach(pushChain)
      }
    })
  }
  return chain.then(() => sourceMap)
}
149951
function compile(inFile, outFile, sourceMap, cb) {
    console.log('Compiling ' + inFile + ' to ' + outFile);
    var outStream = fs.createWriteStream(outFile, 'utf8');
    outStream.on('close', cb);
    browserify({debug: true})
      .require(inFile, { entry: true })
      .bundle()
      .pipe(exorcist(sourceMap))
      .pipe(outStream);
}
1002649
function (out) {
            var tplParam = out.templateParam;
            out.addDependencies(tplParam.$dependencies);
            out.addDependencies(tplParam.$templates, ".tpl");
            if (tplParam.$macrolibs) {
                out.addDependencies(ariaUtilsArray.extractValuesFromMap(tplParam.$macrolibs), ".tml");
            }
            if (tplParam.$csslibs) {
                out.addDependencies(ariaUtilsArray.extractValuesFromMap(tplParam.$csslibs), ".cml");
            }
        }
339949
function includesAtLoader(graph) {
	var found = false;

	var isAtLoader = function(name) {
		return name === "@loader";
	};

	keys(graph).forEach(function(name) {
		var node = graph[name];

		if (isPluginExcludedFromBuild(node)) {
			return;
		}

		if (isAtLoader(name)) {
			return (found = true);
		}

		defaultTo(node.dependencies, []).forEach(function(depName) {
			if (isAtLoader(depName)) {
				return (found = true);
			}
		});
	});

	return found;
}
258923
function builder (config, configPath, callback) {
	var inc = new Include(config)
	inc
		.on('drain', function () {
			// All files and their dependencies loaded, root files (files with no parent file) built
			inc.build(function () {

				var output = path.resolve( configPath, config.output.path )
				var outputFiles = []

				debug('Include DONE: %d roots found output=%s', inc.roots.length, output)
				async.forEach(
					inc.roots
				, function (file, cb) {
						var relfile = path.join( output, path.relative(configPath, file.id) )

						outputFiles.push(relfile)

						debug('Include WRITING: file=%s', relfile)
						var w = fstream
							.Writer({
								path: relfile
							, mode: config.output.mode
							})
							w
							.on('close', cb)

							if (file.content)
								w.end(file.content)
							else
								fs.createReadStream(file.id).pipe(w)
				  }
				, function (err) {
						if (err) return callback(err)
						debug('%d files written out to %s', inc.roots.length, output)
						callback(
							null
						, outputFiles
						, inc.sourceFiles
						, inc.roots.map(function(root) {
								return root.id
							})
						)
					}
				)
			})
		})

	debug( path.resolve( configPath, config.input.include || '*.js' ) )
	debug( config.input.include || '*.js' )
	debug( config.input.exclude || '' )
	fileset(
		config.input.include || '*.js'
	, config.input.exclude || ''
	, { cwd: configPath }
	, function (err, files) {
			if (err) throw err

			debug('files', files)
			files
				.forEach(function (file) {
					inc.add( path.resolve( configPath, file) )
				})
		}
	)
}
758984
function Manifest(output, path) {

    this._output = output;
    this._path = path;

    var buffer = FS.readFileSync(path, {"encoding": "utf8"});
    var json = JSON.parse(buffer);

    // App version is [major.][minor.]micro
    // Major and minor need to be < 100, micro < 1000
    if (json.xwalk_app_version &&
        json.xwalk_app_version.match("^([0-9]+\.){0,2}[0-9]+$")) {

        var valid = true;
        var numbers = json.xwalk_app_version.split(".");
        for (var i = 0; i < numbers.length; i++) {
            if (i == numbers.length - 1 &&
                numbers[i] >= 1000) {
                // Last component, up to 3 digits
                output.warning("App version part '" + numbers[i] + "' must be < 1000");
                valid = false;
                break;
            } else if (i < numbers.length - 1 &&
                       numbers[i] >= 100) {
                // First 2 components, up to 2 digits
                output.warning("App version part '" + numbers[i] + "' must be < 100");
                valid = false;
                break;
            }
        }

        if (valid) {
            this._appVersion = json.xwalk_app_version;
        }
    }

    if (!this._appVersion) {
        output.error("Invalid app version '" + json.xwalk_app_version + "' in the manifest");
        throw new Error("Invalid app version '" + json.xwalk_app_version + "' in the manifest");
    }

    // Splash background colour
    this._backgroundColor = "#ffffff";
    if (json.background_color) {
        var color = ParseColor(json.background_color);
        if (color && color.hex) {
            this._backgroundColor = color.hex;
        } else {
            output.warning("Failed to parse background_color " + json.background_color);
        }
    }

    // Name
    if (json.name &&
        typeof json.name === "string") {
        this._name = json.name;
    }

    if (!this._name) {
        output.warning("Invalid or missing field 'name' in manifest.json");
    }

    // Short name
    if (json.short_name &&
        typeof json.short_name === "string") {
        this._shortName= json.short_name;
    }

    var values;

    // Display
    this._display = "standalone";
    if (json.display) {

        values = ["fullscreen", "standalone", "minimal-ui", "browser"];

        if (values.indexOf(json.display) > -1) {
            // supported mode
            this._display = json.display;
        } else {
            output.warning("Unsupported value '" + json.display + "' for 'display' in manifest.json");
        }
    }

    // Orientation
    this._orientation = "any";
    if (json.orientation) {

        values = [ "any",
                   "natural",
                   "landscape",
                   "portrait",
                   "portrait-primary",
                   "portrait-secondary",
                   "landscape-primary",
                   "landscape-secondary" ];

        if (values.indexOf(json.orientation) > -1) {
            // supported mode
            this._orientation = json.orientation;
        } else {
            output.warning("Unsupported value '" + json.orientation + "' for 'orientation' in manifest.json");
        }
    }

    // Start URL
    // TODO check value
    if (json.start_url &&
        typeof json.start_url === "string") {
        this._startUrl = json.start_url;
    }

    // Icons
    this._icons = [];
    if (json.icons) {
        // TODO validate
        this._icons = json.icons;
    }

    // Command line params
    this._commandLine = null;
    if (json.xwalk_command_line) {
        if (typeof json.xwalk_command_line === "string") {
            this._commandLine = json.xwalk_command_line;
        } else {
            output.warning("Invalid command line '" + json.xwalk_command_line + "'");
        }
    }

    // Package ID
    if (json.xwalk_package_id &&
        CommandParser.validatePackageId(json.xwalk_package_id, this._output)) {
        this._packageId = json.xwalk_package_id;
    } else {
        throw new Error("manifest.json: Invalid package ID '" + json.xwalk_package_id + "'");
    }

    // Extensions
    this._extensions = [];
    if (json.xwalk_extensions) {
        if (json.xwalk_extensions instanceof Array) {
            json.xwalk_extensions.forEach(function (path) {
                var absPath = Path.resolve(Path.dirname(this._path), path);
                absPath = Path.normalize(absPath);
                if (ShellJS.test("-e", absPath)) {
                    this._extensions.push(absPath);
                } else {
                    output.warning("Skipping extension because dir not found: " + absPath);
                }
            }.bind(this));
        } else {
            output.warning("Invalid extensions " + json.xwalk_extensions);
        }
    }
    // Absolute path of Extension Hooks.
    // This info is needed to skip them when generating MSI.
    this._extensionHooks = [];
    this._extensions.forEach(function(extension, i){
      var path = Path.join(extension, "XWalkExtensionHooks.js");
      if (ShellJS.test("-f", path)) {
        this._extensionHooks.push(path);
      }
    }.bind(this));

    // Target platforms
    if (json.xwalk_target_platforms &&
        json.xwalk_target_platforms instanceof Array) {
        this._targetPlatforms = json.xwalk_target_platforms;
    }

    if (!this._targetPlatforms) {
        output.error("Missing or invalid target platforms in the manifest");
        output.error("Try adding");
        output.error('    "xwalk_target_platforms": [ "android" ]');
        output.error("or similar for platform of choice.");
    }

    // Android animatable view
    this._androidAnimatableView = false;
    if (json.xwalk_android_animatable_view) {

        // Recognise boolean or string true.
        if (typeof json.xwalk_android_animatable_view === "boolean" ||
        json.xwalk_android_animatable_view === "true") {
            this._androidAnimatableView = true;
        }
    }

    // Android "keep screen on"
    this._androidKeepScreenOn = false;
    if (json.xwalk_android_keep_screen_on) {

        // Recognise boolean or string true.
        if (typeof json.xwalk_android_keep_screen_on === "boolean" ||
        json.xwalk_android_keep_screen_on === "true") {
            this._androidKeepScreenOn = true;
        }
    }

    // Android permissions
    this._androidPermissions = Manifest.ANDROID_DEFAULT_PERMISSIONS.concat([]); // clone array
    if (json.xwalk_android_permissions) {
        if (json.xwalk_android_permissions instanceof Array) {
            // Merge permissions to the default ones.
            json.xwalk_android_permissions.forEach(function (permission) {
                if (this._androidPermissions.indexOf(permission) < 0) {
                    this._androidPermissions.push(permission);
                }
            }.bind(this));
        } else {
            output.warning("Invalid android permissions '" + json.xwalk_android_permissions + "'");
        }
    }

    // Android webp
    this._androidWebp = false;
    if (json.xwalk_android_webp) {

        if (typeof json.xwalk_android_webp === "string") {
            // TODO better check
            this._androidWebp = json.xwalk_android_webp;
        } else {
            output.warning("Invalid webp parameters '" + json.xwalk_android_webp + "'");
        }
    }

    // Windows update ID
    // Optional field, only check if present.
    this._windowsUpdateId = null;
    if (json.xwalk_windows_update_id) {

        var parts = json.xwalk_windows_update_id.split("-");
        if (parts.length === 5 &&
            parts[0].length === 8 && parts[0].match("^[0-9]*$") &&
            parts[1].length === 4 && parts[1].match("^[0-9]*$") &&
            parts[2].length === 4 && parts[2].match("^[0-9]*$") &&
            parts[3].length === 4 && parts[3].match("^[0-9]*$") &&
            parts[4].length === 12 && parts[4].match("^[0-9]*$")) {

            this._windowsUpdateId = json.xwalk_windows_update_id;

        } else {

            output.error("Invalid Windows Update ID + '" + json.xwalk_windows_update_id + "'");
        }
    }

    // Windows vendor field
    // Optional field, only check if present.
    this._windowsVendor = null;
    if (json.xwalk_windows_vendor) {
        if (typeof json.xwalk_windows_vendor === "string") {
            this._windowsVendor = json.xwalk_windows_vendor;
        } else {
            output.error("Windows target: Invalid vendor field + '" + json.xwalk_windows_vendor + "'");
        }
    }
}
756172
function compile( bundleData, bundleFile, config, callback ) {
	var baseDir = config['path'] || path.dirname(bundleFile);
	var encoder, profileEncoder = [], profileLoader = [], bundleLoader;

	// Compile stages
	var openBundle = function( cb ) {
		return function() {

			// Create encoder
			encoder = new BinaryEncoder(
					bundleFile,
					{
						'name' 			: bundleData['name'],
						'base_dir' 		: baseDir,
						'log'			: config['log'] || 0x00,
						'sparse'		: config['sparse'],
					}
				);

			// Add profiles
			for (var i=0; i<profileEncoder.length; i++) {
				encoder.addProfile( profileEncoder[i] );
			}

			// We are ready
			cb();
		}
	}

	var loadBundles = function( cb ) {
		return function() {
			// Load a bundle by specs
			bundleLoader.addBySpecs( bundleData );
			// Solve dependencies and load resources
			bundleLoader.load( cb );
		}
	}

	var compileExports = function( cb ) {
		return function() {
			// Get the bundle to encode
			var bundle = bundleLoader.bundles[ bundleData['name'] ];

			// Encode resources
			for (var k in bundle.resources) {
				encoder.encode( bundle.resources[k], k );
			}

			// Embed blobs
			for (var k in bundle.blobs) {
				encoder.embedBlob( bundle.blobs[k][0], k, bundle.blobs[k][1] );
			}

			// We are done
			cb();
		}
	}

	var closeBundle = function( cb ) {
		return function() {
			// Close & Complete
			encoder.close();
			cb();
		}
	}

	// Check for profileTable/profileLoader
	if (config['profileEncoder'] || config['profileLoader']) {

		// Check for missing arguments
		if (!config['profileEncoder']) {
			callback( "Got 'profileLoader' but missing 'profileEncoder' in the arguments" );
			return;
		}
		if (!config['profileLoader']) {
			callback( "Got 'profileEncoder' but missing 'profileLoader' in the arguments" );
			return;
		}

		// Fetch
		profileEncoder = config['profileEncoder'];
		profileLoader = config['profileLoader'];

		// Make sure it's array
		if (!(profileEncoder instanceof Array))
			profileEncoder = [ profileEncoder ];
		if (!(profileLoader instanceof Array))
			profileLoader = [ profileLoader ];

	} else {

		// Identify some important information
		var profile = config['profile'] || bundleData['profile'];
		if (!profile) {
			callback( "No jbb profile was specified!");
			return;
		}

		// Make sure it's array
		if (typeof profile === 'string')
			profile = [ profile ];

		// Require
		for (var i=0; i<profile.length; i++) {
			var pname = profile[i];
			if (pname[0] == ".") {
				profileEncoder.push( require( path.join(process.cwd(), pname, '/profile-encode') ) );
				profileLoader.push( require( path.join(process.cwd(), pname, "/profile-loader") ) );
			} else {
				profileEncoder.push( require('jbb-profile-'+pname+'/profile-encode') );
				profileLoader.push( require('jbb-profile-'+pname+"/profile-loader") );
			}
		}

	}

	// Load profile table and compiler helper
	bundleLoader = new BundlesLoader( baseDir );
	for (var i=0; i<profileLoader.length; i++) {
		bundleLoader.addProfileLoader( profileLoader[i] );
	}

	// Chained initialization of profile loaders
	var context = { 'remaining': profileLoader.length }
	var init_callback = (function() {
		if (--this.remaining == 0) {
			openBundle(
				loadBundles(
					compileExports(
						closeBundle( callback || function(){} )
						) 
					) 
			)();
		}
	}).bind(context);

	// Initialize profile compiler with the specs file
	for (var i=0; i<profileLoader.length; i++) {
		if (!profileLoader[i].initialize) {
			init_callback();
		} else {
			profileLoader[i].initialize( init_callback, bundleData );
		}
	}

}
155829
def link_manifest_references_into_repository(self, session, manifest, media_type,
                                                 source_repo, target_repo):
        

        if source_repo == target_repo:
            return

        parsed = json.loads(manifest.decode('utf-8'))

        references = []
        if media_type in (MEDIA_TYPE_DOCKER_V2_SCHEMA2, MEDIA_TYPE_OCI_V1):
            references.append(parsed['config']['digest'])
            for l in parsed['layers']:
                references.append(l['digest'])
        else:
            # manifest list support could be added here, but isn't needed currently, since
            # we never copy a manifest list as a whole between repositories
            raise RuntimeError("Unhandled media-type {}".format(media_type))

        for digest in references:
            self.link_blob_into_repository(session, digest, source_repo, target_repo)
954550
function (e) {
		currentProgram = undefined;
		currentModule = {
			name: null,
			resource: getResourceName(e.filename),
			module: getModuleName(getResourceName(e.filename)),
			localNames: Object.create(null)
		};
	}
485688
function normalizeManifest(manifest, fn) {
  var obj = {};
  manifest.forEach(function(file) {
    if (!file) return;
    obj[file.name] = {
      mtime: file.mtime,
      mode: file.mode,
      size: file.size,
      hash: file.hash,
      link: file.link
    };
  });
  fn(null, obj);
}
380638
def link(self, path, pkg):
        
        # Check if a custom linker exists to handle linking this package
        #for ep in pkg_resources.iter_entry_points(group="enaml_native_linker"):
        #    if ep.name.replace("-", '_') == pkg.replace("-", '_'):
        #        linker = ep.load()
        #        print("Custom linker {} found for '{}'. Linking...".format(
        #            linker, pkg))
        #        if linker(self.ctx, path):
        #            return

        #: Use the default builtin linker script
        if exists(join(path, pkg, 'build.gradle')):
            print(Colors.BLUE+"[INFO] Linking {}/build.gradle".format(
                  pkg)+Colors.RESET)
            self.link_android(path, pkg)
        if exists(join(path, pkg, 'Podfile')):
            print(Colors.BLUE+"[INFO] Linking {}/Podfile".format(
                  pkg)+Colors.RESET)
            self.link_ios(path, pkg)
863918
def _render_jar_tool_args(self, options):
    
    args = []

    with temporary_dir() as manifest_stage_dir:
      # relativize urls in canonical classpath, this needs to be stable too therefore
      # do not follow the symlinks because symlinks may vary from platform to platform.
      classpath = relativize_classpath(self.classpath,
                                       os.path.dirname(self._path),
                                       followlinks=False)

      def as_cli_entry(entry):
        src = entry.materialize(manifest_stage_dir)
        return '{}={}'.format(src, entry.dest) if entry.dest else src
      files = [as_cli_entry(entry) for entry in self._entries] if self._entries else []

      jars = self._jars or []

      with safe_args(classpath, options, delimiter=',') as classpath_args:
        with safe_args(files, options, delimiter=',') as files_args:
          with safe_args(jars, options, delimiter=',') as jars_args:

            # If you specify --manifest to jar-tool you cannot specify --main.
            if self._manifest_entry:
              manifest_file = self._manifest_entry.materialize(manifest_stage_dir)
            else:
              manifest_file = None

            if self._main and manifest_file:
              main_arg = None
              with open(manifest_file, 'a') as f:
                f.write("Main-Class: {}\n".format(self._main))
            else:
              main_arg = self._main

            if main_arg:
              args.append('-main={}'.format(self._main))

            if classpath_args:
              args.append('-classpath={}'.format(','.join(classpath_args)))

            if manifest_file:
              args.append('-manifest={}'.format(manifest_file))

            if files_args:
              args.append('-files={}'.format(','.join(files_args)))

            if jars_args:
              args.append('-jars={}'.format(','.join(jars_args)))

            yield args
696913
function statFile(file, source) {
  return function(cb) {
    var abs = join(source, file);
    stat(abs, function(err, stats) {
      if (err) return cb(err);

      var manifest = {
        name: file,
        abs: abs,
        mtime: Math.floor(stats.mtime.getTime() / 1000),
        mode: '' + parseInt(stats.mode.toString(8), 10),
        size: '' + stats.size // do we need this?
      };

      if (stats.isDirectory()) return cb();
      if (stats.isSymbolicLink()) return fs.readlink(abs, finish('link'));
      calculateHash(abs, finish('hash'));

      function finish(key) {
        return function(err, val) {
          if (err) return cb(err);
          manifest[key] = val;
          cb(null, manifest);
        };
      }
    });
  };
}
838172
function (manifest, file, callback) {
            generate(file.src, options, function (err, sriData) {
                // Make relative if a cwd is specified
                if (file.orig && file.orig.cwd) {
                    file.id = file.id.replace(file.orig.cwd, "");
                    sriData.path = sriData.path.replace(file.orig.cwd, "");
                }
                // Attach a property to the WIP manifest object
                manifest[file.id] = sriData;
                callback(err, manifest);
            });
        }
105027
function elixir(file, buildDirectory) {
        if (!buildDirectory) {
            buildDirectory = 'build';
        }

        var manifestPath = path.join(publicPath(buildDirectory), 'rev-manifest.json');
        var manifest = require(manifestPath);


        if (isset(manifest[file])) {
            return '/'+ str.trim(buildDirectory + '/' + manifest[file], '/');
        }


        throw new Error("File " + file + " not defined in asset manifest.");
    }
1125917
function lookForExternalDependencies( jsFiles ) {
  const
  javascriptSources = [],
  resources = {};

  for ( const jsFileName of Object.keys( jsFiles ) ) {
    const depFileName = `${jsFileName}.dep`;
    if ( Project.srcOrLibPath( depFileName ) ) {
      const depFile = new Source( Project, depFileName );
      try {
        const
        json = depFile.read(),
        dependencies = ToloframeworkPermissiveJson.parse( json );
        // Looking for Javascript dependencies.
        lookForExternalDependenciesJS( dependencies.js, javascriptSources );
        // Looking for other dependencies.
        lookForExternalDependenciesRES( dependencies.res, resources, depFile );
      } catch ( ex ) {
        Fatal.fire(
          `Unable to parse JSON file "${depFile.getAbsoluteFilePath()}"!\n${ex}`,
          Project.srcOrLibPath( jsFileName )
        );
      }
    }
  }

  return {
    js: javascriptSources,
    res: resources
  };
}