├── demo ├── typescript-project │ ├── .gitignore │ ├── tsconfig.json │ ├── README.md │ ├── deploy │ │ └── index.html │ ├── src │ │ ├── index.ts │ │ └── Application.ts │ ├── package.json │ └── webpack.config.js └── simple │ ├── demoFunctions.js │ ├── index.html │ └── layout.js ├── .npmignore ├── .gitignore ├── tslint.json ├── tsconfig.json ├── tsconfig.es6.json ├── index.js ├── index.ts ├── es6 ├── Request │ ├── EventRequest.js │ ├── TextRequest.js │ └── Request.js ├── Errors.js ├── Interfaces.js ├── ApiAiConstants.js ├── ApiAiClient.js └── XhrRequest.js ├── ts ├── Request │ ├── EventRequest.ts │ ├── TextRequest.ts │ ├── ContextsRequest.ts │ ├── LocalTTSRequest.ts │ ├── VoiceRequest.ts │ ├── UserEntitiesRequest.ts │ ├── Request.ts │ └── TTSRequest.ts ├── Utils.ts ├── Models │ └── Entity.ts ├── ApiAiConstants.ts ├── Errors.ts ├── Interfaces.ts ├── ApiAiClient.ts └── XhrRequest.ts ├── spec ├── Utils.spec.ts ├── api.spec.ts └── Client.spec.ts ├── CONTRIBUTING.md ├── package.json ├── karma.conf.js ├── declarations.d.ts ├── webpack.config.js ├── README.md ├── target ├── ApiAi.min.js ├── ApiAi.streamless.min.js ├── ApiAi.js └── ApiAi.streamless.js └── LICENSE /demo/typescript-project/.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | deploy/*.js -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | demo 2 | spec 3 | target 4 | karma.conf.js 5 | tsconfig.es6src.json 6 | tsconfig.json 7 | tslint.json 8 | webpack.config.js -------------------------------------------------------------------------------- /demo/typescript-project/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES5", 4 | "moduleResolution": "node", 5 | "typeRoots": ["./node_modules/@types"] 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .vscode 3 | api-ai-javascript.iml 4 | npm-debug.log 5 | node_modules 6 | target/ApiAi.js.map 7 | target/ApiAi.min.js.map 8 | target/ApiAi.streamless.js.map 9 | target/ApiAi.commonjs2.js.map 10 | .DS_Store 11 | demo/.DS_Store -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:latest", 3 | "rules": { 4 | "max-classes-per-file": 0, 5 | "object-literal-sort-keys": false, 6 | "no-namespace": false, 7 | "trailing-comma": false, 8 | "no-console": false 9 | } 10 | } -------------------------------------------------------------------------------- /demo/typescript-project/README.md: -------------------------------------------------------------------------------- 1 | This is the sample typescript setup with usage of api-ai-javascript library inside. 2 | 3 | Installation: 4 | 5 | `$ npm install` 6 | 7 | Running (webpack-dev-server on localhost:8080 by default): 8 | 9 | `$ npm start` 10 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES5", 4 | "sourceMap": true, 5 | "typeRoots": ["node_modules/@types/"], 6 | "types": ["es6-promise", "mocha", "chai"] 7 | }, 8 | "files": [ 9 | "declarations.d.ts" 10 | ] 11 | } -------------------------------------------------------------------------------- /demo/typescript-project/deploy/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 |

Open dev-console to see logs

8 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /tsconfig.es6.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ES6", 4 | "outDir": "es6", 5 | "sourceMap": false, 6 | "typeRoots": ["node_modules/@types/"], 7 | "types": [], 8 | "declaration": false 9 | }, 10 | "files": [ 11 | "declarations.d.ts", 12 | "ts/ApiAiClient.ts" 13 | ] 14 | } -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export * from "./es6/ApiAiClient"; 18 | -------------------------------------------------------------------------------- /index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /// 18 | export * from "./ts/ApiAiClient"; 19 | -------------------------------------------------------------------------------- /es6/Request/EventRequest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Request from "./Request"; 18 | export class EventRequest extends Request { 19 | } 20 | -------------------------------------------------------------------------------- /es6/Request/TextRequest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Request from "./Request"; 18 | export default class TextRequest extends Request { 19 | } 20 | -------------------------------------------------------------------------------- /ts/Request/EventRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Request from "./Request"; 18 | export class EventRequest extends Request { 19 | 20 | } 21 | -------------------------------------------------------------------------------- /ts/Request/TextRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Request from "./Request"; 18 | export default class TextRequest extends Request { 19 | 20 | } 21 | -------------------------------------------------------------------------------- /ts/Request/ContextsRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Request from "./Request"; 18 | /** 19 | * @todo: implement 20 | */ 21 | 22 | export class ContextsRequest extends Request {} 23 | -------------------------------------------------------------------------------- /ts/Request/LocalTTSRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export class LocalTTSRequest { 18 | private isSupported() { 19 | return !!window.speechSynthesis; 20 | } 21 | private getLanguage() { 22 | 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /demo/typescript-project/src/index.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiEnabledApplication} from "./Application"; 18 | const app = new ApiAiEnabledApplication(); 19 | 20 | app.init("ACCESS_TOKEN"); 21 | 22 | 23 | window["app"] = app; 24 | -------------------------------------------------------------------------------- /demo/typescript-project/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-ai-javascript-typescript-demo-project", 3 | "version": "2.0.0-beta.20", 4 | "description": "Javascript SDK for https://api.ai/ typescript demo project", 5 | "devDependencies": { 6 | "@types/es6-promise": "0.0.32", 7 | "api-ai-javascript": "^2.0.0-beta.21", 8 | "awesome-typescript-loader": "^3.0.8", 9 | "typescript": "^2.2.1", 10 | "webpack": "^2.2.1", 11 | "webpack-dev-server": "^2.4.1" 12 | }, 13 | "scripts": { 14 | "build": "webpack", 15 | "start": "webpack-dev-server" 16 | }, 17 | "repository": { 18 | "type": "git", 19 | "url": "git+https://github.com/api-ai/api-ai-javascript.git" 20 | }, 21 | "author": "Eugeny Shingarev", 22 | "license": "Apache-2.0", 23 | "bugs": { 24 | "url": "https://github.com/api-ai/api-ai-javascript/issues" 25 | }, 26 | "homepage": "https://github.com/api-ai/api-ai-javascript#readme" 27 | } 28 | -------------------------------------------------------------------------------- /ts/Utils.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export default class ApiAiUtils { 18 | /** 19 | * make it in more appropriate way 20 | * @param object 21 | * @returns object 22 | */ 23 | public static cloneObject(object: T): T { 24 | return JSON.parse(JSON.stringify(object)); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /ts/Request/VoiceRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient} from "../ApiAiClient"; 18 | import {IRequestOptions} from "../Interfaces"; 19 | import Request from "./Request"; 20 | 21 | /** 22 | * @todo: implement 23 | */ 24 | 25 | class VoiceRequest extends Request { 26 | constructor(client: ApiAiClient, options: IRequestOptions = {}) { 27 | super(client, options); 28 | 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /demo/simple/demoFunctions.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | "use strict"; 18 | 19 | /** 20 | * All this stuff is moved into global namespace and separate files just to be 21 | * MAXIMUM clear and easy to understand 22 | */ 23 | 24 | var client; 25 | window.init = function(token) { 26 | client = new ApiAi.ApiAiClient({accessToken: token}); 27 | }; 28 | 29 | function sendText(text) { 30 | return client.textRequest(text); 31 | } 32 | -------------------------------------------------------------------------------- /spec/Utils.spec.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import Utils from "../ts/Utils"; 18 | const expect = chai.expect; 19 | 20 | describe("ApiAi.Utils", () => { 21 | describe("#cloneObject", () => { 22 | it ("should clone object", () => { 23 | let originalObject = {}; 24 | let clonedObject = Utils.cloneObject(originalObject); 25 | 26 | expect(originalObject).not.to.eq(clonedObject); 27 | expect(JSON.stringify(originalObject)).to.eq(JSON.stringify(clonedObject)); 28 | }); 29 | }); 30 | }); 31 | -------------------------------------------------------------------------------- /ts/Models/Entity.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export class Entity implements IEntity{ 18 | public name: string; 19 | public entires: Entity.Entry[]; 20 | } 21 | 22 | export namespace Entity { 23 | export class Entry implements IEntity.IEntry { 24 | public value: string; 25 | public synonyms: string[]; 26 | } 27 | } 28 | 29 | export interface IEntity { 30 | name: string; 31 | entires: IEntity.IEntry[]; 32 | } 33 | 34 | export namespace IEntity { 35 | export interface IEntry { 36 | value: string; 37 | synonyms: string[]; 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /es6/Errors.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export class ApiAiBaseError extends Error { 18 | constructor(message) { 19 | super(message); 20 | this.message = message; 21 | this.stack = new Error().stack; 22 | } 23 | } 24 | export class ApiAiClientConfigurationError extends ApiAiBaseError { 25 | constructor(message) { 26 | super(message); 27 | this.name = "ApiAiClientConfigurationError"; 28 | } 29 | } 30 | export class ApiAiRequestError extends ApiAiBaseError { 31 | constructor(message, code = null) { 32 | super(message); 33 | this.message = message; 34 | this.code = code; 35 | this.name = "ApiAiRequestError"; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /ts/ApiAiConstants.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export namespace ApiAiConstants { 18 | export enum AVAILABLE_LANGUAGES { 19 | EN = "en" as any, DE = "de" as any, ES = "es" as any, PT_BR = "pt-BR" as any, ZH_HK = "zh-HK" as any, 20 | ZH_CN = "zh-CN" as any, ZH_TW = "zh-TW" as any, NL = "nl" as any, FR = "fr" as any, IT = "it" as any, 21 | JA = "ja" as any, KO = "ko" as any, PT = "pt" as any, RU = "ru" as any, UK = "uk" as any 22 | } 23 | 24 | export const VERSION: string = "2.0.0-beta.20"; 25 | export const DEFAULT_BASE_URL: string = "https://api.api.ai/v1/"; 26 | export const DEFAULT_API_VERSION: string = "20150910"; 27 | export const DEFAULT_CLIENT_LANG: AVAILABLE_LANGUAGES = AVAILABLE_LANGUAGES.EN; 28 | } 29 | -------------------------------------------------------------------------------- /ts/Errors.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export abstract class ApiAiBaseError extends Error { 18 | 19 | public abstract name: string; 20 | public stack: string; 21 | constructor(public message: string) { 22 | super(message); 23 | this.stack = new Error().stack; 24 | } 25 | } 26 | 27 | export class ApiAiClientConfigurationError extends ApiAiBaseError { 28 | 29 | public name: string = "ApiAiClientConfigurationError"; 30 | 31 | constructor(message: string) { 32 | super(message); 33 | } 34 | } 35 | 36 | export class ApiAiRequestError extends ApiAiBaseError { 37 | 38 | public name: string = "ApiAiRequestError"; 39 | 40 | constructor(public message: string, public code: number = null) { 41 | super(message); 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /spec/api.spec.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient} from "../ts/ApiAiClient"; 18 | describe("API", () => { 19 | 20 | const client = new ApiAiClient({accessToken: "3485a96fb27744db83e78b8c4bc9e7b7"}); 21 | 22 | describe("Text Query", () => { 23 | it ("should return response", function (done) { 24 | this.timeout(5000); 25 | client.textRequest("Hello!").then((response) => { 26 | chai.expect(response.result.action).to.eq("greeting"); 27 | chai.expect(response.result.resolvedQuery).to.eq("Hello!"); 28 | done(); 29 | }); 30 | }); 31 | 32 | it("should respect UTF-8", function(done) { 33 | this.timeout(5000); 34 | client.textRequest("¿Cuál es la población de España?").then((response) => { 35 | chai.expect(response.result.resolvedQuery).to.eq("¿Cuál es la población de España?"); 36 | done(); 37 | }); 38 | }); 39 | }); 40 | 41 | }); 42 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # How to become a contributor and submit your own code 2 | 3 | ## Contributor License Agreements 4 | 5 | We'd love to accept your sample apps and patches! Before we can take them, we 6 | have to jump a couple of legal hurdles. 7 | 8 | Please fill out either the individual or corporate Contributor License Agreement 9 | (CLA). 10 | 11 | * If you are an individual writing original source code and you're sure you 12 | own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). 13 | * If you work for a company that wants to allow you to contribute your work, 14 | then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). 15 | 16 | Follow either of the two links above to access the appropriate CLA and 17 | instructions for how to sign and return it. Once we receive it, we'll be able to 18 | accept your pull requests. 19 | 20 | ## Contributing A Patch 21 | 22 | 1. Submit an issue describing your proposed change to the repo in question. 23 | 1. The repo owner will respond to your issue promptly. 24 | 1. If your proposed change is accepted, and you haven't already done so, sign a 25 | Contributor License Agreement (see details above). 26 | 1. Fork the desired repo, develop and test your code changes. 27 | 1. Ensure that your code adheres to the existing style in the sample to which 28 | you are contributing. Refer to the 29 | [Google Cloud Platform Samples Style Guide](https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the 30 | recommended coding standards for this organization. 31 | 1. Ensure that your code has an appropriate set of unit tests which all pass. 32 | 1. Submit a pull request. 33 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "api-ai-javascript", 3 | "version": "2.0.0-beta.21", 4 | "description": "Javascript SDK for https://api.ai/", 5 | "main": "index", 6 | "dependencies": { 7 | }, 8 | "devDependencies": { 9 | "@types/chai": "^3.4.35", 10 | "@types/es6-promise": "0.0.32", 11 | "@types/mocha": "^2.2.39", 12 | "awesome-typescript-loader": "^3.0.8", 13 | "babel-polyfill": "^6.23.0", 14 | "chai": "^3.5.0", 15 | "eslint": "^3.16.1", 16 | "eslint-config-google": "^0.7.1", 17 | "karma": "^1.5.0", 18 | "karma-chai": "^0.1.0", 19 | "karma-mocha": "^1.1.1", 20 | "karma-phantomjs-launcher": "^1.0.2", 21 | "karma-sinon": "^1.0.5", 22 | "karma-typescript-preprocessor2": "^1.2.1", 23 | "karma-webpack": "^2.0.2", 24 | "mocha": "^3.2.0", 25 | "mocha-phantomjs": "^4.1.0", 26 | "phantomjs-prebuilt": "^2.1.12", 27 | "rimraf": "^2.6.1", 28 | "sinon": "^1.17.3", 29 | "tslint": "^4.5.1", 30 | "typescript": "^2.3.2", 31 | "webpack": "^2.5.1", 32 | "webpack-dev-server": "^2.4.5" 33 | }, 34 | "scripts": { 35 | "start": "webpack-dev-server --port 8002", 36 | "build": "webpack && webpack --env.compress && rimraf ./es6 && tsc -p ./tsconfig.es6.json", 37 | "test": "karma start" 38 | }, 39 | "repository": { 40 | "type": "git", 41 | "url": "git+https://github.com/api-ai/api-ai-javascript.git" 42 | }, 43 | "keywords": [ 44 | "api.ai", 45 | "nlu", 46 | "nlp", 47 | "chatbots", 48 | "conversational", 49 | "UX" 50 | ], 51 | "author": "Eugeny Shingarev", 52 | "license": "Apache-2.0", 53 | "bugs": { 54 | "url": "https://github.com/api-ai/api-ai-javascript/issues" 55 | }, 56 | "homepage": "https://github.com/api-ai/api-ai-javascript#readme", 57 | "eslintConfig": { 58 | "extends": "google" 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | var webpackConfig = require('./webpack.config')({}); 18 | 19 | module.exports = function(config) { 20 | config.set({ 21 | basePath: '', 22 | frameworks: ['mocha', 'chai'], 23 | files: [ 24 | 'node_modules/babel-polyfill/dist/polyfill.js', 25 | 'spec/**/*.spec.ts', 26 | ], 27 | exclude: [], 28 | preprocessors: { 29 | 'spec/**/*.spec.ts': ['webpack'], 30 | }, 31 | webpack: { 32 | module: webpackConfig.module, 33 | resolve: webpackConfig.resolve, 34 | }, 35 | phantomjsLauncher: { 36 | // Have phantomjs exit if a ResourceError is encountered 37 | // (useful if karma exits without killing phantom) 38 | // exitOnResourceError: true, 39 | base: 'PhantomJS', 40 | flags: [ 41 | '--web-security=false', 42 | '--load-images=true', 43 | '--ignore-ssl-errors=yes', 44 | '--ssl-protocol=any', 45 | ], 46 | }, 47 | reporters: ['progress'], 48 | port: 9876, 49 | colors: true, 50 | logLevel: config.LOG_INFO, 51 | autoWatch: true, 52 | browsers: ['PhantomJS'], 53 | singleRun: false, 54 | concurrency: Infinity, 55 | }); 56 | }; 57 | -------------------------------------------------------------------------------- /demo/typescript-project/webpack.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | "use strict"; 18 | 19 | const webpack = require('webpack'); 20 | const path = require('path'); 21 | 22 | module.exports = { 23 | entry: [ 24 | path.join(__dirname, 'src', 'index.ts') 25 | ], 26 | output: { 27 | path: path.join(__dirname, 'deploy'), 28 | publicPath: "/deploy", 29 | filename: 'index.js' 30 | }, 31 | plugins: [ 32 | new webpack.LoaderOptionsPlugin({ 33 | minimize: true, 34 | debug: false 35 | }), 36 | new webpack.optimize.UglifyJsPlugin({ 37 | compress: { 38 | warnings: true 39 | }, 40 | output: { 41 | comments: false 42 | }, 43 | sourceMap: false 44 | }) 45 | ], 46 | module: { 47 | loaders: [ 48 | {test: /\.tsx?$/, loader: "awesome-typescript-loader"} 49 | ] 50 | }, 51 | resolve: { 52 | modules: [ 53 | 'node_modules', 54 | path.resolve(__dirname, 'app') 55 | ], 56 | extensions: ['.ts', '.js'] 57 | }, 58 | devServer: { 59 | port: 8000 60 | } 61 | }; 62 | -------------------------------------------------------------------------------- /demo/typescript-project/src/Application.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient, IStreamClient} from "api-ai-javascript/ApiAiClient"; 18 | import {ApiAiStreamClient} from "api-ai-javascript/ApiAiStreamClient"; 19 | 20 | export class ApiAiEnabledApplication { 21 | 22 | private static BUTTON_ID = "button"; 23 | 24 | private apiAiClient: ApiAiClient; 25 | private button: HTMLButtonElement; 26 | 27 | private isListening: boolean = false; 28 | 29 | public init(accessToken: string): ApiAiEnabledApplication { 30 | 31 | this.apiAiClient = new ApiAiClient({accessToken, streamClientClass: ApiAiStreamClient}); 32 | this.button = document.getElementById(ApiAiEnabledApplication.BUTTON_ID) as HTMLButtonElement; 33 | this.button.addEventListener("click", this.handleClick.bind(this)); 34 | return this; 35 | } 36 | 37 | private handleClick() { 38 | this.apiAiClient.textRequest("test").then((response) => { 39 | console.log(response); 40 | }); 41 | } 42 | 43 | private setIsListening(isListening: boolean) { 44 | this.isListening = isListening; 45 | this.button.innerText = (isListening) ? "Stop listening" : "Start listening"; 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /es6/Interfaces.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export var IStreamClient; 18 | (function (IStreamClient) { 19 | let ERROR; 20 | (function (ERROR) { 21 | ERROR[ERROR["ERR_NETWORK"] = 0] = "ERR_NETWORK"; 22 | ERROR[ERROR["ERR_AUDIO"] = 1] = "ERR_AUDIO"; 23 | ERROR[ERROR["ERR_SERVER"] = 2] = "ERR_SERVER"; 24 | ERROR[ERROR["ERR_CLIENT"] = 3] = "ERR_CLIENT"; 25 | })(ERROR = IStreamClient.ERROR || (IStreamClient.ERROR = {})); 26 | let EVENT; 27 | (function (EVENT) { 28 | EVENT[EVENT["MSG_WAITING_MICROPHONE"] = 0] = "MSG_WAITING_MICROPHONE"; 29 | EVENT[EVENT["MSG_MEDIA_STREAM_CREATED"] = 1] = "MSG_MEDIA_STREAM_CREATED"; 30 | EVENT[EVENT["MSG_INIT_RECORDER"] = 2] = "MSG_INIT_RECORDER"; 31 | EVENT[EVENT["MSG_RECORDING"] = 3] = "MSG_RECORDING"; 32 | EVENT[EVENT["MSG_SEND"] = 4] = "MSG_SEND"; 33 | EVENT[EVENT["MSG_SEND_EMPTY"] = 5] = "MSG_SEND_EMPTY"; 34 | EVENT[EVENT["MSG_SEND_EOS_OR_JSON"] = 6] = "MSG_SEND_EOS_OR_JSON"; 35 | EVENT[EVENT["MSG_WEB_SOCKET"] = 7] = "MSG_WEB_SOCKET"; 36 | EVENT[EVENT["MSG_WEB_SOCKET_OPEN"] = 8] = "MSG_WEB_SOCKET_OPEN"; 37 | EVENT[EVENT["MSG_WEB_SOCKET_CLOSE"] = 9] = "MSG_WEB_SOCKET_CLOSE"; 38 | EVENT[EVENT["MSG_STOP"] = 10] = "MSG_STOP"; 39 | EVENT[EVENT["MSG_CONFIG_CHANGED"] = 11] = "MSG_CONFIG_CHANGED"; 40 | })(EVENT = IStreamClient.EVENT || (IStreamClient.EVENT = {})); 41 | })(IStreamClient || (IStreamClient = {})); 42 | -------------------------------------------------------------------------------- /declarations.d.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | interface Navigator { 18 | Resampler: any; 19 | webkitGetUserMedia: any; 20 | mozGetUserMedia: any; 21 | } 22 | interface AudioContext { 23 | createResampleProcessor: Function; 24 | createEndOfSpeechProcessor: Function; 25 | } 26 | interface Window { 27 | webkitURL: any; 28 | } 29 | 30 | declare var webkitAudioContext: { 31 | new (): AudioContext; 32 | } 33 | 34 | declare var webkitOfflineAudioContext: { 35 | new (numberOfChannels: number, length: number, sampleRate: number): OfflineAudioContext; 36 | } 37 | 38 | interface AudioContextConstructor { 39 | new(): AudioContext; 40 | } 41 | 42 | interface Window { 43 | AudioContext: AudioContextConstructor; 44 | } 45 | 46 | interface AudioContext { 47 | createMediaStreamSource(stream: MediaStream): MediaStreamAudioSourceNode; 48 | } 49 | 50 | interface MediaStreamAudioSourceNode extends AudioNode { 51 | 52 | } 53 | 54 | interface MediaStreamAudioDestinationNode extends AudioNode { 55 | stream: MediaStream; 56 | } 57 | 58 | interface AudioBuffer { 59 | copyFromChannel(destination: Float32Array, channelNumber: number, startInChannel?: number): void; 60 | 61 | copyToChannel(source: Float32Array, channelNumber: number, startInChannel?: number): void; 62 | } 63 | 64 | interface AudioNode { 65 | disconnect(destination: AudioNode): void; 66 | } 67 | 68 | interface AudioContext { 69 | suspend(): Promise; 70 | resume(): Promise; 71 | close(): Promise; 72 | createMediaStreamDestination(): MediaStreamAudioDestinationNode; 73 | } 74 | -------------------------------------------------------------------------------- /es6/ApiAiConstants.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | export var ApiAiConstants; 18 | (function (ApiAiConstants) { 19 | let AVAILABLE_LANGUAGES; 20 | (function (AVAILABLE_LANGUAGES) { 21 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["EN"] = "en"] = "EN"; 22 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["DE"] = "de"] = "DE"; 23 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ES"] = "es"] = "ES"; 24 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["PT_BR"] = "pt-BR"] = "PT_BR"; 25 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_HK"] = "zh-HK"] = "ZH_HK"; 26 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_CN"] = "zh-CN"] = "ZH_CN"; 27 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_TW"] = "zh-TW"] = "ZH_TW"; 28 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["NL"] = "nl"] = "NL"; 29 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["FR"] = "fr"] = "FR"; 30 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["IT"] = "it"] = "IT"; 31 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["JA"] = "ja"] = "JA"; 32 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["KO"] = "ko"] = "KO"; 33 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["PT"] = "pt"] = "PT"; 34 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["RU"] = "ru"] = "RU"; 35 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["UK"] = "uk"] = "UK"; 36 | })(AVAILABLE_LANGUAGES = ApiAiConstants.AVAILABLE_LANGUAGES || (ApiAiConstants.AVAILABLE_LANGUAGES = {})); 37 | ApiAiConstants.VERSION = "2.0.0-beta.20"; 38 | ApiAiConstants.DEFAULT_BASE_URL = "https://api.api.ai/v1/"; 39 | ApiAiConstants.DEFAULT_API_VERSION = "20150910"; 40 | ApiAiConstants.DEFAULT_CLIENT_LANG = AVAILABLE_LANGUAGES.EN; 41 | })(ApiAiConstants || (ApiAiConstants = {})); 42 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | "use strict"; 18 | 19 | const webpack = require('webpack'); 20 | const path = require('path'); 21 | 22 | let libraryName = 'ApiAi'; 23 | let libraryTarget = 'var'; 24 | let outputFile = libraryName; 25 | let sourceMaps = true; 26 | let plugins = []; 27 | let entry = "ApiAiClient.ts"; 28 | 29 | module.exports = function(env) { 30 | if (!env) { 31 | env = {}; 32 | } 33 | 34 | // handle minification 35 | if (env && env.compress) { 36 | plugins.push( 37 | new webpack.LoaderOptionsPlugin({ 38 | minimize: true, 39 | debug: false 40 | }) 41 | ); 42 | 43 | plugins.push( 44 | new webpack.optimize.UglifyJsPlugin({ 45 | compress: { 46 | warnings: true, 47 | keep_fnames: true 48 | }, 49 | mangle: { 50 | keep_fnames: true 51 | } 52 | }) 53 | ); 54 | outputFile += '.min'; 55 | sourceMaps = false; 56 | } else { 57 | // outputFile += libraryName; 58 | } 59 | 60 | // handle custom target 61 | if (env && env.target) { 62 | libraryTarget = env.target; 63 | outputFile += '.' + libraryTarget; 64 | } 65 | 66 | outputFile += '.js'; 67 | 68 | return { 69 | entry: [ 70 | path.join(__dirname, 'ts', entry) 71 | ], 72 | devtool: sourceMaps ? 'source-map' : false, 73 | output: { 74 | path: path.join(__dirname, 'target'), 75 | publicPath: "/target/", 76 | filename: outputFile, 77 | library: libraryName, 78 | libraryTarget: libraryTarget 79 | }, 80 | 81 | module: { 82 | loaders: [ 83 | {test: /\.tsx?$/, loader: "awesome-typescript-loader"} 84 | ] 85 | }, 86 | resolve: { 87 | extensions: ['.js', '.ts'] 88 | }, 89 | plugins: plugins 90 | }; 91 | }; 92 | -------------------------------------------------------------------------------- /es6/Request/Request.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { ApiAiRequestError } from "../Errors"; 18 | import XhrRequest from "../XhrRequest"; 19 | class Request { 20 | constructor(apiAiClient, options) { 21 | this.apiAiClient = apiAiClient; 22 | this.options = options; 23 | this.uri = this.apiAiClient.getApiBaseUrl() + "query?v=" + this.apiAiClient.getApiVersion(); 24 | this.requestMethod = XhrRequest.Method.POST; 25 | this.headers = { 26 | Authorization: "Bearer " + this.apiAiClient.getAccessToken(), 27 | }; 28 | this.options.lang = this.apiAiClient.getApiLang(); 29 | this.options.sessionId = this.apiAiClient.getSessionId(); 30 | } 31 | static handleSuccess(xhr) { 32 | return Promise.resolve(JSON.parse(xhr.responseText)); 33 | } 34 | static handleError(xhr) { 35 | let error = new ApiAiRequestError(null); 36 | try { 37 | const serverResponse = JSON.parse(xhr.responseText); 38 | if (serverResponse.status && serverResponse.status.errorDetails) { 39 | error = new ApiAiRequestError(serverResponse.status.errorDetails, serverResponse.status.code); 40 | } 41 | else { 42 | error = new ApiAiRequestError(xhr.statusText, xhr.status); 43 | } 44 | } 45 | catch (e) { 46 | error = new ApiAiRequestError(xhr.statusText, xhr.status); 47 | } 48 | return Promise.reject(error); 49 | } 50 | perform(overrideOptions = null) { 51 | const options = overrideOptions ? overrideOptions : this.options; 52 | return XhrRequest.ajax(this.requestMethod, this.uri, options, this.headers) 53 | .then(Request.handleSuccess.bind(this)) 54 | .catch(Request.handleError.bind(this)); 55 | } 56 | } 57 | export default Request; 58 | -------------------------------------------------------------------------------- /demo/simple/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | Title 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 26 | 27 | 28 |
29 |
30 |
Configure demo:
31 |
32 |
33 |
34 | 35 | 36 |
37 |
38 | Set 39 |
40 |
41 |
42 |
43 |
Please, fill access token before start
44 |
45 |
46 |
47 |
48 |
49 |
50 | 51 |
52 |
53 | 55 |
56 |
57 |
58 |
59 | 61 |
Response payload:
62 |

63 |             
64 |
65 |
66 |
67 | 68 | 69 | 70 | 71 | -------------------------------------------------------------------------------- /spec/Client.spec.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient} from "../ts/ApiAiClient"; 18 | import {ApiAiConstants} from "../ts/ApiAiConstants"; 19 | 20 | const ACCESS_TOKEN = "AT"; 21 | const expect = chai.expect; 22 | 23 | describe("ApiAi.Client", () => { 24 | 25 | const client = new ApiAiClient({accessToken: ACCESS_TOKEN}); 26 | 27 | it("should instantinates", () => { 28 | expect(client instanceof ApiAiClient).to.be.true; 29 | }); 30 | 31 | it("sould fail without access token", () => { 32 | expect(() => new ApiAiClient({accessToken: undefined})).to.throw( 33 | "Access token is required for new ApiAi.Client instance" 34 | ); 35 | }); 36 | 37 | it("sould create session id in case it was not provided", () => { 38 | expect(typeof client.getSessionId() === "string").to.be.true; 39 | }); 40 | 41 | it("should use valid credentials", () => { 42 | expect(client.getApiLang()).to.eq(ApiAiConstants.DEFAULT_CLIENT_LANG); 43 | expect(client.getApiVersion()).to.eq(ApiAiConstants.DEFAULT_API_VERSION); 44 | expect(client.getApiBaseUrl()).to.eq(ApiAiConstants.DEFAULT_BASE_URL); 45 | expect(client.getAccessToken()).to.eq(ACCESS_TOKEN); 46 | }); 47 | 48 | it("should use valid setted credentilas", () => { 49 | const version = "2"; 50 | const baseUrl = "3"; 51 | const sessionId = "test"; 52 | const innerClient = new ApiAiClient({ 53 | accessToken: ACCESS_TOKEN, 54 | lang: ApiAiConstants.AVAILABLE_LANGUAGES.DE, 55 | baseUrl, 56 | sessionId, 57 | version 58 | }); 59 | 60 | expect(innerClient.getApiLang()).to.eq(ApiAiConstants.AVAILABLE_LANGUAGES.DE); 61 | expect(innerClient.getApiVersion()).to.eq(version); 62 | expect(innerClient.getApiBaseUrl()).to.eq(baseUrl); 63 | expect(innerClient.getAccessToken()).to.eq(ACCESS_TOKEN); 64 | expect(innerClient.getSessionId()).to.eq(sessionId); 65 | }); 66 | }); 67 | -------------------------------------------------------------------------------- /ts/Request/UserEntitiesRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient} from "../ApiAiClient"; 18 | import {IRequestOptions} from "../Interfaces"; 19 | import {IEntity} from "../Models/Entity"; 20 | import ApiAiUtils from "../Utils"; 21 | import XhrRequest from "../XhrRequest"; 22 | import Request from "./Request"; 23 | 24 | export class UserEntitiesRequest extends Request { 25 | 26 | private static ENDPOINT: string = "userEntities"; 27 | private baseUri: string; 28 | 29 | constructor(apiAiClient: ApiAiClient, protected options: IUserEntitiesRequestOptions = {}) { 30 | super(apiAiClient, options); 31 | this.baseUri = this.apiAiClient.getApiBaseUrl() + UserEntitiesRequest.ENDPOINT; 32 | } 33 | 34 | public create(entities: IEntity[]|IEntity) { 35 | this.uri = this.baseUri; 36 | const options = ApiAiUtils.cloneObject(this.options); 37 | options.entities = Array.isArray(entities) ? entities : [entities]; 38 | return this.perform(options); 39 | } 40 | 41 | public retrieve(name: string) { 42 | this.uri = this.baseUri + "/" + name; 43 | this.requestMethod = XhrRequest.Method.GET; 44 | return this.perform(); 45 | } 46 | 47 | public update(name: string, entries: IEntity.IEntry[], extend: boolean = false) { 48 | this.uri = this.baseUri + "/" + name; 49 | this.requestMethod = XhrRequest.Method.PUT; 50 | const options = ApiAiUtils.cloneObject(this.options); 51 | options.extend = extend; 52 | options.entries = entries; 53 | options.name = name; 54 | return this.perform(options); 55 | } 56 | 57 | public delete(name: string) { 58 | this.uri = this.baseUri + "/" + name; 59 | this.requestMethod = XhrRequest.Method.DELETE; 60 | return this.perform(); 61 | } 62 | } 63 | 64 | interface IUserEntitiesRequestOptions extends IRequestOptions { 65 | extend?: boolean; 66 | name?: string; 67 | entities?: IEntity[]; 68 | entries?: IEntity.IEntry[]; 69 | } 70 | -------------------------------------------------------------------------------- /ts/Request/Request.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient} from "../ApiAiClient"; 18 | import {ApiAiRequestError} from "../Errors"; 19 | import {IRequestOptions, IServerResponse, IStringMap} from "../Interfaces"; 20 | import XhrRequest from "../XhrRequest"; 21 | 22 | abstract class Request { 23 | 24 | private static handleSuccess(xhr: XMLHttpRequest): Promise { 25 | return Promise.resolve(JSON.parse(xhr.responseText)); 26 | } 27 | 28 | private static handleError(xhr: XMLHttpRequest): Promise { 29 | 30 | let error = new ApiAiRequestError(null); 31 | try { 32 | const serverResponse: IServerResponse = JSON.parse(xhr.responseText); 33 | if (serverResponse.status && serverResponse.status.errorDetails) { 34 | error = new ApiAiRequestError(serverResponse.status.errorDetails, serverResponse.status.code); 35 | } else { 36 | error = new ApiAiRequestError(xhr.statusText, xhr.status); 37 | } 38 | } catch (e) { 39 | error = new ApiAiRequestError(xhr.statusText, xhr.status); 40 | } 41 | 42 | return Promise.reject(error); 43 | } 44 | 45 | protected uri; 46 | protected requestMethod; 47 | protected headers; 48 | 49 | constructor(protected apiAiClient: ApiAiClient, protected options: IRequestOptions) { 50 | 51 | this.uri = this.apiAiClient.getApiBaseUrl() + "query?v=" + this.apiAiClient.getApiVersion(); 52 | this.requestMethod = XhrRequest.Method.POST; 53 | this.headers = { 54 | Authorization: "Bearer " + this.apiAiClient.getAccessToken(), 55 | }; 56 | 57 | this.options.lang = this.apiAiClient.getApiLang(); 58 | this.options.sessionId = this.apiAiClient.getSessionId(); 59 | 60 | } 61 | 62 | public perform(overrideOptions = null): Promise { 63 | 64 | const options = overrideOptions ? overrideOptions : this.options; 65 | 66 | return XhrRequest.ajax(this.requestMethod, this.uri, options as IStringMap, this.headers) 67 | .then(Request.handleSuccess.bind(this)) 68 | .catch(Request.handleError.bind(this)); 69 | } 70 | } 71 | 72 | export default Request; 73 | -------------------------------------------------------------------------------- /demo/simple/layout.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | (function() { 18 | "use strict"; 19 | 20 | var ENTER_KEY_CODE = 13; 21 | var queryInput, resultDiv, accessTokenInput; 22 | 23 | window.onload = init; 24 | 25 | function init() { 26 | queryInput = document.getElementById("q"); 27 | resultDiv = document.getElementById("result"); 28 | accessTokenInput = document.getElementById("access_token"); 29 | var setAccessTokenButton = document.getElementById("set_access_token"); 30 | 31 | queryInput.addEventListener("keydown", queryInputKeyDown); 32 | setAccessTokenButton.addEventListener("click", setAccessToken); 33 | } 34 | 35 | function setAccessToken() { 36 | document.getElementById("placeholder").style.display = "none"; 37 | document.getElementById("main-wrapper").style.display = "block"; 38 | window.init(accessTokenInput.value); 39 | } 40 | 41 | function queryInputKeyDown(event) { 42 | if (event.which !== ENTER_KEY_CODE) { 43 | return; 44 | } 45 | 46 | var value = queryInput.value; 47 | queryInput.value = ""; 48 | 49 | createQueryNode(value); 50 | var responseNode = createResponseNode(); 51 | 52 | sendText(value) 53 | .then(function(response) { 54 | var result; 55 | try { 56 | result = response.result.fulfillment.speech 57 | } catch(error) { 58 | result = ""; 59 | } 60 | setResponseJSON(response); 61 | setResponseOnNode(result, responseNode); 62 | }) 63 | .catch(function(err) { 64 | setResponseJSON(err); 65 | setResponseOnNode("Something goes wrong", responseNode); 66 | }); 67 | } 68 | 69 | function createQueryNode(query) { 70 | var node = document.createElement('div'); 71 | node.className = "clearfix left-align left card-panel green accent-1"; 72 | node.innerHTML = query; 73 | resultDiv.appendChild(node); 74 | } 75 | 76 | function createResponseNode() { 77 | var node = document.createElement('div'); 78 | node.className = "clearfix right-align right card-panel blue-text text-darken-2 hoverable"; 79 | node.innerHTML = "..."; 80 | resultDiv.appendChild(node); 81 | return node; 82 | } 83 | 84 | function setResponseOnNode(response, node) { 85 | node.innerHTML = response ? response : "[empty response]"; 86 | node.setAttribute('data-actual-response', response); 87 | } 88 | 89 | function setResponseJSON(response) { 90 | var node = document.getElementById("jsonResponse"); 91 | node.innerHTML = JSON.stringify(response, null, 2); 92 | } 93 | 94 | function sendRequest() { 95 | 96 | } 97 | 98 | })(); 99 | -------------------------------------------------------------------------------- /ts/Interfaces.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiConstants} from "./ApiAiConstants"; 18 | 19 | export interface IRequestOptions { 20 | query?: string; 21 | event?: {name: string, data?: IStringMap}; 22 | sessionId?: string; 23 | lang?: ApiAiConstants.AVAILABLE_LANGUAGES; 24 | originalRequest?: {source: string, data?: IStringMap}; 25 | } 26 | 27 | export interface IServerResponse { 28 | id?: string; 29 | result?: { 30 | action: string, 31 | resolvedQuery: string, 32 | speech: string; 33 | fulfillment?: { 34 | speech: string 35 | } 36 | }; 37 | status: { 38 | code: number, 39 | errorDetails?: string, 40 | errorID?: string, 41 | errorType: string 42 | }; 43 | } 44 | 45 | export interface IStringMap { [s: string]: string; } 46 | 47 | export interface IApiClientOptions { 48 | lang?: ApiAiConstants.AVAILABLE_LANGUAGES; 49 | version?: string; 50 | baseUrl?: string; 51 | sessionId?: string; 52 | streamClientClass?: IStreamClientConstructor; 53 | accessToken: string; 54 | } 55 | 56 | export interface IStreamClientConstructor { 57 | new (options: IStreamClientOptions): IStreamClient; 58 | } 59 | 60 | export interface IStreamClient { 61 | init(): void; 62 | open(): void; 63 | close(): void; 64 | startListening(): void; 65 | stopListening(): void; 66 | } 67 | 68 | export interface IStreamClientOptions { 69 | server?: string; 70 | token?: string; 71 | sessionId?: string; 72 | lang?: ApiAiConstants.AVAILABLE_LANGUAGES; 73 | contentType?: string; 74 | readingInterval?: string; 75 | onOpen?: () => void; 76 | onClose?: () => void; 77 | onInit?: () => void; 78 | onStartListening?: () => void; 79 | onStopListening?: () => void; 80 | onResults?: (data: IServerResponse) => void; 81 | onEvent?: (eventCode: IStreamClient.EVENT, message: string) => void; 82 | onError?: (errorCode: IStreamClient.ERROR, message: string) => void; 83 | } 84 | 85 | export namespace IStreamClient { 86 | export enum ERROR { 87 | ERR_NETWORK, 88 | ERR_AUDIO, 89 | ERR_SERVER, 90 | ERR_CLIENT 91 | } 92 | export enum EVENT { 93 | MSG_WAITING_MICROPHONE, 94 | MSG_MEDIA_STREAM_CREATED, 95 | MSG_INIT_RECORDER, 96 | MSG_RECORDING, 97 | MSG_SEND, 98 | MSG_SEND_EMPTY, 99 | MSG_SEND_EOS_OR_JSON, 100 | MSG_WEB_SOCKET, 101 | MSG_WEB_SOCKET_OPEN, 102 | MSG_WEB_SOCKET_CLOSE, 103 | MSG_STOP, 104 | MSG_CONFIG_CHANGED 105 | } 106 | } 107 | -------------------------------------------------------------------------------- /es6/ApiAiClient.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { ApiAiConstants } from "./ApiAiConstants"; 18 | import { ApiAiClientConfigurationError } from "./Errors"; 19 | import { EventRequest } from "./Request/EventRequest"; 20 | import TextRequest from "./Request/TextRequest"; 21 | export * from "./Interfaces"; 22 | export { ApiAiConstants } from "./ApiAiConstants"; 23 | export class ApiAiClient { 24 | constructor(options) { 25 | if (!options || !options.accessToken) { 26 | throw new ApiAiClientConfigurationError("Access token is required for new ApiAi.Client instance"); 27 | } 28 | this.accessToken = options.accessToken; 29 | this.apiLang = options.lang || ApiAiConstants.DEFAULT_CLIENT_LANG; 30 | this.apiVersion = options.version || ApiAiConstants.DEFAULT_API_VERSION; 31 | this.apiBaseUrl = options.baseUrl || ApiAiConstants.DEFAULT_BASE_URL; 32 | this.sessionId = options.sessionId || this.guid(); 33 | } 34 | textRequest(query, options = {}) { 35 | if (!query) { 36 | throw new ApiAiClientConfigurationError("Query should not be empty"); 37 | } 38 | options.query = query; 39 | return new TextRequest(this, options).perform(); 40 | } 41 | eventRequest(eventName, eventData = {}, options = {}) { 42 | if (!eventName) { 43 | throw new ApiAiClientConfigurationError("Event name can not be empty"); 44 | } 45 | options.event = { name: eventName, data: eventData }; 46 | return new EventRequest(this, options).perform(); 47 | } 48 | // @todo: implement local tts request 49 | /*public ttsRequest(query) { 50 | if (!query) { 51 | throw new ApiAiClientConfigurationError("Query should not be empty"); 52 | } 53 | return new TTSRequest(this).makeTTSRequest(query); 54 | }*/ 55 | /*public userEntitiesRequest(options: IRequestOptions = {}): UserEntitiesRequest { 56 | return new UserEntitiesRequest(this, options); 57 | }*/ 58 | getAccessToken() { 59 | return this.accessToken; 60 | } 61 | getApiVersion() { 62 | return (this.apiVersion) ? this.apiVersion : ApiAiConstants.DEFAULT_API_VERSION; 63 | } 64 | getApiLang() { 65 | return (this.apiLang) ? this.apiLang : ApiAiConstants.DEFAULT_CLIENT_LANG; 66 | } 67 | getApiBaseUrl() { 68 | return (this.apiBaseUrl) ? this.apiBaseUrl : ApiAiConstants.DEFAULT_BASE_URL; 69 | } 70 | setSessionId(sessionId) { 71 | this.sessionId = sessionId; 72 | } 73 | getSessionId() { 74 | return this.sessionId; 75 | } 76 | /** 77 | * generates new random UUID 78 | * @returns {string} 79 | */ 80 | guid() { 81 | const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); 82 | return s4() + s4() + "-" + s4() + "-" + s4() + "-" + 83 | s4() + "-" + s4() + s4() + s4(); 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /ts/Request/TTSRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {ApiAiClient} from "../ApiAiClient"; 18 | import {ApiAiConstants} from "../ApiAiConstants"; 19 | import {ApiAiClientConfigurationError, ApiAiRequestError} from "../Errors"; 20 | import {IRequestOptions} from "../Interfaces"; 21 | import XhrRequest from "../XhrRequest"; 22 | import Request from "./Request"; 23 | 24 | export class TTSRequest extends Request { 25 | 26 | private static RESPONSE_TYPE_ARRAYBUFFER = "arraybuffer"; 27 | 28 | private static audioContext: AudioContext; 29 | 30 | constructor(protected apiAiClient: ApiAiClient, options: IRequestOptions = {}) { 31 | super(apiAiClient, options); 32 | // this.requestMethod = XhrRequest.Method.GET; 33 | this.uri = ApiAiConstants.DEFAULT_TTS_HOST; 34 | const AudioContext = window.AudioContext || webkitAudioContext; 35 | 36 | if (!TTSRequest.audioContext) { 37 | TTSRequest.audioContext = new AudioContext(); 38 | } 39 | } 40 | 41 | public makeTTSRequest(text: string) { 42 | 43 | if (!text) { 44 | throw new ApiAiClientConfigurationError("Request can not be empty"); 45 | } 46 | 47 | const params = { 48 | lang: "en-US", // this.apiAiClient.getApiLang(), 49 | text: encodeURIComponent(text), 50 | v: this.apiAiClient.getApiVersion() 51 | }; 52 | 53 | const headers = { 54 | "Accept-language": "en-US", 55 | "Authorization": "Bearer " + this.apiAiClient.getAccessToken() 56 | }; 57 | 58 | return this.makeRequest(this.uri, params, headers, {responseType: TTSRequest.RESPONSE_TYPE_ARRAYBUFFER}) 59 | .then(this.resolveTTSPromise) 60 | .catch(this.rejectTTSPromise.bind(this)) 61 | ; 62 | } 63 | 64 | private resolveTTSPromise = (data: {response: ArrayBuffer}) => { 65 | return this.speak(data.response); 66 | } 67 | 68 | private rejectTTSPromise = (reason: string) => { 69 | throw new ApiAiRequestError(reason); 70 | } 71 | 72 | private makeRequest(url, params, headers, options): Promise<{response: ArrayBuffer}> { 73 | return XhrRequest.get(url, params, headers, options); 74 | } 75 | 76 | private speak(data: ArrayBuffer): Promise { 77 | 78 | if (!data.byteLength) { 79 | return Promise.reject("TTS Server unavailable"); 80 | } 81 | 82 | return new Promise((resolve, reject) => { 83 | TTSRequest.audioContext.decodeAudioData( 84 | data, 85 | (buffer: AudioBuffer) => { 86 | return this.playSound(buffer, resolve); 87 | }, 88 | reject 89 | ).then(null, (err) => reject(err)); 90 | }); 91 | } 92 | 93 | private playSound(buffer: AudioBuffer, resolve) { 94 | const source = TTSRequest.audioContext.createBufferSource(); 95 | source.buffer = buffer; 96 | source.connect(TTSRequest.audioContext.destination); 97 | source.onended = resolve; 98 | source.start(0); 99 | }; 100 | } 101 | -------------------------------------------------------------------------------- /ts/ApiAiClient.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import { ApiAiConstants } from "./ApiAiConstants"; 18 | import { ApiAiClientConfigurationError } from "./Errors"; 19 | import { EventRequest } from "./Request/EventRequest"; 20 | import TextRequest from "./Request/TextRequest"; 21 | // import { TTSRequest } from "./Request/TTSRequest"; 22 | 23 | import { IApiClientOptions, IRequestOptions, IServerResponse, IStringMap } from "./Interfaces"; 24 | 25 | export * from "./Interfaces"; 26 | export {ApiAiConstants} from "./ApiAiConstants"; 27 | 28 | export class ApiAiClient { 29 | 30 | private apiLang: ApiAiConstants.AVAILABLE_LANGUAGES; 31 | private apiVersion: string; 32 | private apiBaseUrl: string; 33 | private sessionId: string; 34 | private accessToken: string; 35 | 36 | constructor(options: IApiClientOptions) { 37 | 38 | if (!options || !options.accessToken) { 39 | throw new ApiAiClientConfigurationError("Access token is required for new ApiAi.Client instance"); 40 | } 41 | 42 | this.accessToken = options.accessToken; 43 | this.apiLang = options.lang || ApiAiConstants.DEFAULT_CLIENT_LANG; 44 | this.apiVersion = options.version || ApiAiConstants.DEFAULT_API_VERSION; 45 | this.apiBaseUrl = options.baseUrl || ApiAiConstants.DEFAULT_BASE_URL; 46 | this.sessionId = options.sessionId || this.guid(); 47 | } 48 | 49 | public textRequest(query, options: IRequestOptions = {}): Promise { 50 | if (!query) { 51 | throw new ApiAiClientConfigurationError("Query should not be empty"); 52 | } 53 | options.query = query; 54 | return new TextRequest(this, options).perform(); 55 | } 56 | 57 | public eventRequest(eventName, eventData: IStringMap = {}, 58 | options: IRequestOptions = {}): Promise { 59 | if (!eventName) { 60 | throw new ApiAiClientConfigurationError("Event name can not be empty"); 61 | } 62 | options.event = {name: eventName, data: eventData}; 63 | return new EventRequest(this, options).perform(); 64 | } 65 | 66 | // @todo: implement local tts request 67 | /*public ttsRequest(query) { 68 | if (!query) { 69 | throw new ApiAiClientConfigurationError("Query should not be empty"); 70 | } 71 | return new TTSRequest(this).makeTTSRequest(query); 72 | }*/ 73 | 74 | /*public userEntitiesRequest(options: IRequestOptions = {}): UserEntitiesRequest { 75 | return new UserEntitiesRequest(this, options); 76 | }*/ 77 | 78 | public getAccessToken(): string { 79 | return this.accessToken; 80 | } 81 | 82 | public getApiVersion(): string { 83 | return (this.apiVersion) ? this.apiVersion : ApiAiConstants.DEFAULT_API_VERSION; 84 | } 85 | 86 | public getApiLang(): ApiAiConstants.AVAILABLE_LANGUAGES { 87 | return (this.apiLang) ? this.apiLang : ApiAiConstants.DEFAULT_CLIENT_LANG; 88 | } 89 | 90 | public getApiBaseUrl(): string { 91 | return (this.apiBaseUrl) ? this.apiBaseUrl : ApiAiConstants.DEFAULT_BASE_URL; 92 | } 93 | 94 | public setSessionId(sessionId: string) { 95 | this.sessionId = sessionId; 96 | } 97 | 98 | public getSessionId(): string { 99 | return this.sessionId; 100 | } 101 | 102 | /** 103 | * generates new random UUID 104 | * @returns {string} 105 | */ 106 | private guid(): string { 107 | const s4 = () => Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); 108 | return s4() + s4() + "-" + s4() + "-" + s4() + "-" + 109 | s4() + "-" + s4() + s4() + s4(); 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | # DEPRECATED 3 | 4 | | Deprecated | 5 | |-------| 6 | | This Dialogflow client library and Dialogflow API V1 [have been deprecated and will be shut down on October 23th, 2019](https://blog.dialogflow.com/post/migrate-to-dialogflow-api-v2/). Please [migrate to Dialogflow API V2](https://cloud.google.com/dialogflow-enterprise/docs/migrating). | 7 | 8 | You can use this library as common pre-built .js ([choose there](target)). 9 | 10 | Or you can install it with nodejs and that import as es6 (or .ts) module. See below. 11 | 12 | `npm install api-ai-javascript@2.0.0-beta.14` 13 | 14 | 15 | # Usage 16 | 17 | ## .textRequest 18 | 19 | ```javascript 20 | 21 | const client = new ApiAi.ApiAiClient({accessToken: 'YOUR_ACCESS_TOKEN'}); 22 | const promise = client.textRequest(longTextRequest); 23 | 24 | promise 25 | .then(handleResponse) 26 | .catch(handleError); 27 | 28 | function handleResponse(serverResponse) { 29 | console.log(serverResponse); 30 | } 31 | function handleError(serverError) { 32 | console.log(serverError); 33 | } 34 | 35 | ``` 36 | 37 | ## .eventRequest 38 | 39 | ```javascript 40 | const promise = client.eventRequest("EVENT_NAME", options); 41 | ``` 42 | 43 | # TypeScript and ES6 44 | 45 | This SDK written with Typescript and all it's sources are available in this package. So basically if you are using something like *webpack* or *browserify* with ES6 imports and so on, you can just install this SDK with `$ npm install api-ai-javascript --save-dev` command and then import original sources with something like: 46 | 47 | ```javascript 48 | 49 | import {ApiAiClient} from "api-ai-javascript"; 50 | 51 | const client = new ApiAiClient({accessToken: 'YOUR_ACCESS_TOKEN'}) 52 | 53 | .textRequest('Hello!') 54 | .then((response) => {/* do something */}) 55 | .catch((error) => {/* do something here too */}) 56 | 57 | ``` 58 | 59 | *Note:* If you are going to build es5 version of your bundle with ApiAiClient inside, please add some typings for promises (e.g. @types/es6-promise) 60 | 61 | You also can import and use all defined interfaces and ApiAiConstants: 62 | 63 | ```javascript 64 | import {IRequestOptions, IServerResponse, ApiAiConstants} from "api-ai-javascript/ApiAiClient" 65 | const lang = ApiAiConstants.AVAILABLE_LANGUAGES.EN; 66 | ``` 67 | 68 | You can find full list of interfaces [here](ts/Interfaces.ts) 69 | 70 | # Development 71 | 72 | * Checkout from this repository, do not forget to switch to "v2" branch 73 | * run `$ npm install` 74 | * run `$ webpack -w` or just `$ npm start` (as an option for non globally installed dev-server - `$ ./node_modules/.bin/webpack-dev-server`) 75 | * develop! (webpack will automatically compile SDK to ./target/ApiAi.js file on each change, just include it into some test HTML file (./demo/index.html will probably do the job) and test it). 76 | 77 | # Building 78 | 79 | `$ npm run-script build` command will build everything 80 | 81 | # Testing 82 | 83 | `$ npm test` 84 | 85 | ## Changelog 86 | 87 | ## 2.0.0-beta.21 88 | * tts and asr support removed (discontinued on API.AI side) 89 | ## 2.0.0-beta.19 90 | * minor typings changes 91 | ## 2.0.0-beta.18 92 | * some minor typings changes 93 | ## 2.0.0-beta.17 94 | * dependencies updated 95 | * webrtc typings removed (now part of typescript default lib) 96 | ## 2.0.0-beta.16 97 | * some linting (ionic2 compatibility issues) 98 | ## 2.0.0-beta.15 99 | * minor fixes, minor readme updates 100 | * exported constants 101 | ## 2.0.0-beta.14 102 | * minor fixes 103 | * GainNode removed (for now) as non-working in current setup 104 | ## 2.0.0-beta.13 105 | * IStreamClient is aligned with StreamClient needs, thanks to @muuki88 (#26) 106 | * Callbacks in IStremClientOptions are now typed properly 107 | * Added IStreamClient.getGain(): GainNode (#25) to allow set up gain of listener 108 | * Fixed UTF8 requests, thanks to @elaval (#24) 109 | ## 2.0.0-beta.12 110 | * Possibility to import ApiAiClient separately from ApiAiStreamClient 111 | * Typescript project demo setup added 112 | ## 2.0.0-beta.8 113 | ### Breaking changes: 114 | * Main class renamed from Client to ApiAiClient 115 | * StreamClient renamed (in exports at least) to ApiAiStreamClient 116 | * StreamClient class is no longer available inside main ApiAiClient class and now should be passed directly in ApiAiClient constructor: `const client = new ApiAiClient("ACCESS_TOKEN", {streamClientClass: ApiAiStreamClient})`.That was made to allow building your applications without streamclient at all (streamclient now takes about 70% of whole library). And also there will be other implementation of streamClient in the future 117 | ### Non-breaking changes: 118 | * Demo updated 119 | 120 | ## How to make contributions? 121 | Please read and follow the steps in the [CONTRIBUTING.md](CONTRIBUTING.md). 122 | 123 | ## License 124 | See [LICENSE](LICENSE). 125 | 126 | ## Terms 127 | Your use of this sample is subject to, and by using or downloading the sample files you agree to comply with, the [Google APIs Terms of Service](https://developers.google.com/terms/). 128 | 129 | This is not an official Google product. 130 | -------------------------------------------------------------------------------- /es6/XhrRequest.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /** 18 | * quick ts implementation of example from 19 | * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise 20 | * with some minor improvements 21 | * @todo: test (?) 22 | * @todo: add node.js implementation with node's http inside. Just to make SDK cross-platform 23 | */ 24 | class XhrRequest { 25 | // Method that performs the ajax request 26 | static ajax(method, url, args = null, headers = null, options = {}) { 27 | // Creating a promise 28 | return new Promise((resolve, reject) => { 29 | // Instantiates the XMLHttpRequest 30 | const client = XhrRequest.createXMLHTTPObject(); 31 | let uri = url; 32 | let payload = null; 33 | // Add given payload to get request 34 | if (args && (method === XhrRequest.Method.GET)) { 35 | uri += "?"; 36 | let argcount = 0; 37 | for (const key in args) { 38 | if (args.hasOwnProperty(key)) { 39 | if (argcount++) { 40 | uri += "&"; 41 | } 42 | uri += encodeURIComponent(key) + "=" + encodeURIComponent(args[key]); 43 | } 44 | } 45 | } 46 | else if (args) { 47 | if (!headers) { 48 | headers = {}; 49 | } 50 | headers["Content-Type"] = "application/json; charset=utf-8"; 51 | payload = JSON.stringify(args); 52 | } 53 | for (const key in options) { 54 | if (key in client) { 55 | client[key] = options[key]; 56 | } 57 | } 58 | // hack: method[method] is somewhat like .toString for enum Method 59 | // should be made in normal way 60 | client.open(XhrRequest.Method[method], uri, true); 61 | // Add given headers 62 | if (headers) { 63 | for (const key in headers) { 64 | if (headers.hasOwnProperty(key)) { 65 | client.setRequestHeader(key, headers[key]); 66 | } 67 | } 68 | } 69 | payload ? client.send(payload) : client.send(); 70 | client.onload = () => { 71 | if (client.status >= 200 && client.status < 300) { 72 | // Performs the function "resolve" when this.status is equal to 2xx 73 | resolve(client); 74 | } 75 | else { 76 | // Performs the function "reject" when this.status is different than 2xx 77 | reject(client); 78 | } 79 | }; 80 | client.onerror = () => { 81 | reject(client); 82 | }; 83 | }); 84 | } 85 | static get(url, payload = null, headers = null, options = {}) { 86 | return XhrRequest.ajax(XhrRequest.Method.GET, url, payload, headers, options); 87 | } 88 | static post(url, payload = null, headers = null, options = {}) { 89 | return XhrRequest.ajax(XhrRequest.Method.POST, url, payload, headers, options); 90 | } 91 | static put(url, payload = null, headers = null, options = {}) { 92 | return XhrRequest.ajax(XhrRequest.Method.PUT, url, payload, headers, options); 93 | } 94 | static delete(url, payload = null, headers = null, options = {}) { 95 | return XhrRequest.ajax(XhrRequest.Method.DELETE, url, payload, headers, options); 96 | } 97 | static createXMLHTTPObject() { 98 | let xmlhttp = null; 99 | for (const i of XhrRequest.XMLHttpFactories) { 100 | try { 101 | xmlhttp = i(); 102 | } 103 | catch (e) { 104 | continue; 105 | } 106 | break; 107 | } 108 | return xmlhttp; 109 | } 110 | } 111 | XhrRequest.XMLHttpFactories = [ 112 | () => new XMLHttpRequest(), 113 | () => new window["ActiveXObject"]("Msxml2.XMLHTTP"), 114 | () => new window["ActiveXObject"]("Msxml3.XMLHTTP"), 115 | () => new window["ActiveXObject"]("Microsoft.XMLHTTP") 116 | ]; 117 | (function (XhrRequest) { 118 | let Method; 119 | (function (Method) { 120 | Method[Method["GET"] = "GET"] = "GET"; 121 | Method[Method["POST"] = "POST"] = "POST"; 122 | Method[Method["PUT"] = "PUT"] = "PUT"; 123 | Method[Method["DELETE"] = "DELETE"] = "DELETE"; 124 | })(Method = XhrRequest.Method || (XhrRequest.Method = {})); 125 | })(XhrRequest || (XhrRequest = {})); 126 | export default XhrRequest; 127 | -------------------------------------------------------------------------------- /ts/XhrRequest.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | import {IStringMap} from "./Interfaces"; 18 | /** 19 | * quick ts implementation of example from 20 | * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise 21 | * with some minor improvements 22 | * @todo: test (?) 23 | * @todo: add node.js implementation with node's http inside. Just to make SDK cross-platform 24 | */ 25 | class XhrRequest { 26 | // Method that performs the ajax request 27 | public static ajax( 28 | method: XhrRequest.Method, 29 | url: string, 30 | args: IStringMap = null, 31 | headers: IStringMap = null, 32 | options: IStringMap = {} 33 | ): Promise { 34 | 35 | // Creating a promise 36 | return new Promise((resolve, reject) => { 37 | 38 | // Instantiates the XMLHttpRequest 39 | const client: XMLHttpRequest = XhrRequest.createXMLHTTPObject(); 40 | let uri: string = url; 41 | let payload = null; 42 | 43 | // Add given payload to get request 44 | if (args && (method === XhrRequest.Method.GET)) { 45 | uri += "?"; 46 | let argcount = 0; 47 | for (const key in args) { 48 | if (args.hasOwnProperty(key)) { 49 | if (argcount++) { 50 | uri += "&"; 51 | } 52 | uri += encodeURIComponent(key) + "=" + encodeURIComponent(args[key]); 53 | } 54 | } 55 | } else if (args) { 56 | if (!headers) { 57 | headers = {}; 58 | } 59 | headers["Content-Type"] = "application/json; charset=utf-8"; 60 | payload = JSON.stringify(args); 61 | } 62 | 63 | for (const key in options) { 64 | if (key in client) { 65 | client[key] = options[key]; 66 | } 67 | } 68 | 69 | // hack: method[method] is somewhat like .toString for enum Method 70 | // should be made in normal way 71 | client.open(XhrRequest.Method[method], uri, true); 72 | // Add given headers 73 | 74 | if (headers) { 75 | for (const key in headers) { 76 | if (headers.hasOwnProperty(key)) { 77 | client.setRequestHeader(key, headers[key]); 78 | } 79 | } 80 | } 81 | 82 | payload ? client.send(payload) : client.send(); 83 | 84 | client.onload = () => { 85 | if (client.status >= 200 && client.status < 300) { 86 | // Performs the function "resolve" when this.status is equal to 2xx 87 | resolve(client); 88 | } else { 89 | // Performs the function "reject" when this.status is different than 2xx 90 | reject(client); 91 | } 92 | }; 93 | client.onerror = () => { 94 | reject(client); 95 | }; 96 | }); 97 | 98 | } 99 | 100 | public static get(url, payload: IStringMap = null, headers: IStringMap = null, options = {}): Promise { 101 | return XhrRequest.ajax(XhrRequest.Method.GET, url, payload, headers, options); 102 | } 103 | 104 | public static post(url: string, payload: IStringMap = null, headers: IStringMap = null, 105 | options = {}): Promise { 106 | return XhrRequest.ajax(XhrRequest.Method.POST, url, payload, headers, options); 107 | } 108 | 109 | public static put(url: string, payload: IStringMap = null, headers: IStringMap = null, 110 | options = {}): Promise { 111 | return XhrRequest.ajax(XhrRequest.Method.PUT, url, payload, headers, options); 112 | } 113 | 114 | public static delete(url: string, payload: IStringMap = null, headers: IStringMap = null, 115 | options = {}): Promise { 116 | return XhrRequest.ajax(XhrRequest.Method.DELETE, url, payload, headers, options); 117 | } 118 | 119 | private static XMLHttpFactories: Function[] = [ 120 | () => new XMLHttpRequest(), 121 | () => new window["ActiveXObject"]("Msxml2.XMLHTTP"), 122 | () => new window["ActiveXObject"]("Msxml3.XMLHTTP"), 123 | () => new window["ActiveXObject"]("Microsoft.XMLHTTP") 124 | ]; 125 | 126 | private static createXMLHTTPObject(): XMLHttpRequest { 127 | let xmlhttp: XMLHttpRequest = null; 128 | for (const i of XhrRequest.XMLHttpFactories) { 129 | try { 130 | xmlhttp = i(); 131 | } catch (e) { 132 | continue; 133 | } 134 | break; 135 | } 136 | 137 | return xmlhttp; 138 | } 139 | } 140 | 141 | namespace XhrRequest { 142 | export enum Method { 143 | GET = "GET" as any, 144 | POST = "POST" as any, 145 | PUT = "PUT" as any, 146 | DELETE = "DELETE" as any 147 | } 148 | } 149 | 150 | export default XhrRequest; 151 | -------------------------------------------------------------------------------- /target/ApiAi.min.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | var ApiAi=function(t){function __webpack_require__(n){if(e[n])return e[n].exports;var r=e[n]={i:n,l:!1,exports:{}};return t[n].call(r.exports,r,r.exports,__webpack_require__),r.l=!0,r.exports}var e={};return __webpack_require__.m=t,__webpack_require__.c=e,__webpack_require__.i=function(t){return t},__webpack_require__.d=function(t,e,n){__webpack_require__.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:n})},__webpack_require__.n=function(t){var e=t&&t.__esModule?function getDefault(){return t.default}:function getModuleExports(){return t};return __webpack_require__.d(e,"a",e),e},__webpack_require__.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},__webpack_require__.p="/target/",__webpack_require__(__webpack_require__.s=8)}([function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});!function(t){var e;!function(t){t[t.EN="en"]="EN",t[t.DE="de"]="DE",t[t.ES="es"]="ES",t[t.PT_BR="pt-BR"]="PT_BR",t[t.ZH_HK="zh-HK"]="ZH_HK",t[t.ZH_CN="zh-CN"]="ZH_CN",t[t.ZH_TW="zh-TW"]="ZH_TW",t[t.NL="nl"]="NL",t[t.FR="fr"]="FR",t[t.IT="it"]="IT",t[t.JA="ja"]="JA",t[t.KO="ko"]="KO",t[t.PT="pt"]="PT",t[t.RU="ru"]="RU",t[t.UK="uk"]="UK"}(e=t.AVAILABLE_LANGUAGES||(t.AVAILABLE_LANGUAGES={})),t.VERSION="2.0.0-beta.20",t.DEFAULT_BASE_URL="https://api.api.ai/v1/",t.DEFAULT_API_VERSION="20150910",t.DEFAULT_CLIENT_LANG=e.EN}(e.ApiAiConstants||(e.ApiAiConstants={}))},function(t,e,n){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function __(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}}();Object.defineProperty(e,"__esModule",{value:!0});var i=function(t){function ApiAiBaseError(e){var n=t.call(this,e)||this;return n.message=e,n.stack=(new Error).stack,n}return r(ApiAiBaseError,t),ApiAiBaseError}(Error);e.ApiAiBaseError=i;var o=function(t){function ApiAiClientConfigurationError(e){var n=t.call(this,e)||this;return n.name="ApiAiClientConfigurationError",n}return r(ApiAiClientConfigurationError,t),ApiAiClientConfigurationError}(i);e.ApiAiClientConfigurationError=o;var s=function(t){function ApiAiRequestError(e,n){void 0===n&&(n=null);var r=t.call(this,e)||this;return r.message=e,r.code=n,r.name="ApiAiRequestError",r}return r(ApiAiRequestError,t),ApiAiRequestError}(i);e.ApiAiRequestError=s},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(1),i=n(7),o=function(){function Request(t,e){this.apiAiClient=t,this.options=e,this.uri=this.apiAiClient.getApiBaseUrl()+"query?v="+this.apiAiClient.getApiVersion(),this.requestMethod=i.default.Method.POST,this.headers={Authorization:"Bearer "+this.apiAiClient.getAccessToken()},this.options.lang=this.apiAiClient.getApiLang(),this.options.sessionId=this.apiAiClient.getSessionId()}return Request.handleSuccess=function(t){return Promise.resolve(JSON.parse(t.responseText))},Request.handleError=function(t){var e=new r.ApiAiRequestError(null);try{var n=JSON.parse(t.responseText);e=n.status&&n.status.errorDetails?new r.ApiAiRequestError(n.status.errorDetails,n.status.code):new r.ApiAiRequestError(t.statusText,t.status)}catch(n){e=new r.ApiAiRequestError(t.statusText,t.status)}return Promise.reject(e)},Request.prototype.perform=function(t){void 0===t&&(t=null);var e=t||this.options;return i.default.ajax(this.requestMethod,this.uri,e,this.headers).then(Request.handleSuccess.bind(this)).catch(Request.handleError.bind(this))},Request}();e.default=o},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=n(0),i=n(1),o=n(5),s=n(6);!function __export(t){for(var n in t)e.hasOwnProperty(n)||(e[n]=t[n])}(n(4));var u=n(0);e.ApiAiConstants=u.ApiAiConstants;var _=function(){function ApiAiClient(t){if(!t||!t.accessToken)throw new i.ApiAiClientConfigurationError("Access token is required for new ApiAi.Client instance");this.accessToken=t.accessToken,this.apiLang=t.lang||r.ApiAiConstants.DEFAULT_CLIENT_LANG,this.apiVersion=t.version||r.ApiAiConstants.DEFAULT_API_VERSION,this.apiBaseUrl=t.baseUrl||r.ApiAiConstants.DEFAULT_BASE_URL,this.sessionId=t.sessionId||this.guid()}return ApiAiClient.prototype.textRequest=function(t,e){if(void 0===e&&(e={}),!t)throw new i.ApiAiClientConfigurationError("Query should not be empty");return e.query=t,new s.default(this,e).perform()},ApiAiClient.prototype.eventRequest=function(t,e,n){if(void 0===e&&(e={}),void 0===n&&(n={}),!t)throw new i.ApiAiClientConfigurationError("Event name can not be empty");return n.event={name:t,data:e},new o.EventRequest(this,n).perform()},ApiAiClient.prototype.getAccessToken=function(){return this.accessToken},ApiAiClient.prototype.getApiVersion=function(){return this.apiVersion?this.apiVersion:r.ApiAiConstants.DEFAULT_API_VERSION},ApiAiClient.prototype.getApiLang=function(){return this.apiLang?this.apiLang:r.ApiAiConstants.DEFAULT_CLIENT_LANG},ApiAiClient.prototype.getApiBaseUrl=function(){return this.apiBaseUrl?this.apiBaseUrl:r.ApiAiConstants.DEFAULT_BASE_URL},ApiAiClient.prototype.setSessionId=function(t){this.sessionId=t},ApiAiClient.prototype.getSessionId=function(){return this.sessionId},ApiAiClient.prototype.guid=function(){var t=function(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)};return t()+t()+"-"+t()+"-"+t()+"-"+t()+"-"+t()+t()+t()},ApiAiClient}();e.ApiAiClient=_},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});!function(t){!function(t){t[t.ERR_NETWORK=0]="ERR_NETWORK",t[t.ERR_AUDIO=1]="ERR_AUDIO",t[t.ERR_SERVER=2]="ERR_SERVER",t[t.ERR_CLIENT=3]="ERR_CLIENT"}(t.ERROR||(t.ERROR={}));!function(t){t[t.MSG_WAITING_MICROPHONE=0]="MSG_WAITING_MICROPHONE",t[t.MSG_MEDIA_STREAM_CREATED=1]="MSG_MEDIA_STREAM_CREATED",t[t.MSG_INIT_RECORDER=2]="MSG_INIT_RECORDER",t[t.MSG_RECORDING=3]="MSG_RECORDING",t[t.MSG_SEND=4]="MSG_SEND",t[t.MSG_SEND_EMPTY=5]="MSG_SEND_EMPTY",t[t.MSG_SEND_EOS_OR_JSON=6]="MSG_SEND_EOS_OR_JSON",t[t.MSG_WEB_SOCKET=7]="MSG_WEB_SOCKET",t[t.MSG_WEB_SOCKET_OPEN=8]="MSG_WEB_SOCKET_OPEN",t[t.MSG_WEB_SOCKET_CLOSE=9]="MSG_WEB_SOCKET_CLOSE",t[t.MSG_STOP=10]="MSG_STOP",t[t.MSG_CONFIG_CHANGED=11]="MSG_CONFIG_CHANGED"}(t.EVENT||(t.EVENT={}))}(e.IStreamClient||(e.IStreamClient={}))},function(t,e,n){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function __(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}}();Object.defineProperty(e,"__esModule",{value:!0});var i=n(2),o=function(t){function EventRequest(){return null!==t&&t.apply(this,arguments)||this}return r(EventRequest,t),EventRequest}(i.default);e.EventRequest=o},function(t,e,n){"use strict";var r=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)e.hasOwnProperty(n)&&(t[n]=e[n])};return function(e,n){function __(){this.constructor=e}t(e,n),e.prototype=null===n?Object.create(n):(__.prototype=n.prototype,new __)}}();Object.defineProperty(e,"__esModule",{value:!0});var i=n(2),o=function(t){function TextRequest(){return null!==t&&t.apply(this,arguments)||this}return r(TextRequest,t),TextRequest}(i.default);e.default=o},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0});var r=function(){function XhrRequest(){}return XhrRequest.ajax=function(t,e,n,r,i){return void 0===n&&(n=null),void 0===r&&(r=null),void 0===i&&(i={}),new Promise(function(o,s){var u=XhrRequest.createXMLHTTPObject(),_=e,a=null;if(n&&t===XhrRequest.Method.GET){_+="?";var c=0;for(var p in n)n.hasOwnProperty(p)&&(c++&&(_+="&"),_+=encodeURIComponent(p)+"="+encodeURIComponent(n[p]))}else n&&(r||(r={}),r["Content-Type"]="application/json; charset=utf-8",a=JSON.stringify(n));for(var p in i)p in u&&(u[p]=i[p]);if(u.open(XhrRequest.Method[t],_,!0),r)for(var p in r)r.hasOwnProperty(p)&&u.setRequestHeader(p,r[p]);a?u.send(a):u.send(),u.onload=function(){u.status>=200&&u.status<300?o(u):s(u)},u.onerror=function(){s(u)}})},XhrRequest.get=function(t,e,n,r){return void 0===e&&(e=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.GET,t,e,n,r)},XhrRequest.post=function(t,e,n,r){return void 0===e&&(e=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.POST,t,e,n,r)},XhrRequest.put=function(t,e,n,r){return void 0===e&&(e=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.PUT,t,e,n,r)},XhrRequest.delete=function(t,e,n,r){return void 0===e&&(e=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.DELETE,t,e,n,r)},XhrRequest.createXMLHTTPObject=function(){for(var t=null,e=0,n=XhrRequest.XMLHttpFactories;e=200&&u.status<300?o(u):s(u)},u.onerror=function(){s(u)}})},XhrRequest.get=function(e,t,n,r){return void 0===t&&(t=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.GET,e,t,n,r)},XhrRequest.post=function(e,t,n,r){return void 0===t&&(t=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.POST,e,t,n,r)},XhrRequest.put=function(e,t,n,r){return void 0===t&&(t=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.PUT,e,t,n,r)},XhrRequest.delete=function(e,t,n,r){return void 0===t&&(t=null),void 0===n&&(n=null),void 0===r&&(r={}),XhrRequest.ajax(XhrRequest.Method.DELETE,e,t,n,r)},XhrRequest.createXMLHTTPObject=function(){for(var e=null,t=0,n=XhrRequest.XMLHttpFactories;t= 200 && client.status < 300) { 469 | // Performs the function "resolve" when this.status is equal to 2xx 470 | resolve(client); 471 | } 472 | else { 473 | // Performs the function "reject" when this.status is different than 2xx 474 | reject(client); 475 | } 476 | }; 477 | client.onerror = function () { 478 | reject(client); 479 | }; 480 | }); 481 | }; 482 | XhrRequest.get = function (url, payload, headers, options) { 483 | if (payload === void 0) { payload = null; } 484 | if (headers === void 0) { headers = null; } 485 | if (options === void 0) { options = {}; } 486 | return XhrRequest.ajax(XhrRequest.Method.GET, url, payload, headers, options); 487 | }; 488 | XhrRequest.post = function (url, payload, headers, options) { 489 | if (payload === void 0) { payload = null; } 490 | if (headers === void 0) { headers = null; } 491 | if (options === void 0) { options = {}; } 492 | return XhrRequest.ajax(XhrRequest.Method.POST, url, payload, headers, options); 493 | }; 494 | XhrRequest.put = function (url, payload, headers, options) { 495 | if (payload === void 0) { payload = null; } 496 | if (headers === void 0) { headers = null; } 497 | if (options === void 0) { options = {}; } 498 | return XhrRequest.ajax(XhrRequest.Method.PUT, url, payload, headers, options); 499 | }; 500 | XhrRequest.delete = function (url, payload, headers, options) { 501 | if (payload === void 0) { payload = null; } 502 | if (headers === void 0) { headers = null; } 503 | if (options === void 0) { options = {}; } 504 | return XhrRequest.ajax(XhrRequest.Method.DELETE, url, payload, headers, options); 505 | }; 506 | XhrRequest.createXMLHTTPObject = function () { 507 | var xmlhttp = null; 508 | for (var _i = 0, _a = XhrRequest.XMLHttpFactories; _i < _a.length; _i++) { 509 | var i = _a[_i]; 510 | try { 511 | xmlhttp = i(); 512 | } 513 | catch (e) { 514 | continue; 515 | } 516 | break; 517 | } 518 | return xmlhttp; 519 | }; 520 | XhrRequest.XMLHttpFactories = [ 521 | function () { return new XMLHttpRequest(); }, 522 | function () { return new window["ActiveXObject"]("Msxml2.XMLHTTP"); }, 523 | function () { return new window["ActiveXObject"]("Msxml3.XMLHTTP"); }, 524 | function () { return new window["ActiveXObject"]("Microsoft.XMLHTTP"); } 525 | ]; 526 | return XhrRequest; 527 | }()); 528 | (function (XhrRequest) { 529 | var Method; 530 | (function (Method) { 531 | Method[Method["GET"] = "GET"] = "GET"; 532 | Method[Method["POST"] = "POST"] = "POST"; 533 | Method[Method["PUT"] = "PUT"] = "PUT"; 534 | Method[Method["DELETE"] = "DELETE"] = "DELETE"; 535 | })(Method = XhrRequest.Method || (XhrRequest.Method = {})); 536 | })(XhrRequest || (XhrRequest = {})); 537 | exports.default = XhrRequest; 538 | 539 | 540 | /***/ }), 541 | /* 8 */ 542 | /***/ (function(module, exports, __webpack_require__) { 543 | 544 | module.exports = __webpack_require__(3); 545 | 546 | 547 | /***/ }) 548 | /******/ ]); 549 | //# sourceMappingURL=ApiAi.js.map -------------------------------------------------------------------------------- /target/ApiAi.streamless.js: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright 2017 Google Inc. All Rights Reserved. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | var ApiAi = 18 | /******/ (function(modules) { // webpackBootstrap 19 | /******/ // The module cache 20 | /******/ var installedModules = {}; 21 | /******/ 22 | /******/ // The require function 23 | /******/ function __webpack_require__(moduleId) { 24 | /******/ 25 | /******/ // Check if module is in cache 26 | /******/ if(installedModules[moduleId]) { 27 | /******/ return installedModules[moduleId].exports; 28 | /******/ } 29 | /******/ // Create a new module (and put it into the cache) 30 | /******/ var module = installedModules[moduleId] = { 31 | /******/ i: moduleId, 32 | /******/ l: false, 33 | /******/ exports: {} 34 | /******/ }; 35 | /******/ 36 | /******/ // Execute the module function 37 | /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); 38 | /******/ 39 | /******/ // Flag the module as loaded 40 | /******/ module.l = true; 41 | /******/ 42 | /******/ // Return the exports of the module 43 | /******/ return module.exports; 44 | /******/ } 45 | /******/ 46 | /******/ 47 | /******/ // expose the modules object (__webpack_modules__) 48 | /******/ __webpack_require__.m = modules; 49 | /******/ 50 | /******/ // expose the module cache 51 | /******/ __webpack_require__.c = installedModules; 52 | /******/ 53 | /******/ // identity function for calling harmony imports with the correct context 54 | /******/ __webpack_require__.i = function(value) { return value; }; 55 | /******/ 56 | /******/ // define getter function for harmony exports 57 | /******/ __webpack_require__.d = function(exports, name, getter) { 58 | /******/ if(!__webpack_require__.o(exports, name)) { 59 | /******/ Object.defineProperty(exports, name, { 60 | /******/ configurable: false, 61 | /******/ enumerable: true, 62 | /******/ get: getter 63 | /******/ }); 64 | /******/ } 65 | /******/ }; 66 | /******/ 67 | /******/ // getDefaultExport function for compatibility with non-harmony modules 68 | /******/ __webpack_require__.n = function(module) { 69 | /******/ var getter = module && module.__esModule ? 70 | /******/ function getDefault() { return module['default']; } : 71 | /******/ function getModuleExports() { return module; }; 72 | /******/ __webpack_require__.d(getter, 'a', getter); 73 | /******/ return getter; 74 | /******/ }; 75 | /******/ 76 | /******/ // Object.prototype.hasOwnProperty.call 77 | /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; 78 | /******/ 79 | /******/ // __webpack_public_path__ 80 | /******/ __webpack_require__.p = "/target/"; 81 | /******/ 82 | /******/ // Load entry module and return exports 83 | /******/ return __webpack_require__(__webpack_require__.s = 10); 84 | /******/ }) 85 | /************************************************************************/ 86 | /******/ ([ 87 | /* 0 */ 88 | /***/ (function(module, exports, __webpack_require__) { 89 | 90 | "use strict"; 91 | 92 | Object.defineProperty(exports, "__esModule", { value: true }); 93 | var ApiAiConstants; 94 | (function (ApiAiConstants) { 95 | var AVAILABLE_LANGUAGES; 96 | (function (AVAILABLE_LANGUAGES) { 97 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["EN"] = "en"] = "EN"; 98 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["DE"] = "de"] = "DE"; 99 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ES"] = "es"] = "ES"; 100 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["PT_BR"] = "pt-BR"] = "PT_BR"; 101 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_HK"] = "zh-HK"] = "ZH_HK"; 102 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_CN"] = "zh-CN"] = "ZH_CN"; 103 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["ZH_TW"] = "zh-TW"] = "ZH_TW"; 104 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["NL"] = "nl"] = "NL"; 105 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["FR"] = "fr"] = "FR"; 106 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["IT"] = "it"] = "IT"; 107 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["JA"] = "ja"] = "JA"; 108 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["KO"] = "ko"] = "KO"; 109 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["PT"] = "pt"] = "PT"; 110 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["RU"] = "ru"] = "RU"; 111 | AVAILABLE_LANGUAGES[AVAILABLE_LANGUAGES["UK"] = "uk"] = "UK"; 112 | })(AVAILABLE_LANGUAGES = ApiAiConstants.AVAILABLE_LANGUAGES || (ApiAiConstants.AVAILABLE_LANGUAGES = {})); 113 | ApiAiConstants.VERSION = "2.0.0-beta.18"; 114 | ApiAiConstants.DEFAULT_BASE_URL = "https://api.api.ai/v1/"; 115 | ApiAiConstants.DEFAULT_API_VERSION = "20150910"; 116 | ApiAiConstants.DEFAULT_CLIENT_LANG = AVAILABLE_LANGUAGES.EN; 117 | // @todo: make configurable, ideally fix non-working v1 118 | ApiAiConstants.DEFAULT_TTS_HOST = "https://api.api.ai/api/tts"; 119 | })(ApiAiConstants = exports.ApiAiConstants || (exports.ApiAiConstants = {})); 120 | 121 | 122 | /***/ }), 123 | /* 1 */ 124 | /***/ (function(module, exports, __webpack_require__) { 125 | 126 | "use strict"; 127 | 128 | var __extends = (this && this.__extends) || (function () { 129 | var extendStatics = Object.setPrototypeOf || 130 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 131 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 132 | return function (d, b) { 133 | extendStatics(d, b); 134 | function __() { this.constructor = d; } 135 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 136 | }; 137 | })(); 138 | Object.defineProperty(exports, "__esModule", { value: true }); 139 | var ApiAiBaseError = (function (_super) { 140 | __extends(ApiAiBaseError, _super); 141 | function ApiAiBaseError(message) { 142 | var _this = _super.call(this, message) || this; 143 | _this.message = message; 144 | _this.stack = new Error().stack; 145 | return _this; 146 | } 147 | return ApiAiBaseError; 148 | }(Error)); 149 | exports.ApiAiBaseError = ApiAiBaseError; 150 | var ApiAiClientConfigurationError = (function (_super) { 151 | __extends(ApiAiClientConfigurationError, _super); 152 | function ApiAiClientConfigurationError(message) { 153 | var _this = _super.call(this, message) || this; 154 | _this.name = "ApiAiClientConfigurationError"; 155 | return _this; 156 | } 157 | return ApiAiClientConfigurationError; 158 | }(ApiAiBaseError)); 159 | exports.ApiAiClientConfigurationError = ApiAiClientConfigurationError; 160 | var ApiAiRequestError = (function (_super) { 161 | __extends(ApiAiRequestError, _super); 162 | function ApiAiRequestError(message, code) { 163 | if (code === void 0) { code = null; } 164 | var _this = _super.call(this, message) || this; 165 | _this.message = message; 166 | _this.code = code; 167 | _this.name = "ApiAiRequestError"; 168 | return _this; 169 | } 170 | return ApiAiRequestError; 171 | }(ApiAiBaseError)); 172 | exports.ApiAiRequestError = ApiAiRequestError; 173 | 174 | 175 | /***/ }), 176 | /* 2 */ 177 | /***/ (function(module, exports, __webpack_require__) { 178 | 179 | "use strict"; 180 | 181 | Object.defineProperty(exports, "__esModule", { value: true }); 182 | var Errors_1 = __webpack_require__(1); 183 | var XhrRequest_1 = __webpack_require__(3); 184 | var Request = (function () { 185 | function Request(apiAiClient, options) { 186 | this.apiAiClient = apiAiClient; 187 | this.options = options; 188 | this.uri = this.apiAiClient.getApiBaseUrl() + "query?v=" + this.apiAiClient.getApiVersion(); 189 | this.requestMethod = XhrRequest_1.default.Method.POST; 190 | this.headers = { 191 | Authorization: "Bearer " + this.apiAiClient.getAccessToken(), 192 | }; 193 | this.options.lang = this.apiAiClient.getApiLang(); 194 | this.options.sessionId = this.apiAiClient.getSessionId(); 195 | } 196 | Request.handleSuccess = function (xhr) { 197 | return Promise.resolve(JSON.parse(xhr.responseText)); 198 | }; 199 | Request.handleError = function (xhr) { 200 | var error = new Errors_1.ApiAiRequestError(null); 201 | try { 202 | var serverResponse = JSON.parse(xhr.responseText); 203 | if (serverResponse.status && serverResponse.status.errorDetails) { 204 | error = new Errors_1.ApiAiRequestError(serverResponse.status.errorDetails, serverResponse.status.code); 205 | } 206 | else { 207 | error = new Errors_1.ApiAiRequestError(xhr.statusText, xhr.status); 208 | } 209 | } 210 | catch (e) { 211 | error = new Errors_1.ApiAiRequestError(xhr.statusText, xhr.status); 212 | } 213 | return Promise.reject(error); 214 | }; 215 | Request.prototype.perform = function (overrideOptions) { 216 | if (overrideOptions === void 0) { overrideOptions = null; } 217 | var options = overrideOptions ? overrideOptions : this.options; 218 | return XhrRequest_1.default.ajax(this.requestMethod, this.uri, options, this.headers) 219 | .then(Request.handleSuccess.bind(this)) 220 | .catch(Request.handleError.bind(this)); 221 | }; 222 | return Request; 223 | }()); 224 | exports.default = Request; 225 | 226 | 227 | /***/ }), 228 | /* 3 */ 229 | /***/ (function(module, exports, __webpack_require__) { 230 | 231 | "use strict"; 232 | 233 | Object.defineProperty(exports, "__esModule", { value: true }); 234 | /** 235 | * quick ts implementation of example from 236 | * https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Promise 237 | * with some minor improvements 238 | * @todo: test (?) 239 | * @todo: add node.js implementation with node's http inside. Just to make SDK cross-platform 240 | */ 241 | var XhrRequest = (function () { 242 | function XhrRequest() { 243 | } 244 | // Method that performs the ajax request 245 | XhrRequest.ajax = function (method, url, args, headers, options) { 246 | if (args === void 0) { args = null; } 247 | if (headers === void 0) { headers = null; } 248 | if (options === void 0) { options = {}; } 249 | // Creating a promise 250 | return new Promise(function (resolve, reject) { 251 | // Instantiates the XMLHttpRequest 252 | var client = XhrRequest.createXMLHTTPObject(); 253 | var uri = url; 254 | var payload = null; 255 | // Add given payload to get request 256 | if (args && (method === XhrRequest.Method.GET)) { 257 | uri += "?"; 258 | var argcount = 0; 259 | for (var key in args) { 260 | if (args.hasOwnProperty(key)) { 261 | if (argcount++) { 262 | uri += "&"; 263 | } 264 | uri += encodeURIComponent(key) + "=" + encodeURIComponent(args[key]); 265 | } 266 | } 267 | } 268 | else if (args) { 269 | if (!headers) { 270 | headers = {}; 271 | } 272 | headers["Content-Type"] = "application/json; charset=utf-8"; 273 | payload = JSON.stringify(args); 274 | } 275 | for (var key in options) { 276 | if (key in client) { 277 | client[key] = options[key]; 278 | } 279 | } 280 | // hack: method[method] is somewhat like .toString for enum Method 281 | // should be made in normal way 282 | client.open(XhrRequest.Method[method], uri, true); 283 | // Add given headers 284 | if (headers) { 285 | for (var key in headers) { 286 | if (headers.hasOwnProperty(key)) { 287 | client.setRequestHeader(key, headers[key]); 288 | } 289 | } 290 | } 291 | payload ? client.send(payload) : client.send(); 292 | client.onload = function () { 293 | if (client.status >= 200 && client.status < 300) { 294 | // Performs the function "resolve" when this.status is equal to 2xx 295 | resolve(client); 296 | } 297 | else { 298 | // Performs the function "reject" when this.status is different than 2xx 299 | reject(client); 300 | } 301 | }; 302 | client.onerror = function () { 303 | reject(client); 304 | }; 305 | }); 306 | }; 307 | XhrRequest.get = function (url, payload, headers, options) { 308 | if (payload === void 0) { payload = null; } 309 | if (headers === void 0) { headers = null; } 310 | if (options === void 0) { options = {}; } 311 | return XhrRequest.ajax(XhrRequest.Method.GET, url, payload, headers, options); 312 | }; 313 | XhrRequest.post = function (url, payload, headers, options) { 314 | if (payload === void 0) { payload = null; } 315 | if (headers === void 0) { headers = null; } 316 | if (options === void 0) { options = {}; } 317 | return XhrRequest.ajax(XhrRequest.Method.POST, url, payload, headers, options); 318 | }; 319 | XhrRequest.put = function (url, payload, headers, options) { 320 | if (payload === void 0) { payload = null; } 321 | if (headers === void 0) { headers = null; } 322 | if (options === void 0) { options = {}; } 323 | return XhrRequest.ajax(XhrRequest.Method.PUT, url, payload, headers, options); 324 | }; 325 | XhrRequest.delete = function (url, payload, headers, options) { 326 | if (payload === void 0) { payload = null; } 327 | if (headers === void 0) { headers = null; } 328 | if (options === void 0) { options = {}; } 329 | return XhrRequest.ajax(XhrRequest.Method.DELETE, url, payload, headers, options); 330 | }; 331 | XhrRequest.createXMLHTTPObject = function () { 332 | var xmlhttp = null; 333 | for (var _i = 0, _a = XhrRequest.XMLHttpFactories; _i < _a.length; _i++) { 334 | var i = _a[_i]; 335 | try { 336 | xmlhttp = i(); 337 | } 338 | catch (e) { 339 | continue; 340 | } 341 | break; 342 | } 343 | return xmlhttp; 344 | }; 345 | return XhrRequest; 346 | }()); 347 | XhrRequest.XMLHttpFactories = [ 348 | function () { return new XMLHttpRequest(); }, 349 | function () { return new window["ActiveXObject"]("Msxml2.XMLHTTP"); }, 350 | function () { return new window["ActiveXObject"]("Msxml3.XMLHTTP"); }, 351 | function () { return new window["ActiveXObject"]("Microsoft.XMLHTTP"); } 352 | ]; 353 | (function (XhrRequest) { 354 | var Method; 355 | (function (Method) { 356 | Method[Method["GET"] = "GET"] = "GET"; 357 | Method[Method["POST"] = "POST"] = "POST"; 358 | Method[Method["PUT"] = "PUT"] = "PUT"; 359 | Method[Method["DELETE"] = "DELETE"] = "DELETE"; 360 | })(Method = XhrRequest.Method || (XhrRequest.Method = {})); 361 | })(XhrRequest || (XhrRequest = {})); 362 | exports.default = XhrRequest; 363 | 364 | 365 | /***/ }), 366 | /* 4 */ 367 | /***/ (function(module, exports, __webpack_require__) { 368 | 369 | "use strict"; 370 | 371 | function __export(m) { 372 | for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; 373 | } 374 | Object.defineProperty(exports, "__esModule", { value: true }); 375 | __export(__webpack_require__(5)); 376 | 377 | 378 | /***/ }), 379 | /* 5 */ 380 | /***/ (function(module, exports, __webpack_require__) { 381 | 382 | "use strict"; 383 | 384 | function __export(m) { 385 | for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p]; 386 | } 387 | Object.defineProperty(exports, "__esModule", { value: true }); 388 | var ApiAiConstants_1 = __webpack_require__(0); 389 | var Errors_1 = __webpack_require__(1); 390 | var EventRequest_1 = __webpack_require__(7); 391 | var TextRequest_1 = __webpack_require__(9); 392 | var TTSRequest_1 = __webpack_require__(8); 393 | __export(__webpack_require__(6)); 394 | var ApiAiConstants_2 = __webpack_require__(0); 395 | exports.ApiAiConstants = ApiAiConstants_2.ApiAiConstants; 396 | var ApiAiClient = (function () { 397 | function ApiAiClient(options) { 398 | if (!options || !options.accessToken) { 399 | throw new Errors_1.ApiAiClientConfigurationError("Access token is required for new ApiAi.Client instance"); 400 | } 401 | this.accessToken = options.accessToken; 402 | this.apiLang = options.lang || ApiAiConstants_1.ApiAiConstants.DEFAULT_CLIENT_LANG; 403 | this.apiVersion = options.version || ApiAiConstants_1.ApiAiConstants.DEFAULT_API_VERSION; 404 | this.apiBaseUrl = options.baseUrl || ApiAiConstants_1.ApiAiConstants.DEFAULT_BASE_URL; 405 | this.sessionId = options.sessionId || this.guid(); 406 | this.streamClientClass = options.streamClientClass || null; 407 | } 408 | ApiAiClient.prototype.textRequest = function (query, options) { 409 | if (options === void 0) { options = {}; } 410 | if (!query) { 411 | throw new Errors_1.ApiAiClientConfigurationError("Query should not be empty"); 412 | } 413 | options.query = query; 414 | return new TextRequest_1.default(this, options).perform(); 415 | }; 416 | ApiAiClient.prototype.eventRequest = function (eventName, eventData, options) { 417 | if (eventData === void 0) { eventData = {}; } 418 | if (options === void 0) { options = {}; } 419 | if (!eventName) { 420 | throw new Errors_1.ApiAiClientConfigurationError("Event name can not be empty"); 421 | } 422 | options.event = { name: eventName, data: eventData }; 423 | return new EventRequest_1.EventRequest(this, options).perform(); 424 | }; 425 | ApiAiClient.prototype.ttsRequest = function (query) { 426 | if (!query) { 427 | throw new Errors_1.ApiAiClientConfigurationError("Query should not be empty"); 428 | } 429 | return new TTSRequest_1.TTSRequest(this).makeTTSRequest(query); 430 | }; 431 | /*public userEntitiesRequest(options: IRequestOptions = {}): UserEntitiesRequest { 432 | return new UserEntitiesRequest(this, options); 433 | }*/ 434 | ApiAiClient.prototype.createStreamClient = function (streamClientOptions) { 435 | if (streamClientOptions === void 0) { streamClientOptions = {}; } 436 | if (this.streamClientClass) { 437 | streamClientOptions.token = this.getAccessToken(); 438 | streamClientOptions.sessionId = this.getSessionId(); 439 | streamClientOptions.lang = this.getApiLang(); 440 | return new this.streamClientClass(streamClientOptions); 441 | } 442 | else { 443 | throw new Errors_1.ApiAiClientConfigurationError("No StreamClient implementation given to ApiAi Client constructor"); 444 | } 445 | }; 446 | ApiAiClient.prototype.getAccessToken = function () { 447 | return this.accessToken; 448 | }; 449 | ApiAiClient.prototype.getApiVersion = function () { 450 | return (this.apiVersion) ? this.apiVersion : ApiAiConstants_1.ApiAiConstants.DEFAULT_API_VERSION; 451 | }; 452 | ApiAiClient.prototype.getApiLang = function () { 453 | return (this.apiLang) ? this.apiLang : ApiAiConstants_1.ApiAiConstants.DEFAULT_CLIENT_LANG; 454 | }; 455 | ApiAiClient.prototype.getApiBaseUrl = function () { 456 | return (this.apiBaseUrl) ? this.apiBaseUrl : ApiAiConstants_1.ApiAiConstants.DEFAULT_BASE_URL; 457 | }; 458 | ApiAiClient.prototype.setSessionId = function (sessionId) { 459 | this.sessionId = sessionId; 460 | }; 461 | ApiAiClient.prototype.getSessionId = function () { 462 | return this.sessionId; 463 | }; 464 | /** 465 | * generates new random UUID 466 | * @returns {string} 467 | */ 468 | ApiAiClient.prototype.guid = function () { 469 | var s4 = function () { return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); }; 470 | return s4() + s4() + "-" + s4() + "-" + s4() + "-" + 471 | s4() + "-" + s4() + s4() + s4(); 472 | }; 473 | return ApiAiClient; 474 | }()); 475 | exports.ApiAiClient = ApiAiClient; 476 | 477 | 478 | /***/ }), 479 | /* 6 */ 480 | /***/ (function(module, exports, __webpack_require__) { 481 | 482 | "use strict"; 483 | 484 | Object.defineProperty(exports, "__esModule", { value: true }); 485 | var IStreamClient; 486 | (function (IStreamClient) { 487 | var ERROR; 488 | (function (ERROR) { 489 | ERROR[ERROR["ERR_NETWORK"] = 0] = "ERR_NETWORK"; 490 | ERROR[ERROR["ERR_AUDIO"] = 1] = "ERR_AUDIO"; 491 | ERROR[ERROR["ERR_SERVER"] = 2] = "ERR_SERVER"; 492 | ERROR[ERROR["ERR_CLIENT"] = 3] = "ERR_CLIENT"; 493 | })(ERROR = IStreamClient.ERROR || (IStreamClient.ERROR = {})); 494 | var EVENT; 495 | (function (EVENT) { 496 | EVENT[EVENT["MSG_WAITING_MICROPHONE"] = 0] = "MSG_WAITING_MICROPHONE"; 497 | EVENT[EVENT["MSG_MEDIA_STREAM_CREATED"] = 1] = "MSG_MEDIA_STREAM_CREATED"; 498 | EVENT[EVENT["MSG_INIT_RECORDER"] = 2] = "MSG_INIT_RECORDER"; 499 | EVENT[EVENT["MSG_RECORDING"] = 3] = "MSG_RECORDING"; 500 | EVENT[EVENT["MSG_SEND"] = 4] = "MSG_SEND"; 501 | EVENT[EVENT["MSG_SEND_EMPTY"] = 5] = "MSG_SEND_EMPTY"; 502 | EVENT[EVENT["MSG_SEND_EOS_OR_JSON"] = 6] = "MSG_SEND_EOS_OR_JSON"; 503 | EVENT[EVENT["MSG_WEB_SOCKET"] = 7] = "MSG_WEB_SOCKET"; 504 | EVENT[EVENT["MSG_WEB_SOCKET_OPEN"] = 8] = "MSG_WEB_SOCKET_OPEN"; 505 | EVENT[EVENT["MSG_WEB_SOCKET_CLOSE"] = 9] = "MSG_WEB_SOCKET_CLOSE"; 506 | EVENT[EVENT["MSG_STOP"] = 10] = "MSG_STOP"; 507 | EVENT[EVENT["MSG_CONFIG_CHANGED"] = 11] = "MSG_CONFIG_CHANGED"; 508 | })(EVENT = IStreamClient.EVENT || (IStreamClient.EVENT = {})); 509 | })(IStreamClient = exports.IStreamClient || (exports.IStreamClient = {})); 510 | 511 | 512 | /***/ }), 513 | /* 7 */ 514 | /***/ (function(module, exports, __webpack_require__) { 515 | 516 | "use strict"; 517 | 518 | var __extends = (this && this.__extends) || (function () { 519 | var extendStatics = Object.setPrototypeOf || 520 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 521 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 522 | return function (d, b) { 523 | extendStatics(d, b); 524 | function __() { this.constructor = d; } 525 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 526 | }; 527 | })(); 528 | Object.defineProperty(exports, "__esModule", { value: true }); 529 | var Request_1 = __webpack_require__(2); 530 | var EventRequest = (function (_super) { 531 | __extends(EventRequest, _super); 532 | function EventRequest() { 533 | return _super !== null && _super.apply(this, arguments) || this; 534 | } 535 | return EventRequest; 536 | }(Request_1.default)); 537 | exports.EventRequest = EventRequest; 538 | 539 | 540 | /***/ }), 541 | /* 8 */ 542 | /***/ (function(module, exports, __webpack_require__) { 543 | 544 | "use strict"; 545 | 546 | var __extends = (this && this.__extends) || (function () { 547 | var extendStatics = Object.setPrototypeOf || 548 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 549 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 550 | return function (d, b) { 551 | extendStatics(d, b); 552 | function __() { this.constructor = d; } 553 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 554 | }; 555 | })(); 556 | Object.defineProperty(exports, "__esModule", { value: true }); 557 | var ApiAiConstants_1 = __webpack_require__(0); 558 | var Errors_1 = __webpack_require__(1); 559 | var XhrRequest_1 = __webpack_require__(3); 560 | var Request_1 = __webpack_require__(2); 561 | var TTSRequest = (function (_super) { 562 | __extends(TTSRequest, _super); 563 | function TTSRequest(apiAiClient, options) { 564 | if (options === void 0) { options = {}; } 565 | var _this = _super.call(this, apiAiClient, options) || this; 566 | _this.apiAiClient = apiAiClient; 567 | _this.resolveTTSPromise = function (data) { 568 | return _this.speak(data.response); 569 | }; 570 | _this.rejectTTSPromise = function (reason) { 571 | throw new Errors_1.ApiAiRequestError(reason); 572 | }; 573 | // this.requestMethod = XhrRequest.Method.GET; 574 | _this.uri = ApiAiConstants_1.ApiAiConstants.DEFAULT_TTS_HOST; 575 | var AudioContext = window.AudioContext || webkitAudioContext; 576 | if (!TTSRequest.audioContext) { 577 | TTSRequest.audioContext = new AudioContext(); 578 | } 579 | return _this; 580 | } 581 | TTSRequest.prototype.makeTTSRequest = function (text) { 582 | if (!text) { 583 | throw new Errors_1.ApiAiClientConfigurationError("Request can not be empty"); 584 | } 585 | var params = { 586 | lang: "en-US", 587 | text: encodeURIComponent(text), 588 | v: this.apiAiClient.getApiVersion() 589 | }; 590 | var headers = { 591 | "Accept-language": "en-US", 592 | "Authorization": "Bearer " + this.apiAiClient.getAccessToken() 593 | }; 594 | return this.makeRequest(this.uri, params, headers, { responseType: TTSRequest.RESPONSE_TYPE_ARRAYBUFFER }) 595 | .then(this.resolveTTSPromise) 596 | .catch(this.rejectTTSPromise.bind(this)); 597 | }; 598 | TTSRequest.prototype.makeRequest = function (url, params, headers, options) { 599 | return XhrRequest_1.default.get(url, params, headers, options); 600 | }; 601 | TTSRequest.prototype.speak = function (data) { 602 | var _this = this; 603 | if (!data.byteLength) { 604 | return Promise.reject("TTS Server unavailable"); 605 | } 606 | return new Promise(function (resolve, reject) { 607 | TTSRequest.audioContext.decodeAudioData(data, function (buffer) { 608 | return _this.playSound(buffer, resolve); 609 | }, reject).then(null, function (err) { return reject(err); }); 610 | }); 611 | }; 612 | TTSRequest.prototype.playSound = function (buffer, resolve) { 613 | var source = TTSRequest.audioContext.createBufferSource(); 614 | source.buffer = buffer; 615 | source.connect(TTSRequest.audioContext.destination); 616 | source.onended = resolve; 617 | source.start(0); 618 | }; 619 | ; 620 | return TTSRequest; 621 | }(Request_1.default)); 622 | TTSRequest.RESPONSE_TYPE_ARRAYBUFFER = "arraybuffer"; 623 | exports.TTSRequest = TTSRequest; 624 | 625 | 626 | /***/ }), 627 | /* 9 */ 628 | /***/ (function(module, exports, __webpack_require__) { 629 | 630 | "use strict"; 631 | 632 | var __extends = (this && this.__extends) || (function () { 633 | var extendStatics = Object.setPrototypeOf || 634 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || 635 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; 636 | return function (d, b) { 637 | extendStatics(d, b); 638 | function __() { this.constructor = d; } 639 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); 640 | }; 641 | })(); 642 | Object.defineProperty(exports, "__esModule", { value: true }); 643 | var Request_1 = __webpack_require__(2); 644 | var TextRequest = (function (_super) { 645 | __extends(TextRequest, _super); 646 | function TextRequest() { 647 | return _super !== null && _super.apply(this, arguments) || this; 648 | } 649 | return TextRequest; 650 | }(Request_1.default)); 651 | exports.default = TextRequest; 652 | 653 | 654 | /***/ }), 655 | /* 10 */ 656 | /***/ (function(module, exports, __webpack_require__) { 657 | 658 | module.exports = __webpack_require__(4); 659 | 660 | 661 | /***/ }) 662 | /******/ ]); 663 | //# sourceMappingURL=ApiAi.streamless.js.map --------------------------------------------------------------------------------