Skip to content

Instantly share code, notes, and snippets.

@raspasov
Last active April 28, 2020 22:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raspasov/b6cf6c59c84bbc3f52a508fbad865ed4 to your computer and use it in GitHub Desktop.
Save raspasov/b6cf6c59c84bbc3f52a508fbad865ed4 to your computer and use it in GitHub Desktop.
Patches metro's worker.js for :advanced compilation to work with React Native
;USAGE
;1. get https://github.com/planck-repl/planck
;2. run it from the project folder like this:
;plk patch-metro-worker.cljs
(require '[planck.core :refer [spit slurp]])
;Works with ReactNative 0.62
(def my-production-index-js-file-name "index.prod.js")
(def file-original
"/**\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n *\n * @format\n */\n\"use strict\";\n\nfunction _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n var target = _objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n return target;\n}\n\nfunction _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}\n\nfunction _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n if (typeof Object.getOwnPropertySymbols === \"function\") {\n ownKeys = ownKeys.concat(\n Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n })\n );\n }\n ownKeys.forEach(function(key) {\n _defineProperty(target, key, source[key]);\n });\n }\n return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\n\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\n\nfunction _asyncToGenerator(fn) {\n return function() {\n var self = this,\n args = arguments;\n return new Promise(function(resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}\n\nconst JsFileWrapping = require(\"../ModuleGraph/worker/JsFileWrapping\");\n\nconst assetTransformer = require(\"../assetTransformer\");\n\nconst babylon = require(\"@babel/parser\");\n\nconst collectDependencies = require(\"../ModuleGraph/worker/collectDependencies\");\n\nconst constantFoldingPlugin = require(\"./worker/constant-folding-plugin\");\n\nconst generateImportNames = require(\"../ModuleGraph/worker/generateImportNames\");\n\nconst generate = require(\"@babel/generator\").default;\n\nconst getKeyFromFiles = require(\"../lib/getKeyFromFiles\");\n\nconst getMinifier = require(\"../lib/getMinifier\");\n\nconst importExportPlugin = require(\"./worker/import-export-plugin\");\n\nconst inlinePlugin = require(\"./worker/inline-plugin\");\n\nconst inlineRequiresPlugin = require(\"babel-preset-fbjs/plugins/inline-requires\");\n\nconst normalizePseudoglobals = require(\"./worker/normalizePseudoglobals\");\n\nconst _require = require(\"@babel/core\"),\n transformFromAstSync = _require.transformFromAstSync;\n\nconst _require2 = require(\"metro-cache\"),\n stableHash = _require2.stableHash;\n\nconst types = require(\"@babel/types\");\n\nconst countLines = require(\"../lib/countLines\");\n\nconst _require3 = require(\"metro-source-map\"),\n fromRawMappings = _require3.fromRawMappings,\n toBabelSegments = _require3.toBabelSegments,\n toSegmentTuple = _require3.toSegmentTuple;\n\nfunction getDynamicDepsBehavior(inPackages, filename) {\n switch (inPackages) {\n case \"reject\":\n return \"reject\";\n\n case \"throwAtRuntime\":\n const isPackage = /(?:^|[/\\\\])node_modules[/\\\\]/.test(filename);\n return isPackage ? inPackages : \"reject\";\n\n default:\n inPackages;\n throw new Error(\n `invalid value for dynamic deps behavior: \\`${inPackages}\\``\n );\n }\n}\n\nclass JsTransformer {\n constructor(projectRoot, config) {\n this._projectRoot = projectRoot;\n this._config = config;\n }\n\n transform(filename, data, options) {\n var _this = this;\n\n return _asyncToGenerator(function*() {\n const sourceCode = data.toString(\"utf8\");\n let type = \"js/module\";\n\n if (options.type === \"asset\") {\n type = \"js/module/asset\";\n }\n\n if (options.type === \"script\") {\n type = \"js/script\";\n }\n\n if (filename.endsWith(\".json\")) {\n let code = JsFileWrapping.wrapJson(sourceCode);\n let map = [];\n\n if (options.minify) {\n var _ref = yield _this._minifyCode(filename, code, sourceCode, map);\n\n map = _ref.map;\n code = _ref.code;\n }\n\n return {\n dependencies: [],\n output: [\n {\n data: {\n code,\n lineCount: countLines(code),\n map,\n functionMap: null\n },\n type\n }\n ]\n };\n } // $FlowFixMe TODO t26372934 Plugin system\n\n const transformer = require(_this._config.babelTransformerPath);\n\n const transformerArgs = {\n filename,\n options: _objectSpread({}, options, {\n enableBabelRCLookup: _this._config.enableBabelRCLookup,\n enableBabelRuntime: _this._config.enableBabelRuntime,\n // Inline requires are now performed at a secondary step. We cannot\n // unfortunately remove it from the internal transformer, since this one\n // is used by other tooling, and this would affect it.\n inlineRequires: false,\n projectRoot: _this._projectRoot,\n publicPath: _this._config.publicPath\n }),\n plugins: [],\n src: sourceCode\n };\n const transformResult =\n type === \"js/module/asset\"\n ? _objectSpread(\n {},\n yield assetTransformer.transform(\n transformerArgs,\n _this._config.assetRegistryPath,\n _this._config.assetPlugins\n ),\n {\n functionMap: null\n }\n )\n : yield transformer.transform(transformerArgs); // Transformers can ouptut null ASTs (if they ignore the file). In that case\n // we need to parse the module source code to get their AST.\n\n let ast =\n transformResult.ast ||\n babylon.parse(sourceCode, {\n sourceType: \"unambiguous\"\n });\n\n const _generateImportNames = generateImportNames(ast),\n importDefault = _generateImportNames.importDefault,\n importAll = _generateImportNames.importAll; // Add \"use strict\" if the file was parsed as a module, and the directive did\n // not exist yet.\n\n const directives = ast.program.directives;\n\n if (\n ast.program.sourceType === \"module\" &&\n directives.findIndex(d => d.value.value === \"use strict\") === -1\n ) {\n directives.push(types.directive(types.directiveLiteral(\"use strict\")));\n } // Perform the import-export transform (in case it's still needed), then\n // fold requires and perform constant folding (if in dev).\n\n const plugins = [];\n\n const opts = _objectSpread({}, options, {\n inlineableCalls: [importDefault, importAll],\n importDefault,\n importAll\n });\n\n if (options.experimentalImportSupport) {\n plugins.push([importExportPlugin, opts]);\n }\n\n if (options.inlineRequires) {\n plugins.push([inlineRequiresPlugin, opts]);\n }\n\n if (!options.dev) {\n plugins.push([constantFoldingPlugin, opts]);\n }\n\n plugins.push([inlinePlugin, opts]);\n\n var _transformFromAstSync = transformFromAstSync(ast, \"\", {\n ast: true,\n babelrc: false,\n code: false,\n configFile: false,\n comments: false,\n compact: false,\n filename,\n plugins,\n sourceMaps: false\n });\n\n ast = _transformFromAstSync.ast;\n let dependencyMapName = \"\";\n let dependencies;\n let wrappedAst; // If the module to transform is a script (meaning that is not part of the\n // dependency graph and it code will just be prepended to the bundle modules),\n // we need to wrap it differently than a commonJS module (also, scripts do\n // not have dependencies).\n\n if (type === \"js/script\") {\n dependencies = [];\n wrappedAst = JsFileWrapping.wrapPolyfill(ast);\n } else {\n try {\n const opts = {\n asyncRequireModulePath: _this._config.asyncRequireModulePath,\n dynamicRequires: getDynamicDepsBehavior(\n _this._config.dynamicDepsInPackages,\n filename\n ),\n inlineableCalls: [importDefault, importAll],\n keepRequireNames: options.dev\n };\n\n var _collectDependencies = collectDependencies(ast, opts);\n\n ast = _collectDependencies.ast;\n dependencies = _collectDependencies.dependencies;\n dependencyMapName = _collectDependencies.dependencyMapName;\n } catch (error) {\n if (error instanceof collectDependencies.InvalidRequireCallError) {\n throw new InvalidRequireCallError(error, filename);\n }\n\n throw error;\n }\n\n var _JsFileWrapping$wrapM = JsFileWrapping.wrapModule(\n ast,\n importDefault,\n importAll,\n dependencyMapName\n );\n\n wrappedAst = _JsFileWrapping$wrapM.ast;\n }\n\n const reserved =\n options.minify && data.length <= _this._config.optimizationSizeLimit\n ? normalizePseudoglobals(wrappedAst)\n : [];\n const result = generate(\n wrappedAst,\n {\n comments: false,\n compact: false,\n filename,\n retainLines: false,\n sourceFileName: filename,\n sourceMaps: true\n },\n sourceCode\n );\n let map = result.rawMappings\n ? result.rawMappings.map(toSegmentTuple)\n : [];\n let code = result.code;\n\n if (options.minify) {\n var _ref2 = yield _this._minifyCode(\n filename,\n result.code,\n sourceCode,\n map,\n reserved\n );\n\n map = _ref2.map;\n code = _ref2.code;\n }\n\n const functionMap = transformResult.functionMap;\n return {\n dependencies,\n output: [\n {\n data: {\n code,\n lineCount: countLines(code),\n map,\n functionMap\n },\n type\n }\n ]\n };\n })();\n }\n\n _minifyCode(filename, code, source, map) {\n var _this2 = this;\n\n let reserved =\n arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];\n return _asyncToGenerator(function*() {\n const sourceMap = fromRawMappings([\n {\n code,\n source,\n map,\n functionMap: null,\n path: filename\n }\n ]).toMap(undefined, {});\n const minify = getMinifier(_this2._config.minifierPath);\n\n try {\n const minified = minify({\n code,\n map: sourceMap,\n filename,\n reserved,\n config: _this2._config.minifierConfig\n });\n return {\n code: minified.code,\n map: minified.map\n ? toBabelSegments(minified.map).map(toSegmentTuple)\n : []\n };\n } catch (error) {\n if (error.constructor.name === \"JS_Parse_Error\") {\n throw new Error(\n `${error.message} in file ${filename} at ${error.line}:${error.col}`\n );\n }\n\n throw error;\n }\n })();\n }\n\n getCacheKey() {\n const _this$_config = this._config,\n babelTransformerPath = _this$_config.babelTransformerPath,\n minifierPath = _this$_config.minifierPath,\n config = _objectWithoutProperties(_this$_config, [\n \"babelTransformerPath\",\n \"minifierPath\"\n ]);\n\n const filesKey = getKeyFromFiles([\n require.resolve(babelTransformerPath),\n require.resolve(minifierPath),\n require.resolve(\"../ModuleGraph/worker/JsFileWrapping\"),\n require.resolve(\"../assetTransformer\"),\n require.resolve(\"../ModuleGraph/worker/collectDependencies\"),\n require.resolve(\"./worker/constant-folding-plugin\"),\n require.resolve(\"../lib/getMinifier\"),\n require.resolve(\"./worker/inline-plugin\"),\n require.resolve(\"./worker/import-export-plugin\"),\n require.resolve(\"./worker/normalizePseudoglobals\"),\n require.resolve(\"../ModuleGraph/worker/optimizeDependencies\"),\n require.resolve(\"../ModuleGraph/worker/generateImportNames\")\n ]);\n\n const babelTransformer = require(babelTransformerPath);\n\n const babelTransformerKey = babelTransformer.getCacheKey\n ? babelTransformer.getCacheKey()\n : \"\";\n return [\n filesKey,\n stableHash(config).toString(\"hex\"),\n babelTransformerKey\n ].join(\"$\");\n }\n}\n\nclass InvalidRequireCallError extends Error {\n constructor(innerError, filename) {\n super(`${filename}:${innerError.message}`);\n this.innerError = innerError;\n this.filename = filename;\n }\n}\n\nmodule.exports = JsTransformer;\n")
(def file-patched
(str
"/**\n * Copyright (c) Facebook, Inc. and its affiliates.\n *\n * This source code is licensed under the MIT license found in the\n * LICENSE file in the root directory of this source tree.\n *\n *\n * @format\n */\n\"use strict\";\n\nfunction _objectWithoutProperties(source, excluded) {\n if (source == null) return {};\n var target = _objectWithoutPropertiesLoose(source, excluded);\n var key, i;\n if (Object.getOwnPropertySymbols) {\n var sourceSymbolKeys = Object.getOwnPropertySymbols(source);\n for (i = 0; i < sourceSymbolKeys.length; i++) {\n key = sourceSymbolKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue;\n target[key] = source[key];\n }\n }\n return target;\n}\n\nfunction _objectWithoutPropertiesLoose(source, excluded) {\n if (source == null) return {};\n var target = {};\n var sourceKeys = Object.keys(source);\n var key, i;\n for (i = 0; i < sourceKeys.length; i++) {\n key = sourceKeys[i];\n if (excluded.indexOf(key) >= 0) continue;\n target[key] = source[key];\n }\n return target;\n}\n\nfunction _objectSpread(target) {\n for (var i = 1; i < arguments.length; i++) {\n var source = arguments[i] != null ? arguments[i] : {};\n var ownKeys = Object.keys(source);\n if (typeof Object.getOwnPropertySymbols === \"function\") {\n ownKeys = ownKeys.concat(\n Object.getOwnPropertySymbols(source).filter(function(sym) {\n return Object.getOwnPropertyDescriptor(source, sym).enumerable;\n })\n );\n }\n ownKeys.forEach(function(key) {\n _defineProperty(target, key, source[key]);\n });\n }\n return target;\n}\n\nfunction _defineProperty(obj, key, value) {\n if (key in obj) {\n Object.defineProperty(obj, key, {\n value: value,\n enumerable: true,\n configurable: true,\n writable: true\n });\n } else {\n obj[key] = value;\n }\n return obj;\n}\n\nfunction asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {\n try {\n var info = gen[key](arg);\n var value = info.value;\n } catch (error) {\n reject(error);\n return;\n }\n if (info.done) {\n resolve(value);\n } else {\n Promise.resolve(value).then(_next, _throw);\n }\n}\n\nfunction _asyncToGenerator(fn) {\n return function() {\n var self = this,\n args = arguments;\n return new Promise(function(resolve, reject) {\n var gen = fn.apply(self, args);\n function _next(value) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"next\", value);\n }\n function _throw(err) {\n asyncGeneratorStep(gen, resolve, reject, _next, _throw, \"throw\", err);\n }\n _next(undefined);\n });\n };\n}\n\nconst JsFileWrapping = require(\"../ModuleGraph/worker/JsFileWrapping\");\n\nconst assetTransformer = require(\"../assetTransformer\");\n\nconst babylon = require(\"@babel/parser\");\n\nconst collectDependencies = require(\"../ModuleGraph/worker/collectDependencies\");\n\nconst constantFoldingPlugin = require(\"./worker/constant-folding-plugin\");\n\nconst generateImportNames = require(\"../ModuleGraph/worker/generateImportNames\");\n\nconst generate = require(\"@babel/generator\").default;\n\nconst getKeyFromFiles = require(\"../lib/getKeyFromFiles\");\n\nconst getMinifier = require(\"../lib/getMinifier\");\n\nconst importExportPlugin = require(\"./worker/import-export-plugin\");\n\nconst inlinePlugin = require(\"./worker/inline-plugin\");\n\nconst inlineRequiresPlugin = require(\"babel-preset-fbjs/plugins/inline-requires\");\n\nconst normalizePseudoglobals = require(\"./worker/normalizePseudoglobals\");\n\nconst _require = require(\"@babel/core\"),\n transformFromAstSync = _require.transformFromAstSync;\n\nconst _require2 = require(\"metro-cache\"),\n stableHash = _require2.stableHash;\n\nconst types = require(\"@babel/types\");\n\nconst countLines = require(\"../lib/countLines\");\n\nconst _require3 = require(\"metro-source-map\"),\n fromRawMappings = _require3.fromRawMappings,\n toBabelSegments = _require3.toBabelSegments,\n toSegmentTuple = _require3.toSegmentTuple;\n\nfunction getDynamicDepsBehavior(inPackages, filename) {\n switch (inPackages) {\n case \"reject\":\n return \"reject\";\n\n case \"throwAtRuntime\":\n const isPackage = /(?:^|[/\\\\])node_modules[/\\\\]/.test(filename);\n return isPackage ? inPackages : \"reject\";\n\n default:\n inPackages;\n throw new Error(\n `invalid value for dynamic deps behavior: \\`${inPackages}\\``\n );\n }\n}\n\nclass JsTransformer {\n constructor(projectRoot, config) {\n this._projectRoot = projectRoot;\n this._config = config;\n }\n\n transform(filename, data, options) {\n var _this = this;\n\n return _asyncToGenerator(function*() {\n const sourceCode = data.toString(\"utf8\");\n let type = \"js/module\";\n\n if (options.type === \"asset\") {\n type = \"js/module/asset\";\n }\n\n if (options.type === \"script\") {\n type = \"js/script\";\n }\n\n if (filename.endsWith(\".json\")) {\n let code = JsFileWrapping.wrapJson(sourceCode);\n let map = [];\n\n if (options.minify) {\n var _ref = yield _this._minifyCode(filename, code, sourceCode, map);\n\n map = _ref.map;\n code = _ref.code;\n }\n\n return {\n dependencies: [],\n output: [\n {\n data: {\n code,\n lineCount: countLines(code),\n map,\n functionMap: null\n },\n type\n }\n ]\n };\n } // $FlowFixMe TODO t26372934 Plugin system\n\n const transformer = require(_this._config.babelTransformerPath);\n\n const transformerArgs = {\n filename,\n options: _objectSpread({}, options, {\n enableBabelRCLookup: _this._config.enableBabelRCLookup,\n enableBabelRuntime: _this._config.enableBabelRuntime,\n // Inline requires are now performed at a secondary step. We cannot\n // unfortunately remove it from the internal transformer, since this one\n // is used by other tooling, and this would affect it.\n inlineRequires: false,\n projectRoot: _this._projectRoot,\n publicPath: _this._config.publicPath\n }),\n plugins: [],\n src: sourceCode\n };\n const transformResult =\n type === \"js/module/asset\"\n ? _objectSpread(\n {},\n yield assetTransformer.transform(\n transformerArgs,\n _this._config.assetRegistryPath,\n _this._config.assetPlugins\n ),\n {\n functionMap: null\n }\n )\n : yield transformer.transform(transformerArgs); // Transformers can ouptut null ASTs (if they ignore the file). In that case\n // we need to parse the module source code to get their AST.\n\n let ast =\n transformResult.ast ||\n babylon.parse(sourceCode, {\n sourceType: \"unambiguous\"\n });\n\n const _generateImportNames = generateImportNames(ast),\n importDefault = _generateImportNames.importDefault,\n importAll = _generateImportNames.importAll; // Add \"use strict\" if the file was parsed as a module, and the directive did\n // not exist yet.\n\n const directives = ast.program.directives;\n\n if (\n ast.program.sourceType === \"module\" &&\n directives.findIndex(d => d.value.value === \"use strict\") === -1\n ) {\n directives.push(types.directive(types.directiveLiteral(\"use strict\")));\n } // Perform the import-export transform (in case it's still needed), then\n // fold requires and perform constant folding (if in dev).\n\n const plugins = [];\n\n const opts = _objectSpread({}, options, {\n inlineableCalls: [importDefault, importAll],\n importDefault,\n importAll\n });\n\n if (options.experimentalImportSupport) {\n plugins.push([importExportPlugin, opts]);\n }\n\n if (options.inlineRequires) {\n plugins.push([inlineRequiresPlugin, opts]);\n }\n\n if (!options.dev) {\n if (filename === \""
my-production-index-js-file-name
"\")\n console.log(\"======= CUSTOM PATCH @chpill ======== IGNORING CONSTANT FOLDING FOR\", filename);\n else\n plugins.push([constantFoldingPlugin, opts]);\n }\n\n plugins.push([inlinePlugin, opts]);\n\n var _transformFromAstSync = transformFromAstSync(ast, \"\", {\n ast: true,\n babelrc: false,\n code: false,\n configFile: false,\n comments: false,\n compact: false,\n filename,\n plugins,\n sourceMaps: false\n });\n\n ast = _transformFromAstSync.ast;\n let dependencyMapName = \"\";\n let dependencies;\n let wrappedAst; // If the module to transform is a script (meaning that is not part of the\n // dependency graph and it code will just be prepended to the bundle modules),\n // we need to wrap it differently than a commonJS module (also, scripts do\n // not have dependencies).\n\n if (type === \"js/script\") {\n dependencies = [];\n wrappedAst = JsFileWrapping.wrapPolyfill(ast);\n } else {\n try {\n const opts = {\n asyncRequireModulePath: _this._config.asyncRequireModulePath,\n dynamicRequires: getDynamicDepsBehavior(\n _this._config.dynamicDepsInPackages,\n filename\n ),\n inlineableCalls: [importDefault, importAll],\n keepRequireNames: options.dev\n };\n\n var _collectDependencies = collectDependencies(ast, opts);\n\n ast = _collectDependencies.ast;\n dependencies = _collectDependencies.dependencies;\n dependencyMapName = _collectDependencies.dependencyMapName;\n } catch (error) {\n if (error instanceof collectDependencies.InvalidRequireCallError) {\n throw new InvalidRequireCallError(error, filename);\n }\n\n throw error;\n }\n\n var _JsFileWrapping$wrapM = JsFileWrapping.wrapModule(\n ast,\n importDefault,\n importAll,\n dependencyMapName\n );\n\n wrappedAst = _JsFileWrapping$wrapM.ast;\n }\n\n const reserved =\n options.minify && data.length <= _this._config.optimizationSizeLimit\n ? normalizePseudoglobals(wrappedAst)\n : [];\n const result = generate(\n wrappedAst,\n {\n comments: false,\n compact: false,\n filename,\n retainLines: false,\n sourceFileName: filename,\n sourceMaps: true\n },\n sourceCode\n );\n let map = result.rawMappings\n ? result.rawMappings.map(toSegmentTuple)\n : [];\n let code = result.code;\n\n if (options.minify) {\n var _ref2 = yield _this._minifyCode(\n filename,\n result.code,\n sourceCode,\n map,\n reserved\n );\n\n map = _ref2.map;\n code = _ref2.code;\n }\n\n const functionMap = transformResult.functionMap;\n return {\n dependencies,\n output: [\n {\n data: {\n code,\n lineCount: countLines(code),\n map,\n functionMap\n },\n type\n }\n ]\n };\n })();\n }\n\n _minifyCode(filename, code, source, map) {\n var _this2 = this;\n\n let reserved =\n arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : [];\n return _asyncToGenerator(function*() {\n const sourceMap = fromRawMappings([\n {\n code,\n source,\n map,\n functionMap: null,\n path: filename\n }\n ]).toMap(undefined, {});\n const minify = getMinifier(_this2._config.minifierPath);\n\n try {\n const minified = minify({\n code,\n map: sourceMap,\n filename,\n reserved,\n config: _this2._config.minifierConfig\n });\n return {\n code: minified.code,\n map: minified.map\n ? toBabelSegments(minified.map).map(toSegmentTuple)\n : []\n };\n } catch (error) {\n if (error.constructor.name === \"JS_Parse_Error\") {\n throw new Error(\n `${error.message} in file ${filename} at ${error.line}:${error.col}`\n );\n }\n\n throw error;\n }\n })();\n }\n\n getCacheKey() {\n const _this$_config = this._config,\n babelTransformerPath = _this$_config.babelTransformerPath,\n minifierPath = _this$_config.minifierPath,\n config = _objectWithoutProperties(_this$_config, [\n \"babelTransformerPath\",\n \"minifierPath\"\n ]);\n\n const filesKey = getKeyFromFiles([\n require.resolve(babelTransformerPath),\n require.resolve(minifierPath),\n require.resolve(\"../ModuleGraph/worker/JsFileWrapping\"),\n require.resolve(\"../assetTransformer\"),\n require.resolve(\"../ModuleGraph/worker/collectDependencies\"),\n require.resolve(\"./worker/constant-folding-plugin\"),\n require.resolve(\"../lib/getMinifier\"),\n require.resolve(\"./worker/inline-plugin\"),\n require.resolve(\"./worker/import-export-plugin\"),\n require.resolve(\"./worker/normalizePseudoglobals\"),\n require.resolve(\"../ModuleGraph/worker/optimizeDependencies\"),\n require.resolve(\"../ModuleGraph/worker/generateImportNames\")\n ]);\n\n const babelTransformer = require(babelTransformerPath);\n\n const babelTransformerKey = babelTransformer.getCacheKey\n ? babelTransformer.getCacheKey()\n : \"\";\n return [\n filesKey,\n stableHash(config).toString(\"hex\"),\n babelTransformerKey\n ].join(\"$\");\n }\n}\n\nclass InvalidRequireCallError extends Error {\n constructor(innerError, filename) {\n super(`${filename}:${innerError.message}`);\n this.innerError = innerError;\n this.filename = filename;\n }\n}\n\nmodule.exports = JsTransformer;\n"))
(def file-path "node_modules/metro/src/JSTransformer/worker.js")
(defn apply-patch []
(println "Patching...")
;write to file
(spit file-path file-patched)
(if (= file-patched (slurp file-path))
(println "Patch success!")
(println "Patching failed. Check" file-path "write permissions.")))
(defn main []
(let [file-content (slurp file-path)]
(cond
(= file-content file-patched) (println file-path "already patched.")
(= file-content file-original) (do
(println file-path " needs patching...")
(apply-patch))
:else (println "Cannot patch because" file-path "does not match original."))))
(main)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment