Giter Site home page Giter Site logo

xpl / get-source Goto Github PK

View Code? Open in Web Editor NEW
27.0 5.0 9.0 739 KB

Fetch source-mapped sources. Peek by file, line, column. Node & browsers. Sync & async.

Home Page: http://npmjs.com/package/get-source

License: MIT License

JavaScript 99.95% HTML 0.05%
source sourcemaps sourcemap-support source-code source-code-analysis sourcecode sourcemap read-source-code reflection javascript

get-source's Introduction

get-source

Build Status Coverage Status npm

Fetch source-mapped sources. Peek by file, line, column. Node & browsers. Sync & async.

npm install get-source

Features

  • Allows to read source code files in Node and browsers
  • Full sourcemap support (path resolving, external/embedded/inline linking, and long chains)
  • Synchronous API — good for CLI tools (e.g. logging). Works in browsers!
  • Asynchronous API — good for everything web!
  • Built-in cache

What For

Usage (Synchronous)

import getSource from 'get-source'
file = getSource ('./scripts/index.min.js')

Will read the file synchronously (either via XHR or by filesystem API, depending on the environment) and return it's cached representation. Result will contain the following fields:

file.path  // normalized file path
file.text  // text contents
file.lines // array of lines

And the resolve method:

file.resolve ({ line: 1, column: 8 }) // indexes here start from 1 (by widely accepted convention). Zero indexes are invalid.

It will look through the sourcemap chain, returning following:

{
   line:       <original line number>,
   column:     <original column number>,
   sourceFile: <original source file object>,
   sourceLine: <original source line text>
}

In that returned object, sourceFile is the same kind of object that getSource returns. So you can access its text, lines and path fields to obtain the full information. And the sourceLine is returned just for the convenience, as a shortcut.

Usage (Asynchronous)

Pretty much the same as synchronous, except it's getSource.async. It returns awaitable promises:

file     = await getSource.async ('./scripts/index.min.js')
location = await file.resolve ({ line: 1, column: 8 })

Error Handling

In synchronous mode, it never throws (due to backward compatibility reasons with existing code):

nonsense = getSource ('/some/nonexistent/file')

nonsense.text  // should be '' (so it's safe to access without checking)
nonsense.error // should be an Error object, representing an actual error thrown during reading/parsing
resolved = nonsense.resolve ({ line: 5, column: 0 })

resolved.sourceLine // empty string (so it's safe to access without checking)
resolved.error      // should be an Error object, representing an actual error thrown during reading/parsing

In asychronous mode, it throws an error:

try { 
   file     = await getSource.async ('/some/file')
   location = await file.resolve ({ line: 5, column: 0 })
} catch (e) {
   ...
}

Resetting Cache

E.g. when you need to force-reload files:

getSource.resetCache ()        // sync cache
getSource.async.resetCache ()  // async cache

Also, viewing cached files:

getSource.getCache ()        // sync cache
getSource.async.getCache ()  // async cache

get-source's People

Contributors

aetonsi avatar dependabot[bot] avatar devilming avatar wycats avatar xpl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

get-source's Issues

Module not found: Error: Can't resolve 'fs'

Hello,
i'm using xpl/stacktracey in a framework7 project with webpack which targets web or cordova.
After npm installing stacktracey and running webpack dev server with target web, the following error is reported:

ERROR in a:/projects/temp/node_modules/get-source/get-source.js
Module not found: Error: Can't resolve 'fs' in 'a:\projects\temp\node_modules\get-source'
 @ a:/projects/temp/node_modules/get-source/get-source.js 144:41-62 156:40-61
 @ a:/projects/temp/node_modules/stacktracey/stacktracey.js
 @ a:/projects/temp/src/js/errorReporter.js
 @ a:/projects/temp/src/js/app.js
 @ multi ./src/js/app.js
i 「wdm」: Failed to compile.

Apparently isBrowser is false so the ifs on lines 138 and 152 go into the non-browser branch... Is this correct?


Have a nice day

Fetch API cannot load file:///android_asset/www/js/app.js. URL scheme "file" is not supported.

Hello again,
i'd like to know if it would be possible to use and xhr request instead of fetch for fetchFileAsync.

Fetch only supports the http protocol, while xhr also supports file for compiled apps on android & similar.
I tried to replace it with an xhr request, and the module seems to be working.

This would be the code (very similar to the synchronous function):

module.exports.async = impl (function fetchFileAsync (path) {
  return new Promise ((resolve, reject) => {
    if (isBrowser) {
        let xhr = new XMLHttpRequest ()
        xhr.open ('GET', path)
        xhr.send (null)
        xhr.onload = r => resolve(xhr.responseText)
    } else {
        module.require ('fs').readFile (path, { encoding: 'utf8' }, (e, x) => {
          e ? reject (e) : resolve (x)
        })
    }
  })
})

Is there any reason why fetch would be necessarily needed?


Have a nice day

Cannot resolve HTTP sourcemaps in Node

Hi, I noticed that I seem to be unable to resolve sourcemaps in Node. Here is a full repro with repro steps.

Notice that, in my repro web app, Chrome is able to parse the stacktrace for script.min.js (source: script.js), so the sourcemap seems to be configured correctly:

Screenshot from 2021-12-26 20-59-24

Yet, in Node.js, when I run:

const stacktrace = "Error\n    at http://localhost:3000/script.min.js:1:29"
console.log(new Stacktracey(stacktrace).withSources().asTable())

The output is:

at   script.min.js:1

Note that it says script.min.js, not script.js.

I believe I've tracked it down to these lines of code:

resolve (nodeRequire ('fs').readFileSync (path, { encoding: 'utf8' }))

nodeRequire ('fs').readFile (path, { encoding: 'utf8' }, (e, x) => {

Note that, in the browser version of the code, it does an XHR to fetch the path – i.e. it assumes it's a URL, not a filepath. But in Node, it assumes it's a filepath. So we get a "no such file or directory" error:

Screenshot from 2021-12-26 21-03-01

It seems to me that the Node code should be making an HTTP request rather than doing fs.readFile / fs.readFileSync, similar to what it does in the browser.

Lines resolved to wrong file silently

Hi, I ran into a possible bug: when I try to resolve a position in a file that isn't covered by an inline source map mapping, the .resolve() method returns an object which points to the file itself instead of its source, and doesn't signal this "resolution failure" in any way.

I forked the repo and wrote some (failing) tests that demonstrate the problem: https://github.com/corvidism/get-source/pull/1/files

The TMP tests show this on a file where I discovered it. It's compiled from typescript, and it looks like the typescript compiler doesn't include the leading spaces in the mappings => when I try to resolve a line from column=1 (I don't have the column number), the resolution fails.

Obviously, the ideal would be if it resolved, but it should at least warn that the resolution failed. As it is, there's no way to detect it. (That, and perhaps the sourceFile could be set anyway? I mean, the filename is there, even if the mapping failed...)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.