Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@arms/rum-bundler-plugin-core

Package Overview
Dependencies
Maintainers
0
Versions
12
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@arms/rum-bundler-plugin-core - npm Package Compare versions

Comparing version 0.0.6 to 0.0.7

dist/index.d.ts

633

dist/index.js
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('unplugin'), require('path'), require('fs/promises'), require('chalk')) :
typeof define === 'function' && define.amd ? define(['exports', 'unplugin', 'path', 'fs/promises', 'chalk'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.rumWebpackPlugin = {}, global.unplugin, global.path, global.fs, global.chalk));
})(this, (function (exports, unplugin, path, fs, chalk) { 'use strict';
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('unplugin'), require('chalk'), require('ali-oss'), require('path'), require('fs/promises'), require('crypto')) :
typeof define === 'function' && define.amd ? define(['exports', 'unplugin', 'chalk', 'ali-oss', 'path', 'fs/promises', 'crypto'], factory) :
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.rumWebpackPlugin = {}, global.unplugin, global.chalk, global.OSS, global.path, global.fs, global.crypto$1));
})(this, (function (exports, unplugin, chalk, OSS, path, fs, crypto$1) { 'use strict';

@@ -27,2 +27,32 @@ function _interopNamespaceDefault(e) {

// @ts-ignore some reason
function createLogger(options) {
var _ref = options,
silent = _ref.silent,
_debug = _ref.debug,
prefix = _ref.prefix;
var cPrefix = prefix && chalk.hex('#74ABBA')(prefix);
var log = function log(level, color, message) {
if (!silent) {
console[level]("".concat(cPrefix, " ").concat(chalk.hex(color)(level.toUpperCase()), ": ").concat(message));
}
};
return {
debug: function debug(message) {
if (_debug) {
log('debug', '#B3B3B3', message);
}
},
info: function info(message) {
log('info', '#2ECC40', message);
},
warn: function warn(message) {
log('warn', '#FFDC00', message);
},
error: function error(message) {
log('error', '#FF4136', message);
}
};
}
function _asyncIterator(r) {

@@ -399,70 +429,136 @@ var n,

//@ts-ignore
function createLogger(options) {
var _ref = options || {},
_ref$enable = _ref.enable,
enable = _ref$enable === void 0 ? true : _ref$enable,
_ref$debug = _ref.debug,
_debug = _ref$debug === void 0 ? true : _ref$debug,
_ref$prefix = _ref.prefix,
prefix = _ref$prefix === void 0 ? '' : _ref$prefix;
var cPrefix = prefix && chalk.hex('#74ABBA')(prefix);
var getAliyunUidByRumPid = function getAliyunUidByRumPid(pid) {
var _pid$split;
var uidStr = ((_pid$split = pid.split('@')) === null || _pid$split === void 0 ? void 0 : _pid$split[0]) || '';
return parseInt(uidStr, 36).toString();
};
var formatFileSize = function formatFileSize(bytes) {
var k = 1024;
var sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};
var ALIYUN_UID_REGEX = /^\d{16}$/;
var DEBUG_ID_REGEX = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
var SUPPORT_EXTENSIONS = ['.js', '.cjs', '.mjs'];
var validateAliyunUid = function validateAliyunUid(uid) {
return ALIYUN_UID_REGEX.test(uid);
};
var validateDebugId = function validateDebugId(debugId) {
return DEBUG_ID_REGEX.test(debugId);
};
var validateJSFile = function validateJSFile(extension) {
return SUPPORT_EXTENSIONS.includes(extension);
};
var validateSourceMapFile = function validateSourceMapFile(fileSize, maxSize) {
return fileSize <= maxSize;
};
var MAX_SOURCE_MAP_SIZE = 50 * 1024 * 1024;
var createAliyunOSSUploader = function createAliyunOSSUploader(options, context) {
var accessKeyId = options.accessKeyId,
accessKeySecret = options.accessKeySecret;
var pid = context.pid,
version = context.version,
region = context.region,
logger = context.logger;
var logError = function logError(message) {
logger.error("Unable to upload to Aliyun OSS, for: ".concat(message));
};
// 检查必填项是否存在
if (!pid) {
logError('Pid is missing.');
return;
}
if (!version) {
logError('Version is missing.');
return;
}
if (!accessKeyId) {
logError('Access Key ID is missing.');
return;
}
if (!accessKeySecret) {
logError('Access Key Secret is missing.');
return;
}
// 获取并验证 UID
var uid = getAliyunUidByRumPid(pid);
if (!validateAliyunUid(uid)) {
logError("Invalid Uid: ".concat(uid));
return;
}
var client = new OSS({
region: "oss-".concat(region),
accessKeyId: accessKeyId,
accessKeySecret: accessKeySecret,
bucket: 'arms-rum-sourcemap-hz'
});
return {
debug: function debug(message) {
if (enable && _debug) {
var _console;
for (var _len = arguments.length, params = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
params[_key - 1] = arguments[_key];
}
(_console = console).debug.apply(_console, ["".concat(cPrefix, " Debug: ").concat(message)].concat(params));
upload: function () {
var _upload = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(_ref, context) {
var filePath, fileSize, debugId, logger, remoteFilePath;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
filePath = _ref.filePath, fileSize = _ref.fileSize, debugId = _ref.debugId;
logger = context.logger;
if (validateSourceMapFile(fileSize, MAX_SOURCE_MAP_SIZE)) {
_context.next = 5;
break;
}
logger.warn("File size is invalid: ".concat(fileSize, ". Maximum allowed size is ").concat(formatFileSize(MAX_SOURCE_MAP_SIZE), "."));
return _context.abrupt("return");
case 5:
remoteFilePath = "".concat(uid, "/").concat(pid, "/").concat(version, "/").concat(debugId, "/").concat(path__namespace.basename(filePath));
_context.prev = 6;
_context.next = 9;
return client.put(remoteFilePath, filePath);
case 9:
_context.sent;
logger.info("Upload Success: ".concat(filePath));
_context.next = 16;
break;
case 13:
_context.prev = 13;
_context.t0 = _context["catch"](6);
logger.error("Upload Failed: ".concat(filePath, " for ").concat(_context.t0.message));
case 16:
case "end":
return _context.stop();
}
}, _callee, null, [[6, 13]]);
}));
function upload(_x, _x2) {
return _upload.apply(this, arguments);
}
},
info: function info(message) {
if (enable) {
var _console2;
for (var _len2 = arguments.length, params = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
params[_key2 - 1] = arguments[_key2];
}
(_console2 = console).info.apply(_console2, ["".concat(cPrefix, " ").concat(chalk.green('Info'), ": ").concat(message)].concat(params));
}
},
warn: function warn(message) {
if (enable) {
var _console3;
for (var _len3 = arguments.length, params = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {
params[_key3 - 1] = arguments[_key3];
}
(_console3 = console).warn.apply(_console3, ["".concat(cPrefix, " ").concat(chalk.hex('#FF851B')('Warn'), ": ").concat(message)].concat(params));
}
},
error: function error(message) {
if (enable) {
var _console4;
for (var _len4 = arguments.length, params = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) {
params[_key4 - 1] = arguments[_key4];
}
(_console4 = console).error.apply(_console4, ["".concat(cPrefix, " ").concat(chalk.hex('#FF4136')('Error'), ": ").concat(message)].concat(params));
}
}
return upload;
}()
};
}
};
function isValidUUID(uuid) {
var UUID_REGEX = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
return UUID_REGEX.test(uuid);
}
function generateUUID() {
return generateGUID();
}
function generateGUID() {
var guid = '';
var generateUUID = function generateUUID() {
var version = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'v4';
var value = arguments.length > 1 ? arguments[1] : undefined;
switch (version) {
case 'v3':
return generateUUIDV3(value);
default:
return generateUUIDV4();
}
};
var generateUUIDV4 = function generateUUIDV4() {
var uuid = '';
try {
if (crypto && crypto.randomUUID) {
guid = crypto.randomUUID();
uuid = crypto.randomUUID();
} else if (crypto && crypto.getRandomValues) {
var buf = new Uint8Array(16);
crypto.getRandomValues(buf);
buf[6] = buf[6] & 0x0f | 0x40; // version 4 UUID
buf[8] = buf[8] & 0x3f | 0x80; // variant 10xxxxxx
guid = buf.reduce(function (str, _byte) {
buf[6] = buf[6] & 0x0f | 0x40;
buf[8] = buf[8] & 0x3f | 0x80;
uuid = buf.reduce(function (str, _byte) {
return str + _byte.toString(16).padStart(2, '0');

@@ -472,4 +568,4 @@ }, '').replace(/^(.{8})(.{4})(.{4})(.{4})(.{12})$/, '$1-$2-$3-$4-$5');

} catch (e) {}
if (!guid) {
guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
if (!uuid) {
uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
var r = Math.random() * 16 | 0,

@@ -480,32 +576,107 @@ v = c == 'x' ? r : r & 0x3 | 0x8;

}
return guid;
return uuid;
};
var REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;
function validate(uuid) {
return typeof uuid === 'string' && REGEX.test(uuid);
}
function parse(uuid) {
if (!validate(uuid)) {
throw TypeError('Invalid UUID');
}
var v;
return Uint8Array.of((v = parseInt(uuid.slice(0, 8), 16)) >>> 24, v >>> 16 & 0xff, v >>> 8 & 0xff, v & 0xff,
// Parse ........-####-....-....-............
(v = parseInt(uuid.slice(9, 13), 16)) >>> 8, v & 0xff,
// Parse ........-....-####-....-............
(v = parseInt(uuid.slice(14, 18), 16)) >>> 8, v & 0xff,
// Parse ........-....-....-####-............
(v = parseInt(uuid.slice(19, 23), 16)) >>> 8, v & 0xff,
// Parse ........-....-....-....-############
// (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
(v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff, v / 0x100000000 & 0xff, v >>> 24 & 0xff, v >>> 16 & 0xff, v >>> 8 & 0xff, v & 0xff);
}
function v35(version, hash, value, namespace, buf, offset) {
var _namespace;
var valueBytes = typeof value === 'string' ? stringToBytes(value) : value;
var namespaceBytes = typeof namespace === 'string' ? parse(namespace) : namespace;
if (typeof namespace === 'string') {
namespace = parse(namespace);
}
if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {
throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
}
var SUPPORT_EXTENSIONS = ['.js', '.cjs', '.mjs'];
function handleUUIDInjection(_x, _x2, _x3, _x4) {
return _handleUUIDInjection.apply(this, arguments);
// Compute hash of namespace and value, Per 4.3
// Future: Use spread syntax when supported on all platforms, e.g. `bytes =
// hashfunc([...namespace, ... value])`
var bytes = new Uint8Array(16 + valueBytes.length);
bytes.set(namespaceBytes);
bytes.set(valueBytes, namespaceBytes.length);
bytes = hash(bytes);
bytes[6] = bytes[6] & 0x0f | version;
bytes[8] = bytes[8] & 0x3f | 0x80;
if (buf) {
offset = offset || 0;
for (var i = 0; i < 16; ++i) {
buf[offset + i] = bytes[i];
}
return buf;
}
return unsafeStringify(bytes);
}
var byteToHex = [];
for (var i = 0; i < 256; ++i) {
byteToHex.push((i + 0x100).toString(16).slice(1));
}
function unsafeStringify(arr) {
var offset = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
// Note: Be careful editing this code! It's been tuned for performance
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
//
// Note to future-self: No, you can't remove the `toLowerCase()` call.
// REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351
return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
}
function stringToBytes(str) {
// TODO: Use TextEncoder (see https://stackoverflow.com/a/48762658/109538)
str = unescape(encodeURIComponent(str));
var bytes = new Uint8Array(str.length);
for (var _i = 0; _i < str.length; ++_i) {
bytes[_i] = str.charCodeAt(_i);
}
return bytes;
}
function md5(bytes) {
if (Array.isArray(bytes)) {
bytes = Buffer.from(bytes);
} else if (typeof bytes === 'string') {
bytes = Buffer.from(bytes, 'utf8');
}
return crypto$1.createHash('md5').update(bytes).digest();
}
var NAME_SPACE = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
var generateUUIDV3 = function generateUUIDV3(value) {
var namespace = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : NAME_SPACE;
var buf = arguments.length > 2 ? arguments[2] : undefined;
var offset = arguments.length > 3 ? arguments[3] : undefined;
return v35(0x30, md5, value, namespace, buf, offset).toString();
};
/**
* 搜索 sourcemap 文件位置
* @param sourceFileContent 对应源代码文件内容
* @param sourceFilePath 对应源代码文件路径
* @return 返回源代码文件对应的 sourcemap 文件路径,没找到返回空字符串
*/
function _handleUUIDInjection() {
_handleUUIDInjection = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(bundlePaths, logger, bundleToolType, uuidManual) {
var successCount, failedCount, sourceMapCount, sourceFilePaths, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, sourceFilePath, sourceFileContent, sourceMapPath, uuid, totalFiles;
var handleDebugIdInjection = /*#__PURE__*/function () {
var _ref = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee(bundlePaths, manualDebugId, uploader, useCache, context) {
var version, logger, jsFilePaths, sourceMapCount, successSourceMapArr, _iteratorAbruptCompletion, _didIteratorError, _iteratorError, _iterator, _step, jsFilePath, jsFileContent, debugId, identifier, sourceMapPath, res, _ref2, _ref2$fileSize, fileSize;
return _regeneratorRuntime().wrap(function _callee$(_context) {
while (1) switch (_context.prev = _context.next) {
case 0:
successCount = 0;
failedCount = 0;
version = context.version, logger = context.logger;
jsFilePaths = bundlePaths.filter(function (bundlePath) {
return validateJSFile(path__namespace.extname(bundlePath));
});
sourceMapCount = 0;
sourceFilePaths = bundlePaths.filter(function (bundlePath) {
return SUPPORT_EXTENSIONS.includes(path__namespace.extname(bundlePath));
});
successSourceMapArr = [];
_iteratorAbruptCompletion = false;
_didIteratorError = false;
_context.prev = 6;
_iterator = _asyncIterator(sourceFilePaths);
_iterator = _asyncIterator(jsFilePaths);
case 8:

@@ -516,82 +687,96 @@ _context.next = 10;

if (!(_iteratorAbruptCompletion = !(_step = _context.sent).done)) {
_context.next = 39;
_context.next = 40;
break;
}
sourceFilePath = _step.value;
jsFilePath = _step.value;
_context.prev = 12;
_context.next = 15;
return fs__namespace.readFile(sourceFilePath);
return fs__namespace.readFile(jsFilePath);
case 15:
sourceFileContent = _context.sent.toString();
_context.next = 18;
return findSourceMapPath(sourceFileContent, sourceFilePath, logger);
case 18:
sourceMapPath = _context.sent;
if (sourceMapPath) {
sourceMapCount++;
}
// 注入 UUID
uuid = getExsitingUUID(sourceFileContent);
if (uuid) {
_context.next = 25;
jsFileContent = _context.sent.toString();
debugId = getExistedDebugId(jsFileContent);
if (debugId) {
_context.next = 21;
break;
}
uuid = isValidUUID(uuidManual) ? uuidManual : generateUUID();
_context.next = 25;
return injectUUIDIntoSourceFile(sourceFileContent, sourceFilePath, uuid, bundleToolType);
case 25:
if (validateDebugId(manualDebugId)) {
debugId = manualDebugId;
} else if (useCache) {
identifier = version + jsFileContent;
debugId = generateUUID('v3', identifier);
} else {
debugId = generateUUID('v4');
}
_context.next = 21;
return injectDebugIdToJSFile(jsFileContent, jsFilePath, debugId);
case 21:
_context.next = 23;
return findSourceMapPath(jsFileContent, jsFilePath);
case 23:
sourceMapPath = _context.sent;
if (!sourceMapPath) {
_context.next = 28;
_context.next = 31;
break;
}
sourceMapCount++;
_context.next = 28;
return injectUUIDIntoSourceMap(sourceMapPath, uuid);
return injectDebugIdToSourceMap(sourceMapPath, debugId);
case 28:
successCount++;
_context.next = 36;
res = _context.sent;
_ref2 = res || {}, _ref2$fileSize = _ref2.fileSize, fileSize = _ref2$fileSize === void 0 ? 0 : _ref2$fileSize;
successSourceMapArr.push({
filePath: sourceMapPath,
debugId: debugId,
fileSize: fileSize
});
case 31:
_context.next = 37;
break;
case 31:
_context.prev = 31;
case 33:
_context.prev = 33;
_context.t0 = _context["catch"](12);
logger.error(_context.t0.message);
failedCount++;
return _context.abrupt("continue", 36);
case 36:
return _context.abrupt("continue", 37);
case 37:
_iteratorAbruptCompletion = false;
_context.next = 8;
break;
case 39:
_context.next = 45;
case 40:
_context.next = 46;
break;
case 41:
_context.prev = 41;
case 42:
_context.prev = 42;
_context.t1 = _context["catch"](6);
_didIteratorError = true;
_iteratorError = _context.t1;
case 45:
_context.prev = 45;
case 46:
_context.prev = 46;
_context.prev = 47;
if (!(_iteratorAbruptCompletion && _iterator["return"] != null)) {
_context.next = 50;
_context.next = 51;
break;
}
_context.next = 50;
_context.next = 51;
return _iterator["return"]();
case 50:
_context.prev = 50;
case 51:
_context.prev = 51;
if (!_didIteratorError) {
_context.next = 53;
_context.next = 54;
break;
}
throw _iteratorError;
case 53:
return _context.finish(50);
case 54:
return _context.finish(45);
return _context.finish(51);
case 55:
return _context.finish(46);
case 56:
if (!sourceMapCount) {
logger.warn('No source maps found for the bundle. Please ensure that source map generation is enabled in your bundler configuration');
}
totalFiles = successCount + failedCount;
logger.info("UUID Injection Update: ".concat(successCount, " successes, ").concat(failedCount, " failures. Total files processed: ").concat(totalFiles));
if (uploader !== null && uploader !== void 0 && uploader.upload) {
logger.info('Starting to upload sourcemap file:');
successSourceMapArr.forEach(function (fileMetaData) {
uploader.upload(fileMetaData, context);
});
}
case 58:

@@ -601,16 +786,18 @@ case "end":

}
}, _callee, null, [[6, 41, 45, 55], [12, 31], [46,, 50, 54]]);
}, _callee, null, [[6, 42, 46, 56], [12, 33], [47,, 51, 55]]);
}));
return _handleUUIDInjection.apply(this, arguments);
}
function findSourceMapPath(_x5, _x6, _x7) {
return _findSourceMapPath.apply(this, arguments);
}
return function handleDebugIdInjection(_x, _x2, _x3, _x4, _x5) {
return _ref.apply(this, arguments);
};
}();
var SOURCE_MAP_REGEX = /^\s*\/\/# sourceMappingURL=(.*)$/m;
/**
* 获取已存在的 UUID 字符串
* @param sourceFileContent 源代码文件内容
* @returns 若存在则返回 UUID 字符串,否之返回空字符串
* 搜索 sourcemap 文件位置
* @param jsFileContent 对应源代码文件内容
* @param jsFilePath 对应源代码文件路径
* @return 返回源代码文件对应的 sourcemap 文件路径,没找到返回空字符串
*/
function _findSourceMapPath() {
_findSourceMapPath = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(sourceFileContent, sourceFilePath, logger) {
var findSourceMapPath = /*#__PURE__*/function () {
var _ref3 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee2(jsFileContent, jsFilePath) {
var sourceMapPath, matchResult, matchUrl, isUrl, isFileProtocolUrl, url;

@@ -621,3 +808,3 @@ return _regeneratorRuntime().wrap(function _callee2$(_context2) {

sourceMapPath = '';
matchResult = sourceFileContent.match(/^\s*\/\/# sourceMappingURL=(.*)$/m);
matchResult = jsFileContent.match(SOURCE_MAP_REGEX);
if (matchResult) {

@@ -637,3 +824,3 @@ matchUrl = path__namespace.normalize(matchResult[1]); // 分四种情况:使用 file: 的 URL、远端 URL (无法写入)、本地相对路径、本地绝对路径

} else {
sourceMapPath = path__namespace.isAbsolute(matchUrl) ? matchUrl : path__namespace.join(path__namespace.dirname(sourceFilePath), matchUrl);
sourceMapPath = path__namespace.isAbsolute(matchUrl) ? matchUrl : path__namespace.join(path__namespace.dirname(jsFilePath), matchUrl);
}

@@ -643,3 +830,3 @@ }

// 若无法在源文件中找到 sourcemap URL,则直接通过文件名寻找
sourceMapPath = sourceMapPath || path__namespace.resolve(sourceFilePath) + '.map';
sourceMapPath = sourceMapPath || path__namespace.resolve(jsFilePath) + '.map';
_context2.prev = 4;

@@ -663,11 +850,21 @@ _context2.next = 7;

}));
return _findSourceMapPath.apply(this, arguments);
}
function getExsitingUUID(sourceFileContent) {
return function findSourceMapPath(_x6, _x7) {
return _ref3.apply(this, arguments);
};
}();
var SENTRY_DEBUG_ID_REGEX = /sentry-dbid-([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})/;
var RUM_DEBUG_ID_REGEX = /armsRum-uuid-([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})/;
/**
* 获取已存在的 UUID 字符串
* @param jsFileContent 源代码文件内容
* @returns 若存在则返回 UUID 字符串,否之返回空字符串
*/
var getExistedDebugId = function getExistedDebugId(jsFileContent) {
// 查看是否有 sentry 注入的 UUID
var sentryUUIDMatch = sourceFileContent.match(/sentry-dbid-([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})/);
var sentryUUIDMatch = jsFileContent.match(SENTRY_DEBUG_ID_REGEX);
if (sentryUUIDMatch) {
return sentryUUIDMatch[1];
}
var rumUUIDMatch = sourceFileContent.match(/armsRum-uuid-([0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12})/);
var rumUUIDMatch = jsFileContent.match(RUM_DEBUG_ID_REGEX);
if (rumUUIDMatch) {

@@ -677,20 +874,13 @@ return rumUUIDMatch[1];

return '';
}
};
var USE_STRICT_REGEX = /^(?:\s*|\/\*[\s\S]*?\*\/|\/\/[^\n\r]*[\n\r])*(?:"use strict";|'use strict';)?/;
/**
* 将 UUID 注入源代码文件中
* @param sourceFileContent 源代码文件内容
* @param sourceFilePath 源代码文件路径
* @param uuid 需要注入的 UUID 字符串
* 将 debugId 注入源代码文件中
* @param jsFileContent 源代码文件内容
* @param jsFilePath 源代码文件路径
* @param debugId 需要注入的 DebugId
*/
function injectUUIDIntoSourceFile(_x8, _x9, _x10, _x11) {
return _injectUUIDIntoSourceFile.apply(this, arguments);
}
/**
* 将新内容注入 sourcemap 文件中
* @param sourceMapPath sourcemap 文件路径
* @param uuid 需要注入的 UUID 字符串
*/
function _injectUUIDIntoSourceFile() {
_injectUUIDIntoSourceFile = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(sourceFileContent, sourceFilePath, uuid, bundleToolType) {
var injectDebugIdToJSFile = /*#__PURE__*/function () {
var _ref4 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee3(jsFileContent, jsFilePath, debugId) {
var debugIdSnippet, matchResult, newContent, len;

@@ -701,13 +891,13 @@ return _regeneratorRuntime().wrap(function _callee3$(_context3) {

_context3.prev = 0;
debugIdSnippet = generateDebugIdSnippet(uuid);
matchResult = sourceFileContent.match(/^(?:\s*|\/\*[\s\S]*?\*\/|\/\/[^\n\r]*[\n\r])*(?:"use strict";|'use strict';)?/);
debugIdSnippet = generateDebugIdSnippet(debugId);
matchResult = jsFileContent.match(USE_STRICT_REGEX);
newContent = '';
if (matchResult !== null && matchResult !== void 0 && matchResult[0]) {
len = matchResult[0].length;
newContent = sourceFileContent.slice(0, len) + debugIdSnippet + sourceFileContent.slice(len);
newContent = jsFileContent.slice(0, len) + debugIdSnippet + jsFileContent.slice(len);
} else {
newContent = debugIdSnippet + sourceFileContent;
newContent = debugIdSnippet + jsFileContent;
}
_context3.next = 7;
return fs__namespace.writeFile(sourceFilePath, newContent);
return fs__namespace.writeFile(jsFilePath, newContent);
case 7:

@@ -719,3 +909,3 @@ _context3.next = 12;

_context3.t0 = _context3["catch"](0);
throw new Error("Failed to write UUID to file ".concat(sourceFilePath, ": ").concat(_context3.t0.message));
throw new Error("Failed to write debug ID to file ".concat(jsFilePath, " for: ").concat(_context3.t0.message));
case 12:

@@ -727,9 +917,14 @@ case "end":

}));
return _injectUUIDIntoSourceFile.apply(this, arguments);
}
function injectUUIDIntoSourceMap(_x12, _x13) {
return _injectUUIDIntoSourceMap.apply(this, arguments);
}
function _injectUUIDIntoSourceMap() {
_injectUUIDIntoSourceMap = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(sourceMapPath, uuid) {
return function injectDebugIdToJSFile(_x8, _x9, _x10) {
return _ref4.apply(this, arguments);
};
}();
/**
* 将 debug ID 注入 sourcemap 文件中
* @param sourceMapPath sourcemap 文件路径
* @param debugId 需要注入的 debug ID
*/
var injectDebugIdToSourceMap = /*#__PURE__*/function () {
var _ref5 = _asyncToGenerator(/*#__PURE__*/_regeneratorRuntime().mark(function _callee4(sourceMapPath, debugId) {
var data, jsonObj;

@@ -745,53 +940,69 @@ return _regeneratorRuntime().wrap(function _callee4$(_context4) {

jsonObj = JSON.parse(data.toString());
jsonObj.debugId = uuid;
jsonObj.debugId = debugId;
_context4.next = 8;
return fs__namespace.writeFile(sourceMapPath, JSON.stringify(jsonObj));
case 8:
_context4.next = 13;
break;
case 10:
_context4.prev = 10;
return _context4.abrupt("return", {
fileSize: Buffer.byteLength(data)
});
case 11:
_context4.prev = 11;
_context4.t0 = _context4["catch"](0);
throw new Error("Failed to write UUID to source map file ".concat(sourceMapPath, ": ").concat(_context4.t0.message));
case 13:
throw new Error("Failed to write debug ID to source map file ".concat(sourceMapPath, " for: ").concat(_context4.t0.message));
case 14:
case "end":
return _context4.stop();
}
}, _callee4, null, [[0, 10]]);
}, _callee4, null, [[0, 11]]);
}));
return _injectUUIDIntoSourceMap.apply(this, arguments);
}
function generateDebugIdSnippet(debugId) {
return function injectDebugIdToSourceMap(_x11, _x12) {
return _ref5.apply(this, arguments);
};
}();
var generateDebugIdSnippet = function generateDebugIdSnippet(debugId) {
return ";!function(){try{var e=\"undefined\"!=typeof window?window:\"undefined\"!=typeof global?global:\"undefined\"!=typeof self?self:{},n=(new e.Error).stack;n&&(e._armsRumDebugIds=e._armsRumDebugIds||{},e._armsRumDebugIds[n]=\"".concat(debugId, "\",e._armsRumDebugIdIdentifier=\"armsRum-uuid-").concat(debugId, "\")}catch(e){}}();");
}
};
function rumUnpluginFactory(rumPlugins, bundleToolType) {
return function (options) {
var createRumPlugin = function createRumPlugin(type, rumPlugins) {
return unplugin.createUnplugin(function (options) {
var plugins = [];
var _ref = options || {},
_ref$debug = _ref.debug,
debug = _ref$debug === void 0 ? true : _ref$debug,
_ref$uuid = _ref.uuid,
uuid = _ref$uuid === void 0 ? '' : _ref$uuid;
var logger = createLogger({
enable: debug,
prefix: 'ARMS RUM'
});
var plugins = [];
var UUIDInjectionPlugin = rumPlugins.UUIDInjectionPlugin;
plugins.push(UUIDInjectionPlugin(function (bundlePaths) {
return handleUUIDInjection(bundlePaths, logger, bundleToolType, uuid);
silent = _ref.silent,
debug = _ref.debug,
_ref$prefix = _ref.prefix,
prefix = _ref$prefix === void 0 ? 'ARMS RUM' : _ref$prefix,
manualDebugId = _ref.manualDebugId,
pid = _ref.pid,
_ref$version = _ref.version,
version = _ref$version === void 0 ? '1.0.0' : _ref$version,
_ref$region = _ref.region,
region = _ref$region === void 0 ? 'cn-hangzhou' : _ref$region,
accessKeyId = _ref.accessKeyId,
accessKeySecret = _ref.accessKeySecret,
customUploader = _ref.customUploader,
useCache = _ref.useCache;
var context = {
pid: pid,
version: version,
region: region,
logger: createLogger({
silent: silent,
debug: debug,
prefix: prefix
})
};
var uploader = customUploader || createAliyunOSSUploader({
accessKeyId: accessKeyId,
accessKeySecret: accessKeySecret
}, context);
var debugIdInjectionPlugin = rumPlugins.debugIdInjectionPlugin;
plugins.push(debugIdInjectionPlugin(function (bundlePaths) {
return handleDebugIdInjection(bundlePaths, manualDebugId, uploader, useCache, context);
}));
return plugins;
};
}
function createRumWebpackPlugin(rumPlugins) {
return unplugin.createWebpackPlugin(rumUnpluginFactory(rumPlugins, 'webpack'));
}
function createRumVitePlugin(rumPlugins) {
return unplugin.createVitePlugin(rumUnpluginFactory(rumPlugins, 'vite'));
}
})[type];
};
exports.createRumVitePlugin = createRumVitePlugin;
exports.createRumWebpackPlugin = createRumWebpackPlugin;
exports.createRumPlugin = createRumPlugin;
}));
{
"name": "@arms/rum-bundler-plugin-core",
"version": "0.0.6",
"version": "0.0.7",
"description": "rum bundler plugin core",

@@ -9,2 +9,3 @@ "author": "ly403664 <ly403664@alibaba-inc.com>",

"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [

@@ -18,3 +19,3 @@ "dist"

"scripts": {
"build": "rollup -c",
"build": "tsc --project types.tsconfig.json --skipLibCheck && rollup -c",
"prepublishOnly": "npm run build"

@@ -35,2 +36,3 @@ },

"dependencies": {
"ali-oss": "^6.22.0",
"chalk": "^4.1.2",

@@ -37,0 +39,0 @@ "unplugin": "^1.14.1"

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc