Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Emoji support 🎉 and other updates #10

Merged
merged 10 commits into from Oct 12, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -29,21 +29,21 @@ jq/jq.o: jq/configure

jq.js: jq/jq.o pre.js post.js
cd jq && \
emcc -O3 -s TOTAL_MEMORY=32MB --memory-init-file 1 --pre-js ../pre.js --post-js ../post.js jq.o -o ../jq.js
emcc -O3 -s TOTAL_MEMORY=32MB -s MODULARIZE_INSTANCE=1 -s EXPORT_NAME="jq" --memory-init-file 1 --pre-js ../pre.js --post-js ../post.js jq.o -o ../jq.js

jq.min.js: node_modules/.bin/uglifyjs jq.js
./node_modules/.bin/uglifyjs jq.js -m -c -o jq.min.js

jq.bundle.js: jq/jq.o pre.js post.js
cd jq && \
emcc -O3 -s ALLOW_MEMORY_GROWTH=1 --memory-init-file 0 --pre-js ../pre.js --post-js ../post.js jq.o -o ../jq.bundle.js
emcc -O3 -s ALLOW_MEMORY_GROWTH=1 -s MODULARIZE_INSTANCE=1 -s EXPORT_NAME="jq" --memory-init-file 0 --pre-js ../pre.js --post-js ../post.js jq.o -o ../jq.bundle.js

jq.bundle.min.js: node_modules/.bin/uglifyjs jq.bundle.js
./node_modules/.bin/uglifyjs jq.js -m -c -o jq.bundle.min.js

jq.wasm.js: jq/jq.o pre.js post.js
cd jq && \
emcc -s WASM=1 -s ALLOW_MEMORY_GROWTH=1 -O0 --pre-js ../pre.js --post-js ../post.js jq.o -o ../jq.wasm.js
emcc -O3 -s ALLOW_MEMORY_GROWTH=1 -s MODULARIZE_INSTANCE=1 -s EXPORT_NAME="jq" -s WASM=1 --pre-js ../pre.js --post-js ../post.js jq.o -o ../jq.wasm.js

jq.wasm.min.js: node_modules/.bin/uglifyjs jq.wasm.js
./node_modules/.bin/uglifyjs jq.wasm.js -m -c -o jq.wasm.min.js
Expand Down
36 changes: 21 additions & 15 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ npm install jq-web
```js
var jq = require('jq-web')

jq({
jq.json({
a: {
big: {
json: [
Expand All @@ -24,14 +24,14 @@ jq({
'important',
'things'
]
}
}
}
}, '.a.big.json | ["empty", .[1], "useless", .[3]] | join(" ")')
```

The code above returns the string `"empty of useless things"`.

You could do the same using the promised API with `jq.promised({...}).then(result => {})`. That is useful if you're loading a `.mem` or `.wasm` file, as the library won't return the correct results until these files are asynchronously fetched by the Emscripten runtime.
You could do the same using the promised API with `jq.promised.json({...}).then(result => {})`. That is useful if you're loading a `.mem` or `.wasm` file, as the library won't return the correct results until these files are asynchronously fetched by the Emscripten runtime.

## WebAssembly

Expand All @@ -41,35 +41,41 @@ If the target browser supports WebAssembly you can just include it normally. It

You can also import it with browserify `require('jq-web/jq.wasm.js')` if you want.

## using the non-bundled version
## Using the non-bundled version

If you can't use WebAssembly, there's a better way to use the asm.js version.

By default, requiring `jq-web` will give you the `./jq.bundle.min.js` file, which comes bundled with the static memory initialization inside the JS code. That's inefficient. For better performance and load sizes, require `jq-web/jq[.min].js` instead, and copy `node_modules/jq-web/jq.js.mem` to the directory you're serving the app from, as it will be loaded asynchronously in the runtime by the library.

### Webpack issues

#### `fs`
The Emscripten runtime will try to `require` the `fs` module, and if it fails it will resort to an in-memory filesystem (almost no use of that is made of the library, but it is needed somehow). In Browserify there's a default `{}` that corresponds to the `fs` module, but in Webpack you must [declare it as an empty module](https://github.com/fiatjaf/jq-web/issues/5#issuecomment-342694955).

## reference
#### 404 error when loading `.wasm` files
By default projects compiled with Emscripten look for `.wasm` files in the same directory that the `.js` file is run from. This causes issues when using webpack because name of the `.wasm` file is altered with a hash and can be placed in a different directory. To fix this problem you can use the [copy-webpack-plugin](https://github.com/webpack-contrib/copy-webpack-plugin) to copy the `jq.wasm` file to the same directory that the webpack bundle is placed.

`jq(<object>, <filter>) <object>` will take a Javascript object, or scalar, whatever, and dump it to JSON, then it will return whatever your filter outputs and try to convert that into a JS object. If you're loading `.mem` or `.wasm` files asynchronously this will return `{}` every time you call it until the loading is finished.
## Reference

`jq.json(<object>, <filter>) <object>` will take a Javascript object, or scalar, whatever, and dump it to JSON, then it will return whatever your filter outputs and try to convert that into a JS object. If you're loading `.mem` or `.wasm` files asynchronously this will return `{}` every time you call it until the loading is finished.

`jq.raw(<json-string>, <filter>) <raw-output>` will take a string that will be passed as it is to jq (like if you were doing `echo '<json-string>' | jq <filter>` on the command line) then return a string with the raw STDOUT response. If you're loading `.mem` or `.wasm` files asynchronously this will return `'{}'` every time you call it until the loading is finished.

`jq.onInitialized.addListener(<function>)` registers a function to be called when `.mem` or `.wasm` files have finished loading and the library is ready to be used. You should register callbacks here to rerun your functions if you're using the sync API (above). If you're using the promised API (below) you don't ever need to look at this. Also, if you're using the sync API but just at a long time after the page is loaded and the user inputs something, for example, you may not need to use this at all.

`jq.promised(<object>, <filter>) Promise<object>` will do the same as `jq()` but returning a Promise to the result instead. This is safe to use anytime.
`jq.promised.json(<object>, <filter>) Promise<object>` will do the same as `jq.json()` but returning a Promise to the result instead. This is safe to use anytime.

`jq.promised.raw(<json-string>, <filter>) Promise<raw-output>` will do the same as `jq.raw()` but returning a Promise to the result instead. This is safe to use anytime.

## Build

## build

```
cat Makefile | head -n 10
# read it.
# then:
1. [Install Emscripten from source](https://kripken.github.io/emscripten-site/docs/getting_started/downloads.html#installation-instructions), we used `1.38.12`
2. Clone `jq-web` and `cd` into it
3. Look over the `Makefile` for more Emscripten instructions
4. `make`
* This may take a while the first time if you have never ran Emscripten before

make
```
## Test
A handful of tests exist in `test.js` and are good place to start when verifying a build
1. `npm install` or `yarn`
2. `node test.js`
2 changes: 1 addition & 1 deletion jq
Submodule jq updated from bd34b8 to 341a5f
7 changes: 5 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@
},
"homepage": "https://github.com/fiatjaf/jq-web#readme",
"devDependencies": {
"tape": "^4.6.3",
"uglify-js": "^2.8.22"
"tape": "^4.9.1",
"uglify-es": "^3.3.9"
},
"dependencies": {
"live-server": "^1.2.0"
}
}
162 changes: 82 additions & 80 deletions post.js
Original file line number Diff line number Diff line change
@@ -1,93 +1,95 @@
// necessary because the default emscriptem exit() logs a lot of text.
function exit () {}

// takes a string as input and returns a string
// like `echo <jsonstring> | jq <filter>`, returning the value of STDOUT
function raw (jsonstring, filter, flags) {
if (!initialized) return '{}'
// necessary because the default emscriptem exit() logs a lot of text.
function exit() {}

stdin = jsonstring
inBuffer = []
outBuffer = []
errBuffer = []

flags = flags || []
Module.callMain(flags.concat(filter))

// calling main closes stdout, so we reopen it here:
FS.streams[1] = FS.open('/dev/stdout', 577, 0)
FS.streams[2] = FS.open('/dev/stderr', 577, 0)
// takes a string as input and returns a string
// like `echo <jsonstring> | jq <filter>`, returning the value of STDOUT
function raw(jsonstring, filter, flags) {
if (!initialized) return "{}";

if (outBuffer.length) {
return fromByteArray(outBuffer).trim();
}

if (errBuffer.length) {
var errBufferContents = fromByteArray(errBuffer)
var errString = errBufferContents
if (errString.indexOf(':') > -1) {
var parts = errString.split(':')
errString = parts[parts.length - 1].trim()
}
throw new Error(errString)
}
stdin = jsonstring;
inBuffer = [];
outBuffer = [];
errBuffer = [];

return ''
}

// takes an object as input and tries to return objects.
function json (json, filter) {
if (!initialized) return {}
flags = flags || [];
Module.callMain(flags.concat(filter));

var jsonstring = JSON.stringify(json)
var result = raw(jsonstring, filter, ['-c']).trim()

if (result.indexOf('\n') !== -1) {
return result
.split('\n')
.filter(function (x) { return x })
.reduce(function (acc, line) { return acc.concat(JSON.parse(line)) }, [])
} else {
return JSON.parse(result)
}
// calling main closes stdout, so we reopen it here:
FS.streams[1] = FS.open("/dev/stdout", 577, 0);
FS.streams[2] = FS.open("/dev/stderr", 577, 0);

if (outBuffer.length) {
return fromByteArray(outBuffer).trim();
}

var jq = json
jq.raw = raw

jq.onInitialized = {
addListener: function (cb) {
if (initialized) {
cb()
}
initListeners.push(cb)
if (errBuffer.length) {
var errBufferContents = fromByteArray(errBuffer);
var errString = errBufferContents;
if (errString.indexOf(":") > -1) {
var parts = errString.split(":");
errString = parts[parts.length - 1].trim();
}
throw new Error(errString);
}

jq.promised = function () {
var args = arguments
return new Promise(function (resolve, reject) {
jq.onInitialized.addListener(function () {
try {
resolve(jq.apply(jq, args))
} catch (e) {
reject(e)
}
return "";
}

// takes an object as input and tries to return objects.
function json(json, filter) {
if (!initialized) return {};

var jsonstring = JSON.stringify(json);
var result = raw(jsonstring, filter, ["-c"]).trim();

if (result.indexOf("\n") !== -1) {
return result
.split("\n")
.filter(function(x) {
return x;
})
})
.reduce(function(acc, line) {
return acc.concat(JSON.parse(line));
}, []);
} else {
return JSON.parse(result);
}
jq.promised.raw = function () {
var args = arguments
return new Promise(function (resolve, reject) {
jq.onInitialized.addListener(function () {
try {
resolve(jq.raw.apply(jq, args))
} catch (e) {
reject(e)
}
})
})
}

jq.json = json;
jq.raw = raw;

jq.onInitialized = {
addListener: function(cb) {
if (initialized) {
cb();
}
initListeners.push(cb);
}
};

return jq
}))
jq.promised = {};
jq.promised.json = function() {
var args = arguments;
return new Promise(function(resolve, reject) {
jq.onInitialized.addListener(function() {
try {
resolve(jq.json.apply(jq, args));
} catch (e) {
reject(e);
}
});
});
};
jq.promised.raw = function() {
var args = arguments;
return new Promise(function(resolve, reject) {
jq.onInitialized.addListener(function() {
try {
resolve(jq.raw.apply(jq, args));
} catch (e) {
reject(e);
}
});
});
};
Loading