@teamscale/javascript-instrumenter 1.0.5 → 1.0.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/main.mjs +1 -1
- package/package.json +17 -17
package/dist/main.mjs
CHANGED
|
@@ -200,7 +200,7 @@ you are using that forgot to add the plugin to its dependencies: you
|
|
|
200
200
|
can workaround this problem by explicitly adding the missing package
|
|
201
201
|
to your top-level package.json.
|
|
202
202
|
`,r}function C(e,t){try{return t?{error:null,value:(((e,t)=>(e=e.split(`.`),t=t.split(`.`),+e[0]>+t[0]||e[0]==t[0]&&+e[1]>=+t[1]))(process.versions.node,`8.9`)?D.resolve:(e,{paths:[t]},n=D(`module`))=>{let r=n._findPath(e,n._nodeModulePaths(t).concat(t));if(r)return r;throw r=Error(`Cannot resolve module '${e}'`),r.code=`MODULE_NOT_FOUND`,r})(e,{paths:[t]})}:{error:null,value:D.resolve(e)}}catch(e){return{error:e,value:null}}}function w(e,t){try{return{error:null,value:(0,o.resolve)(e,t)}}catch(e){return{error:e,value:null}}}function T(e,t,n){let r=S(e,t),i=r.next();for(;!i.done;)i=r.next(C(i.value,n));return{loader:`require`,filepath:i.value}}function E(e,t,r){let i=(0,a().pathToFileURL)(n().join(r,`./babel-virtual-resolve-base.js`)).href,o=S(e,t),s=o.next();for(;!s.done;)s=o.next(w(s.value,i));return{loader:`auto`,filepath:(0,a().fileURLToPath)(s.value)}}function O(e,t,n,r){if(!i.supportsESM||!r)return T(e,t,n);try{let r=E(e,t,n);if(!(0,s().existsSync)(r.filepath))throw Object.assign(Error(`Could not resolve "${t}" in file ${n}.`),{type:`MODULE_NOT_FOUND`});return r}catch(r){try{return T(e,t,n)}catch(e){throw r.type===`MODULE_NOT_FOUND`?r:e.type===`MODULE_NOT_FOUND`?e:r}}}var k=new Set;function*A(e,t,n){if(!(yield*(0,r.isAsync)())&&k.has(n))throw Error(`Reentrant ${e} detected trying to load "${n}". This module is not ignored and is trying to load itself while compiling itself, leading to a dependency cycle. We recommend adding it to your "ignore" list in your babelrc, or to a .babelignore.`);try{return k.add(n),yield*(0,i.default)(n,t,`You appear to be using a native ECMAScript module ${e}, which is only supported when running Babel asynchronously or when using the Node.js \`--experimental-require-module\` flag.`,`You appear to be using a ${e} that contains top-level await, which is only supported when running Babel asynchronously.`,!0)}catch(e){throw e.message=`[BABEL]: ${e.message} (While processing: ${n})`,e}finally{k.delete(n)}}})),Rn=E((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),Object.defineProperty(e,`ROOT_CONFIG_FILENAMES`,{enumerable:!0,get:function(){return n.ROOT_CONFIG_FILENAMES}}),Object.defineProperty(e,`findConfigUpwards`,{enumerable:!0,get:function(){return n.findConfigUpwards}}),Object.defineProperty(e,`findPackageData`,{enumerable:!0,get:function(){return t.findPackageData}}),Object.defineProperty(e,`findRelativeConfig`,{enumerable:!0,get:function(){return n.findRelativeConfig}}),Object.defineProperty(e,`findRootConfig`,{enumerable:!0,get:function(){return n.findRootConfig}}),Object.defineProperty(e,`loadConfig`,{enumerable:!0,get:function(){return n.loadConfig}}),Object.defineProperty(e,`loadPlugin`,{enumerable:!0,get:function(){return r.loadPlugin}}),Object.defineProperty(e,`loadPreset`,{enumerable:!0,get:function(){return r.loadPreset}}),Object.defineProperty(e,`resolvePlugin`,{enumerable:!0,get:function(){return r.resolvePlugin}}),Object.defineProperty(e,`resolvePreset`,{enumerable:!0,get:function(){return r.resolvePreset}}),Object.defineProperty(e,`resolveShowConfigPath`,{enumerable:!0,get:function(){return n.resolveShowConfigPath}});var t=it(),n=Fn(),r=Ln()})),zn=E((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.transform=void 0,e.transformAsync=s,e.transformSync=o;function t(){let e=Z();return t=function(){return e},e}var n=gn(),r=jn(),i=nt();let a=t()(function*(e,t){let i=yield*(0,n.default)(t);return i===null?null:yield*(0,r.run)(i,e)});e.transform=function(e,t,n){let r,o;if(typeof t==`function`?(o=t,r=void 0):(r=t,o=n),o===void 0)return(0,i.beginHiddenCallStack)(a.sync)(e,r);(0,i.beginHiddenCallStack)(a.errback)(e,r,o)};function o(...e){return(0,i.beginHiddenCallStack)(a.sync)(...e)}function s(...e){return(0,i.beginHiddenCallStack)(a.async)(...e)}})),Bn=E((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.transformFromAst=void 0,e.transformFromAstAsync=s,e.transformFromAstSync=o;function t(){let e=Z();return t=function(){return e},e}var n=gn(),r=jn(),i=nt();let a=t()(function*(e,t,i){let a=yield*(0,n.default)(i);if(a===null)return null;if(!e)throw Error(`No AST given`);return yield*(0,r.run)(a,t,e)});e.transformFromAst=function(e,t,n,r){let o,s;if(typeof n==`function`?(s=n,o=void 0):(o=n,s=r),s===void 0)return(0,i.beginHiddenCallStack)(a.sync)(e,t,o);(0,i.beginHiddenCallStack)(a.errback)(e,t,o,s)};function o(...e){return(0,i.beginHiddenCallStack)(a.sync)(...e)}function s(...e){return(0,i.beginHiddenCallStack)(a.async)(...e)}})),Vn=E((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.parse=void 0,e.parseAsync=c,e.parseSync=s;function t(){let e=Z();return t=function(){return e},e}var n=gn(),r=xn(),i=yn(),a=nt();let o=t()(function*(e,t){let a=yield*(0,n.default)(t);return a===null?null:yield*(0,r.default)(a.passes,(0,i.default)(a),e)});e.parse=function(e,t,n){if(typeof t==`function`&&(n=t,t=void 0),n===void 0)return(0,a.beginHiddenCallStack)(o.sync)(e,t);(0,a.beginHiddenCallStack)(o.errback)(e,t,n)};function s(...e){return(0,a.beginHiddenCallStack)(o.sync)(...e)}function c(...e){return(0,a.beginHiddenCallStack)(o.async)(...e)}})),Hn=E((e=>{Object.defineProperty(e,`__esModule`,{value:!0}),e.DEFAULT_EXTENSIONS=void 0,Object.defineProperty(e,`File`,{enumerable:!0,get:function(){return t.default}}),Object.defineProperty(e,`buildExternalHelpers`,{enumerable:!0,get:function(){return n.default}}),Object.defineProperty(e,`createConfigItem`,{enumerable:!0,get:function(){return l.createConfigItem}}),Object.defineProperty(e,`createConfigItemAsync`,{enumerable:!0,get:function(){return l.createConfigItemAsync}}),Object.defineProperty(e,`createConfigItemSync`,{enumerable:!0,get:function(){return l.createConfigItemSync}}),Object.defineProperty(e,`getEnv`,{enumerable:!0,get:function(){return i.getEnv}}),Object.defineProperty(e,`loadOptions`,{enumerable:!0,get:function(){return l.loadOptions}}),Object.defineProperty(e,`loadOptionsAsync`,{enumerable:!0,get:function(){return l.loadOptionsAsync}}),Object.defineProperty(e,`loadOptionsSync`,{enumerable:!0,get:function(){return l.loadOptionsSync}}),Object.defineProperty(e,`loadPartialConfig`,{enumerable:!0,get:function(){return l.loadPartialConfig}}),Object.defineProperty(e,`loadPartialConfigAsync`,{enumerable:!0,get:function(){return l.loadPartialConfigAsync}}),Object.defineProperty(e,`loadPartialConfigSync`,{enumerable:!0,get:function(){return l.loadPartialConfigSync}}),Object.defineProperty(e,`parse`,{enumerable:!0,get:function(){return p.parse}}),Object.defineProperty(e,`parseAsync`,{enumerable:!0,get:function(){return p.parseAsync}}),Object.defineProperty(e,`parseSync`,{enumerable:!0,get:function(){return p.parseSync}}),e.resolvePreset=e.resolvePlugin=void 0,Object.defineProperty(e,`template`,{enumerable:!0,get:function(){return c().default}}),Object.defineProperty(e,`tokTypes`,{enumerable:!0,get:function(){return o().tokTypes}}),Object.defineProperty(e,`transform`,{enumerable:!0,get:function(){return u.transform}}),Object.defineProperty(e,`transformAsync`,{enumerable:!0,get:function(){return u.transformAsync}}),Object.defineProperty(e,`transformFile`,{enumerable:!0,get:function(){return d.transformFile}}),Object.defineProperty(e,`transformFileAsync`,{enumerable:!0,get:function(){return d.transformFileAsync}}),Object.defineProperty(e,`transformFileSync`,{enumerable:!0,get:function(){return d.transformFileSync}}),Object.defineProperty(e,`transformFromAst`,{enumerable:!0,get:function(){return f.transformFromAst}}),Object.defineProperty(e,`transformFromAstAsync`,{enumerable:!0,get:function(){return f.transformFromAstAsync}}),Object.defineProperty(e,`transformFromAstSync`,{enumerable:!0,get:function(){return f.transformFromAstSync}}),Object.defineProperty(e,`transformSync`,{enumerable:!0,get:function(){return u.transformSync}}),Object.defineProperty(e,`traverse`,{enumerable:!0,get:function(){return s().default}}),e.version=e.types=void 0;var t=Ye(),n=Xe(),r=Rn(),i=pn();function a(){let e=D(`@babel/types`);return a=function(){return e},e}Object.defineProperty(e,`types`,{enumerable:!0,get:function(){return a()}});function o(){let e=D(`@babel/parser`);return o=function(){return e},e}function s(){let e=D(`@babel/traverse`);return s=function(){return e},e}function c(){let e=Ne();return c=function(){return e},e}var l=gn(),u=zn(),d=Mn(),f=Bn(),p=Vn();e.version=`7.28.5`,e.resolvePlugin=(e,t)=>r.resolvePlugin(e,t,!1).filepath,e.resolvePreset=(e,t)=>r.resolvePreset(e,t,!1).filepath,e.DEFAULT_EXTENSIONS=Object.freeze([`.js`,`.jsx`,`.es6`,`.es`,`.mjs`,`.cjs`]),e.OptionManager=class{init(e){return(0,l.loadOptionsSync)(e)}},e.Plugin=function(e){throw Error(`The (${e}) Babel 5 plugin is being run with an unsupported Babel version.`)}})),Un=Hn();const Wn=(()=>{let e=process.pid,t=0;return{next:()=>{t++;let n;if(t<1e4)n=e*1e4+t;else if(t<1e5)n=e*1e5+t;else throw Error(`Not more that 100k files supported to be instrumented in one run.`);return n.toString(36)}}})();var Gn=class{sourceMap;originToIdMap;constructor(e){this.originToIdMap=new Map,this.sourceMap=e}ensureKnownOrigin(e){let t,n,r=e.filename??``;this.sourceMap&&(t=this.sourceMap.originalPositionFor({line:e.start.line,column:e.start.column}),n=this.sourceMap.originalPositionFor({line:e.end.line,column:e.end.column}),r=t.source??e.filename),(!t||!n)&&(t={line:e.start.line,column:e.start.column,source:null,name:null},n={line:e.end.line,column:e.end.column,source:null,name:null});let i=this.originToIdMap.get(r);return i||(i=`_$o${Wn.next()}`,this.originToIdMap.set(r,i)),[i,{start:{line:t.line,column:t.column,index:-1},end:{line:n.line,column:n.column,index:-1},filename:r,identifierName:t.name}]}};const Kn=/^\s*istanbul\s+ignore\s+(if|else|next)(?=\W|$)/,qn=/^\s*istanbul\s+ignore\s+(file)(?=\W|$)/;var Jn=class{types;attrs;nextIgnore;ignoreClassMethods;reportLogic;shouldInstrumentCallback;origins;constructor(e,t,n=[],r=!1,i){this.attrs={},this.nextIgnore=null,this.ignoreClassMethods=n,this.types=e,this.reportLogic=r,this.shouldInstrumentCallback=i,this.origins=new Gn(t)}shouldInstrument(e,t){return this.shouldInstrumentCallback?this.shouldInstrumentCallback(e,t):!0}shouldIgnore(e){return this.nextIgnore!==null||!e.node.loc}hintFor(e){let t=null;return e.leadingComments&&e.leadingComments.forEach(e=>{let n=(e.value||``).trim(),r=Kn.exec(n);r&&(t=r[1])}),t}counterNeedsHoisting(e){return e.isFunctionExpression()||e.isArrowFunctionExpression()||e.isClassExpression()}onEnter(e){let t=e.node;if(this.nextIgnore===null){if(this.hintFor(t)===`next`){this.nextIgnore=t;return}if(this.getAttr(e.node,`skip-all`)!==null&&(this.nextIgnore=t),e.isFunctionExpression()&&this.ignoreClassMethods.some(t=>t===e.node.id?.name)){this.nextIgnore=t;return}if(e.isClassMethod()&&this.ignoreClassMethods.some(t=>t===e.node.key.name)){this.nextIgnore=t;return}}}onExit(e){e.node===this.nextIgnore&&(this.nextIgnore=null),delete e.node.__cov__}setAttr(e,t,n){e.__cov__=e.__cov__||{},e.__cov__[t]=n}getAttr(e,t){let n=e.__cov__;return n?n[t]:null}insertCounter(e,t){let n=this.types;if(e.isBlockStatement())e.node.body.unshift(n.expressionStatement(t));else if(e.isStatement())e.insertBefore(n.expressionStatement(t));else if(this.counterNeedsHoisting(e)&&n.isVariableDeclarator(e.parent)){let r=e.parentPath?.parentPath;r&&n.isExportNamedDeclaration(r.parent)?r.parentPath?.insertBefore(n.expressionStatement(t)):r&&(n.isProgram(r.parent)||n.isBlockStatement(r.parent))?r.insertBefore(n.expressionStatement(t)):e.replaceWith(n.sequenceExpression([t,e.node]))}else e.isExpression()?e.replaceWith(n.sequenceExpression([t,e.node])):console.error(`Unable to insert counter for node type:`,e.node.type)}insertFunctionCounter(e){let t=this.types;if(!e.node?.loc)return;let n=e.node,r;switch(n.type){case`FunctionDeclaration`:case`FunctionExpression`:n.id&&(r=n.id.loc??void 0);break}let i=e.get(`body`),a=e.node.loc??r,[o,s]=this.origins.ensureKnownOrigin(a);if(i.isBlockStatement()&&this.shouldInstrument(e,s)){s.end=s.start;let e=Yn(o,s);i.node.body.unshift(t.expressionStatement(e))}}insertStatementCounter(e){let t=e.node?.loc;if(!t)return;let[n,r]=this.origins.ensureKnownOrigin(t);if(!this.shouldInstrument(e,r))return;let i=Yn(n,r);this.insertCounter(e,i)}insertBranchCounter(e,t){if(t??=e.node.loc,!t)return;let[n,r]=this.origins.ensureKnownOrigin(t);if(this.shouldInstrument(e,r)){let t=Yn(n,r);this.insertCounter(e,t)}}findLeaves(e,t,n,r){e&&(e.type===`LogicalExpression`?this.hintFor(e)!==`next`&&(this.findLeaves(e.left,t,e,`left`),this.findLeaves(e.right,t,e,`right`)):t.push({node:e,parent:n,property:r}))}};function Yn(e,t){let n=[{type:`Identifier`,name:e},{type:`NumericLiteral`,value:t.start.line}];return t.start.line!==t.end.line&&n.push({type:`NumericLiteral`,value:t.end.line}),{type:`CallExpression`,callee:{type:`Identifier`,name:`_$l`},arguments:n}}function Xn(e,t){return{type:`VariableDeclaration`,kind:`const`,declarations:[{type:`VariableDeclarator`,id:{type:`Identifier`,name:e},init:{type:`StringLiteral`,value:t}}]}}function Q(...e){return{enter:function(t,n){this.onEnter(t),!this.shouldIgnore(t)&&e.forEach(e=>{e.call(this,t,n)})},exit:function(e){this.onExit(e)}}}function $(e){this.insertStatementCounter(e)}function Zn(e){this.insertBranchCounter(e.get(`right`),void 0)}function Qn(e){this.insertFunctionCounter(e)}function $n(e){this.insertStatementCounter(e.get(`init`))}function er(e){this.insertStatementCounter(e.get(`value`))}function tr(e){let t=this.types;if(!e.isSequenceExpression())return;let n=[];for(let t of e.node.expressions){let[r,i]=this.origins.ensureKnownOrigin(t.loc);if(this.shouldInstrument(e,i)){let e=Yn(r,i);n.push(e)}n.push(t)}e.replaceWith(t.sequenceExpression(n))}function nr(e){let t=this.types;if(e.node||e.replaceWith(t.blockStatement([])),e.isSequenceExpression())tr.call(this,e);else if(!e.isBlockStatement()){e.replaceWith(t.blockStatement([e.node]));let n=e.node;e.node.loc=n.body[0].loc,n.body[0].leadingComments=e.node.leadingComments,e.node.leadingComments=void 0}}function rr(e){return function(t){nr.call(this,t.get(e))}}function ir(e){let t=this.types;e.node&&!e.isIdentifier()&&e.replaceWith(t.parenthesizedExpression(e.node))}function ar(e){return function(t){ir.call(this,t.get(e))}}function or(e){let t=e.node,n=this.types;if(!n.isBlockStatement(t.body)){let e=t.body.loc;t.expression&&=!1,t.body=n.blockStatement([n.returnStatement(t.body)]),t.body.loc=e,t.body.body[0].loc=e}}function sr(e){let t=e.node,n=this.hintFor(t),r=n===`if`,i=n===`else`;r?this.setAttr(t.consequent,`skip-all`,!0):this.insertBranchCounter(e.get(`consequent`),t.loc),i?this.setAttr(t.alternate,`skip-all`,!0):this.insertBranchCounter(e.get(`alternate`),void 0)}function cr(){}function lr(e){let t=this.types,n=e.node.loc;if(!n)return;let[r,i]=this.origins.ensureKnownOrigin(n);if(this.shouldInstrument(e,i)){let n=Yn(r,i);e.node.consequent.unshift(t.expressionStatement(n))}}function ur(e){let t=e.node,n=this.hintFor(t.consequent),r=this.hintFor(t.alternate);n!==`next`&&this.insertBranchCounter(e.get(`consequent`),void 0),r!==`next`&&this.insertBranchCounter(e.get(`alternate`),void 0)}function dr(e){let t=this.types;if(e.parentPath.node.type===`LogicalExpression`)return;let n=[];this.findLeaves(e.node,n,void 0,void 0);for(let r of n){if(this.hintFor(r.node)===`next`)continue;let n=e.node.loc;if(!n)continue;let[i,a]=this.origins.ensureKnownOrigin(n);if(!this.shouldInstrument(e,a))continue;let o=Yn(i,a);o&&(r.parent[r.property]=t.sequenceExpression([o,r.node]))}}const fr={ArrowFunctionExpression:Q(or,Qn),AssignmentPattern:Q(Zn),BlockStatement:Q(),ExportDefaultDeclaration:Q(),ExportNamedDeclaration:Q(),ClassMethod:Q(Qn),ClassDeclaration:Q(ar(`superClass`)),ClassProperty:Q(er),ClassPrivateProperty:Q(er),ObjectMethod:Q(Qn),ExpressionStatement:Q($),BreakStatement:Q($),ContinueStatement:Q($),DebuggerStatement:Q($),ReturnStatement:Q($),ThrowStatement:Q($),TryStatement:Q($),VariableDeclaration:Q(),VariableDeclarator:Q($n),IfStatement:Q(rr(`consequent`),rr(`alternate`),$,sr),ForStatement:Q(rr(`body`),$),ForInStatement:Q(rr(`body`),$),ForOfStatement:Q(rr(`body`),$),WhileStatement:Q(rr(`body`),$),DoWhileStatement:Q(rr(`body`),$),SwitchStatement:Q(cr,$),SwitchCase:Q(lr),WithStatement:Q(rr(`body`),$),FunctionDeclaration:Q(Qn),FunctionExpression:Q(Qn),LabeledStatement:Q($),ConditionalExpression:Q(ur),LogicalExpression:Q(dr),SequenceExpression:Q(tr)};function pr(e,t){return e.scope.hasBinding(t.varName)}function mr(e){return!e?.parent||!(`comments`in e.parent)?[]:e.parent.comments}function hr(e){return e?mr(e).some(e=>qn.test(e.value)):!1}function gr(e,t,n){n={...n};let r=new Jn(e,t,n.ignoreClassMethods,n.reportLogic,n.shouldInstrumentCallback);return{enter(e){hr(e.find(e=>e.isProgram()))||pr(e,r)||e.traverse(fr,r)},exit(t){if(pr(t,r))return;let i=r.origins;if(hr(t.find(e=>e.isProgram())))return;let a=t.node.body;if(n.codeToPrepend){let e=(0,Un.parse)(n.codeToPrepend,{sourceType:`script`});e!==null&&a.unshift(...e.program.body)}for(let[e,t]of i.originToIdMap.entries()){let n=Xn(t,e);a.unshift(n)}n.isInstrumentedToken&&e.addComment(t.node,`leading`,n.isInstrumentedToken,!1)}}}function _r(e){return e===`none`?!1:e===`external`?`both`:e}var vr=class{opts;constructor(e){this.opts={...e}}async instrument(e,t,n,r){t??=String(new Date().getTime())+`.js`;let{opts:i}=this,a=n??i.inputSourceMap,o;return a&&(o=await new y(a)),(0,Un.transformSync)(e,{configFile:!1,babelrc:!1,ast:!0,filename:t,inputSourceMap:n,sourceMaps:_r(i.produceSourceMap),compact:i.compact,comments:i.preserveComments,parserOpts:{allowAwaitOutsideFunction:!0,allowReturnOutsideFunction:i.autoWrap,sourceType:i.esModules?`module`:`script`,plugins:i.parserPlugins},plugins:[[({types:e})=>{let t=gr(e,o,{reportLogic:i.reportLogic,coverageGlobalScopeFunc:i.coverageGlobalScopeFunc,ignoreClassMethods:i.ignoreClassMethods,inputSourceMap:n,isInstrumentedToken:i.isInstrumentedToken,codeToPrepend:i.codeToPrepend,shouldInstrumentCallback:r??i.shouldInstrumentCallback});return{visitor:{Program:{enter:t.enter,exit(e){t.exit(e)}}}}}]]}).code}};function yr(e){return new vr(e)}function br(e){return m.existsSync(e)&&m.lstatSync(e).isFile()}function xr(e){return m.existsSync(e)&&m.lstatSync(e).isDirectory()}function Sr(e){if(m.existsSync(e)||b.sync(e),!m.lstatSync(e).isDirectory())throw new k(`The specified path '${e}' does not point to an existing directory!`)}function Cr(e,t){let n=[],r=m.readdirSync(e,{withFileTypes:!0});for(let i of r){let r=p.join(e,i.name);if(i.name===t&&i.isDirectory()&&n.push(r),i.isDirectory()){let e=Cr(r,t);n.push(...e)}}return n}function wr(e){let t=e;if(m.existsSync(e)){let n=m.lstatSync(e,{});if(n.isFile())return[e];n.isDirectory()&&(t=`${e}${p.sep}**`)}return C(t,{onlyFiles:!0})}function Tr(e){let t=m.readFileSync(e,`utf8`);return JSON.parse(t)}function Er(e){return e.replace(/[^a-zA-Z0-9_\-.\\/]/g,`_`).replace(/_+/g,`_`)}function Dr(e){let t=[],n=null,r=p.resolve(e).split(p.sep);for(let e=r.length-2;e>=0;e--){let i=r.slice(0,e).join(p.sep),a=p.join(i,`WEB-INF`);xr(a)&&(n=a);let o=p.join(i,`symbolMaps`);xr(o)&&t.push(o)}return n!=null&&Cr(n,`symbolMaps`).forEach(e=>t.push(e)),t}function Or(e){if(l(e)&&o(e.property))return`${Or(e.object)}.${Or(e.property)}`;if(c(e))return e.name;throw new O(`Type of expression not yet supported.`)}function kr(e){if(l(e.callee)||c(e.callee))return Or(e.callee);throw new O(`Type of callee not yet supported.`)}function Ar(e){let t=d(e);if(t.program.body.length===0||!s(t.program.body[0]))return null;let n=t.program.body[0].expression;if(!a(n))return null;let r=kr(n),o=n.arguments[0];if(i(o)){let e=[];for(let t of o.elements)if(u(t))e.push(t.value);else throw Error(`Did expect only string arguments in the call of "${r}".`);return{codeArguments:e,functionName:r,codeAsArrayArgument:!0}}else if(u(o))return{codeArguments:[o.value],functionName:r,codeAsArrayArgument:!1};return null}function jr(e,t){let n=Dr(e),r=/sourceURL=(.*)-(\d+).js(\\n)*\s*$/;return t.codeArguments.map(e=>{let t=r.exec(e);return t?[t[1],Number.parseInt(t[2])]:[``,-1]}).map(e=>{for(let r of n){let n=`${r}/${t.fragmentId}_sourceMap${e[1]}.json`;if(br(n))return n}}).map(e=>{if(e)return Tr(e)})}function Mr(e){let t=/.*([0-9A-Fa-f]{32}).*/.exec(e);if(!(!t||t.length<2))return t[1]}function Nr(e){return e.type===`gwt`}const Pr=`$IS_JS_PROFILER_INSTRUMENTED=true`;function Fr(e,t){let n=/^([a-zA-Z0-9]*).cache.js/.exec(f.basename(t.fromFile)),r=f.dirname(t.fromFile).split(f.sep);if(n&&r.length>1){let n=Mr(t.fromFile),r=/^([^(]+)\((.*)\);*\s*$/.exec(e);if(n&&r?.length===3){let t=Ar(e);if(t)return{type:`gwt`,content:e,fragmentId:n,functionName:t.functionName,codeAsArrayArgument:t.codeAsArrayArgument,codeArguments:t.codeArguments}}}return{type:`javascript`,content:e,codeArguments:[e]}}var Ir=class{vaccineSource;logger;constructor(e,t,n,r){A.require(m.existsSync(e),`The vaccine file to inject "${e}" must exist!\nCWD:${process.cwd()}`),this.vaccineSource=this.loadVaccine(A.requireNonEmpty(e),n,r),this.logger=t}async instrument(e){this.clearFile(e.dumpOriginsFile),this.clearFile(e.dumpMatchedOriginsFile);let t=await S.mapLimit(e.elements,1,async t=>await this.instrumentOne(t,e.excludeFilesPattern,e.originSourcePattern,e.dumpOriginsFile)).then(t=>t.reduce((e,t)=>e.withIncrement(t),ve.neutral(e)));return this.dumpToJson(e.dumpMatchedOriginsFile,e.originSourcePattern.retrieveMatchingFiles()),t}async instrumentOne(e,t,n,r){if(!this.isFileTypeSupported(e.fromFile))return e.isInPlace()||Hr(e.toFile,e.fromFile),new ve(0,0,0,0,1,0,0);let i=Fr(m.readFileSync(e.fromFile,`utf8`),e);if(i.content.substring(0,Math.min(i.content.length,100)).includes(Pr))return e.isInPlace()||Vr(e.toFile,i.content),new ve(0,0,0,1,0,0,0);if(t.isExcluded(e.fromFile))return e.isInPlace()||Hr(e.toFile,e.fromFile),new ve(0,1,0,0,0,0,0);this.logger.info(`Instrumenting "${f.basename(e.fromFile)}"`);let a=Lr(e.fromFile,i,e.externalSourceMapFile);if(a.length===0)return ve.warning(`Failed loading input source map for ${e.fromFile}.`);let o=this.configurationAlternativesFor(e);for(let t=0;t<o.length;t++){let s=o[t];try{return await this.instrumentBundle(e,i,a,s,r,n)}catch(n){if(t===o.length-1)return Vr(e.toFile,i.content),ve.error(n)}}return new ve(0,0,0,0,0,1,0)}async instrumentBundle(e,t,n,r,i,a){for(let e of n.filter(e=>e)){let t=e?.sources??[];i&&this.dumpToJson(i,t)}let o=yr(r),s=[];for(let r=0;r<t.codeArguments.length;r++){let i=await o.instrument(t.codeArguments[r],e.fromFile,n[r],(e,t)=>t.filename?a.isIncluded(t.filename):!1);s.push(i)}return this.writeBundleFile(e.toFile,t,s),new ve(1,0,0,0,0,0,0)}writeBundleFile(e,t,n){if(t.type===`gwt`){A.require(n.length===1,`Assuming only one code fragment to be passed as argument.`);let r=JSON.stringify(`${this.vaccineSource} ${n[0]}`);t.codeAsArrayArgument?Vr(e,`${Pr} ${t.functionName}([${r}]);`):Vr(e,`${Pr} ${t.functionName}(${r});`)}else A.require(n.length===1,`Assuming only one code fragment to be passed as argument for JavaScript bundles.`),Vr(e,n[0])}loadVaccine(e,t,n){return m.readFileSync(e,`utf8`).replace(/\$COLLECTOR_SPECIFIER/g,JSON.stringify(t)).replace(/\$BUCKET_SPECIFIER/g,Buffer.from(JSON.stringify(n)).toString(`base64`))}isFileTypeSupported(e){if(e.endsWith(`.devmode.js`)||e.endsWith(`.nocache.js`))return!1;let t=f.extname(e).toLowerCase();return t===`.js`||t===`.mjs`}configurationAlternativesFor(e){this.logger.trace(`Determining configuration alternatives for ${e.fromFile}`);let t={isInstrumentedToken:Pr,produceSourceMap:`none`,codeToPrepend:this.vaccineSource,preserveComments:!1,compact:!1};return[{...t,esModules:!0},{...t,esModules:!1}]}clearFile(e){if(e&&m.existsSync(e))try{m.unlinkSync(e)}catch(t){this.logger.warn(`Could not clear file ${e}:`+t)}}dumpToJson(e,t){if(!e)return;let n=JSON.stringify(t,null,2);m.writeFile(e,n+`
|
|
203
|
-
`,{flag:`a`},t=>{t&&this.logger.warn(`Could not dump JSON to file ${e}:`+t.message)})}};function Lr(e,t,n){return Nr(t)?jr(e,t):Rr(e,t,n)}function Rr(e,t,n){return t.codeArguments.map(t=>zr(t,e,n))}function zr(e,t,n){if(n){let e=n;if(!(e instanceof ye))throw new O(`Type of source map not yet supported!`);return Tr(e.sourceMapFilePath)}else return Br(e,t)}function Br(e,t){let n=/\/\/[#@]\s(source(?:Mapping)?URL)=\s*(\S+)/g,r=0,i,a;do if(a=n.exec(e),a){let e=a[0];try{i=e.slice(0,50).indexOf(`data:application/json`)>0?v.fromComment(e).toObject():v.fromMapFileComment(e,function(e){return m.readFileSync(f.resolve(f.dirname(t),e),`utf-8`)}).toObject()}catch{r++}}while(a);if(i)return i;if(r>0)throw new O(`None of the referenced source map files loaded!`)}function Vr(e,t){b.sync(f.dirname(e)),m.writeFileSync(e,t)}function Hr(e,t){b.sync(f.dirname(e)),m.copyFileSync(t,e)}function Ur(e){if(e){if(!m.existsSync(e))throw new k(`The specified source map file '${e}' was not found.`);return new ye(e)}}var Wr=class{elements;collector;originSourceIncludePatterns;originSourceExcludePatterns;bundleFileExcludePatterns;dumpOriginsFile;dumpMatchedOriginsFile;targetBucket;appId;constructor(){this.appId=w(),this.elements=[],this.collector=null,this.targetBucket=null}setCollectorFromCommandLine(e,t){return A.requireNonEmpty(e,`The collector URL must not be empty`),this.collector=oe(e,t),this}setCollectorTargetBucket(e,t,n,r){return A.requireNonEmpty(t,`The commit must not be empty`),this.appId=Gr(r),this.targetBucket={appId:this.appId,configId:e,commit:t,configOptions:n},this}setOriginSourceIncludePatterns(e){return this.originSourceIncludePatterns=e,this}setOriginSourceExcludePatterns(e){return this.originSourceExcludePatterns=e,this}setBundleExcludePatterns(e){return this.bundleFileExcludePatterns=e,this}addElement(e,t,n){return this.elements.push(new ae(e,t,n)),this}addFromConfig(e){let t=e.input??[],n=e.inPlace??!1,r=e.to,i=e.sourceMap;this.dumpOriginsFile=e.dumpOriginsTo,this.dumpMatchedOriginsFile=e.dumpOriginMatchesTo,this.setCollectorFromCommandLine(e.collector,e.relativeCollector),this.setOriginSourceIncludePatterns(e.includeOrigin),this.setOriginSourceExcludePatterns(e.excludeOrigin),this.setBundleExcludePatterns(e.excludeBundle),this.setCollectorTargetBucket(e.configId,e.commit??`HEAD`,e.collectorConfigFileContent,e.appName);let a=Ur(i);if(n){if(r)throw new k(`No target path must be specified in case an in-place instrumentation is enabled.`);this.addInPlaceTasksFromPattern(t,a)}else if(!n){if(!r)throw new k("A target path must be specified using `--to`.");this.addInstrumentationTasksFromPatternWithTarget(t,r,a)}return this}addInstrumentationTasksFromPatternWithTarget(e,t,n){Sr(t);for(let r of e)if(br(r))xr(t)||t.endsWith(f.sep)?this.addElement(r,f.join(t,f.basename(r)),n):this.addElement(r,t,n);else if(xr(r)||Kr(r)){let i=e.flatMap(e=>wr(e));Kr(r)?i.forEach(e=>this.addElement(e,f.join(t,f.basename(e)),n)):i.forEach(e=>{let i=f.relative(r,e),a=f.join(t,i);this.addElement(e,a,n)})}else throw new k(`The specified input '${r}' was not found.`)}addInPlaceTasksFromPattern(e,t){e.map(e=>qr(e)).reduce((e,t)=>t.concat(e),[]).forEach(e=>this.addElement(e,e,t))}build(){return new _e(A.requireDefined(this.collector),A.requireDefined(this.targetBucket),this.elements,new ue(this.bundleFileExcludePatterns),new le(this.originSourceIncludePatterns,this.originSourceExcludePatterns),this.dumpOriginsFile,this.dumpMatchedOriginsFile)}};function Gr(e){let t=w();return e?`${Er(e).toLowerCase()}-${t.substring(0,10)}`:t}function Kr(e){return e.includes(`*`)||e.includes(`+`)||e.includes(`?`)||e.includes(`|`)}function qr(e){let t=wr(e);if(t.length===0)throw new k(`No files to instrument found. \n\tWorking directory: '${process.cwd()}'\n\tPattern: '${e}'`);return t}var Jr=`@teamscale/javascript-instrumenter`,Yr=`1.0.
|
|
203
|
+
`,{flag:`a`},t=>{t&&this.logger.warn(`Could not dump JSON to file ${e}:`+t.message)})}};function Lr(e,t,n){return Nr(t)?jr(e,t):Rr(e,t,n)}function Rr(e,t,n){return t.codeArguments.map(t=>zr(t,e,n))}function zr(e,t,n){if(n){let e=n;if(!(e instanceof ye))throw new O(`Type of source map not yet supported!`);return Tr(e.sourceMapFilePath)}else return Br(e,t)}function Br(e,t){let n=/\/\/[#@]\s(source(?:Mapping)?URL)=\s*(\S+)/g,r=0,i,a;do if(a=n.exec(e),a){let e=a[0];try{i=e.slice(0,50).indexOf(`data:application/json`)>0?v.fromComment(e).toObject():v.fromMapFileComment(e,function(e){return m.readFileSync(f.resolve(f.dirname(t),e),`utf-8`)}).toObject()}catch{r++}}while(a);if(i)return i;if(r>0)throw new O(`None of the referenced source map files loaded!`)}function Vr(e,t){b.sync(f.dirname(e)),m.writeFileSync(e,t)}function Hr(e,t){b.sync(f.dirname(e)),m.copyFileSync(t,e)}function Ur(e){if(e){if(!m.existsSync(e))throw new k(`The specified source map file '${e}' was not found.`);return new ye(e)}}var Wr=class{elements;collector;originSourceIncludePatterns;originSourceExcludePatterns;bundleFileExcludePatterns;dumpOriginsFile;dumpMatchedOriginsFile;targetBucket;appId;constructor(){this.appId=w(),this.elements=[],this.collector=null,this.targetBucket=null}setCollectorFromCommandLine(e,t){return A.requireNonEmpty(e,`The collector URL must not be empty`),this.collector=oe(e,t),this}setCollectorTargetBucket(e,t,n,r){return A.requireNonEmpty(t,`The commit must not be empty`),this.appId=Gr(r),this.targetBucket={appId:this.appId,configId:e,commit:t,configOptions:n},this}setOriginSourceIncludePatterns(e){return this.originSourceIncludePatterns=e,this}setOriginSourceExcludePatterns(e){return this.originSourceExcludePatterns=e,this}setBundleExcludePatterns(e){return this.bundleFileExcludePatterns=e,this}addElement(e,t,n){return this.elements.push(new ae(e,t,n)),this}addFromConfig(e){let t=e.input??[],n=e.inPlace??!1,r=e.to,i=e.sourceMap;this.dumpOriginsFile=e.dumpOriginsTo,this.dumpMatchedOriginsFile=e.dumpOriginMatchesTo,this.setCollectorFromCommandLine(e.collector,e.relativeCollector),this.setOriginSourceIncludePatterns(e.includeOrigin),this.setOriginSourceExcludePatterns(e.excludeOrigin),this.setBundleExcludePatterns(e.excludeBundle),this.setCollectorTargetBucket(e.configId,e.commit??`HEAD`,e.collectorConfigFileContent,e.appName);let a=Ur(i);if(n){if(r)throw new k(`No target path must be specified in case an in-place instrumentation is enabled.`);this.addInPlaceTasksFromPattern(t,a)}else if(!n){if(!r)throw new k("A target path must be specified using `--to`.");this.addInstrumentationTasksFromPatternWithTarget(t,r,a)}return this}addInstrumentationTasksFromPatternWithTarget(e,t,n){Sr(t);for(let r of e)if(br(r))xr(t)||t.endsWith(f.sep)?this.addElement(r,f.join(t,f.basename(r)),n):this.addElement(r,t,n);else if(xr(r)||Kr(r)){let i=e.flatMap(e=>wr(e));Kr(r)?i.forEach(e=>this.addElement(e,f.join(t,f.basename(e)),n)):i.forEach(e=>{let i=f.relative(r,e),a=f.join(t,i);this.addElement(e,a,n)})}else throw new k(`The specified input '${r}' was not found.`)}addInPlaceTasksFromPattern(e,t){e.map(e=>qr(e)).reduce((e,t)=>t.concat(e),[]).forEach(e=>this.addElement(e,e,t))}build(){return new _e(A.requireDefined(this.collector),A.requireDefined(this.targetBucket),this.elements,new ue(this.bundleFileExcludePatterns),new le(this.originSourceIncludePatterns,this.originSourceExcludePatterns),this.dumpOriginsFile,this.dumpMatchedOriginsFile)}};function Gr(e){let t=w();return e?`${Er(e).toLowerCase()}-${t.substring(0,10)}`:t}function Kr(e){return e.includes(`*`)||e.includes(`+`)||e.includes(`?`)||e.includes(`|`)}function qr(e){let t=wr(e);if(t.length===0)throw new k(`No files to instrument found. \n\tWorking directory: '${process.cwd()}'\n\tPattern: '${e}'`);return t}var Jr=`@teamscale/javascript-instrumenter`,Yr=`1.0.6`,Xr=`JavaScript coverage instrumenter with coverage forwarding to a collector process`;const Zr={order:1,title:`Instrumenter Input and Output`},Qr={order:2,title:`Coverage Target Parameters`},$r={order:3,title:`Coverage Subject`},ei={order:4,title:`Troubleshooting`};function ti(){let e=new F;function t(t,n,r,i){e.addParameter(t,n,r,i)}return t(`-i`,`--input`,`string[]`,{help:`The input file(s) or folder(s) to instrument.`,group:Zr}),t(`-l`,`--in-place`,`bool`,{help:`If set, the original files to instrument are replaced by their instrumented counterparts.`,group:Zr}),t(`-o`,`--to`,`string`,{help:`Path (directory or file name) to write the instrumented version to.`,group:Zr}),t(`-r`,`--commit`,`string`,{help:`The commit (<branch name>:<UNIX timestamp in milliseconds>) or revision (Git hash) of the code to report coverage for.`,group:Qr}),t(`-c`,`--collector`,`string`,{help:"The collector (`host:port` or `wss://host:port/` or `ws://host:port/`) to send coverage information to.",default:`ws://localhost:54678`,group:Qr}),t(`-a`,`--app-name`,`string`,{help:`The name of the application to report coverage for. Will be used to make the automatically generated application ID more readable.`,group:Qr}),t(void 0,`--coverage-target-from-collector`,`bool`,{help:`All coverage target (upload) parameters, for example, the target partition, shall be specified by the collector.`,group:Qr}),t(`-f`,`--config-id`,`string`,{help:`The ID of the profiler configuration to use; this configuration is refetched from Teamscale once a minute.`,group:Qr}),t(`-t`,`--collector-config-file`,`string`,{help:`Provide a configuration file that specifies or overwrites the configuration of the Coverage Collector.`,group:Qr}),t(void 0,`--collector-option`,`string[]`,{help:`Sets a given collector configuration option. Provided as key=value pairs.`,group:Qr}),t(void 0,`--collector-options-list`,`bool`,{help:`Lists the options that can be set for the collector, via a --collector-config-file or via --collector-option.`,group:Qr}),t(void 0,`--source-map`,`string`,{help:`External location of source-map files to consider.`,group:$r}),t(void 0,`--relative-collector`,`string`,{help:"Pattern used to determine the collector URL from the application hostname. Useful for Kubernetes deployments where the collector URL is not known at instrumentation time. Example: `replace-in-host:app collector,scheme:wss`. This causes the first occurrence of `app` in the application hostname to be replaced with `collector` and the URL scheme changed to wss. Available operations: `replace-in-host:SEARCH REPLACE` replaces the literal term SEARCH once in the hostname with REPLACE. `port:NUMBER` changes the port to NUMBER. `port:keep` keeps the port of the application (instead of using the chosen scheme's default port). `scheme:SCHEME` changes the URL scheme to one of ws, wss, http or https. `path:PATH` uses the URL path PATH (instead of no path).",group:Qr}),t(`-x`,`--exclude-origin`,`string[]`,{help:`Glob pattern(s) of files in the source origin to not produce coverage for. Multiple patterns can be separated by comma.`,group:Zr}),t(`-k`,`--include-origin`,`string[]`,{help:`Glob pattern(s) of files in the source origin to produce coverage for. Multiple patterns can be separated by comma.`,group:Zr}),t(`-e`,`--exclude-bundle`,`string[]`,{help:`Glob pattern(s) of input (bundle) files to keep unchanged (to not instrument).`,group:Zr}),t(`-p`,`--dump-origins-to`,`string`,{help:`Path specifying where to dump source origins file names, based on the source maps, as a JSON file.`,group:ei}),t(`-m`,`--dump-origin-matches-to`,`string`,{help:`Path specifying where to dump a JSON with the names of the files that have matched the origin include/exclude patterns.`,group:ei}),t(void 0,`--log-level`,`string`,{help:`Log level`,default:`info`,group:ei}),e.addArgumentCheck(e=>{if(!Array.isArray(e.input)||e.input.length===0)return`The --input parameter must be provided with the list of files or folders to instrument.`}),e.addRequiredArgumentFor(`commit`),e.addArgumentCheck(e=>{if(!X(e.commit))return`The given commit must be of the form <branch>:<UNIX timestamp in milliseconds> or a Git hash.`}),e.addArgumentCheck(e=>{if(!e.collector&&!e.relativeCollector)return`Either a collector URL or a relative collector URL must be specified.`}),e.addArgumentCheck(e=>{if(e.coverageTargetFromCollector){if(Array.isArray(e.collectorOption)&&e.collectorOption.length>0){let t=new Set(e.collectorOption.map(e=>e.split(`=`)[0]));if(t.has(`teamscale-partition`)||t.has(`teamscale-project`)||t.has(`teamscale-repository`)||t.has(`teamscale-message`))return"The parameter `--coverage-target-from-collector` cannot be combined with explicitly setting upload target options in the instrumenter."}}else if(!e.configId&&!e.collectorConfigFile&&!(Array.isArray(e.collectorOption)&&e.collectorOption.length>0))return`Either a configuration ID (--config-id), a collector configuration file (--collector-config-file) or explicit collector options (--collector-option) must be specified. You can also decide to set all coverage upload parameters on the collector side only by setting --coverage-target-from-collector.`}),e.addArgumentCheck(e=>{if(e.logLevel!==void 0){let t=[`trace`,`debug`,`info`,`warn`,`error`,`fatal`];if(!t.includes(e.logLevel))return`Please provide a valid value for --log-level. One of: `+t.join(`, `)}}),e}const ni=f.dirname(_(import.meta.url));(class e{static async run(){return this.runForArgv(t.argv)}static async runForArgv(e){let n=this.parseCommandLine(e.slice(2),e=>{e.collectorOptionsList&&(B(ne(),void 0,!0),console.log(``),console.log(`ATTENTION:
|
|
204
204
|
When specifying credentials of Teamscale or other services via --collector-config-file or --collector-option,
|
|
205
205
|
the credentials will be included in the instrumented source code and are thus visible
|
|
206
206
|
to anyone that can access your deployed application.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@teamscale/javascript-instrumenter",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.6",
|
|
4
4
|
"description": "JavaScript coverage instrumenter with coverage forwarding to a collector process",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/main.mjs",
|
|
@@ -21,24 +21,24 @@
|
|
|
21
21
|
"dist/**/*"
|
|
22
22
|
],
|
|
23
23
|
"dependencies": {
|
|
24
|
-
"@babel/generator": "
|
|
25
|
-
"@babel/parser": "
|
|
26
|
-
"@babel/traverse": "
|
|
27
|
-
"@babel/types": "
|
|
28
|
-
"@types/micromatch": "
|
|
29
|
-
"async": "
|
|
30
|
-
"bunyan": "
|
|
31
|
-
"convert-source-map": "
|
|
32
|
-
"foreground-child": "
|
|
24
|
+
"@babel/generator": "7.28.5",
|
|
25
|
+
"@babel/parser": "7.28.5",
|
|
26
|
+
"@babel/traverse": "7.28.5",
|
|
27
|
+
"@babel/types": "7.28.5",
|
|
28
|
+
"@types/micromatch": "4.0.10",
|
|
29
|
+
"async": "3.2.6",
|
|
30
|
+
"bunyan": "1.8.15",
|
|
31
|
+
"convert-source-map": "2.0.0",
|
|
32
|
+
"foreground-child": "4.0.3",
|
|
33
33
|
"micromatch": "4.0.8",
|
|
34
|
-
"mkdirp": "
|
|
34
|
+
"mkdirp": "3.0.1",
|
|
35
35
|
"source-map": "0.7.6",
|
|
36
|
-
"tinyglobby": "
|
|
37
|
-
"unload": "
|
|
38
|
-
"uuid": "
|
|
39
|
-
"web-worker": "
|
|
40
|
-
"@
|
|
41
|
-
"@
|
|
36
|
+
"tinyglobby": "0.2.15",
|
|
37
|
+
"unload": "2.4.1",
|
|
38
|
+
"uuid": "13.0.0",
|
|
39
|
+
"web-worker": "1.5.0",
|
|
40
|
+
"@cqse/commons": "1.0.6",
|
|
41
|
+
"@teamscale/lib-instrument": "1.0.6"
|
|
42
42
|
},
|
|
43
43
|
"publishConfig": {
|
|
44
44
|
"access": "public"
|