wit.ai quickstart.js error from node, unexpected token{ - wit.ai

I am going through the wit.ai quickstart tutorial and get an error from node (version 4.5.0 LTS), but I don't see the error in the code and also, it is the example code downloaded directly from wit.ai:
examples\quickstart.js:39
const {sessionId, context, entities} = request;
SyntaxError: Unexpected token {
at exports.runInThisContext (vm.js:53:16)
at Module._compile (module.js:373:25)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3
Also, the code in the download from git is different than the code shown on the tutorial page:
Code from the git clone, example/quickstart.js is this:
'use strict';
let Wit = null;
let interactive = null;
try {
// if running from repo
Wit = require('../').Wit;
interactive = require('../').interactive;
} catch (e) {
Wit = require('node-wit').Wit;
interactive = require('node-wit').interactive;
}
const accessToken = (() => {
if (process.argv.length !== 3) {
console.log('usage: node examples/quickstart.js <wit-access-token>');
process.exit(1);
}
return process.argv[2];
})();
// Quickstart example
// See https://wit.ai/ar7hur/quickstart
const firstEntityValue = (entities, entity) => {
const val = entities && entities[entity] &&
Array.isArray(entities[entity]) &&
entities[entity].length > 0 &&
entities[entity][0].value
;
if (!val) {
return null;
}
return typeof val === 'object' ? val.value : val;
};
const actions = {
send(request, response) {
const {sessionId, context, entities} = request;
const {text, quickreplies} = response;
console.log('sending...', JSON.stringify(response));
},
getForecast({context, entities}) {
var location = firstEntityValue(entities, 'location');
if (location) {
context.forecast = 'sunny in ' + location; // we should call a weather API here
delete context.missingLocation;
} else {
context.missingLocation = true;
delete context.forecast;
}
return context;
},
};
const client = new Wit({accessToken, actions});
interactive(client);
but the tutorial says the const actions section should be this:
const actions = {
send(request, response) {
const {sessionId, context, entities} = request;
const {text, quickreplies} = response;
return new Promise(function(resolve, reject) {
console.log('sending...', JSON.stringify(response));
return resolve();
});
},
getForecast({context, entities}) {
return new Promise(function(resolve, reject) {
// Here should go the api call, e.g.:
// context.forecast = apiCall(context.loc)
context.forecast = 'sunny';
return resolve(context);
});
},
};
Regardless, both versions give the same error.

Turns out that, due to some ECMAScript 6 features in the code, if your node version <= 6.x.x, you have to add the flag harmony_destructuring to the node command line, as illustrated here:
node --harmony_destructuring examples/quickstart.js

Related

Problems with deploying first smart contracts

Good day everyone!
I'm trying to deploy the first smart contracts according to the helloWorld manuals, but I'm getting an error please see the snippet. Tell me, please, what can be done about this? Tried lot of way to fix it but failed.
Thanks in advance!
import { Command } from ""commander"";
import prompts, { PromptObject } from ""prompts"";
import { isNumeric, Migration } from ""./utils"";
const program = new Command();
const migration = new Migration();
async function main() {
const promptsData: PromptObject[] = [];
program
.allowUnknownOption()
.option(""-kn, --key_number <key_number>"", ""Public key number"")
.option(
""-b, --balance <balance>"",
""Initial balance in EVERs (will send from Giver)"",
);
program.parse(process.argv);
const options = program.opts();
if (!options.key_number) {
promptsData.push({
type: ""text"",
name: ""keyNumber"",
message: ""Public key number"",
validate: value => (isNumeric(value) ? true : ""Invalid number""),
});
}
if (!options.balance) {
promptsData.push({
type: ""text"",
name: ""balance"",
message: ""Initial balance (will send from Giver)"",
validate: value => (isNumeric(value) ? true : ""Invalid number""),
});
}
const response = await prompts(promptsData);
const keyNumber = +(options.key_number || response.keyNumber);
const balance = +(options.balance || response.balance);
const signer = (await locklift.keystore.getSigner(keyNumber.toString()))!;
let accountsFactory = locklift.factory.getAccountsFactory(""Account"");
const { account: Account } = await accountsFactory.deployNewAccount({
publicKey: signer.publicKey,
initParams: {
_randomNonce: locklift.utils.getRandomNonce(),
},
constructorParams: {},
value: locklift.utils.toNano(balance),
});
migration.store(Account, ""account"");
console.log(`Account deployed at: ${Account.address}`);
}
main()
.then(() => process.exit(0))
.catch(e => {
console.log(e);
process.exit(1);
});"
Crashes on an attempt to collect Account contract assembly artefacts
There is no such thing in the build folder!

Duplicate identifier 'alpha'.deno-ts(2300) Unexpected keyword or identifier

I am trying to use Alpha Vantage NPM package inside my Deno application. I tried to use SkyPack version of it. But it gives me the following error:
Duplicate identifier 'alpha'.deno-ts(2300)
Unexpected keyword or identifier.
This is the code I am using:
import alphavantageTs from 'https://cdn.skypack.dev/alphavantage-ts';
export class StockTimeSeries{
alpha = new alphavantageTs ("ASLDVIWXGEWFWNZG");
alpha.stocks.intraday("msft").then((data: any) => {
console.log(data);
});
alpha.stocks.batch(["msft", "aapl"]).then((data: any) => {
console.log(data);
});
alpha.forex.rate("btc", "usd").then((data: any) => {
console.log(data);
});
alpha.crypto.intraday("btc", "usd").then((data: any) => {
console.log(data);
});
alpha.technicals.sma("msft", "daily", 60, "close").then((data: any) => {
console.log(data);
});
alpha.sectors.performance().then((data: any) => {
console.log(data);
});
}
It looks like SkyPack is responding with a 401 for one of the sub-dependencies for that module. I'm also not even sure it's compatible with Deno.
That said, here's the repo source for the module, and here's the documentation for the API. It looks like it's just a simple REST API which discriminates requests by query parameters, so you can make your own Deno client without too much effort using that module as a template. I'll give you some starter code:
TS Playground
export type Params = NonNullable<ConstructorParameters<typeof URLSearchParams>[0]>;
class AlphaVantageNS { constructor (protected readonly api: AlaphaVantage) {} }
class Forex extends AlphaVantageNS {
rate (from_currency: string, to_currency: string) {
return this.api.query({
function: 'CURRENCY_EXCHANGE_RATE',
from_currency,
to_currency,
});
}
}
export class AlaphaVantage {
#token: string;
constructor (token: string) {
this.#token = token;
}
async query <Result = any>(params: Params): Promise<Result> {
const url = new URL('https://www.alphavantage.co/query');
const usp = new URLSearchParams(params);
usp.set('apikey', this.#token);
url.search = usp.toString();
const request = new Request(url.href);
const response = await fetch(request);
if (!response.ok) throw new Error('Response not OK');
return response.json();
}
forex = new Forex(this);
}
// Use:
const YOUR_API_KEY = 'demo';
const alpha = new AlaphaVantage(YOUR_API_KEY);
alpha.forex.rate('BTC', 'USD').then(data => console.log(data));

How to parse serverless.yml file in script

I need to read the serverless.yml config for use in some test mocks.
The following worked until a recent change:
const serverless = new Serverless()
await serverless.init()
const service = await serverless.variables.populateService()
How does one read the file now? There is an astounding lack of documentation in regards to using serverless progamically.
Well I ended up taking some code from the AppSync emulator package. I am not sure it covers it does a full parsing but it does the job for me.
import Serverless from 'serverless'
import path from 'path'
import fs from 'fs'
class ConfigServerless extends Serverless {
async getConfig(servicePath) {
this.processedInput = {
commands: [],
options: { stage: 'dev' }
}
this.config.servicePath = servicePath
this.pluginManager.setCliOptions(this.processedInput.options)
this.pluginManager.setCliCommands(this.processedInput.commands)
await this.service.load(this.processedInput)
this.pluginManager.validateCommand(this.processedInput.commands)
return this.variables
.populateService(this.pluginManager.cliOptions)
.then(() => {
this.service.mergeArrays()
this.service.setFunctionNames(this.processedInput.options)
this.service.validate()
})
}
}
const normalizeResources = config => {
if (!config.resources) {
return config.resources
}
if (!config.resources.Resources) {
return {}
}
if (!Array.isArray(config.resources.Resources)) {
return config.resources
}
const newResources = config.resources.Resources.reduce(
(sum, { Resources, Outputs = {} }) => ({
...sum,
...Resources,
Outputs: {
...(sum.Outputs || {}),
...Outputs
}
}),
{}
)
return {
Resources: newResources
}
}
export async function loadServerlessConfig(cwd = process.cwd()) {
const stat = fs.statSync(cwd)
if (!stat.isDirectory()) {
cwd = path.dirname(cwd)
}
const serverless = new ConfigServerless()
await serverless.getConfig(cwd)
const { service: config } = serverless
const { custom = {} } = config
const output = {
...config,
custom: {
...custom
},
resources: normalizeResources(config)
}
return output
}

undefined is not an object (evaluating '_effects.buffers.expanding')

I'm getting an error when tried to copy&paste this solution in my app.
undefined is not an object (evaluating 'effects.buffers.expanding')
My code is pretty similar:
export function* handleBleState() {
const {
bleConnections: { manager },
} = yield select()
const stateChannel = yield eventChannel((emit) => {
const subscription = manager.onStateChange((state) => {
emit(state)
}, true)
return () => {
subscription.remove()
}
}, buffers.expanding(1))
try {
for (;;) {
const newState = yield take(stateChannel)
const power = newState === 'PoweredOn'
yield put(BLEActions.updateBleState(power))
}
} finally {
if (yield cancelled()) {
stateChannel.close()
}
}
}
But what is more strange is that I have extracted code from the documentation of redux-saga and the error is similar.
I replaced part of the code with this:
const stateChannel = yield eventChannel((emitter) => {
const iv = setInterval(() => {
secs -= 1
if (secs > 0) {
emitter(secs)
} else {
// this causes the channel to close
emitter(END)
}
}, 1000)
// The subscriber must return an unsubscribe function
return () => {
clearInterval(iv)
}
})
And I get:
undefined is not a function (evaluating '(0, _effects.eventChannel)')
I'm using another version of redux-saga:
"redux-saga": "^1.0.2",
But I tried with the same version that he use
"redux-saga": "0.16.2"
And then the issue is another one:
console.error: "unchaught at root", "at root at takeLatest" at handleBleState etc, etc.
Any help will be welcome, thanks in advance.
PD:
"react": "16.6.1",
"react-native": "0.57.5",
"react-native-ble-plx": "^1.0.1",
the eventChannel is nor part of the effects but defined directly in the main module, see the relevant API doc. So if you're using ES6 import/export you import it with the following statement:
import { eventChannel } from 'redux-saga'
While the require equivalent should be:
const eventChannel = require('redux-saga').eventChannel

relay subscription onNext not triggered on react-native

I am a subscription setup but onNext is not getting triggered I am not sure why since this is my first time implementing subscription and docs was not much help with the issue.
Here are the code implementations:
import {
graphql,
requestSubscription
} from 'react-relay'
import environment from '../network';
const subscription = graphql`
subscription chatCreatedSubscription{
chatCreated{
id
initiate_time
update_time
support_id
category_id
email
name
}
}
`;
function chatCreated(callback) {
const variables = {};
requestSubscription(environment, {
subscription,
variables,
onNext: () => {
console.log("onNext");
callback()
},
updater: () => {
console.log("updater");
}
});
}
module.exports = chatCreated;
and here is my network for the subscription
import { Environment, Network, RecordSource, Store } from "relay-runtime";
import Expo from "expo";
import { SubscriptionClient } from "subscriptions-transport-ws";
import { WebSocketLink } from 'apollo-link-ws';
import { execute } from 'apollo-link';
import accessHelper from "../helper/accessToken";
const networkSubscriptions = async (operation, variables) => {
let token = await accessHelper();
if (token != null || token != undefined) {
const subscriptionClient = new SubscriptionClient("ws://localhost:3000/graphql",
{
reconnect: true,
connectionParams: {
Authorization: token,
},
});
execute(new WebSocketLink(subscriptionClient), {
query: operation.text,
variables,
});
}
}
const network = Network.create(fetchQuery, networkSubscriptions);
const store = new Store(new RecordSource());
const environment = new Environment({
network,
store
});
export default environment;
the subscription is called in a componentDidMount method on a component it executes but the onNext method inside the subscription is never triggered when new information is added to what the subscription is listening to.
so i figured out that my issue was the network js not being setup properly and the version of subscription-transport-ws. i added version 0.8.3 of the package and made the following changes to my network file:
const networkSubscriptions = async (config, variables, cacheConfig, observer) => {
const query = config.text;
let token = await accessHelper();
if (token != null || token != undefined) {
const subscriptionClient = new SubscriptionClient(`ws://${api}/graphql`,
{
reconnect: true,
connectionParams: {
Authorization: token,
},
});
subscriptionClient.subscribe({ query, variables }, (error, result) => {
observer.onNext({ data: result })
})
return {
dispose: subscriptionClient.unsubscribe
};
}
}
i hope this helps you if you get stuck with the same issue as mine.