source-map-consumer.js 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302
  1. /* -*- Mode: js; js-indent-level: 2; -*- */
  2. /*
  3. * Copyright 2011 Mozilla Foundation and contributors
  4. * Licensed under the New BSD license. See LICENSE or:
  5. * http://opensource.org/licenses/BSD-3-Clause
  6. */
  7. const util = require('./util')
  8. const binarySearch = require('./binary-search')
  9. const ArraySet = require('./array-set').ArraySet
  10. const base64VLQ = require('./base64-vlq') // eslint-disable-line no-unused-vars
  11. const readWasm = require('./read-wasm')
  12. const wasm = require('./wasm')
  13. const INTERNAL = Symbol('smcInternal')
  14. class SourceMapConsumer {
  15. constructor(aSourceMap, aSourceMapURL) {
  16. // If the constructor was called by super(), just return Promise<this>.
  17. // Yes, this is a hack to retain the pre-existing API of the base-class
  18. // constructor also being an async factory function.
  19. if (aSourceMap == INTERNAL) {
  20. return Promise.resolve(this)
  21. }
  22. return _factory(aSourceMap, aSourceMapURL)
  23. }
  24. static initialize(opts) {
  25. readWasm.initialize(opts['lib/mappings.wasm'])
  26. }
  27. static fromSourceMap(aSourceMap, aSourceMapURL) {
  28. return _factoryBSM(aSourceMap, aSourceMapURL)
  29. }
  30. /**
  31. * Construct a new `SourceMapConsumer` from `rawSourceMap` and `sourceMapUrl`
  32. * (see the `SourceMapConsumer` constructor for details. Then, invoke the `async
  33. * function f(SourceMapConsumer) -> T` with the newly constructed consumer, wait
  34. * for `f` to complete, call `destroy` on the consumer, and return `f`'s return
  35. * value.
  36. *
  37. * You must not use the consumer after `f` completes!
  38. *
  39. * By using `with`, you do not have to remember to manually call `destroy` on
  40. * the consumer, since it will be called automatically once `f` completes.
  41. *
  42. * ```js
  43. * const xSquared = await SourceMapConsumer.with(
  44. * myRawSourceMap,
  45. * null,
  46. * async function (consumer) {
  47. * // Use `consumer` inside here and don't worry about remembering
  48. * // to call `destroy`.
  49. *
  50. * const x = await whatever(consumer);
  51. * return x * x;
  52. * }
  53. * );
  54. *
  55. * // You may not use that `consumer` anymore out here; it has
  56. * // been destroyed. But you can use `xSquared`.
  57. * console.log(xSquared);
  58. * ```
  59. */
  60. static async with(rawSourceMap, sourceMapUrl, f) {
  61. const consumer = await new SourceMapConsumer(rawSourceMap, sourceMapUrl)
  62. try {
  63. return await f(consumer)
  64. } finally {
  65. consumer.destroy()
  66. }
  67. }
  68. /**
  69. * Parse the mappings in a string in to a data structure which we can easily
  70. * query (the ordered arrays in the `this.__generatedMappings` and
  71. * `this.__originalMappings` properties).
  72. */
  73. _parseMappings(aStr, aSourceRoot) {
  74. throw new Error('Subclasses must implement _parseMappings')
  75. }
  76. /**
  77. * Iterate over each mapping between an original source/line/column and a
  78. * generated line/column in this source map.
  79. *
  80. * @param Function aCallback
  81. * The function that is called with each mapping.
  82. * @param Object aContext
  83. * Optional. If specified, this object will be the value of `this` every
  84. * time that `aCallback` is called.
  85. * @param aOrder
  86. * Either `SourceMapConsumer.GENERATED_ORDER` or
  87. * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to
  88. * iterate over the mappings sorted by the generated file's line/column
  89. * order or the original's source/line/column order, respectively. Defaults to
  90. * `SourceMapConsumer.GENERATED_ORDER`.
  91. */
  92. eachMapping(aCallback, aContext, aOrder) {
  93. throw new Error('Subclasses must implement eachMapping')
  94. }
  95. /**
  96. * Returns all generated line and column information for the original source,
  97. * line, and column provided. If no column is provided, returns all mappings
  98. * corresponding to a either the line we are searching for or the next
  99. * closest line that has any mappings. Otherwise, returns all mappings
  100. * corresponding to the given line and either the column we are searching for
  101. * or the next closest column that has any offsets.
  102. *
  103. * The only argument is an object with the following properties:
  104. *
  105. * - source: The filename of the original source.
  106. * - line: The line number in the original source. The line number is 1-based.
  107. * - column: Optional. the column number in the original source.
  108. * The column number is 0-based.
  109. *
  110. * and an array of objects is returned, each with the following properties:
  111. *
  112. * - line: The line number in the generated source, or null. The
  113. * line number is 1-based.
  114. * - column: The column number in the generated source, or null.
  115. * The column number is 0-based.
  116. */
  117. allGeneratedPositionsFor(aArgs) {
  118. throw new Error('Subclasses must implement allGeneratedPositionsFor')
  119. }
  120. destroy() {
  121. throw new Error('Subclasses must implement destroy')
  122. }
  123. }
  124. /**
  125. * The version of the source mapping spec that we are consuming.
  126. */
  127. SourceMapConsumer.prototype._version = 3
  128. SourceMapConsumer.GENERATED_ORDER = 1
  129. SourceMapConsumer.ORIGINAL_ORDER = 2
  130. SourceMapConsumer.GREATEST_LOWER_BOUND = 1
  131. SourceMapConsumer.LEAST_UPPER_BOUND = 2
  132. exports.SourceMapConsumer = SourceMapConsumer
  133. /**
  134. * A BasicSourceMapConsumer instance represents a parsed source map which we can
  135. * query for information about the original file positions by giving it a file
  136. * position in the generated source.
  137. *
  138. * The first parameter is the raw source map (either as a JSON string, or
  139. * already parsed to an object). According to the spec, source maps have the
  140. * following attributes:
  141. *
  142. * - version: Which version of the source map spec this map is following.
  143. * - sources: An array of URLs to the original source files.
  144. * - names: An array of identifiers which can be referenced by individual mappings.
  145. * - sourceRoot: Optional. The URL root from which all sources are relative.
  146. * - sourcesContent: Optional. An array of contents of the original source files.
  147. * - mappings: A string of base64 VLQs which contain the actual mappings.
  148. * - file: Optional. The generated file this source map is associated with.
  149. *
  150. * Here is an example source map, taken from the source map spec[0]:
  151. *
  152. * {
  153. * version : 3,
  154. * file: "out.js",
  155. * sourceRoot : "",
  156. * sources: ["foo.js", "bar.js"],
  157. * names: ["src", "maps", "are", "fun"],
  158. * mappings: "AA,AB;;ABCDE;"
  159. * }
  160. *
  161. * The second parameter, if given, is a string whose value is the URL
  162. * at which the source map was found. This URL is used to compute the
  163. * sources array.
  164. *
  165. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1#
  166. */
  167. class BasicSourceMapConsumer extends SourceMapConsumer {
  168. constructor(aSourceMap, aSourceMapURL) {
  169. return super(INTERNAL).then((that) => {
  170. let sourceMap = aSourceMap
  171. if (typeof aSourceMap === 'string') {
  172. sourceMap = util.parseSourceMapInput(aSourceMap)
  173. }
  174. const version = util.getArg(sourceMap, 'version')
  175. let sources = util.getArg(sourceMap, 'sources')
  176. // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which
  177. // requires the array) to play nice here.
  178. const names = util.getArg(sourceMap, 'names', [])
  179. let sourceRoot = util.getArg(sourceMap, 'sourceRoot', null)
  180. const sourcesContent = util.getArg(sourceMap, 'sourcesContent', null)
  181. const mappings = util.getArg(sourceMap, 'mappings')
  182. const file = util.getArg(sourceMap, 'file', null)
  183. // Once again, Sass deviates from the spec and supplies the version as a
  184. // string rather than a number, so we use loose equality checking here.
  185. if (version != that._version) {
  186. throw new Error('Unsupported version: ' + version)
  187. }
  188. if (sourceRoot) {
  189. sourceRoot = util.normalize(sourceRoot)
  190. }
  191. sources = sources
  192. .map(String)
  193. // Some source maps produce relative source paths like "./foo.js" instead of
  194. // "foo.js". Normalize these first so that future comparisons will succeed.
  195. // See bugzil.la/1090768.
  196. .map(util.normalize)
  197. // Always ensure that absolute sources are internally stored relative to
  198. // the source root, if the source root is absolute. Not doing this would
  199. // be particularly problematic when the source root is a prefix of the
  200. // source (valid, but why??). See github issue #199 and bugzil.la/1188982.
  201. .map(function (source) {
  202. return sourceRoot &&
  203. util.isAbsolute(sourceRoot) &&
  204. util.isAbsolute(source)
  205. ? util.relative(sourceRoot, source)
  206. : source
  207. })
  208. // Pass `true` below to allow duplicate names and sources. While source maps
  209. // are intended to be compressed and deduplicated, the TypeScript compiler
  210. // sometimes generates source maps with duplicates in them. See Github issue
  211. // #72 and bugzil.la/889492.
  212. that._names = ArraySet.fromArray(names.map(String), true)
  213. that._sources = ArraySet.fromArray(sources, true)
  214. that._absoluteSources = that._sources.toArray().map(function (s) {
  215. return util.computeSourceURL(sourceRoot, s, aSourceMapURL)
  216. })
  217. that.sourceRoot = sourceRoot
  218. that.sourcesContent = sourcesContent
  219. that._mappings = mappings
  220. that._sourceMapURL = aSourceMapURL
  221. that.file = file
  222. that._computedColumnSpans = false
  223. that._mappingsPtr = 0
  224. that._wasm = null
  225. return wasm().then((w) => {
  226. that._wasm = w
  227. return that
  228. })
  229. })
  230. }
  231. /**
  232. * Utility function to find the index of a source. Returns -1 if not
  233. * found.
  234. */
  235. _findSourceIndex(aSource) {
  236. let relativeSource = aSource
  237. if (this.sourceRoot != null) {
  238. relativeSource = util.relative(this.sourceRoot, relativeSource)
  239. }
  240. if (this._sources.has(relativeSource)) {
  241. return this._sources.indexOf(relativeSource)
  242. }
  243. // Maybe aSource is an absolute URL as returned by |sources|. In
  244. // this case we can't simply undo the transform.
  245. for (let i = 0; i < this._absoluteSources.length; ++i) {
  246. if (this._absoluteSources[i] == aSource) {
  247. return i
  248. }
  249. }
  250. return -1
  251. }
  252. /**
  253. * Create a BasicSourceMapConsumer from a SourceMapGenerator.
  254. *
  255. * @param SourceMapGenerator aSourceMap
  256. * The source map that will be consumed.
  257. * @param String aSourceMapURL
  258. * The URL at which the source map can be found (optional)
  259. * @returns BasicSourceMapConsumer
  260. */
  261. static fromSourceMap(aSourceMap, aSourceMapURL) {
  262. return new BasicSourceMapConsumer(aSourceMap.toString())
  263. }
  264. get sources() {
  265. return this._absoluteSources.slice()
  266. }
  267. _getMappingsPtr() {
  268. if (this._mappingsPtr === 0) {
  269. this._parseMappings(this._mappings, this.sourceRoot)
  270. }
  271. return this._mappingsPtr
  272. }
  273. /**
  274. * Parse the mappings in a string in to a data structure which we can easily
  275. * query (the ordered arrays in the `this.__generatedMappings` and
  276. * `this.__originalMappings` properties).
  277. */
  278. _parseMappings(aStr, aSourceRoot) {
  279. const size = aStr.length
  280. const mappingsBufPtr = this._wasm.exports.allocate_mappings(size)
  281. const mappingsBuf = new Uint8Array(
  282. this._wasm.exports.memory.buffer,
  283. mappingsBufPtr,
  284. size
  285. )
  286. for (let i = 0; i < size; i++) {
  287. mappingsBuf[i] = aStr.charCodeAt(i)
  288. }
  289. const mappingsPtr = this._wasm.exports.parse_mappings(mappingsBufPtr)
  290. if (!mappingsPtr) {
  291. const error = this._wasm.exports.get_last_error()
  292. let msg = `Error parsing mappings (code ${error}): `
  293. // XXX: keep these error codes in sync with `fitzgen/source-map-mappings`.
  294. switch (error) {
  295. case 1:
  296. msg +=
  297. 'the mappings contained a negative line, column, source index, or name index'
  298. break
  299. case 2:
  300. msg += 'the mappings contained a number larger than 2**32'
  301. break
  302. case 3:
  303. msg += 'reached EOF while in the middle of parsing a VLQ'
  304. break
  305. case 4:
  306. msg += 'invalid base 64 character while parsing a VLQ'
  307. break
  308. default:
  309. msg += 'unknown error code'
  310. break
  311. }
  312. throw new Error(msg)
  313. }
  314. this._mappingsPtr = mappingsPtr
  315. }
  316. eachMapping(aCallback, aContext, aOrder) {
  317. const context = aContext || null
  318. const order = aOrder || SourceMapConsumer.GENERATED_ORDER
  319. const sourceRoot = this.sourceRoot
  320. this._wasm.withMappingCallback(
  321. (mapping) => {
  322. if (mapping.source !== null) {
  323. mapping.source = this._sources.at(mapping.source)
  324. mapping.source = util.computeSourceURL(
  325. sourceRoot,
  326. mapping.source,
  327. this._sourceMapURL
  328. )
  329. if (mapping.name !== null) {
  330. mapping.name = this._names.at(mapping.name)
  331. }
  332. }
  333. aCallback.call(context, mapping)
  334. },
  335. () => {
  336. switch (order) {
  337. case SourceMapConsumer.GENERATED_ORDER:
  338. this._wasm.exports.by_generated_location(this._getMappingsPtr())
  339. break
  340. case SourceMapConsumer.ORIGINAL_ORDER:
  341. this._wasm.exports.by_original_location(this._getMappingsPtr())
  342. break
  343. default:
  344. throw new Error('Unknown order of iteration.')
  345. }
  346. }
  347. )
  348. }
  349. allGeneratedPositionsFor(aArgs) {
  350. let source = util.getArg(aArgs, 'source')
  351. const originalLine = util.getArg(aArgs, 'line')
  352. const originalColumn = aArgs.column || 0
  353. source = this._findSourceIndex(source)
  354. if (source < 0) {
  355. return []
  356. }
  357. if (originalLine < 1) {
  358. throw new Error('Line numbers must be >= 1')
  359. }
  360. if (originalColumn < 0) {
  361. throw new Error('Column numbers must be >= 0')
  362. }
  363. const mappings = []
  364. this._wasm.withMappingCallback(
  365. (m) => {
  366. let lastColumn = m.lastGeneratedColumn
  367. if (this._computedColumnSpans && lastColumn === null) {
  368. lastColumn = Infinity
  369. }
  370. mappings.push({
  371. line: m.generatedLine,
  372. column: m.generatedColumn,
  373. lastColumn,
  374. })
  375. },
  376. () => {
  377. this._wasm.exports.all_generated_locations_for(
  378. this._getMappingsPtr(),
  379. source,
  380. originalLine - 1,
  381. 'column' in aArgs,
  382. originalColumn
  383. )
  384. }
  385. )
  386. return mappings
  387. }
  388. destroy() {
  389. if (this._mappingsPtr !== 0) {
  390. this._wasm.exports.free_mappings(this._mappingsPtr)
  391. this._mappingsPtr = 0
  392. }
  393. }
  394. /**
  395. * Compute the last column for each generated mapping. The last column is
  396. * inclusive.
  397. */
  398. computeColumnSpans() {
  399. if (this._computedColumnSpans) {
  400. return
  401. }
  402. this._wasm.exports.compute_column_spans(this._getMappingsPtr())
  403. this._computedColumnSpans = true
  404. }
  405. /**
  406. * Returns the original source, line, and column information for the generated
  407. * source's line and column positions provided. The only argument is an object
  408. * with the following properties:
  409. *
  410. * - line: The line number in the generated source. The line number
  411. * is 1-based.
  412. * - column: The column number in the generated source. The column
  413. * number is 0-based.
  414. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  415. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  416. * closest element that is smaller than or greater than the one we are
  417. * searching for, respectively, if the exact element cannot be found.
  418. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  419. *
  420. * and an object is returned with the following properties:
  421. *
  422. * - source: The original source file, or null.
  423. * - line: The line number in the original source, or null. The
  424. * line number is 1-based.
  425. * - column: The column number in the original source, or null. The
  426. * column number is 0-based.
  427. * - name: The original identifier, or null.
  428. */
  429. originalPositionFor(aArgs) {
  430. const needle = {
  431. generatedLine: util.getArg(aArgs, 'line'),
  432. generatedColumn: util.getArg(aArgs, 'column'),
  433. }
  434. if (needle.generatedLine < 1) {
  435. throw new Error('Line numbers must be >= 1')
  436. }
  437. if (needle.generatedColumn < 0) {
  438. throw new Error('Column numbers must be >= 0')
  439. }
  440. let bias = util.getArg(
  441. aArgs,
  442. 'bias',
  443. SourceMapConsumer.GREATEST_LOWER_BOUND
  444. )
  445. if (bias == null) {
  446. bias = SourceMapConsumer.GREATEST_LOWER_BOUND
  447. }
  448. let mapping
  449. this._wasm.withMappingCallback(
  450. (m) => (mapping = m),
  451. () => {
  452. this._wasm.exports.original_location_for(
  453. this._getMappingsPtr(),
  454. needle.generatedLine - 1,
  455. needle.generatedColumn,
  456. bias
  457. )
  458. }
  459. )
  460. if (mapping) {
  461. if (mapping.generatedLine === needle.generatedLine) {
  462. let source = util.getArg(mapping, 'source', null)
  463. if (source !== null) {
  464. source = this._sources.at(source)
  465. source = util.computeSourceURL(
  466. this.sourceRoot,
  467. source,
  468. this._sourceMapURL
  469. )
  470. }
  471. let name = util.getArg(mapping, 'name', null)
  472. if (name !== null) {
  473. name = this._names.at(name)
  474. }
  475. return {
  476. source,
  477. line: util.getArg(mapping, 'originalLine', null),
  478. column: util.getArg(mapping, 'originalColumn', null),
  479. name,
  480. }
  481. }
  482. }
  483. return {
  484. source: null,
  485. line: null,
  486. column: null,
  487. name: null,
  488. }
  489. }
  490. /**
  491. * Return true if we have the source content for every source in the source
  492. * map, false otherwise.
  493. */
  494. hasContentsOfAllSources() {
  495. if (!this.sourcesContent) {
  496. return false
  497. }
  498. return (
  499. this.sourcesContent.length >= this._sources.size() &&
  500. !this.sourcesContent.some(function (sc) {
  501. return sc == null
  502. })
  503. )
  504. }
  505. /**
  506. * Returns the original source content. The only argument is the url of the
  507. * original source file. Returns null if no original source content is
  508. * available.
  509. */
  510. sourceContentFor(aSource, nullOnMissing) {
  511. if (!this.sourcesContent) {
  512. return null
  513. }
  514. const index = this._findSourceIndex(aSource)
  515. if (index >= 0) {
  516. return this.sourcesContent[index]
  517. }
  518. let relativeSource = aSource
  519. if (this.sourceRoot != null) {
  520. relativeSource = util.relative(this.sourceRoot, relativeSource)
  521. }
  522. let url
  523. if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) {
  524. // XXX: file:// URIs and absolute paths lead to unexpected behavior for
  525. // many users. We can help them out when they expect file:// URIs to
  526. // behave like it would if they were running a local HTTP server. See
  527. // https://bugzilla.mozilla.org/show_bug.cgi?id=885597.
  528. const fileUriAbsPath = relativeSource.replace(/^file:\/\//, '')
  529. if (url.scheme == 'file' && this._sources.has(fileUriAbsPath)) {
  530. return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]
  531. }
  532. if (
  533. (!url.path || url.path == '/') &&
  534. this._sources.has('/' + relativeSource)
  535. ) {
  536. return this.sourcesContent[this._sources.indexOf('/' + relativeSource)]
  537. }
  538. }
  539. // This function is used recursively from
  540. // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we
  541. // don't want to throw if we can't find the source - we just want to
  542. // return null, so we provide a flag to exit gracefully.
  543. if (nullOnMissing) {
  544. return null
  545. }
  546. throw new Error('"' + relativeSource + '" is not in the SourceMap.')
  547. }
  548. /**
  549. * Returns the generated line and column information for the original source,
  550. * line, and column positions provided. The only argument is an object with
  551. * the following properties:
  552. *
  553. * - source: The filename of the original source.
  554. * - line: The line number in the original source. The line number
  555. * is 1-based.
  556. * - column: The column number in the original source. The column
  557. * number is 0-based.
  558. * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or
  559. * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the
  560. * closest element that is smaller than or greater than the one we are
  561. * searching for, respectively, if the exact element cannot be found.
  562. * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'.
  563. *
  564. * and an object is returned with the following properties:
  565. *
  566. * - line: The line number in the generated source, or null. The
  567. * line number is 1-based.
  568. * - column: The column number in the generated source, or null.
  569. * The column number is 0-based.
  570. */
  571. generatedPositionFor(aArgs) {
  572. let source = util.getArg(aArgs, 'source')
  573. source = this._findSourceIndex(source)
  574. if (source < 0) {
  575. return {
  576. line: null,
  577. column: null,
  578. lastColumn: null,
  579. }
  580. }
  581. const needle = {
  582. source,
  583. originalLine: util.getArg(aArgs, 'line'),
  584. originalColumn: util.getArg(aArgs, 'column'),
  585. }
  586. if (needle.originalLine < 1) {
  587. throw new Error('Line numbers must be >= 1')
  588. }
  589. if (needle.originalColumn < 0) {
  590. throw new Error('Column numbers must be >= 0')
  591. }
  592. let bias = util.getArg(
  593. aArgs,
  594. 'bias',
  595. SourceMapConsumer.GREATEST_LOWER_BOUND
  596. )
  597. if (bias == null) {
  598. bias = SourceMapConsumer.GREATEST_LOWER_BOUND
  599. }
  600. let mapping
  601. this._wasm.withMappingCallback(
  602. (m) => (mapping = m),
  603. () => {
  604. this._wasm.exports.generated_location_for(
  605. this._getMappingsPtr(),
  606. needle.source,
  607. needle.originalLine - 1,
  608. needle.originalColumn,
  609. bias
  610. )
  611. }
  612. )
  613. if (mapping) {
  614. if (mapping.source === needle.source) {
  615. let lastColumn = mapping.lastGeneratedColumn
  616. if (this._computedColumnSpans && lastColumn === null) {
  617. lastColumn = Infinity
  618. }
  619. return {
  620. line: util.getArg(mapping, 'generatedLine', null),
  621. column: util.getArg(mapping, 'generatedColumn', null),
  622. lastColumn,
  623. }
  624. }
  625. }
  626. return {
  627. line: null,
  628. column: null,
  629. lastColumn: null,
  630. }
  631. }
  632. }
  633. BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer
  634. exports.BasicSourceMapConsumer = BasicSourceMapConsumer
  635. /**
  636. * An IndexedSourceMapConsumer instance represents a parsed source map which
  637. * we can query for information. It differs from BasicSourceMapConsumer in
  638. * that it takes "indexed" source maps (i.e. ones with a "sections" field) as
  639. * input.
  640. *
  641. * The first parameter is a raw source map (either as a JSON string, or already
  642. * parsed to an object). According to the spec for indexed source maps, they
  643. * have the following attributes:
  644. *
  645. * - version: Which version of the source map spec this map is following.
  646. * - file: Optional. The generated file this source map is associated with.
  647. * - sections: A list of section definitions.
  648. *
  649. * Each value under the "sections" field has two fields:
  650. * - offset: The offset into the original specified at which this section
  651. * begins to apply, defined as an object with a "line" and "column"
  652. * field.
  653. * - map: A source map definition. This source map could also be indexed,
  654. * but doesn't have to be.
  655. *
  656. * Instead of the "map" field, it's also possible to have a "url" field
  657. * specifying a URL to retrieve a source map from, but that's currently
  658. * unsupported.
  659. *
  660. * Here's an example source map, taken from the source map spec[0], but
  661. * modified to omit a section which uses the "url" field.
  662. *
  663. * {
  664. * version : 3,
  665. * file: "app.js",
  666. * sections: [{
  667. * offset: {line:100, column:10},
  668. * map: {
  669. * version : 3,
  670. * file: "section.js",
  671. * sources: ["foo.js", "bar.js"],
  672. * names: ["src", "maps", "are", "fun"],
  673. * mappings: "AAAA,E;;ABCDE;"
  674. * }
  675. * }],
  676. * }
  677. *
  678. * The second parameter, if given, is a string whose value is the URL
  679. * at which the source map was found. This URL is used to compute the
  680. * sources array.
  681. *
  682. * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt
  683. */
  684. class IndexedSourceMapConsumer extends SourceMapConsumer {
  685. constructor(aSourceMap, aSourceMapURL) {
  686. return super(INTERNAL).then((that) => {
  687. let sourceMap = aSourceMap
  688. if (typeof aSourceMap === 'string') {
  689. sourceMap = util.parseSourceMapInput(aSourceMap)
  690. }
  691. const version = util.getArg(sourceMap, 'version')
  692. const sections = util.getArg(sourceMap, 'sections')
  693. if (version != that._version) {
  694. throw new Error('Unsupported version: ' + version)
  695. }
  696. that._sources = new ArraySet()
  697. that._names = new ArraySet()
  698. that.__generatedMappings = null
  699. that.__originalMappings = null
  700. that.__generatedMappingsUnsorted = null
  701. that.__originalMappingsUnsorted = null
  702. let lastOffset = {
  703. line: -1,
  704. column: 0,
  705. }
  706. return Promise.all(
  707. sections.map((s) => {
  708. if (s.url) {
  709. // The url field will require support for asynchronicity.
  710. // See https://github.com/mozilla/source-map/issues/16
  711. throw new Error(
  712. 'Support for url field in sections not implemented.'
  713. )
  714. }
  715. const offset = util.getArg(s, 'offset')
  716. const offsetLine = util.getArg(offset, 'line')
  717. const offsetColumn = util.getArg(offset, 'column')
  718. if (
  719. offsetLine < lastOffset.line ||
  720. (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)
  721. ) {
  722. throw new Error(
  723. 'Section offsets must be ordered and non-overlapping.'
  724. )
  725. }
  726. lastOffset = offset
  727. const cons = new SourceMapConsumer(
  728. util.getArg(s, 'map'),
  729. aSourceMapURL
  730. )
  731. return cons.then((consumer) => {
  732. return {
  733. generatedOffset: {
  734. // The offset fields are 0-based, but we use 1-based indices when
  735. // encoding/decoding from VLQ.
  736. generatedLine: offsetLine + 1,
  737. generatedColumn: offsetColumn + 1,
  738. },
  739. consumer,
  740. }
  741. })
  742. })
  743. ).then((s) => {
  744. that._sections = s
  745. return that
  746. })
  747. })
  748. }
  749. // `__generatedMappings` and `__originalMappings` are arrays that hold the
  750. // parsed mapping coordinates from the source map's "mappings" attribute. They
  751. // are lazily instantiated, accessed via the `_generatedMappings` and
  752. // `_originalMappings` getters respectively, and we only parse the mappings
  753. // and create these arrays once queried for a source location. We jump through
  754. // these hoops because there can be many thousands of mappings, and parsing
  755. // them is expensive, so we only want to do it if we must.
  756. //
  757. // Each object in the arrays is of the form:
  758. //
  759. // {
  760. // generatedLine: The line number in the generated code,
  761. // generatedColumn: The column number in the generated code,
  762. // source: The path to the original source file that generated this
  763. // chunk of code,
  764. // originalLine: The line number in the original source that
  765. // corresponds to this chunk of generated code,
  766. // originalColumn: The column number in the original source that
  767. // corresponds to this chunk of generated code,
  768. // name: The name of the original symbol which generated this chunk of
  769. // code.
  770. // }
  771. //
  772. // All properties except for `generatedLine` and `generatedColumn` can be
  773. // `null`.
  774. //
  775. // `_generatedMappings` is ordered by the generated positions.
  776. //
  777. // `_originalMappings` is ordered by the original positions.
  778. get _generatedMappings() {
  779. if (!this.__generatedMappings) {
  780. this._sortGeneratedMappings()
  781. }
  782. return this.__generatedMappings
  783. }
  784. get _originalMappings() {
  785. if (!this.__originalMappings) {
  786. this._sortOriginalMappings()
  787. }
  788. return this.__originalMappings
  789. }
  790. get _generatedMappingsUnsorted() {
  791. if (!this.__generatedMappingsUnsorted) {
  792. this._parseMappings(this._mappings, this.sourceRoot)
  793. }
  794. return this.__generatedMappingsUnsorted
  795. }
  796. get _originalMappingsUnsorted() {
  797. if (!this.__originalMappingsUnsorted) {
  798. this._parseMappings(this._mappings, this.sourceRoot)
  799. }
  800. return this.__originalMappingsUnsorted
  801. }
  802. _sortGeneratedMappings() {
  803. const mappings = this._generatedMappingsUnsorted
  804. mappings.sort(util.compareByGeneratedPositionsDeflated)
  805. this.__generatedMappings = mappings
  806. }
  807. _sortOriginalMappings() {
  808. const mappings = this._originalMappingsUnsorted
  809. mappings.sort(util.compareByOriginalPositions)
  810. this.__originalMappings = mappings
  811. }
  812. /**
  813. * The list of original sources.
  814. */
  815. get sources() {
  816. const sources = []
  817. for (let i = 0; i < this._sections.length; i++) {
  818. for (let j = 0; j < this._sections[i].consumer.sources.length; j++) {
  819. sources.push(this._sections[i].consumer.sources[j])
  820. }
  821. }
  822. return sources
  823. }
  824. /**
  825. * Returns the original source, line, and column information for the generated
  826. * source's line and column positions provided. The only argument is an object
  827. * with the following properties:
  828. *
  829. * - line: The line number in the generated source. The line number
  830. * is 1-based.
  831. * - column: The column number in the generated source. The column
  832. * number is 0-based.
  833. *
  834. * and an object is returned with the following properties:
  835. *
  836. * - source: The original source file, or null.
  837. * - line: The line number in the original source, or null. The
  838. * line number is 1-based.
  839. * - column: The column number in the original source, or null. The
  840. * column number is 0-based.
  841. * - name: The original identifier, or null.
  842. */
  843. originalPositionFor(aArgs) {
  844. const needle = {
  845. generatedLine: util.getArg(aArgs, 'line'),
  846. generatedColumn: util.getArg(aArgs, 'column'),
  847. }
  848. // Find the section containing the generated position we're trying to map
  849. // to an original position.
  850. const sectionIndex = binarySearch.search(
  851. needle,
  852. this._sections,
  853. function (aNeedle, section) {
  854. const cmp =
  855. aNeedle.generatedLine - section.generatedOffset.generatedLine
  856. if (cmp) {
  857. return cmp
  858. }
  859. return aNeedle.generatedColumn - section.generatedOffset.generatedColumn
  860. }
  861. )
  862. const section = this._sections[sectionIndex]
  863. if (!section) {
  864. return {
  865. source: null,
  866. line: null,
  867. column: null,
  868. name: null,
  869. }
  870. }
  871. return section.consumer.originalPositionFor({
  872. line: needle.generatedLine - (section.generatedOffset.generatedLine - 1),
  873. column:
  874. needle.generatedColumn -
  875. (section.generatedOffset.generatedLine === needle.generatedLine
  876. ? section.generatedOffset.generatedColumn - 1
  877. : 0),
  878. bias: aArgs.bias,
  879. })
  880. }
  881. /**
  882. * Return true if we have the source content for every source in the source
  883. * map, false otherwise.
  884. */
  885. hasContentsOfAllSources() {
  886. return this._sections.every(function (s) {
  887. return s.consumer.hasContentsOfAllSources()
  888. })
  889. }
  890. /**
  891. * Returns the original source content. The only argument is the url of the
  892. * original source file. Returns null if no original source content is
  893. * available.
  894. */
  895. sourceContentFor(aSource, nullOnMissing) {
  896. for (let i = 0; i < this._sections.length; i++) {
  897. const section = this._sections[i]
  898. const content = section.consumer.sourceContentFor(aSource, true)
  899. if (content) {
  900. return content
  901. }
  902. }
  903. if (nullOnMissing) {
  904. return null
  905. }
  906. throw new Error('"' + aSource + '" is not in the SourceMap.')
  907. }
  908. /**
  909. * Returns the generated line and column information for the original source,
  910. * line, and column positions provided. The only argument is an object with
  911. * the following properties:
  912. *
  913. * - source: The filename of the original source.
  914. * - line: The line number in the original source. The line number
  915. * is 1-based.
  916. * - column: The column number in the original source. The column
  917. * number is 0-based.
  918. *
  919. * and an object is returned with the following properties:
  920. *
  921. * - line: The line number in the generated source, or null. The
  922. * line number is 1-based.
  923. * - column: The column number in the generated source, or null.
  924. * The column number is 0-based.
  925. */
  926. generatedPositionFor(aArgs) {
  927. for (let i = 0; i < this._sections.length; i++) {
  928. const section = this._sections[i]
  929. // Only consider this section if the requested source is in the list of
  930. // sources of the consumer.
  931. if (
  932. section.consumer._findSourceIndex(util.getArg(aArgs, 'source')) === -1
  933. ) {
  934. continue
  935. }
  936. const generatedPosition = section.consumer.generatedPositionFor(aArgs)
  937. if (generatedPosition) {
  938. const ret = {
  939. line:
  940. generatedPosition.line +
  941. (section.generatedOffset.generatedLine - 1),
  942. column:
  943. generatedPosition.column +
  944. (section.generatedOffset.generatedLine === generatedPosition.line
  945. ? section.generatedOffset.generatedColumn - 1
  946. : 0),
  947. }
  948. return ret
  949. }
  950. }
  951. return {
  952. line: null,
  953. column: null,
  954. }
  955. }
  956. /**
  957. * Parse the mappings in a string in to a data structure which we can easily
  958. * query (the ordered arrays in the `this.__generatedMappings` and
  959. * `this.__originalMappings` properties).
  960. */
  961. _parseMappings(aStr, aSourceRoot) {
  962. const generatedMappings = (this.__generatedMappingsUnsorted = [])
  963. const originalMappings = (this.__originalMappingsUnsorted = [])
  964. for (let i = 0; i < this._sections.length; i++) {
  965. const section = this._sections[i]
  966. const sectionMappings = []
  967. section.consumer.eachMapping((m) => sectionMappings.push(m))
  968. for (let j = 0; j < sectionMappings.length; j++) {
  969. const mapping = sectionMappings[j]
  970. // TODO: test if null is correct here. The original code used
  971. // `source`, which would actually have gotten used as null because
  972. // var's get hoisted.
  973. // See: https://github.com/mozilla/source-map/issues/333
  974. let source = util.computeSourceURL(
  975. section.consumer.sourceRoot,
  976. null,
  977. this._sourceMapURL
  978. )
  979. this._sources.add(source)
  980. source = this._sources.indexOf(source)
  981. let name = null
  982. if (mapping.name) {
  983. this._names.add(mapping.name)
  984. name = this._names.indexOf(mapping.name)
  985. }
  986. // The mappings coming from the consumer for the section have
  987. // generated positions relative to the start of the section, so we
  988. // need to offset them to be relative to the start of the concatenated
  989. // generated file.
  990. const adjustedMapping = {
  991. source,
  992. generatedLine:
  993. mapping.generatedLine + (section.generatedOffset.generatedLine - 1),
  994. generatedColumn:
  995. mapping.generatedColumn +
  996. (section.generatedOffset.generatedLine === mapping.generatedLine
  997. ? section.generatedOffset.generatedColumn - 1
  998. : 0),
  999. originalLine: mapping.originalLine,
  1000. originalColumn: mapping.originalColumn,
  1001. name,
  1002. }
  1003. generatedMappings.push(adjustedMapping)
  1004. if (typeof adjustedMapping.originalLine === 'number') {
  1005. originalMappings.push(adjustedMapping)
  1006. }
  1007. }
  1008. }
  1009. }
  1010. eachMapping(aCallback, aContext, aOrder) {
  1011. const context = aContext || null
  1012. const order = aOrder || SourceMapConsumer.GENERATED_ORDER
  1013. let mappings
  1014. switch (order) {
  1015. case SourceMapConsumer.GENERATED_ORDER:
  1016. mappings = this._generatedMappings
  1017. break
  1018. case SourceMapConsumer.ORIGINAL_ORDER:
  1019. mappings = this._originalMappings
  1020. break
  1021. default:
  1022. throw new Error('Unknown order of iteration.')
  1023. }
  1024. const sourceRoot = this.sourceRoot
  1025. mappings
  1026. .map(function (mapping) {
  1027. let source = null
  1028. if (mapping.source !== null) {
  1029. source = this._sources.at(mapping.source)
  1030. source = util.computeSourceURL(sourceRoot, source, this._sourceMapURL)
  1031. }
  1032. return {
  1033. source,
  1034. generatedLine: mapping.generatedLine,
  1035. generatedColumn: mapping.generatedColumn,
  1036. originalLine: mapping.originalLine,
  1037. originalColumn: mapping.originalColumn,
  1038. name: mapping.name === null ? null : this._names.at(mapping.name),
  1039. }
  1040. }, this)
  1041. .forEach(aCallback, context)
  1042. }
  1043. /**
  1044. * Find the mapping that best matches the hypothetical "needle" mapping that
  1045. * we are searching for in the given "haystack" of mappings.
  1046. */
  1047. _findMapping(aNeedle, aMappings, aLineName, aColumnName, aComparator, aBias) {
  1048. // To return the position we are searching for, we must first find the
  1049. // mapping for the given position and then return the opposite position it
  1050. // points to. Because the mappings are sorted, we can use binary search to
  1051. // find the best mapping.
  1052. if (aNeedle[aLineName] <= 0) {
  1053. throw new TypeError(
  1054. 'Line must be greater than or equal to 1, got ' + aNeedle[aLineName]
  1055. )
  1056. }
  1057. if (aNeedle[aColumnName] < 0) {
  1058. throw new TypeError(
  1059. 'Column must be greater than or equal to 0, got ' + aNeedle[aColumnName]
  1060. )
  1061. }
  1062. return binarySearch.search(aNeedle, aMappings, aComparator, aBias)
  1063. }
  1064. allGeneratedPositionsFor(aArgs) {
  1065. const line = util.getArg(aArgs, 'line')
  1066. // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping
  1067. // returns the index of the closest mapping less than the needle. By
  1068. // setting needle.originalColumn to 0, we thus find the last mapping for
  1069. // the given line, provided such a mapping exists.
  1070. const needle = {
  1071. source: util.getArg(aArgs, 'source'),
  1072. originalLine: line,
  1073. originalColumn: util.getArg(aArgs, 'column', 0),
  1074. }
  1075. needle.source = this._findSourceIndex(needle.source)
  1076. if (needle.source < 0) {
  1077. return []
  1078. }
  1079. if (needle.originalLine < 1) {
  1080. throw new Error('Line numbers must be >= 1')
  1081. }
  1082. if (needle.originalColumn < 0) {
  1083. throw new Error('Column numbers must be >= 0')
  1084. }
  1085. const mappings = []
  1086. let index = this._findMapping(
  1087. needle,
  1088. this._originalMappings,
  1089. 'originalLine',
  1090. 'originalColumn',
  1091. util.compareByOriginalPositions,
  1092. binarySearch.LEAST_UPPER_BOUND
  1093. )
  1094. if (index >= 0) {
  1095. let mapping = this._originalMappings[index]
  1096. if (aArgs.column === undefined) {
  1097. const originalLine = mapping.originalLine
  1098. // Iterate until either we run out of mappings, or we run into
  1099. // a mapping for a different line than the one we found. Since
  1100. // mappings are sorted, this is guaranteed to find all mappings for
  1101. // the line we found.
  1102. while (mapping && mapping.originalLine === originalLine) {
  1103. let lastColumn = mapping.lastGeneratedColumn
  1104. if (this._computedColumnSpans && lastColumn === null) {
  1105. lastColumn = Infinity
  1106. }
  1107. mappings.push({
  1108. line: util.getArg(mapping, 'generatedLine', null),
  1109. column: util.getArg(mapping, 'generatedColumn', null),
  1110. lastColumn,
  1111. })
  1112. mapping = this._originalMappings[++index]
  1113. }
  1114. } else {
  1115. const originalColumn = mapping.originalColumn
  1116. // Iterate until either we run out of mappings, or we run into
  1117. // a mapping for a different line than the one we were searching for.
  1118. // Since mappings are sorted, this is guaranteed to find all mappings for
  1119. // the line we are searching for.
  1120. while (
  1121. mapping &&
  1122. mapping.originalLine === line &&
  1123. mapping.originalColumn == originalColumn
  1124. ) {
  1125. let lastColumn = mapping.lastGeneratedColumn
  1126. if (this._computedColumnSpans && lastColumn === null) {
  1127. lastColumn = Infinity
  1128. }
  1129. mappings.push({
  1130. line: util.getArg(mapping, 'generatedLine', null),
  1131. column: util.getArg(mapping, 'generatedColumn', null),
  1132. lastColumn,
  1133. })
  1134. mapping = this._originalMappings[++index]
  1135. }
  1136. }
  1137. }
  1138. return mappings
  1139. }
  1140. destroy() {
  1141. for (let i = 0; i < this._sections.length; i++) {
  1142. this._sections[i].consumer.destroy()
  1143. }
  1144. }
  1145. }
  1146. exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer
  1147. /*
  1148. * Cheat to get around inter-twingled classes. `factory()` can be at the end
  1149. * where it has access to non-hoisted classes, but it gets hoisted itself.
  1150. */
  1151. function _factory(aSourceMap, aSourceMapURL) {
  1152. let sourceMap = aSourceMap
  1153. if (typeof aSourceMap === 'string') {
  1154. sourceMap = util.parseSourceMapInput(aSourceMap)
  1155. }
  1156. const consumer =
  1157. sourceMap.sections != null
  1158. ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL)
  1159. : new BasicSourceMapConsumer(sourceMap, aSourceMapURL)
  1160. return Promise.resolve(consumer)
  1161. }
  1162. function _factoryBSM(aSourceMap, aSourceMapURL) {
  1163. return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL)
  1164. }