websocket测试

This commit is contained in:
Hinse 2021-08-11 08:16:16 +08:00
parent 967b877220
commit 6a221c14ba
162 changed files with 19452 additions and 31 deletions

View File

@ -57,6 +57,35 @@ namespace Waste.Application.ThirdApiInfo
/// 串口号
/// </summary>
public string serialno { get; set; } = "/dev/ttyS1";
/// <summary>
/// websocket地址
/// </summary>
public string WebSocketUrl { get; set; } = "wss://api.device.suzhou.ljflytjl.cn/device_rpc";
/// <summary>
/// 时间戳
/// </summary>
public int timestamp { get; set; }
/// <summary>
/// 随机数
/// </summary>
public int noncestr { get; set; }
/// <summary>
/// 用户ID
/// </summary>
public string UserId { get; set; }
/// <summary>
/// secret
/// </summary>
public string Secret { get; set; }
/// <summary>
/// secrethash
/// </summary>
public string SecretHash { get; set; }
/// <summary>
/// 设备ID
/// </summary>
public string DeviceId { get; set; } = "";
}
/// <summary>

View File

@ -99,16 +99,11 @@ namespace Waste.Application.ThirdApiInfo
var trashhex = data.data.Substring(16, 10);
var typehex = data.data.Substring(28, 16);
var weighthex = data.data.Substring(46, data.data.Length - 46);
returndata.trash = trashhex;
returndata.trash = Convert.ToInt64(trashhex).ToString(); //垃圾桶编号使用10进制
var type = GetChsFromHex(typehex);
var weight = GetChsFromHex(weighthex);
returndata.type = TrashType(type);
returndata.Weight = weight.ToDouble();
////检查体重是否为整数如:10.0这样的情况,需要去除小数点后的数据
//if (returndata.Weight == ((int)returndata.Weight).ToDouble())
//{
// returndata.Weight = returndata.Weight.ToDouble(0);
//}
returndata.IsSuccessed = true;
string[] paramlist = new string[] {
returndata.Weight.ToString(),returndata.trash,returndata.type.ToString(),returndata.ScanningTime.ToString(),returndata.status.ToString()
@ -150,26 +145,6 @@ namespace Waste.Application.ThirdApiInfo
});
var logger = App.GetService<ILoggerService>();
logger.AddLogger($"发送的数据:{returndata.ToJson()}", 1);
//上传垃圾数据
//if (returndata.Weight > 0)
//{
// if (devicesecret != null && !string.IsNullOrEmpty(devicesecret.Secret)
// && !string.IsNullOrEmpty(devicesecret.SecretHash)
// && !string.IsNullOrEmpty(devicesecret.DevId))
// {
// await _suZhouService.PostGarbagesAsync(new GarbagePltC2SDto
// {
// Weight = returndata.Weight,
// secret = devicesecret.Secret,
// secrethash = devicesecret.SecretHash,
// ScanningTime = timestamp,
// DStatus = 0,
// deviceid = devicesecret.DevId,
// Trash = returndata.trash,
// Type = returndata.type
// });
// }
//}
}
return new ResultInfo(ResultState.SUCCESS, "success", returndata);
}
@ -299,8 +274,22 @@ namespace Waste.Application.ThirdApiInfo
}
var data = new DevRegInfoResponseDto
{
status = 0
status = 0,
WebSocketUrl = App.Configuration["SZDevPlatSetting:SocketUrl"]
};
//获取授权信息
var devicesecret = await dbClient.Queryable<W_SZDevice>().FirstAsync(x => x.DeviceId == device.Id);
if (devicesecret != null && !string.IsNullOrEmpty(devicesecret.Secret)
&& !string.IsNullOrEmpty(devicesecret.SecretHash)
&& !string.IsNullOrEmpty(devicesecret.DevId))
{
data.timestamp = _suZhouService.GetTimestamp();
data.noncestr = _suZhouService.GetNonce();
data.UserId = UserId;
data.Secret = devicesecret.Secret;
data.SecretHash = devicesecret.SecretHash;
data.DeviceId = devicesecret.DeviceId.ToString();
}
return new ResultInfo(ResultState.SUCCESS, "success", data);
}
private int TrashType(string type)

View File

@ -2005,6 +2005,41 @@
串口号
</summary>
</member>
<member name="P:Waste.Application.ThirdApiInfo.DevRegInfoResponseDto.WebSocketUrl">
<summary>
websocket地址
</summary>
</member>
<member name="P:Waste.Application.ThirdApiInfo.DevRegInfoResponseDto.timestamp">
<summary>
时间戳
</summary>
</member>
<member name="P:Waste.Application.ThirdApiInfo.DevRegInfoResponseDto.noncestr">
<summary>
随机数
</summary>
</member>
<member name="P:Waste.Application.ThirdApiInfo.DevRegInfoResponseDto.UserId">
<summary>
用户ID
</summary>
</member>
<member name="P:Waste.Application.ThirdApiInfo.DevRegInfoResponseDto.Secret">
<summary>
secret
</summary>
</member>
<member name="P:Waste.Application.ThirdApiInfo.DevRegInfoResponseDto.SecretHash">
<summary>
secrethash
</summary>
</member>
<member name="P:Waste.Application.ThirdApiInfo.DevRegInfoResponseDto.DeviceId">
<summary>
设备ID
</summary>
</member>
<member name="T:Waste.Application.ThirdApiInfo.GetDevInfoRequestDto">
<summary>
获取设备信息请求数据,并上报数据

View File

@ -48,6 +48,8 @@ namespace Waste.Web.Core
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
MyHttpContext.serviceCollection = services;
#endregion
//添加即时通讯
// services.AddSignalR();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
@ -83,8 +85,11 @@ namespace Waste.Web.Core
app.UseInject();
app.UseEndpoints(endpoints =>
{
//注册集线器
// endpoints.MapHubs();
//endpoints.MapGet("/index.html", async context => {
// await context.Response.WriteAsync("Hello");
//});

View File

@ -47,7 +47,7 @@
});
$(".js-connect").on("click", function () {
var val = {
"protocol": "messagepack",
"protocol": "json",
"version":1
};
var data = JSON.stringify(val);

View File

@ -1,17 +1,100 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Waste.Application;
namespace Waste.Web.Entry.Pages.Socket
{
public class TestModel : PageModel
{
public void OnGet()
private readonly ILoggerService _loggerService;
public TestModel(ILoggerService loggerService)
{
_loggerService = loggerService;
}
public async Task OnGetAsync()
{
await OnGetTestAsync();
}
public async Task OnGetTestAsync()
{
string BaseUrl = "wss://api.device.suzhou.ljflytjl.cn/device_rpc";
ClientWebSocket client = new ClientWebSocket();
client.Options.AddSubProtocol("protocol1");
client.Options.SetRequestHeader("device", "08d9588d-4796-48f9-8c5b-f28f271b51d0");
client.Options.SetRequestHeader("secret", "bfbaf98fb5b343b2");
client.Options.SetRequestHeader("time", GetTimestamp().ToString());
client.Options.SetRequestHeader("os", "12");
client.Options.SetRequestHeader("script", "2");
client.Options.SetRequestHeader("baseProgrameLang", "10");
client.Options.SetRequestHeader("dev", "true");
await client.ConnectAsync(new Uri(BaseUrl), CancellationToken.None);
Console.WriteLine("Connect success");
await client.SendAsync(new ArraySegment<byte>(AddSeparator(Encoding.UTF8.GetBytes(@"{""protocol"":""json"", ""version"":1}")))
, WebSocketMessageType.Text, true, CancellationToken.None);//发送握手包
Console.WriteLine("Send success");
var buffer = new ArraySegment<byte>(new byte[1024]);
while (client.State == WebSocketState.Open)
{
var bytes = Encoding.UTF8.GetBytes(@"{
""type"": 6
}");//发送远程调用 log方法
await client.SendAsync(new ArraySegment<byte>(AddSeparator(bytes)), WebSocketMessageType.Text, true, CancellationToken.None);
await client.ReceiveAsync(buffer, CancellationToken.None);
byte[] databytes = new byte[buffer.Count];
for(int i = buffer.Offset; i < (buffer.Offset + buffer.Count); i++)
{
var aa = buffer.Array[i];
databytes[i] = aa;
}
var str = Encoding.UTF8.GetString(databytes);
//保存数据
_loggerService.AddLogger(str, 1);
Console.WriteLine(str);
}
}
private static byte[] AddSeparator(byte[] data)
{
List<byte> t = new List<byte>(data) { 0x1e };//0x1e record separator
return t.ToArray();
}
private static byte[] RemoveSeparator(byte[] data)
{
List<byte> t = new List<byte>(data);
t.Remove(0x1e);
return t.ToArray();
}
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
private int GetTimestamp()
{
DateTime dateTimeStart = TimeZoneInfo.ConvertTimeToUtc(new DateTime(1970, 1, 1, 8, 0, 0));
int timestamp = Convert.ToInt32((DateTime.Now - dateTimeStart).TotalSeconds);
return timestamp;
}
/// <summary>
/// 获取随机数
/// </summary>
/// <returns></returns>
private int GetNonce()
{
var random = new Random();
int nonce = random.Next(1, Int32.MaxValue);
return nonce;
}
}
}

View File

@ -5,6 +5,6 @@ https://go.microsoft.com/fwlink/?LinkID=208121.
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<_PublishTargetUrl>D:\webpublish\waste.ybhdmob.com</_PublishTargetUrl>
<History>True|2021-08-03T03:16:02.7897282Z;True|2021-08-02T16:39:27.2332369+08:00;True|2021-08-02T15:07:40.7995318+08:00;True|2021-08-02T14:32:29.6885424+08:00;True|2021-08-02T14:31:18.6578543+08:00;True|2021-08-02T14:27:57.1301002+08:00;True|2021-08-02T10:55:40.3542370+08:00;True|2021-08-02T09:44:28.0994056+08:00;True|2021-08-01T13:49:38.4071985+08:00;True|2021-08-01T13:36:45.5372120+08:00;True|2021-08-01T11:00:19.6165520+08:00;True|2021-08-01T10:38:51.4029710+08:00;True|2021-07-31T20:27:53.6583811+08:00;True|2021-07-31T18:35:23.4214441+08:00;True|2021-07-31T17:34:14.0712243+08:00;True|2021-07-31T14:50:43.2065556+08:00;True|2021-07-30T17:59:30.2223340+08:00;True|2021-07-30T17:57:35.9412910+08:00;True|2021-07-30T17:07:58.3305971+08:00;True|2021-07-30T17:04:10.9244859+08:00;True|2021-07-30T17:02:12.1943634+08:00;True|2021-07-30T16:16:22.2838331+08:00;True|2021-07-30T15:05:26.5664155+08:00;True|2021-07-30T14:57:59.1966108+08:00;True|2021-07-30T14:54:25.8172908+08:00;True|2021-07-30T14:52:20.9209995+08:00;True|2021-07-30T14:35:29.5239463+08:00;True|2021-07-30T09:32:38.2676032+08:00;True|2021-07-30T09:14:42.6170851+08:00;True|2021-07-29T19:06:09.1449349+08:00;True|2021-06-11T08:16:29.9542894+08:00;True|2021-06-04T14:46:02.2707457+08:00;True|2021-06-02T15:08:52.8245632+08:00;True|2021-06-02T15:05:50.3614099+08:00;True|2021-06-02T14:59:32.3690948+08:00;True|2021-06-02T14:10:25.1182836+08:00;True|2021-06-02T14:09:54.9215833+08:00;True|2021-06-01T10:41:54.9488501+08:00;True|2021-06-01T10:38:56.0283198+08:00;True|2021-05-28T13:59:02.2308877+08:00;True|2021-05-28T11:56:26.6796406+08:00;True|2021-05-28T11:28:00.4087907+08:00;True|2021-05-27T16:18:09.5993838+08:00;True|2021-05-27T16:07:31.3484951+08:00;True|2021-05-27T11:30:37.9119310+08:00;True|2021-05-27T11:28:35.5374674+08:00;True|2021-05-27T08:00:09.1625592+08:00;True|2021-05-26T20:42:17.0852150+08:00;True|2021-05-26T20:36:49.7527415+08:00;True|2021-05-25T17:57:31.8791293+08:00;True|2021-05-25T13:49:29.6488978+08:00;True|2021-05-25T13:48:24.6686105+08:00;True|2021-05-25T13:25:41.2512493+08:00;True|2021-05-24T17:55:33.3800078+08:00;True|2021-05-20T14:35:30.6957985+08:00;True|2021-05-20T13:17:22.6192995+08:00;True|2021-05-20T10:51:38.1268169+08:00;True|2021-05-19T19:50:03.7000224+08:00;True|2021-05-19T19:44:27.2518811+08:00;True|2021-05-19T19:43:26.5916681+08:00;True|2021-05-19T19:36:29.3197365+08:00;True|2021-05-19T19:30:00.3802430+08:00;True|2021-05-19T17:55:23.7939835+08:00;True|2021-05-19T11:05:17.9043392+08:00;True|2021-05-19T10:19:38.4839988+08:00;True|2021-05-19T10:17:19.7430612+08:00;True|2021-05-19T10:13:23.0031721+08:00;True|2021-05-19T10:06:03.9881599+08:00;True|2021-05-18T14:39:03.8876574+08:00;True|2021-05-18T14:23:46.9818836+08:00;True|2021-05-18T14:19:56.2382079+08:00;True|2021-05-18T11:29:53.5497590+08:00;True|2021-05-18T11:16:18.0123853+08:00;True|2021-05-17T18:59:52.4159105+08:00;True|2021-05-17T18:53:37.9438984+08:00;True|2021-05-17T18:48:14.9625161+08:00;True|2021-05-17T17:46:03.7723404+08:00;True|2021-05-17T17:14:20.2312990+08:00;True|2021-05-17T16:44:34.5837616+08:00;True|2021-05-17T16:25:20.1087804+08:00;True|2021-05-17T11:35:27.9388562+08:00;</History>
<History>True|2021-08-10T23:54:57.1322848Z;True|2021-08-10T10:16:40.7495389+08:00;True|2021-08-03T11:16:02.7897282+08:00;True|2021-08-02T16:39:27.2332369+08:00;True|2021-08-02T15:07:40.7995318+08:00;True|2021-08-02T14:32:29.6885424+08:00;True|2021-08-02T14:31:18.6578543+08:00;True|2021-08-02T14:27:57.1301002+08:00;True|2021-08-02T10:55:40.3542370+08:00;True|2021-08-02T09:44:28.0994056+08:00;True|2021-08-01T13:49:38.4071985+08:00;True|2021-08-01T13:36:45.5372120+08:00;True|2021-08-01T11:00:19.6165520+08:00;True|2021-08-01T10:38:51.4029710+08:00;True|2021-07-31T20:27:53.6583811+08:00;True|2021-07-31T18:35:23.4214441+08:00;True|2021-07-31T17:34:14.0712243+08:00;True|2021-07-31T14:50:43.2065556+08:00;True|2021-07-30T17:59:30.2223340+08:00;True|2021-07-30T17:57:35.9412910+08:00;True|2021-07-30T17:07:58.3305971+08:00;True|2021-07-30T17:04:10.9244859+08:00;True|2021-07-30T17:02:12.1943634+08:00;True|2021-07-30T16:16:22.2838331+08:00;True|2021-07-30T15:05:26.5664155+08:00;True|2021-07-30T14:57:59.1966108+08:00;True|2021-07-30T14:54:25.8172908+08:00;True|2021-07-30T14:52:20.9209995+08:00;True|2021-07-30T14:35:29.5239463+08:00;True|2021-07-30T09:32:38.2676032+08:00;True|2021-07-30T09:14:42.6170851+08:00;True|2021-07-29T19:06:09.1449349+08:00;True|2021-06-11T08:16:29.9542894+08:00;True|2021-06-04T14:46:02.2707457+08:00;True|2021-06-02T15:08:52.8245632+08:00;True|2021-06-02T15:05:50.3614099+08:00;True|2021-06-02T14:59:32.3690948+08:00;True|2021-06-02T14:10:25.1182836+08:00;True|2021-06-02T14:09:54.9215833+08:00;True|2021-06-01T10:41:54.9488501+08:00;True|2021-06-01T10:38:56.0283198+08:00;True|2021-05-28T13:59:02.2308877+08:00;True|2021-05-28T11:56:26.6796406+08:00;True|2021-05-28T11:28:00.4087907+08:00;True|2021-05-27T16:18:09.5993838+08:00;True|2021-05-27T16:07:31.3484951+08:00;True|2021-05-27T11:30:37.9119310+08:00;True|2021-05-27T11:28:35.5374674+08:00;True|2021-05-27T08:00:09.1625592+08:00;True|2021-05-26T20:42:17.0852150+08:00;True|2021-05-26T20:36:49.7527415+08:00;True|2021-05-25T17:57:31.8791293+08:00;True|2021-05-25T13:49:29.6488978+08:00;True|2021-05-25T13:48:24.6686105+08:00;True|2021-05-25T13:25:41.2512493+08:00;True|2021-05-24T17:55:33.3800078+08:00;True|2021-05-20T14:35:30.6957985+08:00;True|2021-05-20T13:17:22.6192995+08:00;True|2021-05-20T10:51:38.1268169+08:00;True|2021-05-19T19:50:03.7000224+08:00;True|2021-05-19T19:44:27.2518811+08:00;True|2021-05-19T19:43:26.5916681+08:00;True|2021-05-19T19:36:29.3197365+08:00;True|2021-05-19T19:30:00.3802430+08:00;True|2021-05-19T17:55:23.7939835+08:00;True|2021-05-19T11:05:17.9043392+08:00;True|2021-05-19T10:19:38.4839988+08:00;True|2021-05-19T10:17:19.7430612+08:00;True|2021-05-19T10:13:23.0031721+08:00;True|2021-05-19T10:06:03.9881599+08:00;True|2021-05-18T14:39:03.8876574+08:00;True|2021-05-18T14:23:46.9818836+08:00;True|2021-05-18T14:19:56.2382079+08:00;True|2021-05-18T11:29:53.5497590+08:00;True|2021-05-18T11:16:18.0123853+08:00;True|2021-05-17T18:59:52.4159105+08:00;True|2021-05-17T18:53:37.9438984+08:00;True|2021-05-17T18:48:14.9625161+08:00;True|2021-05-17T17:46:03.7723404+08:00;True|2021-05-17T17:14:20.2312990+08:00;True|2021-05-17T16:44:34.5837616+08:00;True|2021-05-17T16:25:20.1087804+08:00;True|2021-05-17T11:35:27.9388562+08:00;</History>
</PropertyGroup>
</Project>

View File

@ -47,7 +47,8 @@
"ApiUrl": "https://api.data.suzhou.ljflytjl.cn",
"UserId": "55863a65-a28c-4e7f-8835-1fa779e1eb9f",
"ApiSecret": "EtifGTppTL0TTjie",
"ApiSecretHash": "3f907fe05acb58c6"
"ApiSecretHash": "3f907fe05acb58c6",
"SocketUrl": "wss://api.device.suzhou.ljflytjl.cn/device_rpc"
},
"IsTask": "false", //
"SoftName": "巨鼎物联网数字平台", //

View File

@ -0,0 +1,10 @@
{
"version": "1.0",
"defaultProvider": "unpkg",
"libraries": [
{
"library": "@microsoft/signalr@latest",
"destination": "wwwroot/lib/microsoft/signalr/"
}
]
}

View File

@ -0,0 +1,85 @@
JavaScript and TypeScript clients for SignalR for ASP.NET Core and Azure SignalR Service
## Installation
```bash
npm install @microsoft/signalr
# or
yarn add @microsoft/signalr
```
To try previews of the next version, use the `next` tag on NPM:
```bash
npm install @microsoft/signalr@next
# or
yarn add @microsoft/signalr@next
```
## Usage
See the [SignalR Documentation](https://docs.microsoft.com/aspnet/core/signalr) at docs.microsoft.com for documentation on the latest release. [API Reference Documentation](https://docs.microsoft.com/javascript/api/%40aspnet/signalr/?view=signalr-js-latest) is also available on docs.microsoft.com.
For documentation on using this client with Azure SignalR Service and Azure Functions, see the [SignalR Service serverless developer guide](https://docs.microsoft.com/azure/azure-signalr/signalr-concept-serverless-development-config).
### Browser
To use the client in a browser, copy `*.js` files from the `dist/browser` folder to your script folder include on your page using the `<script>` tag.
### WebWorker
To use the client in a webworker, copy `*.js` files from the `dist/webworker` folder to your script folder include on your webworker using the `importScripts` function. Note that webworker SignalR hub connection supports only absolute path to a SignalR hub.
### Node.js
To use the client in a NodeJS application, install the package to your `node_modules` folder and use `require('@microsoft/signalr')` to load the module. The object returned by `require('@microsoft/signalr')` has the same members as the global `signalR` object (when used in a browser).
### Example (Browser)
```javascript
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chat")
.build();
connection.on("send", data => {
console.log(data);
});
connection.start()
.then(() => connection.invoke("send", "Hello"));
```
### Example (WebWorker)
```javascript
importScripts('signalr.js');
let connection = new signalR.HubConnectionBuilder()
.withUrl("https://example.com/signalr/chat")
.build();
connection.on("send", data => {
console.log(data);
});
connection.start()
.then(() => connection.invoke("send", "Hello"));
```
### Example (NodeJS)
```javascript
const signalR = require("@microsoft/signalr");
let connection = new signalR.HubConnectionBuilder()
.withUrl("/chat")
.build();
connection.on("send", data => {
console.log(data);
});
connection.start()
.then(() => connection.invoke("send", "Hello"));
```

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,40 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController
// We don't actually ever use the API being polyfilled, we always use the polyfill because
// it's a very new API right now.
// Not exported from index.
/** @private */
var AbortController = /** @class */ (function () {
function AbortController() {
this.isAborted = false;
this.onabort = null;
}
AbortController.prototype.abort = function () {
if (!this.isAborted) {
this.isAborted = true;
if (this.onabort) {
this.onabort();
}
}
};
Object.defineProperty(AbortController.prototype, "signal", {
get: function () {
return this;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbortController.prototype, "aborted", {
get: function () {
return this.isAborted;
},
enumerable: true,
configurable: true
});
return AbortController;
}());
exports.AbortController = AbortController;
//# sourceMappingURL=AbortController.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"AbortController.js","sourceRoot":"","sources":["../../src/AbortController.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G;;AAE/G,qFAAqF;AACrF,0FAA0F;AAC1F,iCAAiC;AAEjC,2BAA2B;AAC3B,eAAe;AACf;IAAA;QACY,cAAS,GAAY,KAAK,CAAC;QAC5B,YAAO,GAAwB,IAAI,CAAC;IAkB/C,CAAC;IAhBU,+BAAK,GAAZ;QACI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACjB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;YACtB,IAAI,IAAI,CAAC,OAAO,EAAE;gBACd,IAAI,CAAC,OAAO,EAAE,CAAC;aAClB;SACJ;IACL,CAAC;IAED,sBAAI,mCAAM;aAAV;YACI,OAAO,IAAI,CAAC;QAChB,CAAC;;;OAAA;IAED,sBAAI,oCAAO;aAAX;YACI,OAAO,IAAI,CAAC,SAAS,CAAC;QAC1B,CAAC;;;OAAA;IACL,sBAAC;AAAD,CAAC,AApBD,IAoBC;AApBY,0CAAe","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController\r\n// We don't actually ever use the API being polyfilled, we always use the polyfill because\r\n// it's a very new API right now.\r\n\r\n// Not exported from index.\r\n/** @private */\r\nexport class AbortController implements AbortSignal {\r\n private isAborted: boolean = false;\r\n public onabort: (() => void) | null = null;\r\n\r\n public abort() {\r\n if (!this.isAborted) {\r\n this.isAborted = true;\r\n if (this.onabort) {\r\n this.onabort();\r\n }\r\n }\r\n }\r\n\r\n get signal(): AbortSignal {\r\n return this;\r\n }\r\n\r\n get aborted(): boolean {\r\n return this.isAborted;\r\n }\r\n}\r\n\r\n/** Represents a signal that can be monitored to determine if a request has been aborted. */\r\nexport interface AbortSignal {\r\n /** Indicates if the request has been aborted. */\r\n aborted: boolean;\r\n /** Set this to a handler that will be invoked when the request is aborted. */\r\n onabort: (() => void) | null;\r\n}\r\n"]}

View File

@ -0,0 +1,57 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Errors_1 = require("./Errors");
var FetchHttpClient_1 = require("./FetchHttpClient");
var HttpClient_1 = require("./HttpClient");
var Utils_1 = require("./Utils");
var XhrHttpClient_1 = require("./XhrHttpClient");
/** Default implementation of {@link @microsoft/signalr.HttpClient}. */
var DefaultHttpClient = /** @class */ (function (_super) {
__extends(DefaultHttpClient, _super);
/** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */
function DefaultHttpClient(logger) {
var _this = _super.call(this) || this;
if (typeof fetch !== "undefined" || Utils_1.Platform.isNode) {
_this.httpClient = new FetchHttpClient_1.FetchHttpClient(logger);
}
else if (typeof XMLHttpRequest !== "undefined") {
_this.httpClient = new XhrHttpClient_1.XhrHttpClient(logger);
}
else {
throw new Error("No usable HttpClient found.");
}
return _this;
}
/** @inheritDoc */
DefaultHttpClient.prototype.send = function (request) {
// Check that abort was not signaled before calling send
if (request.abortSignal && request.abortSignal.aborted) {
return Promise.reject(new Errors_1.AbortError());
}
if (!request.method) {
return Promise.reject(new Error("No method defined."));
}
if (!request.url) {
return Promise.reject(new Error("No url defined."));
}
return this.httpClient.send(request);
};
DefaultHttpClient.prototype.getCookieString = function (url) {
return this.httpClient.getCookieString(url);
};
return DefaultHttpClient;
}(HttpClient_1.HttpClient));
exports.DefaultHttpClient = DefaultHttpClient;
//# sourceMappingURL=DefaultHttpClient.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"DefaultHttpClient.js","sourceRoot":"","sources":["../../src/DefaultHttpClient.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G;;;;;;;;;;;;AAE/G,mCAAsC;AACtC,qDAAoD;AACpD,2CAAqE;AAErE,iCAAmC;AACnC,iDAAgD;AAEhD,uEAAuE;AACvE;IAAuC,qCAAU;IAG7C,yJAAyJ;IACzJ,2BAAmB,MAAe;QAAlC,YACI,iBAAO,SASV;QAPG,IAAI,OAAO,KAAK,KAAK,WAAW,IAAI,gBAAQ,CAAC,MAAM,EAAE;YACjD,KAAI,CAAC,UAAU,GAAG,IAAI,iCAAe,CAAC,MAAM,CAAC,CAAC;SACjD;aAAM,IAAI,OAAO,cAAc,KAAK,WAAW,EAAE;YAC9C,KAAI,CAAC,UAAU,GAAG,IAAI,6BAAa,CAAC,MAAM,CAAC,CAAC;SAC/C;aAAM;YACH,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;SAClD;;IACL,CAAC;IAED,kBAAkB;IACX,gCAAI,GAAX,UAAY,OAAoB;QAC5B,wDAAwD;QACxD,IAAI,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE;YACpD,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,mBAAU,EAAE,CAAC,CAAC;SAC3C;QAED,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;YACjB,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC,CAAC;SAC1D;QACD,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE;YACd,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC;SACvD;QAED,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACzC,CAAC;IAEM,2CAAe,GAAtB,UAAuB,GAAW;QAC9B,OAAO,IAAI,CAAC,UAAU,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;IAChD,CAAC;IACL,wBAAC;AAAD,CAAC,AApCD,CAAuC,uBAAU,GAoChD;AApCY,8CAAiB","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { AbortError } from \"./Errors\";\r\nimport { FetchHttpClient } from \"./FetchHttpClient\";\r\nimport { HttpClient, HttpRequest, HttpResponse } from \"./HttpClient\";\r\nimport { ILogger } from \"./ILogger\";\r\nimport { Platform } from \"./Utils\";\r\nimport { XhrHttpClient } from \"./XhrHttpClient\";\r\n\r\n/** Default implementation of {@link @microsoft/signalr.HttpClient}. */\r\nexport class DefaultHttpClient extends HttpClient {\r\n private readonly httpClient: HttpClient;\r\n\r\n /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */\r\n public constructor(logger: ILogger) {\r\n super();\r\n\r\n if (typeof fetch !== \"undefined\" || Platform.isNode) {\r\n this.httpClient = new FetchHttpClient(logger);\r\n } else if (typeof XMLHttpRequest !== \"undefined\") {\r\n this.httpClient = new XhrHttpClient(logger);\r\n } else {\r\n throw new Error(\"No usable HttpClient found.\");\r\n }\r\n }\r\n\r\n /** @inheritDoc */\r\n public send(request: HttpRequest): Promise<HttpResponse> {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n return Promise.reject(new AbortError());\r\n }\r\n\r\n if (!request.method) {\r\n return Promise.reject(new Error(\"No method defined.\"));\r\n }\r\n if (!request.url) {\r\n return Promise.reject(new Error(\"No url defined.\"));\r\n }\r\n\r\n return this.httpClient.send(request);\r\n }\r\n\r\n public getCookieString(url: string): string {\r\n return this.httpClient.getCookieString(url);\r\n }\r\n}\r\n"]}

View File

@ -0,0 +1,18 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
// 0, 2, 10, 30 second delays before reconnect attempts.
var DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];
/** @private */
var DefaultReconnectPolicy = /** @class */ (function () {
function DefaultReconnectPolicy(retryDelays) {
this.retryDelays = retryDelays !== undefined ? retryDelays.concat([null]) : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;
}
DefaultReconnectPolicy.prototype.nextRetryDelayInMilliseconds = function (retryContext) {
return this.retryDelays[retryContext.previousRetryCount];
};
return DefaultReconnectPolicy;
}());
exports.DefaultReconnectPolicy = DefaultReconnectPolicy;
//# sourceMappingURL=DefaultReconnectPolicy.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"DefaultReconnectPolicy.js","sourceRoot":"","sources":["../../src/DefaultReconnectPolicy.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G;;AAI/G,wDAAwD;AACxD,IAAM,oCAAoC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;AAE3E,eAAe;AACf;IAGI,gCAAY,WAAsB;QAC9B,IAAI,CAAC,WAAW,GAAG,WAAW,KAAK,SAAS,CAAC,CAAC,CAAK,WAAW,SAAE,IAAI,GAAE,CAAC,CAAC,oCAAoC,CAAC;IACjH,CAAC;IAEM,6DAA4B,GAAnC,UAAoC,YAA0B;QAC1D,OAAO,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC,kBAAkB,CAAC,CAAC;IAC7D,CAAC;IACL,6BAAC;AAAD,CAAC,AAVD,IAUC;AAVY,wDAAsB","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { IRetryPolicy, RetryContext } from \"./IRetryPolicy\";\r\n\r\n// 0, 2, 10, 30 second delays before reconnect attempts.\r\nconst DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];\r\n\r\n/** @private */\r\nexport class DefaultReconnectPolicy implements IRetryPolicy {\r\n private readonly retryDelays: Array<number | null>;\r\n\r\n constructor(retryDelays?: number[]) {\r\n this.retryDelays = retryDelays !== undefined ? [...retryDelays, null] : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;\r\n }\r\n\r\n public nextRetryDelayInMilliseconds(retryContext: RetryContext): number | null {\r\n return this.retryDelays[retryContext.previousRetryCount];\r\n }\r\n}\r\n"]}

View File

@ -0,0 +1,79 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
/** Error thrown when an HTTP request fails. */
var HttpError = /** @class */ (function (_super) {
__extends(HttpError, _super);
/** Constructs a new instance of {@link @microsoft/signalr.HttpError}.
*
* @param {string} errorMessage A descriptive error message.
* @param {number} statusCode The HTTP status code represented by this error.
*/
function HttpError(errorMessage, statusCode) {
var _newTarget = this.constructor;
var _this = this;
var trueProto = _newTarget.prototype;
_this = _super.call(this, errorMessage) || this;
_this.statusCode = statusCode;
// Workaround issue in Typescript compiler
// https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
_this.__proto__ = trueProto;
return _this;
}
return HttpError;
}(Error));
exports.HttpError = HttpError;
/** Error thrown when a timeout elapses. */
var TimeoutError = /** @class */ (function (_super) {
__extends(TimeoutError, _super);
/** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.
*
* @param {string} errorMessage A descriptive error message.
*/
function TimeoutError(errorMessage) {
var _newTarget = this.constructor;
if (errorMessage === void 0) { errorMessage = "A timeout occurred."; }
var _this = this;
var trueProto = _newTarget.prototype;
_this = _super.call(this, errorMessage) || this;
// Workaround issue in Typescript compiler
// https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
_this.__proto__ = trueProto;
return _this;
}
return TimeoutError;
}(Error));
exports.TimeoutError = TimeoutError;
/** Error thrown when an action is aborted. */
var AbortError = /** @class */ (function (_super) {
__extends(AbortError, _super);
/** Constructs a new instance of {@link AbortError}.
*
* @param {string} errorMessage A descriptive error message.
*/
function AbortError(errorMessage) {
var _newTarget = this.constructor;
if (errorMessage === void 0) { errorMessage = "An abort occurred."; }
var _this = this;
var trueProto = _newTarget.prototype;
_this = _super.call(this, errorMessage) || this;
// Workaround issue in Typescript compiler
// https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
_this.__proto__ = trueProto;
return _this;
}
return AbortError;
}(Error));
exports.AbortError = AbortError;
//# sourceMappingURL=Errors.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"Errors.js","sourceRoot":"","sources":["../../src/Errors.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G;;;;;;;;;;;;AAE/G,+CAA+C;AAC/C;IAA+B,6BAAK;IAQhC;;;;OAIG;IACH,mBAAY,YAAoB,EAAE,UAAkB;;QAApD,iBAQC;QAPG,IAAM,SAAS,GAAG,WAAW,SAAS,CAAC;QACvC,QAAA,kBAAM,YAAY,CAAC,SAAC;QACpB,KAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAE7B,0CAA0C;QAC1C,8EAA8E;QAC9E,KAAI,CAAC,SAAS,GAAG,SAAS,CAAC;;IAC/B,CAAC;IACL,gBAAC;AAAD,CAAC,AAtBD,CAA+B,KAAK,GAsBnC;AAtBY,8BAAS;AAwBtB,2CAA2C;AAC3C;IAAkC,gCAAK;IAKnC;;;OAGG;IACH,sBAAY,YAA4C;;QAA5C,6BAAA,EAAA,oCAA4C;QAAxD,iBAOC;QANG,IAAM,SAAS,GAAG,WAAW,SAAS,CAAC;QACvC,QAAA,kBAAM,YAAY,CAAC,SAAC;QAEpB,0CAA0C;QAC1C,8EAA8E;QAC9E,KAAI,CAAC,SAAS,GAAG,SAAS,CAAC;;IAC/B,CAAC;IACL,mBAAC;AAAD,CAAC,AAjBD,CAAkC,KAAK,GAiBtC;AAjBY,oCAAY;AAmBzB,8CAA8C;AAC9C;IAAgC,8BAAK;IAKjC;;;OAGG;IACH,oBAAY,YAA2C;;QAA3C,6BAAA,EAAA,mCAA2C;QAAvD,iBAOC;QANG,IAAM,SAAS,GAAG,WAAW,SAAS,CAAC;QACvC,QAAA,kBAAM,YAAY,CAAC,SAAC;QAEpB,0CAA0C;QAC1C,8EAA8E;QAC9E,KAAI,CAAC,SAAS,GAAG,SAAS,CAAC;;IAC/B,CAAC;IACL,iBAAC;AAAD,CAAC,AAjBD,CAAgC,KAAK,GAiBpC;AAjBY,gCAAU","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n/** Error thrown when an HTTP request fails. */\r\nexport class HttpError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // tslint:disable-next-line:variable-name\r\n private __proto__: Error;\r\n\r\n /** The HTTP status code represented by this error. */\r\n public statusCode: number;\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n * @param {number} statusCode The HTTP status code represented by this error.\r\n */\r\n constructor(errorMessage: string, statusCode: number) {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n this.statusCode = statusCode;\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when a timeout elapses. */\r\nexport class TimeoutError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // tslint:disable-next-line:variable-name\r\n private __proto__: Error;\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\r\n constructor(errorMessage: string = \"A timeout occurred.\") {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when an action is aborted. */\r\nexport class AbortError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // tslint:disable-next-line:variable-name\r\n private __proto__: Error;\r\n\r\n /** Constructs a new instance of {@link AbortError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\r\n constructor(errorMessage: string = \"An abort occurred.\") {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n"]}

View File

@ -0,0 +1,195 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var Errors_1 = require("./Errors");
var HttpClient_1 = require("./HttpClient");
var ILogger_1 = require("./ILogger");
var Utils_1 = require("./Utils");
var FetchHttpClient = /** @class */ (function (_super) {
__extends(FetchHttpClient, _super);
function FetchHttpClient(logger) {
var _this = _super.call(this) || this;
_this.logger = logger;
if (typeof fetch === "undefined") {
// In order to ignore the dynamic require in webpack builds we need to do this magic
// @ts-ignore: TS doesn't know about these names
var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
// Cookies aren't automatically handled in Node so we need to add a CookieJar to preserve cookies across requests
_this.jar = new (requireFunc("tough-cookie")).CookieJar();
_this.fetchType = requireFunc("node-fetch");
// node-fetch doesn't have a nice API for getting and setting cookies
// fetch-cookie will wrap a fetch implementation with a default CookieJar or a provided one
_this.fetchType = requireFunc("fetch-cookie")(_this.fetchType, _this.jar);
// Node needs EventListener methods on AbortController which our custom polyfill doesn't provide
_this.abortControllerType = requireFunc("abort-controller");
}
else {
_this.fetchType = fetch.bind(self);
_this.abortControllerType = AbortController;
}
return _this;
}
/** @inheritDoc */
FetchHttpClient.prototype.send = function (request) {
return __awaiter(this, void 0, void 0, function () {
var abortController, error, timeoutId, msTimeout, response, e_1, content, payload;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Check that abort was not signaled before calling send
if (request.abortSignal && request.abortSignal.aborted) {
throw new Errors_1.AbortError();
}
if (!request.method) {
throw new Error("No method defined.");
}
if (!request.url) {
throw new Error("No url defined.");
}
abortController = new this.abortControllerType();
// Hook our abortSignal into the abort controller
if (request.abortSignal) {
request.abortSignal.onabort = function () {
abortController.abort();
error = new Errors_1.AbortError();
};
}
timeoutId = null;
if (request.timeout) {
msTimeout = request.timeout;
timeoutId = setTimeout(function () {
abortController.abort();
_this.logger.log(ILogger_1.LogLevel.Warning, "Timeout from HTTP request.");
error = new Errors_1.TimeoutError();
}, msTimeout);
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, 4, 5]);
return [4 /*yield*/, this.fetchType(request.url, {
body: request.content,
cache: "no-cache",
credentials: request.withCredentials === true ? "include" : "same-origin",
headers: __assign({ "Content-Type": "text/plain;charset=UTF-8", "X-Requested-With": "XMLHttpRequest" }, request.headers),
method: request.method,
mode: "cors",
redirect: "manual",
signal: abortController.signal,
})];
case 2:
response = _a.sent();
return [3 /*break*/, 5];
case 3:
e_1 = _a.sent();
if (error) {
throw error;
}
this.logger.log(ILogger_1.LogLevel.Warning, "Error from HTTP request. " + e_1 + ".");
throw e_1;
case 4:
if (timeoutId) {
clearTimeout(timeoutId);
}
if (request.abortSignal) {
request.abortSignal.onabort = null;
}
return [7 /*endfinally*/];
case 5:
if (!response.ok) {
throw new Errors_1.HttpError(response.statusText, response.status);
}
content = deserializeContent(response, request.responseType);
return [4 /*yield*/, content];
case 6:
payload = _a.sent();
return [2 /*return*/, new HttpClient_1.HttpResponse(response.status, response.statusText, payload)];
}
});
});
};
FetchHttpClient.prototype.getCookieString = function (url) {
var cookies = "";
if (Utils_1.Platform.isNode && this.jar) {
// @ts-ignore: unused variable
this.jar.getCookies(url, function (e, c) { return cookies = c.join("; "); });
}
return cookies;
};
return FetchHttpClient;
}(HttpClient_1.HttpClient));
exports.FetchHttpClient = FetchHttpClient;
function deserializeContent(response, responseType) {
var content;
switch (responseType) {
case "arraybuffer":
content = response.arrayBuffer();
break;
case "text":
content = response.text();
break;
case "blob":
case "document":
case "json":
throw new Error(responseType + " is not supported.");
default:
content = response.text();
break;
}
return content;
}
//# sourceMappingURL=FetchHttpClient.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,58 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
var TextMessageFormat_1 = require("./TextMessageFormat");
var Utils_1 = require("./Utils");
/** @private */
var HandshakeProtocol = /** @class */ (function () {
function HandshakeProtocol() {
}
// Handshake request is always JSON
HandshakeProtocol.prototype.writeHandshakeRequest = function (handshakeRequest) {
return TextMessageFormat_1.TextMessageFormat.write(JSON.stringify(handshakeRequest));
};
HandshakeProtocol.prototype.parseHandshakeResponse = function (data) {
var responseMessage;
var messageData;
var remainingData;
if (Utils_1.isArrayBuffer(data) || (typeof Buffer !== "undefined" && data instanceof Buffer)) {
// Format is binary but still need to read JSON text from handshake response
var binaryData = new Uint8Array(data);
var separatorIndex = binaryData.indexOf(TextMessageFormat_1.TextMessageFormat.RecordSeparatorCode);
if (separatorIndex === -1) {
throw new Error("Message is incomplete.");
}
// content before separator is handshake response
// optional content after is additional messages
var responseLength = separatorIndex + 1;
messageData = String.fromCharCode.apply(null, binaryData.slice(0, responseLength));
remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;
}
else {
var textData = data;
var separatorIndex = textData.indexOf(TextMessageFormat_1.TextMessageFormat.RecordSeparator);
if (separatorIndex === -1) {
throw new Error("Message is incomplete.");
}
// content before separator is handshake response
// optional content after is additional messages
var responseLength = separatorIndex + 1;
messageData = textData.substring(0, responseLength);
remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;
}
// At this point we should have just the single handshake message
var messages = TextMessageFormat_1.TextMessageFormat.parse(messageData);
var response = JSON.parse(messages[0]);
if (response.type) {
throw new Error("Expected a handshake response from the server.");
}
responseMessage = response;
// multiple messages could have arrived with handshake
// return additional data to be parsed as usual, or null if all parsed
return [remainingData, responseMessage];
};
return HandshakeProtocol;
}());
exports.HandshakeProtocol = HandshakeProtocol;
//# sourceMappingURL=HandshakeProtocol.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,51 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
/** Represents an HTTP response. */
var HttpResponse = /** @class */ (function () {
function HttpResponse(statusCode, statusText, content) {
this.statusCode = statusCode;
this.statusText = statusText;
this.content = content;
}
return HttpResponse;
}());
exports.HttpResponse = HttpResponse;
/** Abstraction over an HTTP client.
*
* This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms.
*/
var HttpClient = /** @class */ (function () {
function HttpClient() {
}
HttpClient.prototype.get = function (url, options) {
return this.send(__assign({}, options, { method: "GET", url: url }));
};
HttpClient.prototype.post = function (url, options) {
return this.send(__assign({}, options, { method: "POST", url: url }));
};
HttpClient.prototype.delete = function (url, options) {
return this.send(__assign({}, options, { method: "DELETE", url: url }));
};
/** Gets all cookies that apply to the specified URL.
*
* @param url The URL that the cookies are valid for.
* @returns {string} A string containing all the key-value cookie pairs for the specified URL.
*/
// @ts-ignore
HttpClient.prototype.getCookieString = function (url) {
return "";
};
return HttpClient;
}());
exports.HttpClient = HttpClient;
//# sourceMappingURL=HttpClient.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,709 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var DefaultHttpClient_1 = require("./DefaultHttpClient");
var ILogger_1 = require("./ILogger");
var ITransport_1 = require("./ITransport");
var LongPollingTransport_1 = require("./LongPollingTransport");
var ServerSentEventsTransport_1 = require("./ServerSentEventsTransport");
var Utils_1 = require("./Utils");
var WebSocketTransport_1 = require("./WebSocketTransport");
var MAX_REDIRECTS = 100;
/** @private */
var HttpConnection = /** @class */ (function () {
function HttpConnection(url, options) {
if (options === void 0) { options = {}; }
this.stopPromiseResolver = function () { };
this.features = {};
this.negotiateVersion = 1;
Utils_1.Arg.isRequired(url, "url");
this.logger = Utils_1.createLogger(options.logger);
this.baseUrl = this.resolveUrl(url);
options = options || {};
options.logMessageContent = options.logMessageContent === undefined ? false : options.logMessageContent;
if (typeof options.withCredentials === "boolean" || options.withCredentials === undefined) {
options.withCredentials = options.withCredentials === undefined ? true : options.withCredentials;
}
else {
throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");
}
var webSocketModule = null;
var eventSourceModule = null;
if (Utils_1.Platform.isNode && typeof require !== "undefined") {
// In order to ignore the dynamic require in webpack builds we need to do this magic
// @ts-ignore: TS doesn't know about these names
var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
webSocketModule = requireFunc("ws");
eventSourceModule = requireFunc("eventsource");
}
if (!Utils_1.Platform.isNode && typeof WebSocket !== "undefined" && !options.WebSocket) {
options.WebSocket = WebSocket;
}
else if (Utils_1.Platform.isNode && !options.WebSocket) {
if (webSocketModule) {
options.WebSocket = webSocketModule;
}
}
if (!Utils_1.Platform.isNode && typeof EventSource !== "undefined" && !options.EventSource) {
options.EventSource = EventSource;
}
else if (Utils_1.Platform.isNode && !options.EventSource) {
if (typeof eventSourceModule !== "undefined") {
options.EventSource = eventSourceModule;
}
}
this.httpClient = options.httpClient || new DefaultHttpClient_1.DefaultHttpClient(this.logger);
this.connectionState = "Disconnected" /* Disconnected */;
this.connectionStarted = false;
this.options = options;
this.onreceive = null;
this.onclose = null;
}
HttpConnection.prototype.start = function (transferFormat) {
return __awaiter(this, void 0, void 0, function () {
var message, message;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
transferFormat = transferFormat || ITransport_1.TransferFormat.Binary;
Utils_1.Arg.isIn(transferFormat, ITransport_1.TransferFormat, "transferFormat");
this.logger.log(ILogger_1.LogLevel.Debug, "Starting connection with transfer format '" + ITransport_1.TransferFormat[transferFormat] + "'.");
if (this.connectionState !== "Disconnected" /* Disconnected */) {
return [2 /*return*/, Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."))];
}
this.connectionState = "Connecting" /* Connecting */;
this.startInternalPromise = this.startInternal(transferFormat);
return [4 /*yield*/, this.startInternalPromise];
case 1:
_a.sent();
if (!(this.connectionState === "Disconnecting" /* Disconnecting */)) return [3 /*break*/, 3];
message = "Failed to start the HttpConnection before stop() was called.";
this.logger.log(ILogger_1.LogLevel.Error, message);
// We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.
return [4 /*yield*/, this.stopPromise];
case 2:
// We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.
_a.sent();
return [2 /*return*/, Promise.reject(new Error(message))];
case 3:
if (this.connectionState !== "Connected" /* Connected */) {
message = "HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";
this.logger.log(ILogger_1.LogLevel.Error, message);
return [2 /*return*/, Promise.reject(new Error(message))];
}
_a.label = 4;
case 4:
this.connectionStarted = true;
return [2 /*return*/];
}
});
});
};
HttpConnection.prototype.send = function (data) {
if (this.connectionState !== "Connected" /* Connected */) {
return Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State."));
}
if (!this.sendQueue) {
this.sendQueue = new TransportSendQueue(this.transport);
}
// Transport will not be null if state is connected
return this.sendQueue.send(data);
};
HttpConnection.prototype.stop = function (error) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.connectionState === "Disconnected" /* Disconnected */) {
this.logger.log(ILogger_1.LogLevel.Debug, "Call to HttpConnection.stop(" + error + ") ignored because the connection is already in the disconnected state.");
return [2 /*return*/, Promise.resolve()];
}
if (this.connectionState === "Disconnecting" /* Disconnecting */) {
this.logger.log(ILogger_1.LogLevel.Debug, "Call to HttpConnection.stop(" + error + ") ignored because the connection is already in the disconnecting state.");
return [2 /*return*/, this.stopPromise];
}
this.connectionState = "Disconnecting" /* Disconnecting */;
this.stopPromise = new Promise(function (resolve) {
// Don't complete stop() until stopConnection() completes.
_this.stopPromiseResolver = resolve;
});
// stopInternal should never throw so just observe it.
return [4 /*yield*/, this.stopInternal(error)];
case 1:
// stopInternal should never throw so just observe it.
_a.sent();
return [4 /*yield*/, this.stopPromise];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
};
HttpConnection.prototype.stopInternal = function (error) {
return __awaiter(this, void 0, void 0, function () {
var e_1, e_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Set error as soon as possible otherwise there is a race between
// the transport closing and providing an error and the error from a close message
// We would prefer the close message error.
this.stopError = error;
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.startInternalPromise];
case 2:
_a.sent();
return [3 /*break*/, 4];
case 3:
e_1 = _a.sent();
return [3 /*break*/, 4];
case 4:
if (!this.transport) return [3 /*break*/, 9];
_a.label = 5;
case 5:
_a.trys.push([5, 7, , 8]);
return [4 /*yield*/, this.transport.stop()];
case 6:
_a.sent();
return [3 /*break*/, 8];
case 7:
e_2 = _a.sent();
this.logger.log(ILogger_1.LogLevel.Error, "HttpConnection.transport.stop() threw error '" + e_2 + "'.");
this.stopConnection();
return [3 /*break*/, 8];
case 8:
this.transport = undefined;
return [3 /*break*/, 10];
case 9:
this.logger.log(ILogger_1.LogLevel.Debug, "HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.");
_a.label = 10;
case 10: return [2 /*return*/];
}
});
});
};
HttpConnection.prototype.startInternal = function (transferFormat) {
return __awaiter(this, void 0, void 0, function () {
var url, negotiateResponse, redirects, _loop_1, this_1, e_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
url = this.baseUrl;
this.accessTokenFactory = this.options.accessTokenFactory;
_a.label = 1;
case 1:
_a.trys.push([1, 12, , 13]);
if (!this.options.skipNegotiation) return [3 /*break*/, 5];
if (!(this.options.transport === ITransport_1.HttpTransportType.WebSockets)) return [3 /*break*/, 3];
// No need to add a connection ID in this case
this.transport = this.constructTransport(ITransport_1.HttpTransportType.WebSockets);
// We should just call connect directly in this case.
// No fallback or negotiate in this case.
return [4 /*yield*/, this.startTransport(url, transferFormat)];
case 2:
// We should just call connect directly in this case.
// No fallback or negotiate in this case.
_a.sent();
return [3 /*break*/, 4];
case 3: throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");
case 4: return [3 /*break*/, 11];
case 5:
negotiateResponse = null;
redirects = 0;
_loop_1 = function () {
var accessToken_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this_1.getNegotiationResponse(url)];
case 1:
negotiateResponse = _a.sent();
// the user tries to stop the connection when it is being started
if (this_1.connectionState === "Disconnecting" /* Disconnecting */ || this_1.connectionState === "Disconnected" /* Disconnected */) {
throw new Error("The connection was stopped during negotiation.");
}
if (negotiateResponse.error) {
throw new Error(negotiateResponse.error);
}
if (negotiateResponse.ProtocolVersion) {
throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");
}
if (negotiateResponse.url) {
url = negotiateResponse.url;
}
if (negotiateResponse.accessToken) {
accessToken_1 = negotiateResponse.accessToken;
this_1.accessTokenFactory = function () { return accessToken_1; };
}
redirects++;
return [2 /*return*/];
}
});
};
this_1 = this;
_a.label = 6;
case 6: return [5 /*yield**/, _loop_1()];
case 7:
_a.sent();
_a.label = 8;
case 8:
if (negotiateResponse.url && redirects < MAX_REDIRECTS) return [3 /*break*/, 6];
_a.label = 9;
case 9:
if (redirects === MAX_REDIRECTS && negotiateResponse.url) {
throw new Error("Negotiate redirection limit exceeded.");
}
return [4 /*yield*/, this.createTransport(url, this.options.transport, negotiateResponse, transferFormat)];
case 10:
_a.sent();
_a.label = 11;
case 11:
if (this.transport instanceof LongPollingTransport_1.LongPollingTransport) {
this.features.inherentKeepAlive = true;
}
if (this.connectionState === "Connecting" /* Connecting */) {
// Ensure the connection transitions to the connected state prior to completing this.startInternalPromise.
// start() will handle the case when stop was called and startInternal exits still in the disconnecting state.
this.logger.log(ILogger_1.LogLevel.Debug, "The HttpConnection connected successfully.");
this.connectionState = "Connected" /* Connected */;
}
return [3 /*break*/, 13];
case 12:
e_3 = _a.sent();
this.logger.log(ILogger_1.LogLevel.Error, "Failed to start the connection: " + e_3);
this.connectionState = "Disconnected" /* Disconnected */;
this.transport = undefined;
// if start fails, any active calls to stop assume that start will complete the stop promise
this.stopPromiseResolver();
return [2 /*return*/, Promise.reject(e_3)];
case 13: return [2 /*return*/];
}
});
});
};
HttpConnection.prototype.getNegotiationResponse = function (url) {
return __awaiter(this, void 0, void 0, function () {
var headers, token, _a, name, value, negotiateUrl, response, negotiateResponse, e_4;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
headers = {};
if (!this.accessTokenFactory) return [3 /*break*/, 2];
return [4 /*yield*/, this.accessTokenFactory()];
case 1:
token = _b.sent();
if (token) {
headers["Authorization"] = "Bearer " + token;
}
_b.label = 2;
case 2:
_a = Utils_1.getUserAgentHeader(), name = _a[0], value = _a[1];
headers[name] = value;
negotiateUrl = this.resolveNegotiateUrl(url);
this.logger.log(ILogger_1.LogLevel.Debug, "Sending negotiation request: " + negotiateUrl + ".");
_b.label = 3;
case 3:
_b.trys.push([3, 5, , 6]);
return [4 /*yield*/, this.httpClient.post(negotiateUrl, {
content: "",
headers: __assign({}, headers, this.options.headers),
withCredentials: this.options.withCredentials,
})];
case 4:
response = _b.sent();
if (response.statusCode !== 200) {
return [2 /*return*/, Promise.reject(new Error("Unexpected status code returned from negotiate '" + response.statusCode + "'"))];
}
negotiateResponse = JSON.parse(response.content);
if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) {
// Negotiate version 0 doesn't use connectionToken
// So we set it equal to connectionId so all our logic can use connectionToken without being aware of the negotiate version
negotiateResponse.connectionToken = negotiateResponse.connectionId;
}
return [2 /*return*/, negotiateResponse];
case 5:
e_4 = _b.sent();
this.logger.log(ILogger_1.LogLevel.Error, "Failed to complete negotiation with the server: " + e_4);
return [2 /*return*/, Promise.reject(e_4)];
case 6: return [2 /*return*/];
}
});
});
};
HttpConnection.prototype.createConnectUrl = function (url, connectionToken) {
if (!connectionToken) {
return url;
}
return url + (url.indexOf("?") === -1 ? "?" : "&") + ("id=" + connectionToken);
};
HttpConnection.prototype.createTransport = function (url, requestedTransport, negotiateResponse, requestedTransferFormat) {
return __awaiter(this, void 0, void 0, function () {
var connectUrl, transportExceptions, transports, negotiate, _i, transports_1, endpoint, transportOrError, ex_1, ex_2, message;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
connectUrl = this.createConnectUrl(url, negotiateResponse.connectionToken);
if (!this.isITransport(requestedTransport)) return [3 /*break*/, 2];
this.logger.log(ILogger_1.LogLevel.Debug, "Connection was provided an instance of ITransport, using that directly.");
this.transport = requestedTransport;
return [4 /*yield*/, this.startTransport(connectUrl, requestedTransferFormat)];
case 1:
_a.sent();
this.connectionId = negotiateResponse.connectionId;
return [2 /*return*/];
case 2:
transportExceptions = [];
transports = negotiateResponse.availableTransports || [];
negotiate = negotiateResponse;
_i = 0, transports_1 = transports;
_a.label = 3;
case 3:
if (!(_i < transports_1.length)) return [3 /*break*/, 13];
endpoint = transports_1[_i];
transportOrError = this.resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat);
if (!(transportOrError instanceof Error)) return [3 /*break*/, 4];
// Store the error and continue, we don't want to cause a re-negotiate in these cases
transportExceptions.push(endpoint.transport + " failed: " + transportOrError);
return [3 /*break*/, 12];
case 4:
if (!this.isITransport(transportOrError)) return [3 /*break*/, 12];
this.transport = transportOrError;
if (!!negotiate) return [3 /*break*/, 9];
_a.label = 5;
case 5:
_a.trys.push([5, 7, , 8]);
return [4 /*yield*/, this.getNegotiationResponse(url)];
case 6:
negotiate = _a.sent();
return [3 /*break*/, 8];
case 7:
ex_1 = _a.sent();
return [2 /*return*/, Promise.reject(ex_1)];
case 8:
connectUrl = this.createConnectUrl(url, negotiate.connectionToken);
_a.label = 9;
case 9:
_a.trys.push([9, 11, , 12]);
return [4 /*yield*/, this.startTransport(connectUrl, requestedTransferFormat)];
case 10:
_a.sent();
this.connectionId = negotiate.connectionId;
return [2 /*return*/];
case 11:
ex_2 = _a.sent();
this.logger.log(ILogger_1.LogLevel.Error, "Failed to start the transport '" + endpoint.transport + "': " + ex_2);
negotiate = undefined;
transportExceptions.push(endpoint.transport + " failed: " + ex_2);
if (this.connectionState !== "Connecting" /* Connecting */) {
message = "Failed to select transport before stop() was called.";
this.logger.log(ILogger_1.LogLevel.Debug, message);
return [2 /*return*/, Promise.reject(new Error(message))];
}
return [3 /*break*/, 12];
case 12:
_i++;
return [3 /*break*/, 3];
case 13:
if (transportExceptions.length > 0) {
return [2 /*return*/, Promise.reject(new Error("Unable to connect to the server with any of the available transports. " + transportExceptions.join(" ")))];
}
return [2 /*return*/, Promise.reject(new Error("None of the transports supported by the client are supported by the server."))];
}
});
});
};
HttpConnection.prototype.constructTransport = function (transport) {
switch (transport) {
case ITransport_1.HttpTransportType.WebSockets:
if (!this.options.WebSocket) {
throw new Error("'WebSocket' is not supported in your environment.");
}
return new WebSocketTransport_1.WebSocketTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.WebSocket, this.options.headers || {});
case ITransport_1.HttpTransportType.ServerSentEvents:
if (!this.options.EventSource) {
throw new Error("'EventSource' is not supported in your environment.");
}
return new ServerSentEventsTransport_1.ServerSentEventsTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.EventSource, this.options.withCredentials, this.options.headers || {});
case ITransport_1.HttpTransportType.LongPolling:
return new LongPollingTransport_1.LongPollingTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.withCredentials, this.options.headers || {});
default:
throw new Error("Unknown transport: " + transport + ".");
}
};
HttpConnection.prototype.startTransport = function (url, transferFormat) {
var _this = this;
this.transport.onreceive = this.onreceive;
this.transport.onclose = function (e) { return _this.stopConnection(e); };
return this.transport.connect(url, transferFormat);
};
HttpConnection.prototype.resolveTransportOrError = function (endpoint, requestedTransport, requestedTransferFormat) {
var transport = ITransport_1.HttpTransportType[endpoint.transport];
if (transport === null || transport === undefined) {
this.logger.log(ILogger_1.LogLevel.Debug, "Skipping transport '" + endpoint.transport + "' because it is not supported by this client.");
return new Error("Skipping transport '" + endpoint.transport + "' because it is not supported by this client.");
}
else {
if (transportMatches(requestedTransport, transport)) {
var transferFormats = endpoint.transferFormats.map(function (s) { return ITransport_1.TransferFormat[s]; });
if (transferFormats.indexOf(requestedTransferFormat) >= 0) {
if ((transport === ITransport_1.HttpTransportType.WebSockets && !this.options.WebSocket) ||
(transport === ITransport_1.HttpTransportType.ServerSentEvents && !this.options.EventSource)) {
this.logger.log(ILogger_1.LogLevel.Debug, "Skipping transport '" + ITransport_1.HttpTransportType[transport] + "' because it is not supported in your environment.'");
return new Error("'" + ITransport_1.HttpTransportType[transport] + "' is not supported in your environment.");
}
else {
this.logger.log(ILogger_1.LogLevel.Debug, "Selecting transport '" + ITransport_1.HttpTransportType[transport] + "'.");
try {
return this.constructTransport(transport);
}
catch (ex) {
return ex;
}
}
}
else {
this.logger.log(ILogger_1.LogLevel.Debug, "Skipping transport '" + ITransport_1.HttpTransportType[transport] + "' because it does not support the requested transfer format '" + ITransport_1.TransferFormat[requestedTransferFormat] + "'.");
return new Error("'" + ITransport_1.HttpTransportType[transport] + "' does not support " + ITransport_1.TransferFormat[requestedTransferFormat] + ".");
}
}
else {
this.logger.log(ILogger_1.LogLevel.Debug, "Skipping transport '" + ITransport_1.HttpTransportType[transport] + "' because it was disabled by the client.");
return new Error("'" + ITransport_1.HttpTransportType[transport] + "' is disabled by the client.");
}
}
};
HttpConnection.prototype.isITransport = function (transport) {
return transport && typeof (transport) === "object" && "connect" in transport;
};
HttpConnection.prototype.stopConnection = function (error) {
var _this = this;
this.logger.log(ILogger_1.LogLevel.Debug, "HttpConnection.stopConnection(" + error + ") called while in state " + this.connectionState + ".");
this.transport = undefined;
// If we have a stopError, it takes precedence over the error from the transport
error = this.stopError || error;
this.stopError = undefined;
if (this.connectionState === "Disconnected" /* Disconnected */) {
this.logger.log(ILogger_1.LogLevel.Debug, "Call to HttpConnection.stopConnection(" + error + ") was ignored because the connection is already in the disconnected state.");
return;
}
if (this.connectionState === "Connecting" /* Connecting */) {
this.logger.log(ILogger_1.LogLevel.Warning, "Call to HttpConnection.stopConnection(" + error + ") was ignored because the connection is still in the connecting state.");
throw new Error("HttpConnection.stopConnection(" + error + ") was called while the connection is still in the connecting state.");
}
if (this.connectionState === "Disconnecting" /* Disconnecting */) {
// A call to stop() induced this call to stopConnection and needs to be completed.
// Any stop() awaiters will be scheduled to continue after the onclose callback fires.
this.stopPromiseResolver();
}
if (error) {
this.logger.log(ILogger_1.LogLevel.Error, "Connection disconnected with error '" + error + "'.");
}
else {
this.logger.log(ILogger_1.LogLevel.Information, "Connection disconnected.");
}
if (this.sendQueue) {
this.sendQueue.stop().catch(function (e) {
_this.logger.log(ILogger_1.LogLevel.Error, "TransportSendQueue.stop() threw error '" + e + "'.");
});
this.sendQueue = undefined;
}
this.connectionId = undefined;
this.connectionState = "Disconnected" /* Disconnected */;
if (this.connectionStarted) {
this.connectionStarted = false;
try {
if (this.onclose) {
this.onclose(error);
}
}
catch (e) {
this.logger.log(ILogger_1.LogLevel.Error, "HttpConnection.onclose(" + error + ") threw error '" + e + "'.");
}
}
};
HttpConnection.prototype.resolveUrl = function (url) {
// startsWith is not supported in IE
if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) {
return url;
}
if (!Utils_1.Platform.isBrowser || !window.document) {
throw new Error("Cannot resolve '" + url + "'.");
}
// Setting the url to the href propery of an anchor tag handles normalization
// for us. There are 3 main cases.
// 1. Relative path normalization e.g "b" -> "http://localhost:5000/a/b"
// 2. Absolute path normalization e.g "/a/b" -> "http://localhost:5000/a/b"
// 3. Networkpath reference normalization e.g "//localhost:5000/a/b" -> "http://localhost:5000/a/b"
var aTag = window.document.createElement("a");
aTag.href = url;
this.logger.log(ILogger_1.LogLevel.Information, "Normalizing '" + url + "' to '" + aTag.href + "'.");
return aTag.href;
};
HttpConnection.prototype.resolveNegotiateUrl = function (url) {
var index = url.indexOf("?");
var negotiateUrl = url.substring(0, index === -1 ? url.length : index);
if (negotiateUrl[negotiateUrl.length - 1] !== "/") {
negotiateUrl += "/";
}
negotiateUrl += "negotiate";
negotiateUrl += index === -1 ? "" : url.substring(index);
if (negotiateUrl.indexOf("negotiateVersion") === -1) {
negotiateUrl += index === -1 ? "?" : "&";
negotiateUrl += "negotiateVersion=" + this.negotiateVersion;
}
return negotiateUrl;
};
return HttpConnection;
}());
exports.HttpConnection = HttpConnection;
function transportMatches(requestedTransport, actualTransport) {
return !requestedTransport || ((actualTransport & requestedTransport) !== 0);
}
/** @private */
var TransportSendQueue = /** @class */ (function () {
function TransportSendQueue(transport) {
this.transport = transport;
this.buffer = [];
this.executing = true;
this.sendBufferedData = new PromiseSource();
this.transportResult = new PromiseSource();
this.sendLoopPromise = this.sendLoop();
}
TransportSendQueue.prototype.send = function (data) {
this.bufferData(data);
if (!this.transportResult) {
this.transportResult = new PromiseSource();
}
return this.transportResult.promise;
};
TransportSendQueue.prototype.stop = function () {
this.executing = false;
this.sendBufferedData.resolve();
return this.sendLoopPromise;
};
TransportSendQueue.prototype.bufferData = function (data) {
if (this.buffer.length && typeof (this.buffer[0]) !== typeof (data)) {
throw new Error("Expected data to be of type " + typeof (this.buffer) + " but was of type " + typeof (data));
}
this.buffer.push(data);
this.sendBufferedData.resolve();
};
TransportSendQueue.prototype.sendLoop = function () {
return __awaiter(this, void 0, void 0, function () {
var transportResult, data, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!true) return [3 /*break*/, 6];
return [4 /*yield*/, this.sendBufferedData.promise];
case 1:
_a.sent();
if (!this.executing) {
if (this.transportResult) {
this.transportResult.reject("Connection stopped.");
}
return [3 /*break*/, 6];
}
this.sendBufferedData = new PromiseSource();
transportResult = this.transportResult;
this.transportResult = undefined;
data = typeof (this.buffer[0]) === "string" ?
this.buffer.join("") :
TransportSendQueue.concatBuffers(this.buffer);
this.buffer.length = 0;
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, this.transport.send(data)];
case 3:
_a.sent();
transportResult.resolve();
return [3 /*break*/, 5];
case 4:
error_1 = _a.sent();
transportResult.reject(error_1);
return [3 /*break*/, 5];
case 5: return [3 /*break*/, 0];
case 6: return [2 /*return*/];
}
});
});
};
TransportSendQueue.concatBuffers = function (arrayBuffers) {
var totalLength = arrayBuffers.map(function (b) { return b.byteLength; }).reduce(function (a, b) { return a + b; });
var result = new Uint8Array(totalLength);
var offset = 0;
for (var _i = 0, arrayBuffers_1 = arrayBuffers; _i < arrayBuffers_1.length; _i++) {
var item = arrayBuffers_1[_i];
result.set(new Uint8Array(item), offset);
offset += item.byteLength;
}
return result.buffer;
};
return TransportSendQueue;
}());
exports.TransportSendQueue = TransportSendQueue;
var PromiseSource = /** @class */ (function () {
function PromiseSource() {
var _this = this;
this.promise = new Promise(function (resolve, reject) {
var _a;
return _a = [resolve, reject], _this.resolver = _a[0], _this.rejecter = _a[1], _a;
});
}
PromiseSource.prototype.resolve = function () {
this.resolver();
};
PromiseSource.prototype.reject = function (reason) {
this.rejecter(reason);
};
return PromiseSource;
}());
//# sourceMappingURL=HttpConnection.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,968 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var HandshakeProtocol_1 = require("./HandshakeProtocol");
var IHubProtocol_1 = require("./IHubProtocol");
var ILogger_1 = require("./ILogger");
var Subject_1 = require("./Subject");
var Utils_1 = require("./Utils");
var DEFAULT_TIMEOUT_IN_MS = 30 * 1000;
var DEFAULT_PING_INTERVAL_IN_MS = 15 * 1000;
/** Describes the current state of the {@link HubConnection} to the server. */
var HubConnectionState;
(function (HubConnectionState) {
/** The hub connection is disconnected. */
HubConnectionState["Disconnected"] = "Disconnected";
/** The hub connection is connecting. */
HubConnectionState["Connecting"] = "Connecting";
/** The hub connection is connected. */
HubConnectionState["Connected"] = "Connected";
/** The hub connection is disconnecting. */
HubConnectionState["Disconnecting"] = "Disconnecting";
/** The hub connection is reconnecting. */
HubConnectionState["Reconnecting"] = "Reconnecting";
})(HubConnectionState = exports.HubConnectionState || (exports.HubConnectionState = {}));
/** Represents a connection to a SignalR Hub. */
var HubConnection = /** @class */ (function () {
function HubConnection(connection, logger, protocol, reconnectPolicy) {
var _this = this;
this.nextKeepAlive = 0;
Utils_1.Arg.isRequired(connection, "connection");
Utils_1.Arg.isRequired(logger, "logger");
Utils_1.Arg.isRequired(protocol, "protocol");
this.serverTimeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MS;
this.keepAliveIntervalInMilliseconds = DEFAULT_PING_INTERVAL_IN_MS;
this.logger = logger;
this.protocol = protocol;
this.connection = connection;
this.reconnectPolicy = reconnectPolicy;
this.handshakeProtocol = new HandshakeProtocol_1.HandshakeProtocol();
this.connection.onreceive = function (data) { return _this.processIncomingData(data); };
this.connection.onclose = function (error) { return _this.connectionClosed(error); };
this.callbacks = {};
this.methods = {};
this.closedCallbacks = [];
this.reconnectingCallbacks = [];
this.reconnectedCallbacks = [];
this.invocationId = 0;
this.receivedHandshakeResponse = false;
this.connectionState = HubConnectionState.Disconnected;
this.connectionStarted = false;
this.cachedPingMessage = this.protocol.writeMessage({ type: IHubProtocol_1.MessageType.Ping });
}
/** @internal */
// Using a public static factory method means we can have a private constructor and an _internal_
// create method that can be used by HubConnectionBuilder. An "internal" constructor would just
// be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a
// public parameter-less constructor.
HubConnection.create = function (connection, logger, protocol, reconnectPolicy) {
return new HubConnection(connection, logger, protocol, reconnectPolicy);
};
Object.defineProperty(HubConnection.prototype, "state", {
/** Indicates the state of the {@link HubConnection} to the server. */
get: function () {
return this.connectionState;
},
enumerable: true,
configurable: true
});
Object.defineProperty(HubConnection.prototype, "connectionId", {
/** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either
* in the disconnected state or if the negotiation step was skipped.
*/
get: function () {
return this.connection ? (this.connection.connectionId || null) : null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(HubConnection.prototype, "baseUrl", {
/** Indicates the url of the {@link HubConnection} to the server. */
get: function () {
return this.connection.baseUrl || "";
},
/**
* Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or
* Reconnecting states.
* @param {string} url The url to connect to.
*/
set: function (url) {
if (this.connectionState !== HubConnectionState.Disconnected && this.connectionState !== HubConnectionState.Reconnecting) {
throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");
}
if (!url) {
throw new Error("The HubConnection url must be a valid url.");
}
this.connection.baseUrl = url;
},
enumerable: true,
configurable: true
});
/** Starts the connection.
*
* @returns {Promise<void>} A Promise that resolves when the connection has been successfully established, or rejects with an error.
*/
HubConnection.prototype.start = function () {
this.startPromise = this.startWithStateTransitions();
return this.startPromise;
};
HubConnection.prototype.startWithStateTransitions = function () {
return __awaiter(this, void 0, void 0, function () {
var e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.connectionState !== HubConnectionState.Disconnected) {
return [2 /*return*/, Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."))];
}
this.connectionState = HubConnectionState.Connecting;
this.logger.log(ILogger_1.LogLevel.Debug, "Starting HubConnection.");
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.startInternal()];
case 2:
_a.sent();
this.connectionState = HubConnectionState.Connected;
this.connectionStarted = true;
this.logger.log(ILogger_1.LogLevel.Debug, "HubConnection connected successfully.");
return [3 /*break*/, 4];
case 3:
e_1 = _a.sent();
this.connectionState = HubConnectionState.Disconnected;
this.logger.log(ILogger_1.LogLevel.Debug, "HubConnection failed to start successfully because of error '" + e_1 + "'.");
return [2 /*return*/, Promise.reject(e_1)];
case 4: return [2 /*return*/];
}
});
});
};
HubConnection.prototype.startInternal = function () {
return __awaiter(this, void 0, void 0, function () {
var handshakePromise, handshakeRequest, e_2;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.stopDuringStartError = undefined;
this.receivedHandshakeResponse = false;
handshakePromise = new Promise(function (resolve, reject) {
_this.handshakeResolver = resolve;
_this.handshakeRejecter = reject;
});
return [4 /*yield*/, this.connection.start(this.protocol.transferFormat)];
case 1:
_a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 5, , 7]);
handshakeRequest = {
protocol: this.protocol.name,
version: this.protocol.version,
};
this.logger.log(ILogger_1.LogLevel.Debug, "Sending handshake request.");
return [4 /*yield*/, this.sendMessage(this.handshakeProtocol.writeHandshakeRequest(handshakeRequest))];
case 3:
_a.sent();
this.logger.log(ILogger_1.LogLevel.Information, "Using HubProtocol '" + this.protocol.name + "'.");
// defensively cleanup timeout in case we receive a message from the server before we finish start
this.cleanupTimeout();
this.resetTimeoutPeriod();
this.resetKeepAliveInterval();
return [4 /*yield*/, handshakePromise];
case 4:
_a.sent();
// It's important to check the stopDuringStartError instead of just relying on the handshakePromise
// being rejected on close, because this continuation can run after both the handshake completed successfully
// and the connection was closed.
if (this.stopDuringStartError) {
// It's important to throw instead of returning a rejected promise, because we don't want to allow any state
// transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise
// will cause the calling continuation to get scheduled to run later.
throw this.stopDuringStartError;
}
return [3 /*break*/, 7];
case 5:
e_2 = _a.sent();
this.logger.log(ILogger_1.LogLevel.Debug, "Hub handshake failed with error '" + e_2 + "' during start(). Stopping HubConnection.");
this.cleanupTimeout();
this.cleanupPingTimer();
// HttpConnection.stop() should not complete until after the onclose callback is invoked.
// This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.
return [4 /*yield*/, this.connection.stop(e_2)];
case 6:
// HttpConnection.stop() should not complete until after the onclose callback is invoked.
// This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.
_a.sent();
throw e_2;
case 7: return [2 /*return*/];
}
});
});
};
/** Stops the connection.
*
* @returns {Promise<void>} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.
*/
HubConnection.prototype.stop = function () {
return __awaiter(this, void 0, void 0, function () {
var startPromise, e_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
startPromise = this.startPromise;
this.stopPromise = this.stopInternal();
return [4 /*yield*/, this.stopPromise];
case 1:
_a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
// Awaiting undefined continues immediately
return [4 /*yield*/, startPromise];
case 3:
// Awaiting undefined continues immediately
_a.sent();
return [3 /*break*/, 5];
case 4:
e_3 = _a.sent();
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
});
};
HubConnection.prototype.stopInternal = function (error) {
if (this.connectionState === HubConnectionState.Disconnected) {
this.logger.log(ILogger_1.LogLevel.Debug, "Call to HubConnection.stop(" + error + ") ignored because it is already in the disconnected state.");
return Promise.resolve();
}
if (this.connectionState === HubConnectionState.Disconnecting) {
this.logger.log(ILogger_1.LogLevel.Debug, "Call to HttpConnection.stop(" + error + ") ignored because the connection is already in the disconnecting state.");
return this.stopPromise;
}
this.connectionState = HubConnectionState.Disconnecting;
this.logger.log(ILogger_1.LogLevel.Debug, "Stopping HubConnection.");
if (this.reconnectDelayHandle) {
// We're in a reconnect delay which means the underlying connection is currently already stopped.
// Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and
// fire the onclose callbacks.
this.logger.log(ILogger_1.LogLevel.Debug, "Connection stopped during reconnect delay. Done reconnecting.");
clearTimeout(this.reconnectDelayHandle);
this.reconnectDelayHandle = undefined;
this.completeClose();
return Promise.resolve();
}
this.cleanupTimeout();
this.cleanupPingTimer();
this.stopDuringStartError = error || new Error("The connection was stopped before the hub handshake could complete.");
// HttpConnection.stop() should not complete until after either HttpConnection.start() fails
// or the onclose callback is invoked. The onclose callback will transition the HubConnection
// to the disconnected state if need be before HttpConnection.stop() completes.
return this.connection.stop(error);
};
/** Invokes a streaming hub method on the server using the specified name and arguments.
*
* @typeparam T The type of the items returned by the server.
* @param {string} methodName The name of the server method to invoke.
* @param {any[]} args The arguments used to invoke the server method.
* @returns {IStreamResult<T>} An object that yields results from the server as they are received.
*/
HubConnection.prototype.stream = function (methodName) {
var _this = this;
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var _a = this.replaceStreamingParams(args), streams = _a[0], streamIds = _a[1];
var invocationDescriptor = this.createStreamInvocation(methodName, args, streamIds);
var promiseQueue;
var subject = new Subject_1.Subject();
subject.cancelCallback = function () {
var cancelInvocation = _this.createCancelInvocation(invocationDescriptor.invocationId);
delete _this.callbacks[invocationDescriptor.invocationId];
return promiseQueue.then(function () {
return _this.sendWithProtocol(cancelInvocation);
});
};
this.callbacks[invocationDescriptor.invocationId] = function (invocationEvent, error) {
if (error) {
subject.error(error);
return;
}
else if (invocationEvent) {
// invocationEvent will not be null when an error is not passed to the callback
if (invocationEvent.type === IHubProtocol_1.MessageType.Completion) {
if (invocationEvent.error) {
subject.error(new Error(invocationEvent.error));
}
else {
subject.complete();
}
}
else {
subject.next((invocationEvent.item));
}
}
};
promiseQueue = this.sendWithProtocol(invocationDescriptor)
.catch(function (e) {
subject.error(e);
delete _this.callbacks[invocationDescriptor.invocationId];
});
this.launchStreams(streams, promiseQueue);
return subject;
};
HubConnection.prototype.sendMessage = function (message) {
this.resetKeepAliveInterval();
return this.connection.send(message);
};
/**
* Sends a js object to the server.
* @param message The js object to serialize and send.
*/
HubConnection.prototype.sendWithProtocol = function (message) {
return this.sendMessage(this.protocol.writeMessage(message));
};
/** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.
*
* The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still
* be processing the invocation.
*
* @param {string} methodName The name of the server method to invoke.
* @param {any[]} args The arguments used to invoke the server method.
* @returns {Promise<void>} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.
*/
HubConnection.prototype.send = function (methodName) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var _a = this.replaceStreamingParams(args), streams = _a[0], streamIds = _a[1];
var sendPromise = this.sendWithProtocol(this.createInvocation(methodName, args, true, streamIds));
this.launchStreams(streams, sendPromise);
return sendPromise;
};
/** Invokes a hub method on the server using the specified name and arguments.
*
* The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise
* resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of
* resolving the Promise.
*
* @typeparam T The expected return type.
* @param {string} methodName The name of the server method to invoke.
* @param {any[]} args The arguments used to invoke the server method.
* @returns {Promise<T>} A Promise that resolves with the result of the server method (if any), or rejects with an error.
*/
HubConnection.prototype.invoke = function (methodName) {
var _this = this;
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var _a = this.replaceStreamingParams(args), streams = _a[0], streamIds = _a[1];
var invocationDescriptor = this.createInvocation(methodName, args, false, streamIds);
var p = new Promise(function (resolve, reject) {
// invocationId will always have a value for a non-blocking invocation
_this.callbacks[invocationDescriptor.invocationId] = function (invocationEvent, error) {
if (error) {
reject(error);
return;
}
else if (invocationEvent) {
// invocationEvent will not be null when an error is not passed to the callback
if (invocationEvent.type === IHubProtocol_1.MessageType.Completion) {
if (invocationEvent.error) {
reject(new Error(invocationEvent.error));
}
else {
resolve(invocationEvent.result);
}
}
else {
reject(new Error("Unexpected message type: " + invocationEvent.type));
}
}
};
var promiseQueue = _this.sendWithProtocol(invocationDescriptor)
.catch(function (e) {
reject(e);
// invocationId will always have a value for a non-blocking invocation
delete _this.callbacks[invocationDescriptor.invocationId];
});
_this.launchStreams(streams, promiseQueue);
});
return p;
};
/** Registers a handler that will be invoked when the hub method with the specified method name is invoked.
*
* @param {string} methodName The name of the hub method to define.
* @param {Function} newMethod The handler that will be raised when the hub method is invoked.
*/
HubConnection.prototype.on = function (methodName, newMethod) {
if (!methodName || !newMethod) {
return;
}
methodName = methodName.toLowerCase();
if (!this.methods[methodName]) {
this.methods[methodName] = [];
}
// Preventing adding the same handler multiple times.
if (this.methods[methodName].indexOf(newMethod) !== -1) {
return;
}
this.methods[methodName].push(newMethod);
};
HubConnection.prototype.off = function (methodName, method) {
if (!methodName) {
return;
}
methodName = methodName.toLowerCase();
var handlers = this.methods[methodName];
if (!handlers) {
return;
}
if (method) {
var removeIdx = handlers.indexOf(method);
if (removeIdx !== -1) {
handlers.splice(removeIdx, 1);
if (handlers.length === 0) {
delete this.methods[methodName];
}
}
}
else {
delete this.methods[methodName];
}
};
/** Registers a handler that will be invoked when the connection is closed.
*
* @param {Function} callback The handler that will be invoked when the connection is closed. Optionally receives a single argument containing the error that caused the connection to close (if any).
*/
HubConnection.prototype.onclose = function (callback) {
if (callback) {
this.closedCallbacks.push(callback);
}
};
/** Registers a handler that will be invoked when the connection starts reconnecting.
*
* @param {Function} callback The handler that will be invoked when the connection starts reconnecting. Optionally receives a single argument containing the error that caused the connection to start reconnecting (if any).
*/
HubConnection.prototype.onreconnecting = function (callback) {
if (callback) {
this.reconnectingCallbacks.push(callback);
}
};
/** Registers a handler that will be invoked when the connection successfully reconnects.
*
* @param {Function} callback The handler that will be invoked when the connection successfully reconnects.
*/
HubConnection.prototype.onreconnected = function (callback) {
if (callback) {
this.reconnectedCallbacks.push(callback);
}
};
HubConnection.prototype.processIncomingData = function (data) {
this.cleanupTimeout();
if (!this.receivedHandshakeResponse) {
data = this.processHandshakeResponse(data);
this.receivedHandshakeResponse = true;
}
// Data may have all been read when processing handshake response
if (data) {
// Parse the messages
var messages = this.protocol.parseMessages(data, this.logger);
for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) {
var message = messages_1[_i];
switch (message.type) {
case IHubProtocol_1.MessageType.Invocation:
this.invokeClientMethod(message);
break;
case IHubProtocol_1.MessageType.StreamItem:
case IHubProtocol_1.MessageType.Completion:
var callback = this.callbacks[message.invocationId];
if (callback) {
if (message.type === IHubProtocol_1.MessageType.Completion) {
delete this.callbacks[message.invocationId];
}
callback(message);
}
break;
case IHubProtocol_1.MessageType.Ping:
// Don't care about pings
break;
case IHubProtocol_1.MessageType.Close:
this.logger.log(ILogger_1.LogLevel.Information, "Close message received from server.");
var error = message.error ? new Error("Server returned an error on close: " + message.error) : undefined;
if (message.allowReconnect === true) {
// It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async,
// this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions.
// tslint:disable-next-line:no-floating-promises
this.connection.stop(error);
}
else {
// We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing.
this.stopPromise = this.stopInternal(error);
}
break;
default:
this.logger.log(ILogger_1.LogLevel.Warning, "Invalid message type: " + message.type + ".");
break;
}
}
}
this.resetTimeoutPeriod();
};
HubConnection.prototype.processHandshakeResponse = function (data) {
var _a;
var responseMessage;
var remainingData;
try {
_a = this.handshakeProtocol.parseHandshakeResponse(data), remainingData = _a[0], responseMessage = _a[1];
}
catch (e) {
var message = "Error parsing handshake response: " + e;
this.logger.log(ILogger_1.LogLevel.Error, message);
var error = new Error(message);
this.handshakeRejecter(error);
throw error;
}
if (responseMessage.error) {
var message = "Server returned handshake error: " + responseMessage.error;
this.logger.log(ILogger_1.LogLevel.Error, message);
var error = new Error(message);
this.handshakeRejecter(error);
throw error;
}
else {
this.logger.log(ILogger_1.LogLevel.Debug, "Server handshake complete.");
}
this.handshakeResolver();
return remainingData;
};
HubConnection.prototype.resetKeepAliveInterval = function () {
if (this.connection.features.inherentKeepAlive) {
return;
}
// Set the time we want the next keep alive to be sent
// Timer will be setup on next message receive
this.nextKeepAlive = new Date().getTime() + this.keepAliveIntervalInMilliseconds;
this.cleanupPingTimer();
};
HubConnection.prototype.resetTimeoutPeriod = function () {
var _this = this;
if (!this.connection.features || !this.connection.features.inherentKeepAlive) {
// Set the timeout timer
this.timeoutHandle = setTimeout(function () { return _this.serverTimeout(); }, this.serverTimeoutInMilliseconds);
// Set keepAlive timer if there isn't one
if (this.pingServerHandle === undefined) {
var nextPing = this.nextKeepAlive - new Date().getTime();
if (nextPing < 0) {
nextPing = 0;
}
// The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute
this.pingServerHandle = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!(this.connectionState === HubConnectionState.Connected)) return [3 /*break*/, 4];
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.sendMessage(this.cachedPingMessage)];
case 2:
_b.sent();
return [3 /*break*/, 4];
case 3:
_a = _b.sent();
// We don't care about the error. It should be seen elsewhere in the client.
// The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering
this.cleanupPingTimer();
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
}); }, nextPing);
}
}
};
HubConnection.prototype.serverTimeout = function () {
// The server hasn't talked to us in a while. It doesn't like us anymore ... :(
// Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting.
// tslint:disable-next-line:no-floating-promises
this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."));
};
HubConnection.prototype.invokeClientMethod = function (invocationMessage) {
var _this = this;
var methods = this.methods[invocationMessage.target.toLowerCase()];
if (methods) {
try {
methods.forEach(function (m) { return m.apply(_this, invocationMessage.arguments); });
}
catch (e) {
this.logger.log(ILogger_1.LogLevel.Error, "A callback for the method " + invocationMessage.target.toLowerCase() + " threw error '" + e + "'.");
}
if (invocationMessage.invocationId) {
// This is not supported in v1. So we return an error to avoid blocking the server waiting for the response.
var message = "Server requested a response, which is not supported in this version of the client.";
this.logger.log(ILogger_1.LogLevel.Error, message);
// We don't want to wait on the stop itself.
this.stopPromise = this.stopInternal(new Error(message));
}
}
else {
this.logger.log(ILogger_1.LogLevel.Warning, "No client method with the name '" + invocationMessage.target + "' found.");
}
};
HubConnection.prototype.connectionClosed = function (error) {
this.logger.log(ILogger_1.LogLevel.Debug, "HubConnection.connectionClosed(" + error + ") called while in state " + this.connectionState + ".");
// Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet.
this.stopDuringStartError = this.stopDuringStartError || error || new Error("The underlying connection was closed before the hub handshake could complete.");
// If the handshake is in progress, start will be waiting for the handshake promise, so we complete it.
// If it has already completed, this should just noop.
if (this.handshakeResolver) {
this.handshakeResolver();
}
this.cancelCallbacksWithError(error || new Error("Invocation canceled due to the underlying connection being closed."));
this.cleanupTimeout();
this.cleanupPingTimer();
if (this.connectionState === HubConnectionState.Disconnecting) {
this.completeClose(error);
}
else if (this.connectionState === HubConnectionState.Connected && this.reconnectPolicy) {
// tslint:disable-next-line:no-floating-promises
this.reconnect(error);
}
else if (this.connectionState === HubConnectionState.Connected) {
this.completeClose(error);
}
// If none of the above if conditions were true were called the HubConnection must be in either:
// 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it.
// 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt
// and potentially continue the reconnect() loop.
// 3. The Disconnected state in which case we're already done.
};
HubConnection.prototype.completeClose = function (error) {
var _this = this;
if (this.connectionStarted) {
this.connectionState = HubConnectionState.Disconnected;
this.connectionStarted = false;
try {
this.closedCallbacks.forEach(function (c) { return c.apply(_this, [error]); });
}
catch (e) {
this.logger.log(ILogger_1.LogLevel.Error, "An onclose callback called with error '" + error + "' threw error '" + e + "'.");
}
}
};
HubConnection.prototype.reconnect = function (error) {
return __awaiter(this, void 0, void 0, function () {
var reconnectStartTime, previousReconnectAttempts, retryError, nextRetryDelay, e_4;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
reconnectStartTime = Date.now();
previousReconnectAttempts = 0;
retryError = error !== undefined ? error : new Error("Attempting to reconnect due to a unknown error.");
nextRetryDelay = this.getNextRetryDelay(previousReconnectAttempts++, 0, retryError);
if (nextRetryDelay === null) {
this.logger.log(ILogger_1.LogLevel.Debug, "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.");
this.completeClose(error);
return [2 /*return*/];
}
this.connectionState = HubConnectionState.Reconnecting;
if (error) {
this.logger.log(ILogger_1.LogLevel.Information, "Connection reconnecting because of error '" + error + "'.");
}
else {
this.logger.log(ILogger_1.LogLevel.Information, "Connection reconnecting.");
}
if (this.onreconnecting) {
try {
this.reconnectingCallbacks.forEach(function (c) { return c.apply(_this, [error]); });
}
catch (e) {
this.logger.log(ILogger_1.LogLevel.Error, "An onreconnecting callback called with error '" + error + "' threw error '" + e + "'.");
}
// Exit early if an onreconnecting callback called connection.stop().
if (this.connectionState !== HubConnectionState.Reconnecting) {
this.logger.log(ILogger_1.LogLevel.Debug, "Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");
return [2 /*return*/];
}
}
_a.label = 1;
case 1:
if (!(nextRetryDelay !== null)) return [3 /*break*/, 7];
this.logger.log(ILogger_1.LogLevel.Information, "Reconnect attempt number " + previousReconnectAttempts + " will start in " + nextRetryDelay + " ms.");
return [4 /*yield*/, new Promise(function (resolve) {
_this.reconnectDelayHandle = setTimeout(resolve, nextRetryDelay);
})];
case 2:
_a.sent();
this.reconnectDelayHandle = undefined;
if (this.connectionState !== HubConnectionState.Reconnecting) {
this.logger.log(ILogger_1.LogLevel.Debug, "Connection left the reconnecting state during reconnect delay. Done reconnecting.");
return [2 /*return*/];
}
_a.label = 3;
case 3:
_a.trys.push([3, 5, , 6]);
return [4 /*yield*/, this.startInternal()];
case 4:
_a.sent();
this.connectionState = HubConnectionState.Connected;
this.logger.log(ILogger_1.LogLevel.Information, "HubConnection reconnected successfully.");
if (this.onreconnected) {
try {
this.reconnectedCallbacks.forEach(function (c) { return c.apply(_this, [_this.connection.connectionId]); });
}
catch (e) {
this.logger.log(ILogger_1.LogLevel.Error, "An onreconnected callback called with connectionId '" + this.connection.connectionId + "; threw error '" + e + "'.");
}
}
return [2 /*return*/];
case 5:
e_4 = _a.sent();
this.logger.log(ILogger_1.LogLevel.Information, "Reconnect attempt failed because of error '" + e_4 + "'.");
if (this.connectionState !== HubConnectionState.Reconnecting) {
this.logger.log(ILogger_1.LogLevel.Debug, "Connection moved to the '" + this.connectionState + "' from the reconnecting state during reconnect attempt. Done reconnecting.");
// The TypeScript compiler thinks that connectionState must be Connected here. The TypeScript compiler is wrong.
if (this.connectionState === HubConnectionState.Disconnecting) {
this.completeClose();
}
return [2 /*return*/];
}
retryError = e_4 instanceof Error ? e_4 : new Error(e_4.toString());
nextRetryDelay = this.getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError);
return [3 /*break*/, 6];
case 6: return [3 /*break*/, 1];
case 7:
this.logger.log(ILogger_1.LogLevel.Information, "Reconnect retries have been exhausted after " + (Date.now() - reconnectStartTime) + " ms and " + previousReconnectAttempts + " failed attempts. Connection disconnecting.");
this.completeClose();
return [2 /*return*/];
}
});
});
};
HubConnection.prototype.getNextRetryDelay = function (previousRetryCount, elapsedMilliseconds, retryReason) {
try {
return this.reconnectPolicy.nextRetryDelayInMilliseconds({
elapsedMilliseconds: elapsedMilliseconds,
previousRetryCount: previousRetryCount,
retryReason: retryReason,
});
}
catch (e) {
this.logger.log(ILogger_1.LogLevel.Error, "IRetryPolicy.nextRetryDelayInMilliseconds(" + previousRetryCount + ", " + elapsedMilliseconds + ") threw error '" + e + "'.");
return null;
}
};
HubConnection.prototype.cancelCallbacksWithError = function (error) {
var callbacks = this.callbacks;
this.callbacks = {};
Object.keys(callbacks)
.forEach(function (key) {
var callback = callbacks[key];
callback(null, error);
});
};
HubConnection.prototype.cleanupPingTimer = function () {
if (this.pingServerHandle) {
clearTimeout(this.pingServerHandle);
this.pingServerHandle = undefined;
}
};
HubConnection.prototype.cleanupTimeout = function () {
if (this.timeoutHandle) {
clearTimeout(this.timeoutHandle);
}
};
HubConnection.prototype.createInvocation = function (methodName, args, nonblocking, streamIds) {
if (nonblocking) {
if (streamIds.length !== 0) {
return {
arguments: args,
streamIds: streamIds,
target: methodName,
type: IHubProtocol_1.MessageType.Invocation,
};
}
else {
return {
arguments: args,
target: methodName,
type: IHubProtocol_1.MessageType.Invocation,
};
}
}
else {
var invocationId = this.invocationId;
this.invocationId++;
if (streamIds.length !== 0) {
return {
arguments: args,
invocationId: invocationId.toString(),
streamIds: streamIds,
target: methodName,
type: IHubProtocol_1.MessageType.Invocation,
};
}
else {
return {
arguments: args,
invocationId: invocationId.toString(),
target: methodName,
type: IHubProtocol_1.MessageType.Invocation,
};
}
}
};
HubConnection.prototype.launchStreams = function (streams, promiseQueue) {
var _this = this;
if (streams.length === 0) {
return;
}
// Synchronize stream data so they arrive in-order on the server
if (!promiseQueue) {
promiseQueue = Promise.resolve();
}
var _loop_1 = function (streamId) {
streams[streamId].subscribe({
complete: function () {
promiseQueue = promiseQueue.then(function () { return _this.sendWithProtocol(_this.createCompletionMessage(streamId)); });
},
error: function (err) {
var message;
if (err instanceof Error) {
message = err.message;
}
else if (err && err.toString) {
message = err.toString();
}
else {
message = "Unknown error";
}
promiseQueue = promiseQueue.then(function () { return _this.sendWithProtocol(_this.createCompletionMessage(streamId, message)); });
},
next: function (item) {
promiseQueue = promiseQueue.then(function () { return _this.sendWithProtocol(_this.createStreamItemMessage(streamId, item)); });
},
});
};
// We want to iterate over the keys, since the keys are the stream ids
// tslint:disable-next-line:forin
for (var streamId in streams) {
_loop_1(streamId);
}
};
HubConnection.prototype.replaceStreamingParams = function (args) {
var streams = [];
var streamIds = [];
for (var i = 0; i < args.length; i++) {
var argument = args[i];
if (this.isObservable(argument)) {
var streamId = this.invocationId;
this.invocationId++;
// Store the stream for later use
streams[streamId] = argument;
streamIds.push(streamId.toString());
// remove stream from args
args.splice(i, 1);
}
}
return [streams, streamIds];
};
HubConnection.prototype.isObservable = function (arg) {
// This allows other stream implementations to just work (like rxjs)
return arg && arg.subscribe && typeof arg.subscribe === "function";
};
HubConnection.prototype.createStreamInvocation = function (methodName, args, streamIds) {
var invocationId = this.invocationId;
this.invocationId++;
if (streamIds.length !== 0) {
return {
arguments: args,
invocationId: invocationId.toString(),
streamIds: streamIds,
target: methodName,
type: IHubProtocol_1.MessageType.StreamInvocation,
};
}
else {
return {
arguments: args,
invocationId: invocationId.toString(),
target: methodName,
type: IHubProtocol_1.MessageType.StreamInvocation,
};
}
};
HubConnection.prototype.createCancelInvocation = function (id) {
return {
invocationId: id,
type: IHubProtocol_1.MessageType.CancelInvocation,
};
};
HubConnection.prototype.createStreamItemMessage = function (id, item) {
return {
invocationId: id,
item: item,
type: IHubProtocol_1.MessageType.StreamItem,
};
};
HubConnection.prototype.createCompletionMessage = function (id, error, result) {
if (error) {
return {
error: error,
invocationId: id,
type: IHubProtocol_1.MessageType.Completion,
};
}
return {
invocationId: id,
result: result,
type: IHubProtocol_1.MessageType.Completion,
};
};
return HubConnection;
}());
exports.HubConnection = HubConnection;
//# sourceMappingURL=HubConnection.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,126 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
Object.defineProperty(exports, "__esModule", { value: true });
var DefaultReconnectPolicy_1 = require("./DefaultReconnectPolicy");
var HttpConnection_1 = require("./HttpConnection");
var HubConnection_1 = require("./HubConnection");
var ILogger_1 = require("./ILogger");
var JsonHubProtocol_1 = require("./JsonHubProtocol");
var Loggers_1 = require("./Loggers");
var Utils_1 = require("./Utils");
// tslint:disable:object-literal-sort-keys
var LogLevelNameMapping = {
trace: ILogger_1.LogLevel.Trace,
debug: ILogger_1.LogLevel.Debug,
info: ILogger_1.LogLevel.Information,
information: ILogger_1.LogLevel.Information,
warn: ILogger_1.LogLevel.Warning,
warning: ILogger_1.LogLevel.Warning,
error: ILogger_1.LogLevel.Error,
critical: ILogger_1.LogLevel.Critical,
none: ILogger_1.LogLevel.None,
};
function parseLogLevel(name) {
// Case-insensitive matching via lower-casing
// Yes, I know case-folding is a complicated problem in Unicode, but we only support
// the ASCII strings defined in LogLevelNameMapping anyway, so it's fine -anurse.
var mapping = LogLevelNameMapping[name.toLowerCase()];
if (typeof mapping !== "undefined") {
return mapping;
}
else {
throw new Error("Unknown log level: " + name);
}
}
/** A builder for configuring {@link @microsoft/signalr.HubConnection} instances. */
var HubConnectionBuilder = /** @class */ (function () {
function HubConnectionBuilder() {
}
HubConnectionBuilder.prototype.configureLogging = function (logging) {
Utils_1.Arg.isRequired(logging, "logging");
if (isLogger(logging)) {
this.logger = logging;
}
else if (typeof logging === "string") {
var logLevel = parseLogLevel(logging);
this.logger = new Utils_1.ConsoleLogger(logLevel);
}
else {
this.logger = new Utils_1.ConsoleLogger(logging);
}
return this;
};
HubConnectionBuilder.prototype.withUrl = function (url, transportTypeOrOptions) {
Utils_1.Arg.isRequired(url, "url");
Utils_1.Arg.isNotEmpty(url, "url");
this.url = url;
// Flow-typing knows where it's at. Since HttpTransportType is a number and IHttpConnectionOptions is guaranteed
// to be an object, we know (as does TypeScript) this comparison is all we need to figure out which overload was called.
if (typeof transportTypeOrOptions === "object") {
this.httpConnectionOptions = __assign({}, this.httpConnectionOptions, transportTypeOrOptions);
}
else {
this.httpConnectionOptions = __assign({}, this.httpConnectionOptions, { transport: transportTypeOrOptions });
}
return this;
};
/** Configures the {@link @microsoft/signalr.HubConnection} to use the specified Hub Protocol.
*
* @param {IHubProtocol} protocol The {@link @microsoft/signalr.IHubProtocol} implementation to use.
*/
HubConnectionBuilder.prototype.withHubProtocol = function (protocol) {
Utils_1.Arg.isRequired(protocol, "protocol");
this.protocol = protocol;
return this;
};
HubConnectionBuilder.prototype.withAutomaticReconnect = function (retryDelaysOrReconnectPolicy) {
if (this.reconnectPolicy) {
throw new Error("A reconnectPolicy has already been set.");
}
if (!retryDelaysOrReconnectPolicy) {
this.reconnectPolicy = new DefaultReconnectPolicy_1.DefaultReconnectPolicy();
}
else if (Array.isArray(retryDelaysOrReconnectPolicy)) {
this.reconnectPolicy = new DefaultReconnectPolicy_1.DefaultReconnectPolicy(retryDelaysOrReconnectPolicy);
}
else {
this.reconnectPolicy = retryDelaysOrReconnectPolicy;
}
return this;
};
/** Creates a {@link @microsoft/signalr.HubConnection} from the configuration options specified in this builder.
*
* @returns {HubConnection} The configured {@link @microsoft/signalr.HubConnection}.
*/
HubConnectionBuilder.prototype.build = function () {
// If httpConnectionOptions has a logger, use it. Otherwise, override it with the one
// provided to configureLogger
var httpConnectionOptions = this.httpConnectionOptions || {};
// If it's 'null', the user **explicitly** asked for null, don't mess with it.
if (httpConnectionOptions.logger === undefined) {
// If our logger is undefined or null, that's OK, the HttpConnection constructor will handle it.
httpConnectionOptions.logger = this.logger;
}
// Now create the connection
if (!this.url) {
throw new Error("The 'HubConnectionBuilder.withUrl' method must be called before building the connection.");
}
var connection = new HttpConnection_1.HttpConnection(this.url, httpConnectionOptions);
return HubConnection_1.HubConnection.create(connection, this.logger || Loggers_1.NullLogger.instance, this.protocol || new JsonHubProtocol_1.JsonHubProtocol(), this.reconnectPolicy);
};
return HubConnectionBuilder;
}());
exports.HubConnectionBuilder = HubConnectionBuilder;
function isLogger(logger) {
return logger.log !== undefined;
}
//# sourceMappingURL=HubConnectionBuilder.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,5 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IConnection.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"IConnection.js","sourceRoot":"","sources":["../../src/IConnection.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { TransferFormat } from \"./ITransport\";\r\n\r\n/** @private */\r\nexport interface IConnection {\r\n readonly features: any;\r\n readonly connectionId?: string;\r\n\r\n baseUrl: string;\r\n\r\n start(transferFormat: TransferFormat): Promise<void>;\r\n send(data: string | ArrayBuffer): Promise<void>;\r\n stop(error?: Error): Promise<void>;\r\n\r\n onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n onclose: ((error?: Error) => void) | null;\r\n}\r\n"]}

View File

@ -0,0 +1,5 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IHttpConnectionOptions.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"IHttpConnectionOptions.js","sourceRoot":"","sources":["../../src/IHttpConnectionOptions.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { HttpClient } from \"./HttpClient\";\r\nimport { MessageHeaders } from \"./IHubProtocol\";\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\nimport { HttpTransportType, ITransport } from \"./ITransport\";\r\nimport { EventSourceConstructor, WebSocketConstructor } from \"./Polyfills\";\r\n\r\n/** Options provided to the 'withUrl' method on {@link @microsoft/signalr.HubConnectionBuilder} to configure options for the HTTP-based transports. */\r\nexport interface IHttpConnectionOptions {\r\n /** {@link @microsoft/signalr.MessageHeaders} containing custom headers to be sent with every HTTP request. Note, setting headers in the browser will not work for WebSockets or the ServerSentEvents stream. */\r\n headers?: MessageHeaders;\r\n\r\n /** An {@link @microsoft/signalr.HttpClient} that will be used to make HTTP requests. */\r\n httpClient?: HttpClient;\r\n\r\n /** An {@link @microsoft/signalr.HttpTransportType} value specifying the transport to use for the connection. */\r\n transport?: HttpTransportType | ITransport;\r\n\r\n /** Configures the logger used for logging.\r\n *\r\n * Provide an {@link @microsoft/signalr.ILogger} instance, and log messages will be logged via that instance. Alternatively, provide a value from\r\n * the {@link @microsoft/signalr.LogLevel} enumeration and a default logger which logs to the Console will be configured to log messages of the specified\r\n * level (or higher).\r\n */\r\n logger?: ILogger | LogLevel;\r\n\r\n /** A function that provides an access token required for HTTP Bearer authentication.\r\n *\r\n * @returns {string | Promise<string>} A string containing the access token, or a Promise that resolves to a string containing the access token.\r\n */\r\n accessTokenFactory?(): string | Promise<string>;\r\n\r\n /** A boolean indicating if message content should be logged.\r\n *\r\n * Message content can contain sensitive user data, so this is disabled by default.\r\n */\r\n logMessageContent?: boolean;\r\n\r\n /** A boolean indicating if negotiation should be skipped.\r\n *\r\n * Negotiation can only be skipped when the {@link @microsoft/signalr.IHttpConnectionOptions.transport} property is set to 'HttpTransportType.WebSockets'.\r\n */\r\n skipNegotiation?: boolean;\r\n\r\n // Used for unit testing and code spelunkers\r\n /** A constructor that can be used to create a WebSocket.\r\n *\r\n * @internal\r\n */\r\n WebSocket?: WebSocketConstructor;\r\n\r\n // Used for unit testing and code spelunkers\r\n /** A constructor that can be used to create an EventSource.\r\n *\r\n * @internal\r\n */\r\n EventSource?: EventSourceConstructor;\r\n\r\n /**\r\n * Default value is 'true'.\r\n * This controls whether credentials such as cookies are sent in cross-site requests.\r\n *\r\n * Cookies are used by many load-balancers for sticky sessions which is required when your app is deployed with multiple servers.\r\n */\r\n withCredentials?: boolean;\r\n}\r\n"]}

View File

@ -0,0 +1,23 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
/** Defines the type of a Hub Message. */
var MessageType;
(function (MessageType) {
/** Indicates the message is an Invocation message and implements the {@link @microsoft/signalr.InvocationMessage} interface. */
MessageType[MessageType["Invocation"] = 1] = "Invocation";
/** Indicates the message is a StreamItem message and implements the {@link @microsoft/signalr.StreamItemMessage} interface. */
MessageType[MessageType["StreamItem"] = 2] = "StreamItem";
/** Indicates the message is a Completion message and implements the {@link @microsoft/signalr.CompletionMessage} interface. */
MessageType[MessageType["Completion"] = 3] = "Completion";
/** Indicates the message is a Stream Invocation message and implements the {@link @microsoft/signalr.StreamInvocationMessage} interface. */
MessageType[MessageType["StreamInvocation"] = 4] = "StreamInvocation";
/** Indicates the message is a Cancel Invocation message and implements the {@link @microsoft/signalr.CancelInvocationMessage} interface. */
MessageType[MessageType["CancelInvocation"] = 5] = "CancelInvocation";
/** Indicates the message is a Ping message and implements the {@link @microsoft/signalr.PingMessage} interface. */
MessageType[MessageType["Ping"] = 6] = "Ping";
/** Indicates the message is a Close message and implements the {@link @microsoft/signalr.CloseMessage} interface. */
MessageType[MessageType["Close"] = 7] = "Close";
})(MessageType = exports.MessageType || (exports.MessageType = {}));
//# sourceMappingURL=IHubProtocol.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,27 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
// These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here.
/** Indicates the severity of a log message.
*
* Log Levels are ordered in increasing severity. So `Debug` is more severe than `Trace`, etc.
*/
var LogLevel;
(function (LogLevel) {
/** Log level for very low severity diagnostic messages. */
LogLevel[LogLevel["Trace"] = 0] = "Trace";
/** Log level for low severity diagnostic messages. */
LogLevel[LogLevel["Debug"] = 1] = "Debug";
/** Log level for informational diagnostic messages. */
LogLevel[LogLevel["Information"] = 2] = "Information";
/** Log level for diagnostic messages that indicate a non-fatal problem. */
LogLevel[LogLevel["Warning"] = 3] = "Warning";
/** Log level for diagnostic messages that indicate a failure in the current operation. */
LogLevel[LogLevel["Error"] = 4] = "Error";
/** Log level for diagnostic messages that indicate a failure that will terminate the entire application. */
LogLevel[LogLevel["Critical"] = 5] = "Critical";
/** The highest possible log level. Used when configuring logging to indicate that no log messages should be emitted. */
LogLevel[LogLevel["None"] = 6] = "None";
})(LogLevel = exports.LogLevel || (exports.LogLevel = {}));
//# sourceMappingURL=ILogger.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"ILogger.js","sourceRoot":"","sources":["../../src/ILogger.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G;;AAE/G,2GAA2G;AAC3G;;;GAGG;AACH,IAAY,QAeX;AAfD,WAAY,QAAQ;IAChB,2DAA2D;IAC3D,yCAAS,CAAA;IACT,sDAAsD;IACtD,yCAAS,CAAA;IACT,uDAAuD;IACvD,qDAAe,CAAA;IACf,2EAA2E;IAC3E,6CAAW,CAAA;IACX,0FAA0F;IAC1F,yCAAS,CAAA;IACT,4GAA4G;IAC5G,+CAAY,CAAA;IACZ,wHAAwH;IACxH,uCAAQ,CAAA;AACZ,CAAC,EAfW,QAAQ,GAAR,gBAAQ,KAAR,gBAAQ,QAenB","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// These values are designed to match the ASP.NET Log Levels since that's the pattern we're emulating here.\r\n/** Indicates the severity of a log message.\r\n *\r\n * Log Levels are ordered in increasing severity. So `Debug` is more severe than `Trace`, etc.\r\n */\r\nexport enum LogLevel {\r\n /** Log level for very low severity diagnostic messages. */\r\n Trace = 0,\r\n /** Log level for low severity diagnostic messages. */\r\n Debug = 1,\r\n /** Log level for informational diagnostic messages. */\r\n Information = 2,\r\n /** Log level for diagnostic messages that indicate a non-fatal problem. */\r\n Warning = 3,\r\n /** Log level for diagnostic messages that indicate a failure in the current operation. */\r\n Error = 4,\r\n /** Log level for diagnostic messages that indicate a failure that will terminate the entire application. */\r\n Critical = 5,\r\n /** The highest possible log level. Used when configuring logging to indicate that no log messages should be emitted. */\r\n None = 6,\r\n}\r\n\r\n/** An abstraction that provides a sink for diagnostic messages. */\r\nexport interface ILogger {\r\n /** Called by the framework to emit a diagnostic message.\r\n *\r\n * @param {LogLevel} logLevel The severity level of the message.\r\n * @param {string} message The message.\r\n */\r\n log(logLevel: LogLevel, message: string): void;\r\n}\r\n"]}

View File

@ -0,0 +1,5 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=IRetryPolicy.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"IRetryPolicy.js","sourceRoot":"","sources":["../../src/IRetryPolicy.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n/** An abstraction that controls when the client attempts to reconnect and how many times it does so. */\r\nexport interface IRetryPolicy {\r\n /** Called after the transport loses the connection.\r\n *\r\n * @param {RetryContext} retryContext Details related to the retry event to help determine how long to wait for the next retry.\r\n *\r\n * @returns {number | null} The amount of time in milliseconds to wait before the next retry. `null` tells the client to stop retrying.\r\n */\r\n nextRetryDelayInMilliseconds(retryContext: RetryContext): number | null;\r\n}\r\n\r\nexport interface RetryContext {\r\n /**\r\n * The number of consecutive failed tries so far.\r\n */\r\n readonly previousRetryCount: number;\r\n\r\n /**\r\n * The amount of time in milliseconds spent retrying so far.\r\n */\r\n readonly elapsedMilliseconds: number;\r\n\r\n /**\r\n * The error that forced the upcoming retry.\r\n */\r\n readonly retryReason: Error;\r\n}\r\n"]}

View File

@ -0,0 +1,26 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
// This will be treated as a bit flag in the future, so we keep it using power-of-two values.
/** Specifies a specific HTTP transport type. */
var HttpTransportType;
(function (HttpTransportType) {
/** Specifies no transport preference. */
HttpTransportType[HttpTransportType["None"] = 0] = "None";
/** Specifies the WebSockets transport. */
HttpTransportType[HttpTransportType["WebSockets"] = 1] = "WebSockets";
/** Specifies the Server-Sent Events transport. */
HttpTransportType[HttpTransportType["ServerSentEvents"] = 2] = "ServerSentEvents";
/** Specifies the Long Polling transport. */
HttpTransportType[HttpTransportType["LongPolling"] = 4] = "LongPolling";
})(HttpTransportType = exports.HttpTransportType || (exports.HttpTransportType = {}));
/** Specifies the transfer format for a connection. */
var TransferFormat;
(function (TransferFormat) {
/** Specifies that only text data will be transmitted over the connection. */
TransferFormat[TransferFormat["Text"] = 1] = "Text";
/** Specifies that binary data will be transmitted over the connection. */
TransferFormat[TransferFormat["Binary"] = 2] = "Binary";
})(TransferFormat = exports.TransferFormat || (exports.TransferFormat = {}));
//# sourceMappingURL=ITransport.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"ITransport.js","sourceRoot":"","sources":["../../src/ITransport.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G;;AAE/G,6FAA6F;AAC7F,gDAAgD;AAChD,IAAY,iBASX;AATD,WAAY,iBAAiB;IACzB,yCAAyC;IACzC,yDAAQ,CAAA;IACR,0CAA0C;IAC1C,qEAAc,CAAA;IACd,kDAAkD;IAClD,iFAAoB,CAAA;IACpB,4CAA4C;IAC5C,uEAAe,CAAA;AACnB,CAAC,EATW,iBAAiB,GAAjB,yBAAiB,KAAjB,yBAAiB,QAS5B;AAED,sDAAsD;AACtD,IAAY,cAKX;AALD,WAAY,cAAc;IACtB,6EAA6E;IAC7E,mDAAQ,CAAA;IACR,0EAA0E;IAC1E,uDAAU,CAAA;AACd,CAAC,EALW,cAAc,GAAd,sBAAc,KAAd,sBAAc,QAKzB","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// This will be treated as a bit flag in the future, so we keep it using power-of-two values.\r\n/** Specifies a specific HTTP transport type. */\r\nexport enum HttpTransportType {\r\n /** Specifies no transport preference. */\r\n None = 0,\r\n /** Specifies the WebSockets transport. */\r\n WebSockets = 1,\r\n /** Specifies the Server-Sent Events transport. */\r\n ServerSentEvents = 2,\r\n /** Specifies the Long Polling transport. */\r\n LongPolling = 4,\r\n}\r\n\r\n/** Specifies the transfer format for a connection. */\r\nexport enum TransferFormat {\r\n /** Specifies that only text data will be transmitted over the connection. */\r\n Text = 1,\r\n /** Specifies that binary data will be transmitted over the connection. */\r\n Binary = 2,\r\n}\r\n\r\n/** An abstraction over the behavior of transports. This is designed to support the framework and not intended for use by applications. */\r\nexport interface ITransport {\r\n connect(url: string, transferFormat: TransferFormat): Promise<void>;\r\n send(data: any): Promise<void>;\r\n stop(): Promise<void>;\r\n onreceive: ((data: string | ArrayBuffer) => void) | null;\r\n onclose: ((error?: Error) => void) | null;\r\n}\r\n"]}

View File

@ -0,0 +1,108 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
var IHubProtocol_1 = require("./IHubProtocol");
var ILogger_1 = require("./ILogger");
var ITransport_1 = require("./ITransport");
var Loggers_1 = require("./Loggers");
var TextMessageFormat_1 = require("./TextMessageFormat");
var JSON_HUB_PROTOCOL_NAME = "json";
/** Implements the JSON Hub Protocol. */
var JsonHubProtocol = /** @class */ (function () {
function JsonHubProtocol() {
/** @inheritDoc */
this.name = JSON_HUB_PROTOCOL_NAME;
/** @inheritDoc */
this.version = 1;
/** @inheritDoc */
this.transferFormat = ITransport_1.TransferFormat.Text;
}
/** Creates an array of {@link @microsoft/signalr.HubMessage} objects from the specified serialized representation.
*
* @param {string} input A string containing the serialized representation.
* @param {ILogger} logger A logger that will be used to log messages that occur during parsing.
*/
JsonHubProtocol.prototype.parseMessages = function (input, logger) {
// The interface does allow "ArrayBuffer" to be passed in, but this implementation does not. So let's throw a useful error.
if (typeof input !== "string") {
throw new Error("Invalid input for JSON hub protocol. Expected a string.");
}
if (!input) {
return [];
}
if (logger === null) {
logger = Loggers_1.NullLogger.instance;
}
// Parse the messages
var messages = TextMessageFormat_1.TextMessageFormat.parse(input);
var hubMessages = [];
for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) {
var message = messages_1[_i];
var parsedMessage = JSON.parse(message);
if (typeof parsedMessage.type !== "number") {
throw new Error("Invalid payload.");
}
switch (parsedMessage.type) {
case IHubProtocol_1.MessageType.Invocation:
this.isInvocationMessage(parsedMessage);
break;
case IHubProtocol_1.MessageType.StreamItem:
this.isStreamItemMessage(parsedMessage);
break;
case IHubProtocol_1.MessageType.Completion:
this.isCompletionMessage(parsedMessage);
break;
case IHubProtocol_1.MessageType.Ping:
// Single value, no need to validate
break;
case IHubProtocol_1.MessageType.Close:
// All optional values, no need to validate
break;
default:
// Future protocol changes can add message types, old clients can ignore them
logger.log(ILogger_1.LogLevel.Information, "Unknown message type '" + parsedMessage.type + "' ignored.");
continue;
}
hubMessages.push(parsedMessage);
}
return hubMessages;
};
/** Writes the specified {@link @microsoft/signalr.HubMessage} to a string and returns it.
*
* @param {HubMessage} message The message to write.
* @returns {string} A string containing the serialized representation of the message.
*/
JsonHubProtocol.prototype.writeMessage = function (message) {
return TextMessageFormat_1.TextMessageFormat.write(JSON.stringify(message));
};
JsonHubProtocol.prototype.isInvocationMessage = function (message) {
this.assertNotEmptyString(message.target, "Invalid payload for Invocation message.");
if (message.invocationId !== undefined) {
this.assertNotEmptyString(message.invocationId, "Invalid payload for Invocation message.");
}
};
JsonHubProtocol.prototype.isStreamItemMessage = function (message) {
this.assertNotEmptyString(message.invocationId, "Invalid payload for StreamItem message.");
if (message.item === undefined) {
throw new Error("Invalid payload for StreamItem message.");
}
};
JsonHubProtocol.prototype.isCompletionMessage = function (message) {
if (message.result && message.error) {
throw new Error("Invalid payload for Completion message.");
}
if (!message.result && message.error) {
this.assertNotEmptyString(message.error, "Invalid payload for Completion message.");
}
this.assertNotEmptyString(message.invocationId, "Invalid payload for Completion message.");
};
JsonHubProtocol.prototype.assertNotEmptyString = function (value, errorMessage) {
if (typeof value !== "string" || value === "") {
throw new Error(errorMessage);
}
};
return JsonHubProtocol;
}());
exports.JsonHubProtocol = JsonHubProtocol;
//# sourceMappingURL=JsonHubProtocol.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,18 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
/** A logger that does nothing when log messages are sent to it. */
var NullLogger = /** @class */ (function () {
function NullLogger() {
}
/** @inheritDoc */
// tslint:disable-next-line
NullLogger.prototype.log = function (_logLevel, _message) {
};
/** The singleton instance of the {@link @microsoft/signalr.NullLogger}. */
NullLogger.instance = new NullLogger();
return NullLogger;
}());
exports.NullLogger = NullLogger;
//# sourceMappingURL=Loggers.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"Loggers.js","sourceRoot":"","sources":["../../src/Loggers.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G;;AAI/G,mEAAmE;AACnE;IAII;IAAuB,CAAC;IAExB,kBAAkB;IAClB,2BAA2B;IACpB,wBAAG,GAAV,UAAW,SAAmB,EAAE,QAAgB;IAChD,CAAC;IARD,2EAA2E;IAC7D,mBAAQ,GAAY,IAAI,UAAU,EAAE,CAAC;IAQvD,iBAAC;CAAA,AAVD,IAUC;AAVY,gCAAU","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { ILogger, LogLevel } from \"./ILogger\";\r\n\r\n/** A logger that does nothing when log messages are sent to it. */\r\nexport class NullLogger implements ILogger {\r\n /** The singleton instance of the {@link @microsoft/signalr.NullLogger}. */\r\n public static instance: ILogger = new NullLogger();\r\n\r\n private constructor() {}\r\n\r\n /** @inheritDoc */\r\n // tslint:disable-next-line\r\n public log(_logLevel: LogLevel, _message: string): void {\r\n }\r\n}\r\n"]}

View File

@ -0,0 +1,302 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var AbortController_1 = require("./AbortController");
var Errors_1 = require("./Errors");
var ILogger_1 = require("./ILogger");
var ITransport_1 = require("./ITransport");
var Utils_1 = require("./Utils");
// Not exported from 'index', this type is internal.
/** @private */
var LongPollingTransport = /** @class */ (function () {
function LongPollingTransport(httpClient, accessTokenFactory, logger, logMessageContent, withCredentials, headers) {
this.httpClient = httpClient;
this.accessTokenFactory = accessTokenFactory;
this.logger = logger;
this.pollAbort = new AbortController_1.AbortController();
this.logMessageContent = logMessageContent;
this.withCredentials = withCredentials;
this.headers = headers;
this.running = false;
this.onreceive = null;
this.onclose = null;
}
Object.defineProperty(LongPollingTransport.prototype, "pollAborted", {
// This is an internal type, not exported from 'index' so this is really just internal.
get: function () {
return this.pollAbort.aborted;
},
enumerable: true,
configurable: true
});
LongPollingTransport.prototype.connect = function (url, transferFormat) {
return __awaiter(this, void 0, void 0, function () {
var _a, _b, name, value, headers, pollOptions, token, pollUrl, response;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
Utils_1.Arg.isRequired(url, "url");
Utils_1.Arg.isRequired(transferFormat, "transferFormat");
Utils_1.Arg.isIn(transferFormat, ITransport_1.TransferFormat, "transferFormat");
this.url = url;
this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Connecting.");
// Allow binary format on Node and Browsers that support binary content (indicated by the presence of responseType property)
if (transferFormat === ITransport_1.TransferFormat.Binary &&
(typeof XMLHttpRequest !== "undefined" && typeof new XMLHttpRequest().responseType !== "string")) {
throw new Error("Binary protocols over XmlHttpRequest not implementing advanced features are not supported.");
}
_b = Utils_1.getUserAgentHeader(), name = _b[0], value = _b[1];
headers = __assign((_a = {}, _a[name] = value, _a), this.headers);
pollOptions = {
abortSignal: this.pollAbort.signal,
headers: headers,
timeout: 100000,
withCredentials: this.withCredentials,
};
if (transferFormat === ITransport_1.TransferFormat.Binary) {
pollOptions.responseType = "arraybuffer";
}
return [4 /*yield*/, this.getAccessToken()];
case 1:
token = _c.sent();
this.updateHeaderToken(pollOptions, token);
pollUrl = url + "&_=" + Date.now();
this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) polling: " + pollUrl + ".");
return [4 /*yield*/, this.httpClient.get(pollUrl, pollOptions)];
case 2:
response = _c.sent();
if (response.statusCode !== 200) {
this.logger.log(ILogger_1.LogLevel.Error, "(LongPolling transport) Unexpected response code: " + response.statusCode + ".");
// Mark running as false so that the poll immediately ends and runs the close logic
this.closeError = new Errors_1.HttpError(response.statusText || "", response.statusCode);
this.running = false;
}
else {
this.running = true;
}
this.receiving = this.poll(this.url, pollOptions);
return [2 /*return*/];
}
});
});
};
LongPollingTransport.prototype.getAccessToken = function () {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!this.accessTokenFactory) return [3 /*break*/, 2];
return [4 /*yield*/, this.accessTokenFactory()];
case 1: return [2 /*return*/, _a.sent()];
case 2: return [2 /*return*/, null];
}
});
});
};
LongPollingTransport.prototype.updateHeaderToken = function (request, token) {
if (!request.headers) {
request.headers = {};
}
if (token) {
// tslint:disable-next-line:no-string-literal
request.headers["Authorization"] = "Bearer " + token;
return;
}
// tslint:disable-next-line:no-string-literal
if (request.headers["Authorization"]) {
// tslint:disable-next-line:no-string-literal
delete request.headers["Authorization"];
}
};
LongPollingTransport.prototype.poll = function (url, pollOptions) {
return __awaiter(this, void 0, void 0, function () {
var token, pollUrl, response, e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
_a.trys.push([0, , 8, 9]);
_a.label = 1;
case 1:
if (!this.running) return [3 /*break*/, 7];
return [4 /*yield*/, this.getAccessToken()];
case 2:
token = _a.sent();
this.updateHeaderToken(pollOptions, token);
_a.label = 3;
case 3:
_a.trys.push([3, 5, , 6]);
pollUrl = url + "&_=" + Date.now();
this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) polling: " + pollUrl + ".");
return [4 /*yield*/, this.httpClient.get(pollUrl, pollOptions)];
case 4:
response = _a.sent();
if (response.statusCode === 204) {
this.logger.log(ILogger_1.LogLevel.Information, "(LongPolling transport) Poll terminated by server.");
this.running = false;
}
else if (response.statusCode !== 200) {
this.logger.log(ILogger_1.LogLevel.Error, "(LongPolling transport) Unexpected response code: " + response.statusCode + ".");
// Unexpected status code
this.closeError = new Errors_1.HttpError(response.statusText || "", response.statusCode);
this.running = false;
}
else {
// Process the response
if (response.content) {
this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) data received. " + Utils_1.getDataDetail(response.content, this.logMessageContent) + ".");
if (this.onreceive) {
this.onreceive(response.content);
}
}
else {
// This is another way timeout manifest.
this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing.");
}
}
return [3 /*break*/, 6];
case 5:
e_1 = _a.sent();
if (!this.running) {
// Log but disregard errors that occur after stopping
this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Poll errored after shutdown: " + e_1.message);
}
else {
if (e_1 instanceof Errors_1.TimeoutError) {
// Ignore timeouts and reissue the poll.
this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Poll timed out, reissuing.");
}
else {
// Close the connection with the error as the result.
this.closeError = e_1;
this.running = false;
}
}
return [3 /*break*/, 6];
case 6: return [3 /*break*/, 1];
case 7: return [3 /*break*/, 9];
case 8:
this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Polling complete.");
// We will reach here with pollAborted==false when the server returned a response causing the transport to stop.
// If pollAborted==true then client initiated the stop and the stop method will raise the close event after DELETE is sent.
if (!this.pollAborted) {
this.raiseOnClose();
}
return [7 /*endfinally*/];
case 9: return [2 /*return*/];
}
});
});
};
LongPollingTransport.prototype.send = function (data) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (!this.running) {
return [2 /*return*/, Promise.reject(new Error("Cannot send until the transport is connected"))];
}
return [2 /*return*/, Utils_1.sendMessage(this.logger, "LongPolling", this.httpClient, this.url, this.accessTokenFactory, data, this.logMessageContent, this.withCredentials, this.headers)];
});
});
};
LongPollingTransport.prototype.stop = function () {
return __awaiter(this, void 0, void 0, function () {
var headers, _a, name_1, value, deleteOptions, token;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Stopping polling.");
// Tell receiving loop to stop, abort any current request, and then wait for it to finish
this.running = false;
this.pollAbort.abort();
_b.label = 1;
case 1:
_b.trys.push([1, , 5, 6]);
return [4 /*yield*/, this.receiving];
case 2:
_b.sent();
// Send DELETE to clean up long polling on the server
this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) sending DELETE request to " + this.url + ".");
headers = {};
_a = Utils_1.getUserAgentHeader(), name_1 = _a[0], value = _a[1];
headers[name_1] = value;
deleteOptions = {
headers: __assign({}, headers, this.headers),
withCredentials: this.withCredentials,
};
return [4 /*yield*/, this.getAccessToken()];
case 3:
token = _b.sent();
this.updateHeaderToken(deleteOptions, token);
return [4 /*yield*/, this.httpClient.delete(this.url, deleteOptions)];
case 4:
_b.sent();
this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) DELETE request sent.");
return [3 /*break*/, 6];
case 5:
this.logger.log(ILogger_1.LogLevel.Trace, "(LongPolling transport) Stop finished.");
// Raise close event here instead of in polling
// It needs to happen after the DELETE request is sent
this.raiseOnClose();
return [7 /*endfinally*/];
case 6: return [2 /*return*/];
}
});
});
};
LongPollingTransport.prototype.raiseOnClose = function () {
if (this.onclose) {
var logMessage = "(LongPolling transport) Firing onclose event.";
if (this.closeError) {
logMessage += " Error: " + this.closeError;
}
this.logger.log(ILogger_1.LogLevel.Trace, logMessage);
this.onclose(this.closeError);
}
};
return LongPollingTransport;
}());
exports.LongPollingTransport = LongPollingTransport;
//# sourceMappingURL=LongPollingTransport.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,5 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=Polyfills.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"Polyfills.js","sourceRoot":"","sources":["../../src/Polyfills.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// Not exported from index\r\n\r\n/** @private */\r\nexport type EventSourceConstructor = new(url: string, eventSourceInitDict?: EventSourceInit) => EventSource;\r\n\r\n/** @private */\r\nexport interface WebSocketConstructor {\r\n new(url: string, protocols?: string | string[], options?: any): WebSocket;\r\n readonly CLOSED: number;\r\n readonly CLOSING: number;\r\n readonly CONNECTING: number;\r\n readonly OPEN: number;\r\n}\r\n"]}

View File

@ -0,0 +1,168 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var ILogger_1 = require("./ILogger");
var ITransport_1 = require("./ITransport");
var Utils_1 = require("./Utils");
/** @private */
var ServerSentEventsTransport = /** @class */ (function () {
function ServerSentEventsTransport(httpClient, accessTokenFactory, logger, logMessageContent, eventSourceConstructor, withCredentials, headers) {
this.httpClient = httpClient;
this.accessTokenFactory = accessTokenFactory;
this.logger = logger;
this.logMessageContent = logMessageContent;
this.withCredentials = withCredentials;
this.eventSourceConstructor = eventSourceConstructor;
this.headers = headers;
this.onreceive = null;
this.onclose = null;
}
ServerSentEventsTransport.prototype.connect = function (url, transferFormat) {
return __awaiter(this, void 0, void 0, function () {
var token;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
Utils_1.Arg.isRequired(url, "url");
Utils_1.Arg.isRequired(transferFormat, "transferFormat");
Utils_1.Arg.isIn(transferFormat, ITransport_1.TransferFormat, "transferFormat");
this.logger.log(ILogger_1.LogLevel.Trace, "(SSE transport) Connecting.");
// set url before accessTokenFactory because this.url is only for send and we set the auth header instead of the query string for send
this.url = url;
if (!this.accessTokenFactory) return [3 /*break*/, 2];
return [4 /*yield*/, this.accessTokenFactory()];
case 1:
token = _a.sent();
if (token) {
url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token));
}
_a.label = 2;
case 2: return [2 /*return*/, new Promise(function (resolve, reject) {
var opened = false;
if (transferFormat !== ITransport_1.TransferFormat.Text) {
reject(new Error("The Server-Sent Events transport only supports the 'Text' transfer format"));
return;
}
var eventSource;
if (Utils_1.Platform.isBrowser || Utils_1.Platform.isWebWorker) {
eventSource = new _this.eventSourceConstructor(url, { withCredentials: _this.withCredentials });
}
else {
// Non-browser passes cookies via the dictionary
var cookies = _this.httpClient.getCookieString(url);
var headers = {};
headers.Cookie = cookies;
var _a = Utils_1.getUserAgentHeader(), name_1 = _a[0], value = _a[1];
headers[name_1] = value;
eventSource = new _this.eventSourceConstructor(url, { withCredentials: _this.withCredentials, headers: __assign({}, headers, _this.headers) });
}
try {
eventSource.onmessage = function (e) {
if (_this.onreceive) {
try {
_this.logger.log(ILogger_1.LogLevel.Trace, "(SSE transport) data received. " + Utils_1.getDataDetail(e.data, _this.logMessageContent) + ".");
_this.onreceive(e.data);
}
catch (error) {
_this.close(error);
return;
}
}
};
eventSource.onerror = function (e) {
var error = new Error(e.data || "Error occurred");
if (opened) {
_this.close(error);
}
else {
reject(error);
}
};
eventSource.onopen = function () {
_this.logger.log(ILogger_1.LogLevel.Information, "SSE connected to " + _this.url);
_this.eventSource = eventSource;
opened = true;
resolve();
};
}
catch (e) {
reject(e);
return;
}
})];
}
});
});
};
ServerSentEventsTransport.prototype.send = function (data) {
return __awaiter(this, void 0, void 0, function () {
return __generator(this, function (_a) {
if (!this.eventSource) {
return [2 /*return*/, Promise.reject(new Error("Cannot send until the transport is connected"))];
}
return [2 /*return*/, Utils_1.sendMessage(this.logger, "SSE", this.httpClient, this.url, this.accessTokenFactory, data, this.logMessageContent, this.withCredentials, this.headers)];
});
});
};
ServerSentEventsTransport.prototype.stop = function () {
this.close();
return Promise.resolve();
};
ServerSentEventsTransport.prototype.close = function (e) {
if (this.eventSource) {
this.eventSource.close();
this.eventSource = undefined;
if (this.onclose) {
this.onclose(e);
}
}
};
return ServerSentEventsTransport;
}());
exports.ServerSentEventsTransport = ServerSentEventsTransport;
//# sourceMappingURL=ServerSentEventsTransport.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,5 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
//# sourceMappingURL=Stream.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"Stream.js","sourceRoot":"","sources":["../../src/Stream.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// This is an API that is similar to Observable, but we don't want users to confuse it for that so we rename things. Someone could\r\n// easily adapt it into the Rx interface if they wanted to. Unlike in C#, we can't just implement an \"interface\" and get extension\r\n// methods for free. The methods have to actually be added to the object (there are no extension methods in JS!). We don't want to\r\n// depend on RxJS in the core library, so instead we duplicate the minimum logic needed and then users can easily adapt these into\r\n// proper RxJS observables if they want.\r\n\r\n/** Defines the expected type for a receiver of results streamed by the server.\r\n *\r\n * @typeparam T The type of the items being sent by the server.\r\n */\r\nexport interface IStreamSubscriber<T> {\r\n /** A boolean that will be set by the {@link @microsoft/signalr.IStreamResult} when the stream is closed. */\r\n closed?: boolean;\r\n /** Called by the framework when a new item is available. */\r\n next(value: T): void;\r\n /** Called by the framework when an error has occurred.\r\n *\r\n * After this method is called, no additional methods on the {@link @microsoft/signalr.IStreamSubscriber} will be called.\r\n */\r\n error(err: any): void;\r\n /** Called by the framework when the end of the stream is reached.\r\n *\r\n * After this method is called, no additional methods on the {@link @microsoft/signalr.IStreamSubscriber} will be called.\r\n */\r\n complete(): void;\r\n}\r\n\r\n/** Defines the result of a streaming hub method.\r\n *\r\n * @typeparam T The type of the items being sent by the server.\r\n */\r\nexport interface IStreamResult<T> {\r\n /** Attaches a {@link @microsoft/signalr.IStreamSubscriber}, which will be invoked when new items are available from the stream.\r\n *\r\n * @param {IStreamSubscriber<T>} observer The subscriber to attach.\r\n * @returns {ISubscription<T>} A subscription that can be disposed to terminate the stream and stop calling methods on the {@link @microsoft/signalr.IStreamSubscriber}.\r\n */\r\n subscribe(subscriber: IStreamSubscriber<T>): ISubscription<T>;\r\n}\r\n\r\n/** An interface that allows an {@link @microsoft/signalr.IStreamSubscriber} to be disconnected from a stream.\r\n *\r\n * @typeparam T The type of the items being sent by the server.\r\n */\r\n// @ts-ignore: We can't remove this, it's a breaking change, but it's not used.\r\nexport interface ISubscription<T> {\r\n /** Disconnects the {@link @microsoft/signalr.IStreamSubscriber} associated with this subscription from the stream. */\r\n dispose(): void;\r\n}\r\n"]}

View File

@ -0,0 +1,40 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
var Utils_1 = require("./Utils");
/** Stream implementation to stream items to the server. */
var Subject = /** @class */ (function () {
function Subject() {
this.observers = [];
}
Subject.prototype.next = function (item) {
for (var _i = 0, _a = this.observers; _i < _a.length; _i++) {
var observer = _a[_i];
observer.next(item);
}
};
Subject.prototype.error = function (err) {
for (var _i = 0, _a = this.observers; _i < _a.length; _i++) {
var observer = _a[_i];
if (observer.error) {
observer.error(err);
}
}
};
Subject.prototype.complete = function () {
for (var _i = 0, _a = this.observers; _i < _a.length; _i++) {
var observer = _a[_i];
if (observer.complete) {
observer.complete();
}
}
};
Subject.prototype.subscribe = function (observer) {
this.observers.push(observer);
return new Utils_1.SubjectSubscription(this, observer);
};
return Subject;
}());
exports.Subject = Subject;
//# sourceMappingURL=Subject.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"Subject.js","sourceRoot":"","sources":["../../src/Subject.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G;;AAG/G,iCAA8C;AAE9C,2DAA2D;AAC3D;IAOI;QACI,IAAI,CAAC,SAAS,GAAG,EAAE,CAAC;IACxB,CAAC;IAEM,sBAAI,GAAX,UAAY,IAAO;QACf,KAAuB,UAAc,EAAd,KAAA,IAAI,CAAC,SAAS,EAAd,cAAc,EAAd,IAAc,EAAE;YAAlC,IAAM,QAAQ,SAAA;YACf,QAAQ,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;SACvB;IACL,CAAC;IAEM,uBAAK,GAAZ,UAAa,GAAQ;QACjB,KAAuB,UAAc,EAAd,KAAA,IAAI,CAAC,SAAS,EAAd,cAAc,EAAd,IAAc,EAAE;YAAlC,IAAM,QAAQ,SAAA;YACf,IAAI,QAAQ,CAAC,KAAK,EAAE;gBAChB,QAAQ,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;aACvB;SACJ;IACL,CAAC;IAEM,0BAAQ,GAAf;QACI,KAAuB,UAAc,EAAd,KAAA,IAAI,CAAC,SAAS,EAAd,cAAc,EAAd,IAAc,EAAE;YAAlC,IAAM,QAAQ,SAAA;YACf,IAAI,QAAQ,CAAC,QAAQ,EAAE;gBACnB,QAAQ,CAAC,QAAQ,EAAE,CAAC;aACvB;SACJ;IACL,CAAC;IAEM,2BAAS,GAAhB,UAAiB,QAA8B;QAC3C,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QAC9B,OAAO,IAAI,2BAAmB,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IACnD,CAAC;IACL,cAAC;AAAD,CAAC,AArCD,IAqCC;AArCY,0BAAO","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { IStreamResult, IStreamSubscriber, ISubscription } from \"./Stream\";\r\nimport { SubjectSubscription } from \"./Utils\";\r\n\r\n/** Stream implementation to stream items to the server. */\r\nexport class Subject<T> implements IStreamResult<T> {\r\n /** @internal */\r\n public observers: Array<IStreamSubscriber<T>>;\r\n\r\n /** @internal */\r\n public cancelCallback?: () => Promise<void>;\r\n\r\n constructor() {\r\n this.observers = [];\r\n }\r\n\r\n public next(item: T): void {\r\n for (const observer of this.observers) {\r\n observer.next(item);\r\n }\r\n }\r\n\r\n public error(err: any): void {\r\n for (const observer of this.observers) {\r\n if (observer.error) {\r\n observer.error(err);\r\n }\r\n }\r\n }\r\n\r\n public complete(): void {\r\n for (const observer of this.observers) {\r\n if (observer.complete) {\r\n observer.complete();\r\n }\r\n }\r\n }\r\n\r\n public subscribe(observer: IStreamSubscriber<T>): ISubscription<T> {\r\n this.observers.push(observer);\r\n return new SubjectSubscription(this, observer);\r\n }\r\n}\r\n"]}

View File

@ -0,0 +1,26 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
// Not exported from index
/** @private */
var TextMessageFormat = /** @class */ (function () {
function TextMessageFormat() {
}
TextMessageFormat.write = function (output) {
return "" + output + TextMessageFormat.RecordSeparator;
};
TextMessageFormat.parse = function (input) {
if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {
throw new Error("Message is incomplete.");
}
var messages = input.split(TextMessageFormat.RecordSeparator);
messages.pop();
return messages;
};
TextMessageFormat.RecordSeparatorCode = 0x1e;
TextMessageFormat.RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode);
return TextMessageFormat;
}());
exports.TextMessageFormat = TextMessageFormat;
//# sourceMappingURL=TextMessageFormat.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"TextMessageFormat.js","sourceRoot":"","sources":["../../src/TextMessageFormat.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G;;AAE/G,0BAA0B;AAC1B,eAAe;AACf;IAAA;IAiBA,CAAC;IAbiB,uBAAK,GAAnB,UAAoB,MAAc;QAC9B,OAAO,KAAG,MAAM,GAAG,iBAAiB,CAAC,eAAiB,CAAC;IAC3D,CAAC;IAEa,uBAAK,GAAnB,UAAoB,KAAa;QAC7B,IAAI,KAAK,CAAC,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC,KAAK,iBAAiB,CAAC,eAAe,EAAE;YAC/D,MAAM,IAAI,KAAK,CAAC,wBAAwB,CAAC,CAAC;SAC7C;QAED,IAAM,QAAQ,GAAG,KAAK,CAAC,KAAK,CAAC,iBAAiB,CAAC,eAAe,CAAC,CAAC;QAChE,QAAQ,CAAC,GAAG,EAAE,CAAC;QACf,OAAO,QAAQ,CAAC;IACpB,CAAC;IAfa,qCAAmB,GAAG,IAAI,CAAC;IAC3B,iCAAe,GAAG,MAAM,CAAC,YAAY,CAAC,iBAAiB,CAAC,mBAAmB,CAAC,CAAC;IAe/F,wBAAC;CAAA,AAjBD,IAiBC;AAjBY,8CAAiB","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// Not exported from index\r\n/** @private */\r\nexport class TextMessageFormat {\r\n public static RecordSeparatorCode = 0x1e;\r\n public static RecordSeparator = String.fromCharCode(TextMessageFormat.RecordSeparatorCode);\r\n\r\n public static write(output: string): string {\r\n return `${output}${TextMessageFormat.RecordSeparator}`;\r\n }\r\n\r\n public static parse(input: string): string[] {\r\n if (input[input.length - 1] !== TextMessageFormat.RecordSeparator) {\r\n throw new Error(\"Message is incomplete.\");\r\n }\r\n\r\n const messages = input.split(TextMessageFormat.RecordSeparator);\r\n messages.pop();\r\n return messages;\r\n }\r\n}\r\n"]}

View File

@ -0,0 +1,307 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var ILogger_1 = require("./ILogger");
var Loggers_1 = require("./Loggers");
// Version token that will be replaced by the prepack command
/** The version of the SignalR client. */
exports.VERSION = "5.0.8";
/** @private */
var Arg = /** @class */ (function () {
function Arg() {
}
Arg.isRequired = function (val, name) {
if (val === null || val === undefined) {
throw new Error("The '" + name + "' argument is required.");
}
};
Arg.isNotEmpty = function (val, name) {
if (!val || val.match(/^\s*$/)) {
throw new Error("The '" + name + "' argument should not be empty.");
}
};
Arg.isIn = function (val, values, name) {
// TypeScript enums have keys for **both** the name and the value of each enum member on the type itself.
if (!(val in values)) {
throw new Error("Unknown " + name + " value: " + val + ".");
}
};
return Arg;
}());
exports.Arg = Arg;
/** @private */
var Platform = /** @class */ (function () {
function Platform() {
}
Object.defineProperty(Platform, "isBrowser", {
get: function () {
return typeof window === "object";
},
enumerable: true,
configurable: true
});
Object.defineProperty(Platform, "isWebWorker", {
get: function () {
return typeof self === "object" && "importScripts" in self;
},
enumerable: true,
configurable: true
});
Object.defineProperty(Platform, "isNode", {
get: function () {
return !this.isBrowser && !this.isWebWorker;
},
enumerable: true,
configurable: true
});
return Platform;
}());
exports.Platform = Platform;
/** @private */
function getDataDetail(data, includeContent) {
var detail = "";
if (isArrayBuffer(data)) {
detail = "Binary data of length " + data.byteLength;
if (includeContent) {
detail += ". Content: '" + formatArrayBuffer(data) + "'";
}
}
else if (typeof data === "string") {
detail = "String data of length " + data.length;
if (includeContent) {
detail += ". Content: '" + data + "'";
}
}
return detail;
}
exports.getDataDetail = getDataDetail;
/** @private */
function formatArrayBuffer(data) {
var view = new Uint8Array(data);
// Uint8Array.map only supports returning another Uint8Array?
var str = "";
view.forEach(function (num) {
var pad = num < 16 ? "0" : "";
str += "0x" + pad + num.toString(16) + " ";
});
// Trim of trailing space.
return str.substr(0, str.length - 1);
}
exports.formatArrayBuffer = formatArrayBuffer;
// Also in signalr-protocol-msgpack/Utils.ts
/** @private */
function isArrayBuffer(val) {
return val && typeof ArrayBuffer !== "undefined" &&
(val instanceof ArrayBuffer ||
// Sometimes we get an ArrayBuffer that doesn't satisfy instanceof
(val.constructor && val.constructor.name === "ArrayBuffer"));
}
exports.isArrayBuffer = isArrayBuffer;
/** @private */
function sendMessage(logger, transportName, httpClient, url, accessTokenFactory, content, logMessageContent, withCredentials, defaultHeaders) {
return __awaiter(this, void 0, void 0, function () {
var _a, headers, token, _b, name, value, responseType, response;
return __generator(this, function (_c) {
switch (_c.label) {
case 0:
headers = {};
if (!accessTokenFactory) return [3 /*break*/, 2];
return [4 /*yield*/, accessTokenFactory()];
case 1:
token = _c.sent();
if (token) {
headers = (_a = {},
_a["Authorization"] = "Bearer " + token,
_a);
}
_c.label = 2;
case 2:
_b = getUserAgentHeader(), name = _b[0], value = _b[1];
headers[name] = value;
logger.log(ILogger_1.LogLevel.Trace, "(" + transportName + " transport) sending data. " + getDataDetail(content, logMessageContent) + ".");
responseType = isArrayBuffer(content) ? "arraybuffer" : "text";
return [4 /*yield*/, httpClient.post(url, {
content: content,
headers: __assign({}, headers, defaultHeaders),
responseType: responseType,
withCredentials: withCredentials,
})];
case 3:
response = _c.sent();
logger.log(ILogger_1.LogLevel.Trace, "(" + transportName + " transport) request complete. Response status: " + response.statusCode + ".");
return [2 /*return*/];
}
});
});
}
exports.sendMessage = sendMessage;
/** @private */
function createLogger(logger) {
if (logger === undefined) {
return new ConsoleLogger(ILogger_1.LogLevel.Information);
}
if (logger === null) {
return Loggers_1.NullLogger.instance;
}
if (logger.log) {
return logger;
}
return new ConsoleLogger(logger);
}
exports.createLogger = createLogger;
/** @private */
var SubjectSubscription = /** @class */ (function () {
function SubjectSubscription(subject, observer) {
this.subject = subject;
this.observer = observer;
}
SubjectSubscription.prototype.dispose = function () {
var index = this.subject.observers.indexOf(this.observer);
if (index > -1) {
this.subject.observers.splice(index, 1);
}
if (this.subject.observers.length === 0 && this.subject.cancelCallback) {
this.subject.cancelCallback().catch(function (_) { });
}
};
return SubjectSubscription;
}());
exports.SubjectSubscription = SubjectSubscription;
/** @private */
var ConsoleLogger = /** @class */ (function () {
function ConsoleLogger(minimumLogLevel) {
this.minimumLogLevel = minimumLogLevel;
this.outputConsole = console;
}
ConsoleLogger.prototype.log = function (logLevel, message) {
if (logLevel >= this.minimumLogLevel) {
switch (logLevel) {
case ILogger_1.LogLevel.Critical:
case ILogger_1.LogLevel.Error:
this.outputConsole.error("[" + new Date().toISOString() + "] " + ILogger_1.LogLevel[logLevel] + ": " + message);
break;
case ILogger_1.LogLevel.Warning:
this.outputConsole.warn("[" + new Date().toISOString() + "] " + ILogger_1.LogLevel[logLevel] + ": " + message);
break;
case ILogger_1.LogLevel.Information:
this.outputConsole.info("[" + new Date().toISOString() + "] " + ILogger_1.LogLevel[logLevel] + ": " + message);
break;
default:
// console.debug only goes to attached debuggers in Node, so we use console.log for Trace and Debug
this.outputConsole.log("[" + new Date().toISOString() + "] " + ILogger_1.LogLevel[logLevel] + ": " + message);
break;
}
}
};
return ConsoleLogger;
}());
exports.ConsoleLogger = ConsoleLogger;
/** @private */
function getUserAgentHeader() {
var userAgentHeaderName = "X-SignalR-User-Agent";
if (Platform.isNode) {
userAgentHeaderName = "User-Agent";
}
return [userAgentHeaderName, constructUserAgent(exports.VERSION, getOsName(), getRuntime(), getRuntimeVersion())];
}
exports.getUserAgentHeader = getUserAgentHeader;
/** @private */
function constructUserAgent(version, os, runtime, runtimeVersion) {
// Microsoft SignalR/[Version] ([Detailed Version]; [Operating System]; [Runtime]; [Runtime Version])
var userAgent = "Microsoft SignalR/";
var majorAndMinor = version.split(".");
userAgent += majorAndMinor[0] + "." + majorAndMinor[1];
userAgent += " (" + version + "; ";
if (os && os !== "") {
userAgent += os + "; ";
}
else {
userAgent += "Unknown OS; ";
}
userAgent += "" + runtime;
if (runtimeVersion) {
userAgent += "; " + runtimeVersion;
}
else {
userAgent += "; Unknown Runtime Version";
}
userAgent += ")";
return userAgent;
}
exports.constructUserAgent = constructUserAgent;
function getOsName() {
if (Platform.isNode) {
switch (process.platform) {
case "win32":
return "Windows NT";
case "darwin":
return "macOS";
case "linux":
return "Linux";
default:
return process.platform;
}
}
else {
return "";
}
}
function getRuntimeVersion() {
if (Platform.isNode) {
return process.versions.node;
}
return undefined;
}
function getRuntime() {
if (Platform.isNode) {
return "NodeJS";
}
else {
return "Browser";
}
}
//# sourceMappingURL=Utils.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,204 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
Object.defineProperty(exports, "__esModule", { value: true });
var ILogger_1 = require("./ILogger");
var ITransport_1 = require("./ITransport");
var Utils_1 = require("./Utils");
/** @private */
var WebSocketTransport = /** @class */ (function () {
function WebSocketTransport(httpClient, accessTokenFactory, logger, logMessageContent, webSocketConstructor, headers) {
this.logger = logger;
this.accessTokenFactory = accessTokenFactory;
this.logMessageContent = logMessageContent;
this.webSocketConstructor = webSocketConstructor;
this.httpClient = httpClient;
this.onreceive = null;
this.onclose = null;
this.headers = headers;
}
WebSocketTransport.prototype.connect = function (url, transferFormat) {
return __awaiter(this, void 0, void 0, function () {
var token;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
Utils_1.Arg.isRequired(url, "url");
Utils_1.Arg.isRequired(transferFormat, "transferFormat");
Utils_1.Arg.isIn(transferFormat, ITransport_1.TransferFormat, "transferFormat");
this.logger.log(ILogger_1.LogLevel.Trace, "(WebSockets transport) Connecting.");
if (!this.accessTokenFactory) return [3 /*break*/, 2];
return [4 /*yield*/, this.accessTokenFactory()];
case 1:
token = _a.sent();
if (token) {
url += (url.indexOf("?") < 0 ? "?" : "&") + ("access_token=" + encodeURIComponent(token));
}
_a.label = 2;
case 2: return [2 /*return*/, new Promise(function (resolve, reject) {
url = url.replace(/^http/, "ws");
var webSocket;
var cookies = _this.httpClient.getCookieString(url);
var opened = false;
if (Utils_1.Platform.isNode) {
var headers = {};
var _a = Utils_1.getUserAgentHeader(), name_1 = _a[0], value = _a[1];
headers[name_1] = value;
if (cookies) {
headers["Cookie"] = "" + cookies;
}
// Only pass headers when in non-browser environments
webSocket = new _this.webSocketConstructor(url, undefined, {
headers: __assign({}, headers, _this.headers),
});
}
if (!webSocket) {
// Chrome is not happy with passing 'undefined' as protocol
webSocket = new _this.webSocketConstructor(url);
}
if (transferFormat === ITransport_1.TransferFormat.Binary) {
webSocket.binaryType = "arraybuffer";
}
// tslint:disable-next-line:variable-name
webSocket.onopen = function (_event) {
_this.logger.log(ILogger_1.LogLevel.Information, "WebSocket connected to " + url + ".");
_this.webSocket = webSocket;
opened = true;
resolve();
};
webSocket.onerror = function (event) {
var error = null;
// ErrorEvent is a browser only type we need to check if the type exists before using it
if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) {
error = event.error;
}
else {
error = new Error("There was an error with the transport.");
}
reject(error);
};
webSocket.onmessage = function (message) {
_this.logger.log(ILogger_1.LogLevel.Trace, "(WebSockets transport) data received. " + Utils_1.getDataDetail(message.data, _this.logMessageContent) + ".");
if (_this.onreceive) {
try {
_this.onreceive(message.data);
}
catch (error) {
_this.close(error);
return;
}
}
};
webSocket.onclose = function (event) {
// Don't call close handler if connection was never established
// We'll reject the connect call instead
if (opened) {
_this.close(event);
}
else {
var error = null;
// ErrorEvent is a browser only type we need to check if the type exists before using it
if (typeof ErrorEvent !== "undefined" && event instanceof ErrorEvent) {
error = event.error;
}
else {
error = new Error("There was an error with the transport.");
}
reject(error);
}
};
})];
}
});
});
};
WebSocketTransport.prototype.send = function (data) {
if (this.webSocket && this.webSocket.readyState === this.webSocketConstructor.OPEN) {
this.logger.log(ILogger_1.LogLevel.Trace, "(WebSockets transport) sending data. " + Utils_1.getDataDetail(data, this.logMessageContent) + ".");
this.webSocket.send(data);
return Promise.resolve();
}
return Promise.reject("WebSocket is not in the OPEN state");
};
WebSocketTransport.prototype.stop = function () {
if (this.webSocket) {
// Manually invoke onclose callback inline so we know the HttpConnection was closed properly before returning
// This also solves an issue where websocket.onclose could take 18+ seconds to trigger during network disconnects
this.close(undefined);
}
return Promise.resolve();
};
WebSocketTransport.prototype.close = function (event) {
// webSocket will be null if the transport did not start successfully
if (this.webSocket) {
// Clear websocket handlers because we are considering the socket closed now
this.webSocket.onclose = function () { };
this.webSocket.onmessage = function () { };
this.webSocket.onerror = function () { };
this.webSocket.close();
this.webSocket = undefined;
}
this.logger.log(ILogger_1.LogLevel.Trace, "(WebSockets transport) socket closed.");
if (this.onclose) {
if (this.isCloseEvent(event) && (event.wasClean === false || event.code !== 1000)) {
this.onclose(new Error("WebSocket closed with status code: " + event.code + " (" + event.reason + ")."));
}
else if (event instanceof Error) {
this.onclose(event);
}
else {
this.onclose();
}
}
};
WebSocketTransport.prototype.isCloseEvent = function (event) {
return event && typeof event.wasClean === "boolean" && typeof event.code === "number";
};
return WebSocketTransport;
}());
exports.WebSocketTransport = WebSocketTransport;
//# sourceMappingURL=WebSocketTransport.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,89 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Errors_1 = require("./Errors");
var HttpClient_1 = require("./HttpClient");
var ILogger_1 = require("./ILogger");
var XhrHttpClient = /** @class */ (function (_super) {
__extends(XhrHttpClient, _super);
function XhrHttpClient(logger) {
var _this = _super.call(this) || this;
_this.logger = logger;
return _this;
}
/** @inheritDoc */
XhrHttpClient.prototype.send = function (request) {
var _this = this;
// Check that abort was not signaled before calling send
if (request.abortSignal && request.abortSignal.aborted) {
return Promise.reject(new Errors_1.AbortError());
}
if (!request.method) {
return Promise.reject(new Error("No method defined."));
}
if (!request.url) {
return Promise.reject(new Error("No url defined."));
}
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open(request.method, request.url, true);
xhr.withCredentials = request.withCredentials === undefined ? true : request.withCredentials;
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
// Explicitly setting the Content-Type header for React Native on Android platform.
xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
var headers = request.headers;
if (headers) {
Object.keys(headers)
.forEach(function (header) {
xhr.setRequestHeader(header, headers[header]);
});
}
if (request.responseType) {
xhr.responseType = request.responseType;
}
if (request.abortSignal) {
request.abortSignal.onabort = function () {
xhr.abort();
reject(new Errors_1.AbortError());
};
}
if (request.timeout) {
xhr.timeout = request.timeout;
}
xhr.onload = function () {
if (request.abortSignal) {
request.abortSignal.onabort = null;
}
if (xhr.status >= 200 && xhr.status < 300) {
resolve(new HttpClient_1.HttpResponse(xhr.status, xhr.statusText, xhr.response || xhr.responseText));
}
else {
reject(new Errors_1.HttpError(xhr.statusText, xhr.status));
}
};
xhr.onerror = function () {
_this.logger.log(ILogger_1.LogLevel.Warning, "Error from HTTP request. " + xhr.status + ": " + xhr.statusText + ".");
reject(new Errors_1.HttpError(xhr.statusText, xhr.status));
};
xhr.ontimeout = function () {
_this.logger.log(ILogger_1.LogLevel.Warning, "Timeout from HTTP request.");
reject(new Errors_1.TimeoutError());
};
xhr.send(request.content || "");
});
};
return XhrHttpClient;
}(HttpClient_1.HttpClient));
exports.XhrHttpClient = XhrHttpClient;
//# sourceMappingURL=XhrHttpClient.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,34 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
function __export(m) {
for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
}
Object.defineProperty(exports, "__esModule", { value: true });
// This is where we add any polyfills we'll need for the browser. It is the entry module for browser-specific builds.
require("es6-promise/dist/es6-promise.auto.js");
// Copy from Array.prototype into Uint8Array to polyfill on IE. It's OK because the implementations of indexOf and slice use properties
// that exist on Uint8Array with the same name, and JavaScript is magic.
// We make them 'writable' because the Buffer polyfill messes with it as well.
if (!Uint8Array.prototype.indexOf) {
Object.defineProperty(Uint8Array.prototype, "indexOf", {
value: Array.prototype.indexOf,
writable: true,
});
}
if (!Uint8Array.prototype.slice) {
Object.defineProperty(Uint8Array.prototype, "slice", {
// wrap the slice in Uint8Array so it looks like a Uint8Array.slice call
// tslint:disable-next-line:object-literal-shorthand
value: function (start, end) { return new Uint8Array(Array.prototype.slice.call(this, start, end)); },
writable: true,
});
}
if (!Uint8Array.prototype.forEach) {
Object.defineProperty(Uint8Array.prototype, "forEach", {
value: Array.prototype.forEach,
writable: true,
});
}
__export(require("./index"));
//# sourceMappingURL=browser-index.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"browser-index.js","sourceRoot":"","sources":["../../src/browser-index.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G;;;;;AAE/G,qHAAqH;AAErH,gDAA8C;AAE9C,uIAAuI;AACvI,wEAAwE;AACxE,8EAA8E;AAC9E,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,OAAO,EAAE;IAC/B,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,SAAS,EAAE,SAAS,EAAE;QACnD,KAAK,EAAE,KAAK,CAAC,SAAS,CAAC,OAAO;QAC9B,QAAQ,EAAE,IAAI;KACjB,CAAC,CAAC;CACN;AACD,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,KAAK,EAAE;IAC7B,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,SAAS,EAAE,OAAO,EAAE;QACjD,wEAAwE;QACxE,oDAAoD;QACpD,KAAK,EAAE,UAAS,KAAc,EAAE,GAAY,IAAI,OAAO,IAAI,UAAU,CAAC,KAAK,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;QACtH,QAAQ,EAAE,IAAI;KACjB,CAAC,CAAC;CACN;AACD,IAAI,CAAC,UAAU,CAAC,SAAS,CAAC,OAAO,EAAE;IAC/B,MAAM,CAAC,cAAc,CAAC,UAAU,CAAC,SAAS,EAAE,SAAS,EAAE;QACnD,KAAK,EAAE,KAAK,CAAC,SAAS,CAAC,OAAO;QAC9B,QAAQ,EAAE,IAAI;KACjB,CAAC,CAAC;CACN;AAED,6BAAwB","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// This is where we add any polyfills we'll need for the browser. It is the entry module for browser-specific builds.\r\n\r\nimport \"es6-promise/dist/es6-promise.auto.js\";\r\n\r\n// Copy from Array.prototype into Uint8Array to polyfill on IE. It's OK because the implementations of indexOf and slice use properties\r\n// that exist on Uint8Array with the same name, and JavaScript is magic.\r\n// We make them 'writable' because the Buffer polyfill messes with it as well.\r\nif (!Uint8Array.prototype.indexOf) {\r\n Object.defineProperty(Uint8Array.prototype, \"indexOf\", {\r\n value: Array.prototype.indexOf,\r\n writable: true,\r\n });\r\n}\r\nif (!Uint8Array.prototype.slice) {\r\n Object.defineProperty(Uint8Array.prototype, \"slice\", {\r\n // wrap the slice in Uint8Array so it looks like a Uint8Array.slice call\r\n // tslint:disable-next-line:object-literal-shorthand\r\n value: function(start?: number, end?: number) { return new Uint8Array(Array.prototype.slice.call(this, start, end)); },\r\n writable: true,\r\n });\r\n}\r\nif (!Uint8Array.prototype.forEach) {\r\n Object.defineProperty(Uint8Array.prototype, \"forEach\", {\r\n value: Array.prototype.forEach,\r\n writable: true,\r\n });\r\n}\r\n\r\nexport * from \"./index\";\r\n"]}

View File

@ -0,0 +1,34 @@
"use strict";
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
Object.defineProperty(exports, "__esModule", { value: true });
var Errors_1 = require("./Errors");
exports.AbortError = Errors_1.AbortError;
exports.HttpError = Errors_1.HttpError;
exports.TimeoutError = Errors_1.TimeoutError;
var HttpClient_1 = require("./HttpClient");
exports.HttpClient = HttpClient_1.HttpClient;
exports.HttpResponse = HttpClient_1.HttpResponse;
var DefaultHttpClient_1 = require("./DefaultHttpClient");
exports.DefaultHttpClient = DefaultHttpClient_1.DefaultHttpClient;
var HubConnection_1 = require("./HubConnection");
exports.HubConnection = HubConnection_1.HubConnection;
exports.HubConnectionState = HubConnection_1.HubConnectionState;
var HubConnectionBuilder_1 = require("./HubConnectionBuilder");
exports.HubConnectionBuilder = HubConnectionBuilder_1.HubConnectionBuilder;
var IHubProtocol_1 = require("./IHubProtocol");
exports.MessageType = IHubProtocol_1.MessageType;
var ILogger_1 = require("./ILogger");
exports.LogLevel = ILogger_1.LogLevel;
var ITransport_1 = require("./ITransport");
exports.HttpTransportType = ITransport_1.HttpTransportType;
exports.TransferFormat = ITransport_1.TransferFormat;
var Loggers_1 = require("./Loggers");
exports.NullLogger = Loggers_1.NullLogger;
var JsonHubProtocol_1 = require("./JsonHubProtocol");
exports.JsonHubProtocol = JsonHubProtocol_1.JsonHubProtocol;
var Subject_1 = require("./Subject");
exports.Subject = Subject_1.Subject;
var Utils_1 = require("./Utils");
exports.VERSION = Utils_1.VERSION;
//# sourceMappingURL=index.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA,sDAAsD;AACtD,+GAA+G;;AAI/G,mCAA+D;AAAtD,8BAAA,UAAU,CAAA;AAAE,6BAAA,SAAS,CAAA;AAAE,gCAAA,YAAY,CAAA;AAC5C,2CAAqE;AAA5D,kCAAA,UAAU,CAAA;AAAe,oCAAA,YAAY,CAAA;AAC9C,yDAAwD;AAA/C,gDAAA,iBAAiB,CAAA;AAE1B,iDAAoE;AAA3D,wCAAA,aAAa,CAAA;AAAE,6CAAA,kBAAkB,CAAA;AAC1C,+DAA8D;AAArD,sDAAA,oBAAoB,CAAA;AAC7B,+CAC6F;AADpF,qCAAA,WAAW,CAAA;AAEpB,qCAA8C;AAA5B,6BAAA,QAAQ,CAAA;AAC1B,2CAA6E;AAApE,yCAAA,iBAAiB,CAAA;AAAE,sCAAA,cAAc,CAAA;AAE1C,qCAAuC;AAA9B,+BAAA,UAAU,CAAA;AACnB,qDAAoD;AAA3C,4CAAA,eAAe,CAAA;AACxB,qCAAoC;AAA3B,4BAAA,OAAO,CAAA;AAEhB,iCAAkC;AAAzB,0BAAA,OAAO,CAAA","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// Everything that users need to access must be exported here. Including interfaces.\r\nexport { AbortSignal } from \"./AbortController\";\r\nexport { AbortError, HttpError, TimeoutError } from \"./Errors\";\r\nexport { HttpClient, HttpRequest, HttpResponse } from \"./HttpClient\";\r\nexport { DefaultHttpClient } from \"./DefaultHttpClient\";\r\nexport { IHttpConnectionOptions } from \"./IHttpConnectionOptions\";\r\nexport { HubConnection, HubConnectionState } from \"./HubConnection\";\r\nexport { HubConnectionBuilder } from \"./HubConnectionBuilder\";\r\nexport { MessageType, MessageHeaders, HubMessage, HubMessageBase, HubInvocationMessage, InvocationMessage, StreamInvocationMessage, StreamItemMessage, CompletionMessage,\r\n PingMessage, CloseMessage, CancelInvocationMessage, IHubProtocol } from \"./IHubProtocol\";\r\nexport { ILogger, LogLevel } from \"./ILogger\";\r\nexport { HttpTransportType, TransferFormat, ITransport } from \"./ITransport\";\r\nexport { IStreamSubscriber, IStreamResult, ISubscription } from \"./Stream\";\r\nexport { NullLogger } from \"./Loggers\";\r\nexport { JsonHubProtocol } from \"./JsonHubProtocol\";\r\nexport { Subject } from \"./Subject\";\r\nexport { IRetryPolicy, RetryContext } from \"./IRetryPolicy\";\r\nexport { VERSION } from \"./Utils\";\r\n"]}

View File

@ -0,0 +1,15 @@
/** @private */
export declare class AbortController implements AbortSignal {
private isAborted;
onabort: (() => void) | null;
abort(): void;
readonly signal: AbortSignal;
readonly aborted: boolean;
}
/** Represents a signal that can be monitored to determine if a request has been aborted. */
export interface AbortSignal {
/** Indicates if the request has been aborted. */
aborted: boolean;
/** Set this to a handler that will be invoked when the request is aborted. */
onabort: (() => void) | null;
}

View File

@ -0,0 +1,38 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController
// We don't actually ever use the API being polyfilled, we always use the polyfill because
// it's a very new API right now.
// Not exported from index.
/** @private */
var AbortController = /** @class */ (function () {
function AbortController() {
this.isAborted = false;
this.onabort = null;
}
AbortController.prototype.abort = function () {
if (!this.isAborted) {
this.isAborted = true;
if (this.onabort) {
this.onabort();
}
}
};
Object.defineProperty(AbortController.prototype, "signal", {
get: function () {
return this;
},
enumerable: true,
configurable: true
});
Object.defineProperty(AbortController.prototype, "aborted", {
get: function () {
return this.isAborted;
},
enumerable: true,
configurable: true
});
return AbortController;
}());
export { AbortController };
//# sourceMappingURL=AbortController.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"AbortController.js","sourceRoot":"","sources":["../../src/AbortController.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,+GAA+G;AAE/G,qFAAqF;AACrF,0FAA0F;AAC1F,iCAAiC;AAEjC,2BAA2B;AAC3B,eAAe;AACf;IAAA;QACY,cAAS,GAAY,KAAK,CAAC;QAC5B,YAAO,GAAwB,IAAI,CAAC;IAkB/C,CAAC;IAhBU,+BAAK,GAAZ;QACI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE;YACjB,IAAI,CAAC,SAAS,GAAG,IAAI,CAAC;YACtB,IAAI,IAAI,CAAC,OAAO,EAAE;gBACd,IAAI,CAAC,OAAO,EAAE,CAAC;aAClB;SACJ;IACL,CAAC;IAED,sBAAI,mCAAM;aAAV;YACI,OAAO,IAAI,CAAC;QAChB,CAAC;;;OAAA;IAED,sBAAI,oCAAO;aAAX;YACI,OAAO,IAAI,CAAC,SAAS,CAAC;QAC1B,CAAC;;;OAAA;IACL,sBAAC;AAAD,CAAC,AApBD,IAoBC","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n// Rough polyfill of https://developer.mozilla.org/en-US/docs/Web/API/AbortController\r\n// We don't actually ever use the API being polyfilled, we always use the polyfill because\r\n// it's a very new API right now.\r\n\r\n// Not exported from index.\r\n/** @private */\r\nexport class AbortController implements AbortSignal {\r\n private isAborted: boolean = false;\r\n public onabort: (() => void) | null = null;\r\n\r\n public abort() {\r\n if (!this.isAborted) {\r\n this.isAborted = true;\r\n if (this.onabort) {\r\n this.onabort();\r\n }\r\n }\r\n }\r\n\r\n get signal(): AbortSignal {\r\n return this;\r\n }\r\n\r\n get aborted(): boolean {\r\n return this.isAborted;\r\n }\r\n}\r\n\r\n/** Represents a signal that can be monitored to determine if a request has been aborted. */\r\nexport interface AbortSignal {\r\n /** Indicates if the request has been aborted. */\r\n aborted: boolean;\r\n /** Set this to a handler that will be invoked when the request is aborted. */\r\n onabort: (() => void) | null;\r\n}\r\n"]}

View File

@ -0,0 +1,11 @@
import { HttpClient, HttpRequest, HttpResponse } from "./HttpClient";
import { ILogger } from "./ILogger";
/** Default implementation of {@link @microsoft/signalr.HttpClient}. */
export declare class DefaultHttpClient extends HttpClient {
private readonly httpClient;
/** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */
constructor(logger: ILogger);
/** @inheritDoc */
send(request: HttpRequest): Promise<HttpResponse>;
getCookieString(url: string): string;
}

View File

@ -0,0 +1,55 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
import { AbortError } from "./Errors";
import { FetchHttpClient } from "./FetchHttpClient";
import { HttpClient } from "./HttpClient";
import { Platform } from "./Utils";
import { XhrHttpClient } from "./XhrHttpClient";
/** Default implementation of {@link @microsoft/signalr.HttpClient}. */
var DefaultHttpClient = /** @class */ (function (_super) {
__extends(DefaultHttpClient, _super);
/** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */
function DefaultHttpClient(logger) {
var _this = _super.call(this) || this;
if (typeof fetch !== "undefined" || Platform.isNode) {
_this.httpClient = new FetchHttpClient(logger);
}
else if (typeof XMLHttpRequest !== "undefined") {
_this.httpClient = new XhrHttpClient(logger);
}
else {
throw new Error("No usable HttpClient found.");
}
return _this;
}
/** @inheritDoc */
DefaultHttpClient.prototype.send = function (request) {
// Check that abort was not signaled before calling send
if (request.abortSignal && request.abortSignal.aborted) {
return Promise.reject(new AbortError());
}
if (!request.method) {
return Promise.reject(new Error("No method defined."));
}
if (!request.url) {
return Promise.reject(new Error("No url defined."));
}
return this.httpClient.send(request);
};
DefaultHttpClient.prototype.getCookieString = function (url) {
return this.httpClient.getCookieString(url);
};
return DefaultHttpClient;
}(HttpClient));
export { DefaultHttpClient };
//# sourceMappingURL=DefaultHttpClient.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"DefaultHttpClient.js","sourceRoot":"","sources":["../../src/DefaultHttpClient.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,+GAA+G;;;;;;;;;;;AAE/G,OAAO,EAAE,UAAU,EAAE,MAAM,UAAU,CAAC;AACtC,OAAO,EAAE,eAAe,EAAE,MAAM,mBAAmB,CAAC;AACpD,OAAO,EAAE,UAAU,EAA6B,MAAM,cAAc,CAAC;AAErE,OAAO,EAAE,QAAQ,EAAE,MAAM,SAAS,CAAC;AACnC,OAAO,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAC;AAEhD,uEAAuE;AACvE;IAAuC,qCAAU;IAG7C,yJAAyJ;IACzJ,2BAAmB,MAAe;QAAlC,YACI,iBAAO,SASV;QAPG,IAAI,OAAO,KAAK,KAAK,WAAW,IAAI,QAAQ,CAAC,MAAM,EAAE;YACjD,KAAI,CAAC,UAAU,GAAG,IAAI,eAAe,CAAC,MAAM,CAAC,CAAC;SACjD;aAAM,IAAI,OAAO,cAAc,KAAK,WAAW,EAAE;YAC9C,KAAI,CAAC,UAAU,GAAG,IAAI,aAAa,CAAC,MAAM,CAAC,CAAC;SAC/C;aAAM;YACH,MAAM,IAAI,KAAK,CAAC,6BAA6B,CAAC,CAAC;SAClD;;IACL,CAAC;IAED,kBAAkB;IACX,gCAAI,GAAX,UAAY,OAAoB;QAC5B,wDAAwD;QACxD,IAAI,OAAO,CAAC,WAAW,IAAI,OAAO,CAAC,WAAW,CAAC,OAAO,EAAE;YACpD,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,UAAU,EAAE,CAAC,CAAC;SAC3C;QAED,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;YACjB,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC,CAAC;SAC1D;QACD,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE;YACd,OAAO,OAAO,CAAC,MAAM,CAAC,IAAI,KAAK,CAAC,iBAAiB,CAAC,CAAC,CAAC;SACvD;QAED,OAAO,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACzC,CAAC;IAEM,2CAAe,GAAtB,UAAuB,GAAW;QAC9B,OAAO,IAAI,CAAC,UAAU,CAAC,eAAe,CAAC,GAAG,CAAC,CAAC;IAChD,CAAC;IACL,wBAAC;AAAD,CAAC,AApCD,CAAuC,UAAU,GAoChD","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { AbortError } from \"./Errors\";\r\nimport { FetchHttpClient } from \"./FetchHttpClient\";\r\nimport { HttpClient, HttpRequest, HttpResponse } from \"./HttpClient\";\r\nimport { ILogger } from \"./ILogger\";\r\nimport { Platform } from \"./Utils\";\r\nimport { XhrHttpClient } from \"./XhrHttpClient\";\r\n\r\n/** Default implementation of {@link @microsoft/signalr.HttpClient}. */\r\nexport class DefaultHttpClient extends HttpClient {\r\n private readonly httpClient: HttpClient;\r\n\r\n /** Creates a new instance of the {@link @microsoft/signalr.DefaultHttpClient}, using the provided {@link @microsoft/signalr.ILogger} to log messages. */\r\n public constructor(logger: ILogger) {\r\n super();\r\n\r\n if (typeof fetch !== \"undefined\" || Platform.isNode) {\r\n this.httpClient = new FetchHttpClient(logger);\r\n } else if (typeof XMLHttpRequest !== \"undefined\") {\r\n this.httpClient = new XhrHttpClient(logger);\r\n } else {\r\n throw new Error(\"No usable HttpClient found.\");\r\n }\r\n }\r\n\r\n /** @inheritDoc */\r\n public send(request: HttpRequest): Promise<HttpResponse> {\r\n // Check that abort was not signaled before calling send\r\n if (request.abortSignal && request.abortSignal.aborted) {\r\n return Promise.reject(new AbortError());\r\n }\r\n\r\n if (!request.method) {\r\n return Promise.reject(new Error(\"No method defined.\"));\r\n }\r\n if (!request.url) {\r\n return Promise.reject(new Error(\"No url defined.\"));\r\n }\r\n\r\n return this.httpClient.send(request);\r\n }\r\n\r\n public getCookieString(url: string): string {\r\n return this.httpClient.getCookieString(url);\r\n }\r\n}\r\n"]}

View File

@ -0,0 +1,7 @@
import { IRetryPolicy, RetryContext } from "./IRetryPolicy";
/** @private */
export declare class DefaultReconnectPolicy implements IRetryPolicy {
private readonly retryDelays;
constructor(retryDelays?: number[]);
nextRetryDelayInMilliseconds(retryContext: RetryContext): number | null;
}

View File

@ -0,0 +1,16 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
// 0, 2, 10, 30 second delays before reconnect attempts.
var DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];
/** @private */
var DefaultReconnectPolicy = /** @class */ (function () {
function DefaultReconnectPolicy(retryDelays) {
this.retryDelays = retryDelays !== undefined ? retryDelays.concat([null]) : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;
}
DefaultReconnectPolicy.prototype.nextRetryDelayInMilliseconds = function (retryContext) {
return this.retryDelays[retryContext.previousRetryCount];
};
return DefaultReconnectPolicy;
}());
export { DefaultReconnectPolicy };
//# sourceMappingURL=DefaultReconnectPolicy.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"DefaultReconnectPolicy.js","sourceRoot":"","sources":["../../src/DefaultReconnectPolicy.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,+GAA+G;AAI/G,wDAAwD;AACxD,IAAM,oCAAoC,GAAG,CAAC,CAAC,EAAE,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC;AAE3E,eAAe;AACf;IAGI,gCAAY,WAAsB;QAC9B,IAAI,CAAC,WAAW,GAAG,WAAW,KAAK,SAAS,CAAC,CAAC,CAAK,WAAW,SAAE,IAAI,GAAE,CAAC,CAAC,oCAAoC,CAAC;IACjH,CAAC;IAEM,6DAA4B,GAAnC,UAAoC,YAA0B;QAC1D,OAAO,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC,kBAAkB,CAAC,CAAC;IAC7D,CAAC;IACL,6BAAC;AAAD,CAAC,AAVD,IAUC","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\nimport { IRetryPolicy, RetryContext } from \"./IRetryPolicy\";\r\n\r\n// 0, 2, 10, 30 second delays before reconnect attempts.\r\nconst DEFAULT_RETRY_DELAYS_IN_MILLISECONDS = [0, 2000, 10000, 30000, null];\r\n\r\n/** @private */\r\nexport class DefaultReconnectPolicy implements IRetryPolicy {\r\n private readonly retryDelays: Array<number | null>;\r\n\r\n constructor(retryDelays?: number[]) {\r\n this.retryDelays = retryDelays !== undefined ? [...retryDelays, null] : DEFAULT_RETRY_DELAYS_IN_MILLISECONDS;\r\n }\r\n\r\n public nextRetryDelayInMilliseconds(retryContext: RetryContext): number | null {\r\n return this.retryDelays[retryContext.previousRetryCount];\r\n }\r\n}\r\n"]}

View File

@ -0,0 +1,30 @@
/** Error thrown when an HTTP request fails. */
export declare class HttpError extends Error {
private __proto__;
/** The HTTP status code represented by this error. */
statusCode: number;
/** Constructs a new instance of {@link @microsoft/signalr.HttpError}.
*
* @param {string} errorMessage A descriptive error message.
* @param {number} statusCode The HTTP status code represented by this error.
*/
constructor(errorMessage: string, statusCode: number);
}
/** Error thrown when a timeout elapses. */
export declare class TimeoutError extends Error {
private __proto__;
/** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.
*
* @param {string} errorMessage A descriptive error message.
*/
constructor(errorMessage?: string);
}
/** Error thrown when an action is aborted. */
export declare class AbortError extends Error {
private __proto__;
/** Constructs a new instance of {@link AbortError}.
*
* @param {string} errorMessage A descriptive error message.
*/
constructor(errorMessage?: string);
}

View File

@ -0,0 +1,77 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
/** Error thrown when an HTTP request fails. */
var HttpError = /** @class */ (function (_super) {
__extends(HttpError, _super);
/** Constructs a new instance of {@link @microsoft/signalr.HttpError}.
*
* @param {string} errorMessage A descriptive error message.
* @param {number} statusCode The HTTP status code represented by this error.
*/
function HttpError(errorMessage, statusCode) {
var _newTarget = this.constructor;
var _this = this;
var trueProto = _newTarget.prototype;
_this = _super.call(this, errorMessage) || this;
_this.statusCode = statusCode;
// Workaround issue in Typescript compiler
// https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
_this.__proto__ = trueProto;
return _this;
}
return HttpError;
}(Error));
export { HttpError };
/** Error thrown when a timeout elapses. */
var TimeoutError = /** @class */ (function (_super) {
__extends(TimeoutError, _super);
/** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.
*
* @param {string} errorMessage A descriptive error message.
*/
function TimeoutError(errorMessage) {
var _newTarget = this.constructor;
if (errorMessage === void 0) { errorMessage = "A timeout occurred."; }
var _this = this;
var trueProto = _newTarget.prototype;
_this = _super.call(this, errorMessage) || this;
// Workaround issue in Typescript compiler
// https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
_this.__proto__ = trueProto;
return _this;
}
return TimeoutError;
}(Error));
export { TimeoutError };
/** Error thrown when an action is aborted. */
var AbortError = /** @class */ (function (_super) {
__extends(AbortError, _super);
/** Constructs a new instance of {@link AbortError}.
*
* @param {string} errorMessage A descriptive error message.
*/
function AbortError(errorMessage) {
var _newTarget = this.constructor;
if (errorMessage === void 0) { errorMessage = "An abort occurred."; }
var _this = this;
var trueProto = _newTarget.prototype;
_this = _super.call(this, errorMessage) || this;
// Workaround issue in Typescript compiler
// https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200
_this.__proto__ = trueProto;
return _this;
}
return AbortError;
}(Error));
export { AbortError };
//# sourceMappingURL=Errors.js.map

View File

@ -0,0 +1 @@
{"version":3,"file":"Errors.js","sourceRoot":"","sources":["../../src/Errors.ts"],"names":[],"mappings":"AAAA,sDAAsD;AACtD,+GAA+G;;;;;;;;;;;AAE/G,+CAA+C;AAC/C;IAA+B,6BAAK;IAQhC;;;;OAIG;IACH,mBAAY,YAAoB,EAAE,UAAkB;;QAApD,iBAQC;QAPG,IAAM,SAAS,GAAG,WAAW,SAAS,CAAC;QACvC,QAAA,kBAAM,YAAY,CAAC,SAAC;QACpB,KAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAE7B,0CAA0C;QAC1C,8EAA8E;QAC9E,KAAI,CAAC,SAAS,GAAG,SAAS,CAAC;;IAC/B,CAAC;IACL,gBAAC;AAAD,CAAC,AAtBD,CAA+B,KAAK,GAsBnC;;AAED,2CAA2C;AAC3C;IAAkC,gCAAK;IAKnC;;;OAGG;IACH,sBAAY,YAA4C;;QAA5C,6BAAA,EAAA,oCAA4C;QAAxD,iBAOC;QANG,IAAM,SAAS,GAAG,WAAW,SAAS,CAAC;QACvC,QAAA,kBAAM,YAAY,CAAC,SAAC;QAEpB,0CAA0C;QAC1C,8EAA8E;QAC9E,KAAI,CAAC,SAAS,GAAG,SAAS,CAAC;;IAC/B,CAAC;IACL,mBAAC;AAAD,CAAC,AAjBD,CAAkC,KAAK,GAiBtC;;AAED,8CAA8C;AAC9C;IAAgC,8BAAK;IAKjC;;;OAGG;IACH,oBAAY,YAA2C;;QAA3C,6BAAA,EAAA,mCAA2C;QAAvD,iBAOC;QANG,IAAM,SAAS,GAAG,WAAW,SAAS,CAAC;QACvC,QAAA,kBAAM,YAAY,CAAC,SAAC;QAEpB,0CAA0C;QAC1C,8EAA8E;QAC9E,KAAI,CAAC,SAAS,GAAG,SAAS,CAAC;;IAC/B,CAAC;IACL,iBAAC;AAAD,CAAC,AAjBD,CAAgC,KAAK,GAiBpC","sourcesContent":["// Copyright (c) .NET Foundation. All rights reserved.\r\n// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.\r\n\r\n/** Error thrown when an HTTP request fails. */\r\nexport class HttpError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // tslint:disable-next-line:variable-name\r\n private __proto__: Error;\r\n\r\n /** The HTTP status code represented by this error. */\r\n public statusCode: number;\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.HttpError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n * @param {number} statusCode The HTTP status code represented by this error.\r\n */\r\n constructor(errorMessage: string, statusCode: number) {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n this.statusCode = statusCode;\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when a timeout elapses. */\r\nexport class TimeoutError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // tslint:disable-next-line:variable-name\r\n private __proto__: Error;\r\n\r\n /** Constructs a new instance of {@link @microsoft/signalr.TimeoutError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\r\n constructor(errorMessage: string = \"A timeout occurred.\") {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n\r\n/** Error thrown when an action is aborted. */\r\nexport class AbortError extends Error {\r\n // @ts-ignore: Intentionally unused.\r\n // tslint:disable-next-line:variable-name\r\n private __proto__: Error;\r\n\r\n /** Constructs a new instance of {@link AbortError}.\r\n *\r\n * @param {string} errorMessage A descriptive error message.\r\n */\r\n constructor(errorMessage: string = \"An abort occurred.\") {\r\n const trueProto = new.target.prototype;\r\n super(errorMessage);\r\n\r\n // Workaround issue in Typescript compiler\r\n // https://github.com/Microsoft/TypeScript/issues/13965#issuecomment-278570200\r\n this.__proto__ = trueProto;\r\n }\r\n}\r\n"]}

View File

@ -0,0 +1,12 @@
import { HttpClient, HttpRequest, HttpResponse } from "./HttpClient";
import { ILogger } from "./ILogger";
export declare class FetchHttpClient extends HttpClient {
private readonly abortControllerType;
private readonly fetchType;
private readonly jar?;
private readonly logger;
constructor(logger: ILogger);
/** @inheritDoc */
send(request: HttpRequest): Promise<HttpResponse>;
getCookieString(url: string): string;
}

View File

@ -0,0 +1,193 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { AbortError, HttpError, TimeoutError } from "./Errors";
import { HttpClient, HttpResponse } from "./HttpClient";
import { LogLevel } from "./ILogger";
import { Platform } from "./Utils";
var FetchHttpClient = /** @class */ (function (_super) {
__extends(FetchHttpClient, _super);
function FetchHttpClient(logger) {
var _this = _super.call(this) || this;
_this.logger = logger;
if (typeof fetch === "undefined") {
// In order to ignore the dynamic require in webpack builds we need to do this magic
// @ts-ignore: TS doesn't know about these names
var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
// Cookies aren't automatically handled in Node so we need to add a CookieJar to preserve cookies across requests
_this.jar = new (requireFunc("tough-cookie")).CookieJar();
_this.fetchType = requireFunc("node-fetch");
// node-fetch doesn't have a nice API for getting and setting cookies
// fetch-cookie will wrap a fetch implementation with a default CookieJar or a provided one
_this.fetchType = requireFunc("fetch-cookie")(_this.fetchType, _this.jar);
// Node needs EventListener methods on AbortController which our custom polyfill doesn't provide
_this.abortControllerType = requireFunc("abort-controller");
}
else {
_this.fetchType = fetch.bind(self);
_this.abortControllerType = AbortController;
}
return _this;
}
/** @inheritDoc */
FetchHttpClient.prototype.send = function (request) {
return __awaiter(this, void 0, void 0, function () {
var abortController, error, timeoutId, msTimeout, response, e_1, content, payload;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Check that abort was not signaled before calling send
if (request.abortSignal && request.abortSignal.aborted) {
throw new AbortError();
}
if (!request.method) {
throw new Error("No method defined.");
}
if (!request.url) {
throw new Error("No url defined.");
}
abortController = new this.abortControllerType();
// Hook our abortSignal into the abort controller
if (request.abortSignal) {
request.abortSignal.onabort = function () {
abortController.abort();
error = new AbortError();
};
}
timeoutId = null;
if (request.timeout) {
msTimeout = request.timeout;
timeoutId = setTimeout(function () {
abortController.abort();
_this.logger.log(LogLevel.Warning, "Timeout from HTTP request.");
error = new TimeoutError();
}, msTimeout);
}
_a.label = 1;
case 1:
_a.trys.push([1, 3, 4, 5]);
return [4 /*yield*/, this.fetchType(request.url, {
body: request.content,
cache: "no-cache",
credentials: request.withCredentials === true ? "include" : "same-origin",
headers: __assign({ "Content-Type": "text/plain;charset=UTF-8", "X-Requested-With": "XMLHttpRequest" }, request.headers),
method: request.method,
mode: "cors",
redirect: "manual",
signal: abortController.signal,
})];
case 2:
response = _a.sent();
return [3 /*break*/, 5];
case 3:
e_1 = _a.sent();
if (error) {
throw error;
}
this.logger.log(LogLevel.Warning, "Error from HTTP request. " + e_1 + ".");
throw e_1;
case 4:
if (timeoutId) {
clearTimeout(timeoutId);
}
if (request.abortSignal) {
request.abortSignal.onabort = null;
}
return [7 /*endfinally*/];
case 5:
if (!response.ok) {
throw new HttpError(response.statusText, response.status);
}
content = deserializeContent(response, request.responseType);
return [4 /*yield*/, content];
case 6:
payload = _a.sent();
return [2 /*return*/, new HttpResponse(response.status, response.statusText, payload)];
}
});
});
};
FetchHttpClient.prototype.getCookieString = function (url) {
var cookies = "";
if (Platform.isNode && this.jar) {
// @ts-ignore: unused variable
this.jar.getCookies(url, function (e, c) { return cookies = c.join("; "); });
}
return cookies;
};
return FetchHttpClient;
}(HttpClient));
export { FetchHttpClient };
function deserializeContent(response, responseType) {
var content;
switch (responseType) {
case "arraybuffer":
content = response.arrayBuffer();
break;
case "text":
content = response.text();
break;
case "blob":
case "document":
case "json":
throw new Error(responseType + " is not supported.");
default:
content = response.text();
break;
}
return content;
}
//# sourceMappingURL=FetchHttpClient.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,15 @@
/** @private */
export interface HandshakeRequestMessage {
readonly protocol: string;
readonly version: number;
}
/** @private */
export interface HandshakeResponseMessage {
readonly error: string;
readonly minorVersion: number;
}
/** @private */
export declare class HandshakeProtocol {
writeHandshakeRequest(handshakeRequest: HandshakeRequestMessage): string;
parseHandshakeResponse(data: any): [any, HandshakeResponseMessage];
}

View File

@ -0,0 +1,56 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
import { TextMessageFormat } from "./TextMessageFormat";
import { isArrayBuffer } from "./Utils";
/** @private */
var HandshakeProtocol = /** @class */ (function () {
function HandshakeProtocol() {
}
// Handshake request is always JSON
HandshakeProtocol.prototype.writeHandshakeRequest = function (handshakeRequest) {
return TextMessageFormat.write(JSON.stringify(handshakeRequest));
};
HandshakeProtocol.prototype.parseHandshakeResponse = function (data) {
var responseMessage;
var messageData;
var remainingData;
if (isArrayBuffer(data) || (typeof Buffer !== "undefined" && data instanceof Buffer)) {
// Format is binary but still need to read JSON text from handshake response
var binaryData = new Uint8Array(data);
var separatorIndex = binaryData.indexOf(TextMessageFormat.RecordSeparatorCode);
if (separatorIndex === -1) {
throw new Error("Message is incomplete.");
}
// content before separator is handshake response
// optional content after is additional messages
var responseLength = separatorIndex + 1;
messageData = String.fromCharCode.apply(null, binaryData.slice(0, responseLength));
remainingData = (binaryData.byteLength > responseLength) ? binaryData.slice(responseLength).buffer : null;
}
else {
var textData = data;
var separatorIndex = textData.indexOf(TextMessageFormat.RecordSeparator);
if (separatorIndex === -1) {
throw new Error("Message is incomplete.");
}
// content before separator is handshake response
// optional content after is additional messages
var responseLength = separatorIndex + 1;
messageData = textData.substring(0, responseLength);
remainingData = (textData.length > responseLength) ? textData.substring(responseLength) : null;
}
// At this point we should have just the single handshake message
var messages = TextMessageFormat.parse(messageData);
var response = JSON.parse(messages[0]);
if (response.type) {
throw new Error("Expected a handshake response from the server.");
}
responseMessage = response;
// multiple messages could have arrived with handshake
// return additional data to be parsed as usual, or null if all parsed
return [remainingData, responseMessage];
};
return HandshakeProtocol;
}());
export { HandshakeProtocol };
//# sourceMappingURL=HandshakeProtocol.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,116 @@
import { AbortSignal } from "./AbortController";
import { MessageHeaders } from "./IHubProtocol";
/** Represents an HTTP request. */
export interface HttpRequest {
/** The HTTP method to use for the request. */
method?: string;
/** The URL for the request. */
url?: string;
/** The body content for the request. May be a string or an ArrayBuffer (for binary data). */
content?: string | ArrayBuffer;
/** An object describing headers to apply to the request. */
headers?: MessageHeaders;
/** The XMLHttpRequestResponseType to apply to the request. */
responseType?: XMLHttpRequestResponseType;
/** An AbortSignal that can be monitored for cancellation. */
abortSignal?: AbortSignal;
/** The time to wait for the request to complete before throwing a TimeoutError. Measured in milliseconds. */
timeout?: number;
/** This controls whether credentials such as cookies are sent in cross-site requests. */
withCredentials?: boolean;
}
/** Represents an HTTP response. */
export declare class HttpResponse {
readonly statusCode: number;
readonly statusText?: string | undefined;
readonly content?: string | ArrayBuffer | undefined;
/** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code.
*
* @param {number} statusCode The status code of the response.
*/
constructor(statusCode: number);
/** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code and message.
*
* @param {number} statusCode The status code of the response.
* @param {string} statusText The status message of the response.
*/
constructor(statusCode: number, statusText: string);
/** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code, message and string content.
*
* @param {number} statusCode The status code of the response.
* @param {string} statusText The status message of the response.
* @param {string} content The content of the response.
*/
constructor(statusCode: number, statusText: string, content: string);
/** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code, message and binary content.
*
* @param {number} statusCode The status code of the response.
* @param {string} statusText The status message of the response.
* @param {ArrayBuffer} content The content of the response.
*/
constructor(statusCode: number, statusText: string, content: ArrayBuffer);
/** Constructs a new instance of {@link @microsoft/signalr.HttpResponse} with the specified status code, message and binary content.
*
* @param {number} statusCode The status code of the response.
* @param {string} statusText The status message of the response.
* @param {string | ArrayBuffer} content The content of the response.
*/
constructor(statusCode: number, statusText: string, content: string | ArrayBuffer);
}
/** Abstraction over an HTTP client.
*
* This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms.
*/
export declare abstract class HttpClient {
/** Issues an HTTP GET request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.
*
* @param {string} url The URL for the request.
* @returns {Promise<HttpResponse>} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.
*/
get(url: string): Promise<HttpResponse>;
/** Issues an HTTP GET request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.
*
* @param {string} url The URL for the request.
* @param {HttpRequest} options Additional options to configure the request. The 'url' field in this object will be overridden by the url parameter.
* @returns {Promise<HttpResponse>} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.
*/
get(url: string, options: HttpRequest): Promise<HttpResponse>;
/** Issues an HTTP POST request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.
*
* @param {string} url The URL for the request.
* @returns {Promise<HttpResponse>} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.
*/
post(url: string): Promise<HttpResponse>;
/** Issues an HTTP POST request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.
*
* @param {string} url The URL for the request.
* @param {HttpRequest} options Additional options to configure the request. The 'url' field in this object will be overridden by the url parameter.
* @returns {Promise<HttpResponse>} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.
*/
post(url: string, options: HttpRequest): Promise<HttpResponse>;
/** Issues an HTTP DELETE request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.
*
* @param {string} url The URL for the request.
* @returns {Promise<HttpResponse>} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.
*/
delete(url: string): Promise<HttpResponse>;
/** Issues an HTTP DELETE request to the specified URL, returning a Promise that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.
*
* @param {string} url The URL for the request.
* @param {HttpRequest} options Additional options to configure the request. The 'url' field in this object will be overridden by the url parameter.
* @returns {Promise<HttpResponse>} A Promise that resolves with an {@link @microsoft/signalr.HttpResponse} describing the response, or rejects with an Error indicating a failure.
*/
delete(url: string, options: HttpRequest): Promise<HttpResponse>;
/** Issues an HTTP request to the specified URL, returning a {@link Promise} that resolves with an {@link @microsoft/signalr.HttpResponse} representing the result.
*
* @param {HttpRequest} request An {@link @microsoft/signalr.HttpRequest} describing the request to send.
* @returns {Promise<HttpResponse>} A Promise that resolves with an HttpResponse describing the response, or rejects with an Error indicating a failure.
*/
abstract send(request: HttpRequest): Promise<HttpResponse>;
/** Gets all cookies that apply to the specified URL.
*
* @param url The URL that the cookies are valid for.
* @returns {string} A string containing all the key-value cookie pairs for the specified URL.
*/
getCookieString(url: string): string;
}

View File

@ -0,0 +1,49 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
/** Represents an HTTP response. */
var HttpResponse = /** @class */ (function () {
function HttpResponse(statusCode, statusText, content) {
this.statusCode = statusCode;
this.statusText = statusText;
this.content = content;
}
return HttpResponse;
}());
export { HttpResponse };
/** Abstraction over an HTTP client.
*
* This class provides an abstraction over an HTTP client so that a different implementation can be provided on different platforms.
*/
var HttpClient = /** @class */ (function () {
function HttpClient() {
}
HttpClient.prototype.get = function (url, options) {
return this.send(__assign({}, options, { method: "GET", url: url }));
};
HttpClient.prototype.post = function (url, options) {
return this.send(__assign({}, options, { method: "POST", url: url }));
};
HttpClient.prototype.delete = function (url, options) {
return this.send(__assign({}, options, { method: "DELETE", url: url }));
};
/** Gets all cookies that apply to the specified URL.
*
* @param url The URL that the cookies are valid for.
* @returns {string} A string containing all the key-value cookie pairs for the specified URL.
*/
// @ts-ignore
HttpClient.prototype.getCookieString = function (url) {
return "";
};
return HttpClient;
}());
export { HttpClient };
//# sourceMappingURL=HttpClient.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,71 @@
import { IConnection } from "./IConnection";
import { IHttpConnectionOptions } from "./IHttpConnectionOptions";
import { HttpTransportType, ITransport, TransferFormat } from "./ITransport";
/** @private */
export interface INegotiateResponse {
connectionId?: string;
connectionToken?: string;
negotiateVersion?: number;
availableTransports?: IAvailableTransport[];
url?: string;
accessToken?: string;
error?: string;
}
/** @private */
export interface IAvailableTransport {
transport: keyof typeof HttpTransportType;
transferFormats: Array<keyof typeof TransferFormat>;
}
/** @private */
export declare class HttpConnection implements IConnection {
private connectionState;
private connectionStarted;
private readonly httpClient;
private readonly logger;
private readonly options;
private transport?;
private startInternalPromise?;
private stopPromise?;
private stopPromiseResolver;
private stopError?;
private accessTokenFactory?;
private sendQueue?;
readonly features: any;
baseUrl: string;
connectionId?: string;
onreceive: ((data: string | ArrayBuffer) => void) | null;
onclose: ((e?: Error) => void) | null;
private readonly negotiateVersion;
constructor(url: string, options?: IHttpConnectionOptions);
start(): Promise<void>;
start(transferFormat: TransferFormat): Promise<void>;
send(data: string | ArrayBuffer): Promise<void>;
stop(error?: Error): Promise<void>;
private stopInternal;
private startInternal;
private getNegotiationResponse;
private createConnectUrl;
private createTransport;
private constructTransport;
private startTransport;
private resolveTransportOrError;
private isITransport;
private stopConnection;
private resolveUrl;
private resolveNegotiateUrl;
}
/** @private */
export declare class TransportSendQueue {
private readonly transport;
private buffer;
private sendBufferedData;
private executing;
private transportResult?;
private sendLoopPromise;
constructor(transport: ITransport);
send(data: string | ArrayBuffer): Promise<void>;
stop(): Promise<void>;
private bufferData;
private sendLoop;
private static concatBuffers;
}

View File

@ -0,0 +1,707 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __assign = (this && this.__assign) || Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { DefaultHttpClient } from "./DefaultHttpClient";
import { LogLevel } from "./ILogger";
import { HttpTransportType, TransferFormat } from "./ITransport";
import { LongPollingTransport } from "./LongPollingTransport";
import { ServerSentEventsTransport } from "./ServerSentEventsTransport";
import { Arg, createLogger, getUserAgentHeader, Platform } from "./Utils";
import { WebSocketTransport } from "./WebSocketTransport";
var MAX_REDIRECTS = 100;
/** @private */
var HttpConnection = /** @class */ (function () {
function HttpConnection(url, options) {
if (options === void 0) { options = {}; }
this.stopPromiseResolver = function () { };
this.features = {};
this.negotiateVersion = 1;
Arg.isRequired(url, "url");
this.logger = createLogger(options.logger);
this.baseUrl = this.resolveUrl(url);
options = options || {};
options.logMessageContent = options.logMessageContent === undefined ? false : options.logMessageContent;
if (typeof options.withCredentials === "boolean" || options.withCredentials === undefined) {
options.withCredentials = options.withCredentials === undefined ? true : options.withCredentials;
}
else {
throw new Error("withCredentials option was not a 'boolean' or 'undefined' value");
}
var webSocketModule = null;
var eventSourceModule = null;
if (Platform.isNode && typeof require !== "undefined") {
// In order to ignore the dynamic require in webpack builds we need to do this magic
// @ts-ignore: TS doesn't know about these names
var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : require;
webSocketModule = requireFunc("ws");
eventSourceModule = requireFunc("eventsource");
}
if (!Platform.isNode && typeof WebSocket !== "undefined" && !options.WebSocket) {
options.WebSocket = WebSocket;
}
else if (Platform.isNode && !options.WebSocket) {
if (webSocketModule) {
options.WebSocket = webSocketModule;
}
}
if (!Platform.isNode && typeof EventSource !== "undefined" && !options.EventSource) {
options.EventSource = EventSource;
}
else if (Platform.isNode && !options.EventSource) {
if (typeof eventSourceModule !== "undefined") {
options.EventSource = eventSourceModule;
}
}
this.httpClient = options.httpClient || new DefaultHttpClient(this.logger);
this.connectionState = "Disconnected" /* Disconnected */;
this.connectionStarted = false;
this.options = options;
this.onreceive = null;
this.onclose = null;
}
HttpConnection.prototype.start = function (transferFormat) {
return __awaiter(this, void 0, void 0, function () {
var message, message;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
transferFormat = transferFormat || TransferFormat.Binary;
Arg.isIn(transferFormat, TransferFormat, "transferFormat");
this.logger.log(LogLevel.Debug, "Starting connection with transfer format '" + TransferFormat[transferFormat] + "'.");
if (this.connectionState !== "Disconnected" /* Disconnected */) {
return [2 /*return*/, Promise.reject(new Error("Cannot start an HttpConnection that is not in the 'Disconnected' state."))];
}
this.connectionState = "Connecting" /* Connecting */;
this.startInternalPromise = this.startInternal(transferFormat);
return [4 /*yield*/, this.startInternalPromise];
case 1:
_a.sent();
if (!(this.connectionState === "Disconnecting" /* Disconnecting */)) return [3 /*break*/, 3];
message = "Failed to start the HttpConnection before stop() was called.";
this.logger.log(LogLevel.Error, message);
// We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.
return [4 /*yield*/, this.stopPromise];
case 2:
// We cannot await stopPromise inside startInternal since stopInternal awaits the startInternalPromise.
_a.sent();
return [2 /*return*/, Promise.reject(new Error(message))];
case 3:
if (this.connectionState !== "Connected" /* Connected */) {
message = "HttpConnection.startInternal completed gracefully but didn't enter the connection into the connected state!";
this.logger.log(LogLevel.Error, message);
return [2 /*return*/, Promise.reject(new Error(message))];
}
_a.label = 4;
case 4:
this.connectionStarted = true;
return [2 /*return*/];
}
});
});
};
HttpConnection.prototype.send = function (data) {
if (this.connectionState !== "Connected" /* Connected */) {
return Promise.reject(new Error("Cannot send data if the connection is not in the 'Connected' State."));
}
if (!this.sendQueue) {
this.sendQueue = new TransportSendQueue(this.transport);
}
// Transport will not be null if state is connected
return this.sendQueue.send(data);
};
HttpConnection.prototype.stop = function (error) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.connectionState === "Disconnected" /* Disconnected */) {
this.logger.log(LogLevel.Debug, "Call to HttpConnection.stop(" + error + ") ignored because the connection is already in the disconnected state.");
return [2 /*return*/, Promise.resolve()];
}
if (this.connectionState === "Disconnecting" /* Disconnecting */) {
this.logger.log(LogLevel.Debug, "Call to HttpConnection.stop(" + error + ") ignored because the connection is already in the disconnecting state.");
return [2 /*return*/, this.stopPromise];
}
this.connectionState = "Disconnecting" /* Disconnecting */;
this.stopPromise = new Promise(function (resolve) {
// Don't complete stop() until stopConnection() completes.
_this.stopPromiseResolver = resolve;
});
// stopInternal should never throw so just observe it.
return [4 /*yield*/, this.stopInternal(error)];
case 1:
// stopInternal should never throw so just observe it.
_a.sent();
return [4 /*yield*/, this.stopPromise];
case 2:
_a.sent();
return [2 /*return*/];
}
});
});
};
HttpConnection.prototype.stopInternal = function (error) {
return __awaiter(this, void 0, void 0, function () {
var e_1, e_2;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
// Set error as soon as possible otherwise there is a race between
// the transport closing and providing an error and the error from a close message
// We would prefer the close message error.
this.stopError = error;
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.startInternalPromise];
case 2:
_a.sent();
return [3 /*break*/, 4];
case 3:
e_1 = _a.sent();
return [3 /*break*/, 4];
case 4:
if (!this.transport) return [3 /*break*/, 9];
_a.label = 5;
case 5:
_a.trys.push([5, 7, , 8]);
return [4 /*yield*/, this.transport.stop()];
case 6:
_a.sent();
return [3 /*break*/, 8];
case 7:
e_2 = _a.sent();
this.logger.log(LogLevel.Error, "HttpConnection.transport.stop() threw error '" + e_2 + "'.");
this.stopConnection();
return [3 /*break*/, 8];
case 8:
this.transport = undefined;
return [3 /*break*/, 10];
case 9:
this.logger.log(LogLevel.Debug, "HttpConnection.transport is undefined in HttpConnection.stop() because start() failed.");
_a.label = 10;
case 10: return [2 /*return*/];
}
});
});
};
HttpConnection.prototype.startInternal = function (transferFormat) {
return __awaiter(this, void 0, void 0, function () {
var url, negotiateResponse, redirects, _loop_1, this_1, e_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
url = this.baseUrl;
this.accessTokenFactory = this.options.accessTokenFactory;
_a.label = 1;
case 1:
_a.trys.push([1, 12, , 13]);
if (!this.options.skipNegotiation) return [3 /*break*/, 5];
if (!(this.options.transport === HttpTransportType.WebSockets)) return [3 /*break*/, 3];
// No need to add a connection ID in this case
this.transport = this.constructTransport(HttpTransportType.WebSockets);
// We should just call connect directly in this case.
// No fallback or negotiate in this case.
return [4 /*yield*/, this.startTransport(url, transferFormat)];
case 2:
// We should just call connect directly in this case.
// No fallback or negotiate in this case.
_a.sent();
return [3 /*break*/, 4];
case 3: throw new Error("Negotiation can only be skipped when using the WebSocket transport directly.");
case 4: return [3 /*break*/, 11];
case 5:
negotiateResponse = null;
redirects = 0;
_loop_1 = function () {
var accessToken_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0: return [4 /*yield*/, this_1.getNegotiationResponse(url)];
case 1:
negotiateResponse = _a.sent();
// the user tries to stop the connection when it is being started
if (this_1.connectionState === "Disconnecting" /* Disconnecting */ || this_1.connectionState === "Disconnected" /* Disconnected */) {
throw new Error("The connection was stopped during negotiation.");
}
if (negotiateResponse.error) {
throw new Error(negotiateResponse.error);
}
if (negotiateResponse.ProtocolVersion) {
throw new Error("Detected a connection attempt to an ASP.NET SignalR Server. This client only supports connecting to an ASP.NET Core SignalR Server. See https://aka.ms/signalr-core-differences for details.");
}
if (negotiateResponse.url) {
url = negotiateResponse.url;
}
if (negotiateResponse.accessToken) {
accessToken_1 = negotiateResponse.accessToken;
this_1.accessTokenFactory = function () { return accessToken_1; };
}
redirects++;
return [2 /*return*/];
}
});
};
this_1 = this;
_a.label = 6;
case 6: return [5 /*yield**/, _loop_1()];
case 7:
_a.sent();
_a.label = 8;
case 8:
if (negotiateResponse.url && redirects < MAX_REDIRECTS) return [3 /*break*/, 6];
_a.label = 9;
case 9:
if (redirects === MAX_REDIRECTS && negotiateResponse.url) {
throw new Error("Negotiate redirection limit exceeded.");
}
return [4 /*yield*/, this.createTransport(url, this.options.transport, negotiateResponse, transferFormat)];
case 10:
_a.sent();
_a.label = 11;
case 11:
if (this.transport instanceof LongPollingTransport) {
this.features.inherentKeepAlive = true;
}
if (this.connectionState === "Connecting" /* Connecting */) {
// Ensure the connection transitions to the connected state prior to completing this.startInternalPromise.
// start() will handle the case when stop was called and startInternal exits still in the disconnecting state.
this.logger.log(LogLevel.Debug, "The HttpConnection connected successfully.");
this.connectionState = "Connected" /* Connected */;
}
return [3 /*break*/, 13];
case 12:
e_3 = _a.sent();
this.logger.log(LogLevel.Error, "Failed to start the connection: " + e_3);
this.connectionState = "Disconnected" /* Disconnected */;
this.transport = undefined;
// if start fails, any active calls to stop assume that start will complete the stop promise
this.stopPromiseResolver();
return [2 /*return*/, Promise.reject(e_3)];
case 13: return [2 /*return*/];
}
});
});
};
HttpConnection.prototype.getNegotiationResponse = function (url) {
return __awaiter(this, void 0, void 0, function () {
var headers, token, _a, name, value, negotiateUrl, response, negotiateResponse, e_4;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
headers = {};
if (!this.accessTokenFactory) return [3 /*break*/, 2];
return [4 /*yield*/, this.accessTokenFactory()];
case 1:
token = _b.sent();
if (token) {
headers["Authorization"] = "Bearer " + token;
}
_b.label = 2;
case 2:
_a = getUserAgentHeader(), name = _a[0], value = _a[1];
headers[name] = value;
negotiateUrl = this.resolveNegotiateUrl(url);
this.logger.log(LogLevel.Debug, "Sending negotiation request: " + negotiateUrl + ".");
_b.label = 3;
case 3:
_b.trys.push([3, 5, , 6]);
return [4 /*yield*/, this.httpClient.post(negotiateUrl, {
content: "",
headers: __assign({}, headers, this.options.headers),
withCredentials: this.options.withCredentials,
})];
case 4:
response = _b.sent();
if (response.statusCode !== 200) {
return [2 /*return*/, Promise.reject(new Error("Unexpected status code returned from negotiate '" + response.statusCode + "'"))];
}
negotiateResponse = JSON.parse(response.content);
if (!negotiateResponse.negotiateVersion || negotiateResponse.negotiateVersion < 1) {
// Negotiate version 0 doesn't use connectionToken
// So we set it equal to connectionId so all our logic can use connectionToken without being aware of the negotiate version
negotiateResponse.connectionToken = negotiateResponse.connectionId;
}
return [2 /*return*/, negotiateResponse];
case 5:
e_4 = _b.sent();
this.logger.log(LogLevel.Error, "Failed to complete negotiation with the server: " + e_4);
return [2 /*return*/, Promise.reject(e_4)];
case 6: return [2 /*return*/];
}
});
});
};
HttpConnection.prototype.createConnectUrl = function (url, connectionToken) {
if (!connectionToken) {
return url;
}
return url + (url.indexOf("?") === -1 ? "?" : "&") + ("id=" + connectionToken);
};
HttpConnection.prototype.createTransport = function (url, requestedTransport, negotiateResponse, requestedTransferFormat) {
return __awaiter(this, void 0, void 0, function () {
var connectUrl, transportExceptions, transports, negotiate, _i, transports_1, endpoint, transportOrError, ex_1, ex_2, message;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
connectUrl = this.createConnectUrl(url, negotiateResponse.connectionToken);
if (!this.isITransport(requestedTransport)) return [3 /*break*/, 2];
this.logger.log(LogLevel.Debug, "Connection was provided an instance of ITransport, using that directly.");
this.transport = requestedTransport;
return [4 /*yield*/, this.startTransport(connectUrl, requestedTransferFormat)];
case 1:
_a.sent();
this.connectionId = negotiateResponse.connectionId;
return [2 /*return*/];
case 2:
transportExceptions = [];
transports = negotiateResponse.availableTransports || [];
negotiate = negotiateResponse;
_i = 0, transports_1 = transports;
_a.label = 3;
case 3:
if (!(_i < transports_1.length)) return [3 /*break*/, 13];
endpoint = transports_1[_i];
transportOrError = this.resolveTransportOrError(endpoint, requestedTransport, requestedTransferFormat);
if (!(transportOrError instanceof Error)) return [3 /*break*/, 4];
// Store the error and continue, we don't want to cause a re-negotiate in these cases
transportExceptions.push(endpoint.transport + " failed: " + transportOrError);
return [3 /*break*/, 12];
case 4:
if (!this.isITransport(transportOrError)) return [3 /*break*/, 12];
this.transport = transportOrError;
if (!!negotiate) return [3 /*break*/, 9];
_a.label = 5;
case 5:
_a.trys.push([5, 7, , 8]);
return [4 /*yield*/, this.getNegotiationResponse(url)];
case 6:
negotiate = _a.sent();
return [3 /*break*/, 8];
case 7:
ex_1 = _a.sent();
return [2 /*return*/, Promise.reject(ex_1)];
case 8:
connectUrl = this.createConnectUrl(url, negotiate.connectionToken);
_a.label = 9;
case 9:
_a.trys.push([9, 11, , 12]);
return [4 /*yield*/, this.startTransport(connectUrl, requestedTransferFormat)];
case 10:
_a.sent();
this.connectionId = negotiate.connectionId;
return [2 /*return*/];
case 11:
ex_2 = _a.sent();
this.logger.log(LogLevel.Error, "Failed to start the transport '" + endpoint.transport + "': " + ex_2);
negotiate = undefined;
transportExceptions.push(endpoint.transport + " failed: " + ex_2);
if (this.connectionState !== "Connecting" /* Connecting */) {
message = "Failed to select transport before stop() was called.";
this.logger.log(LogLevel.Debug, message);
return [2 /*return*/, Promise.reject(new Error(message))];
}
return [3 /*break*/, 12];
case 12:
_i++;
return [3 /*break*/, 3];
case 13:
if (transportExceptions.length > 0) {
return [2 /*return*/, Promise.reject(new Error("Unable to connect to the server with any of the available transports. " + transportExceptions.join(" ")))];
}
return [2 /*return*/, Promise.reject(new Error("None of the transports supported by the client are supported by the server."))];
}
});
});
};
HttpConnection.prototype.constructTransport = function (transport) {
switch (transport) {
case HttpTransportType.WebSockets:
if (!this.options.WebSocket) {
throw new Error("'WebSocket' is not supported in your environment.");
}
return new WebSocketTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.WebSocket, this.options.headers || {});
case HttpTransportType.ServerSentEvents:
if (!this.options.EventSource) {
throw new Error("'EventSource' is not supported in your environment.");
}
return new ServerSentEventsTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.EventSource, this.options.withCredentials, this.options.headers || {});
case HttpTransportType.LongPolling:
return new LongPollingTransport(this.httpClient, this.accessTokenFactory, this.logger, this.options.logMessageContent || false, this.options.withCredentials, this.options.headers || {});
default:
throw new Error("Unknown transport: " + transport + ".");
}
};
HttpConnection.prototype.startTransport = function (url, transferFormat) {
var _this = this;
this.transport.onreceive = this.onreceive;
this.transport.onclose = function (e) { return _this.stopConnection(e); };
return this.transport.connect(url, transferFormat);
};
HttpConnection.prototype.resolveTransportOrError = function (endpoint, requestedTransport, requestedTransferFormat) {
var transport = HttpTransportType[endpoint.transport];
if (transport === null || transport === undefined) {
this.logger.log(LogLevel.Debug, "Skipping transport '" + endpoint.transport + "' because it is not supported by this client.");
return new Error("Skipping transport '" + endpoint.transport + "' because it is not supported by this client.");
}
else {
if (transportMatches(requestedTransport, transport)) {
var transferFormats = endpoint.transferFormats.map(function (s) { return TransferFormat[s]; });
if (transferFormats.indexOf(requestedTransferFormat) >= 0) {
if ((transport === HttpTransportType.WebSockets && !this.options.WebSocket) ||
(transport === HttpTransportType.ServerSentEvents && !this.options.EventSource)) {
this.logger.log(LogLevel.Debug, "Skipping transport '" + HttpTransportType[transport] + "' because it is not supported in your environment.'");
return new Error("'" + HttpTransportType[transport] + "' is not supported in your environment.");
}
else {
this.logger.log(LogLevel.Debug, "Selecting transport '" + HttpTransportType[transport] + "'.");
try {
return this.constructTransport(transport);
}
catch (ex) {
return ex;
}
}
}
else {
this.logger.log(LogLevel.Debug, "Skipping transport '" + HttpTransportType[transport] + "' because it does not support the requested transfer format '" + TransferFormat[requestedTransferFormat] + "'.");
return new Error("'" + HttpTransportType[transport] + "' does not support " + TransferFormat[requestedTransferFormat] + ".");
}
}
else {
this.logger.log(LogLevel.Debug, "Skipping transport '" + HttpTransportType[transport] + "' because it was disabled by the client.");
return new Error("'" + HttpTransportType[transport] + "' is disabled by the client.");
}
}
};
HttpConnection.prototype.isITransport = function (transport) {
return transport && typeof (transport) === "object" && "connect" in transport;
};
HttpConnection.prototype.stopConnection = function (error) {
var _this = this;
this.logger.log(LogLevel.Debug, "HttpConnection.stopConnection(" + error + ") called while in state " + this.connectionState + ".");
this.transport = undefined;
// If we have a stopError, it takes precedence over the error from the transport
error = this.stopError || error;
this.stopError = undefined;
if (this.connectionState === "Disconnected" /* Disconnected */) {
this.logger.log(LogLevel.Debug, "Call to HttpConnection.stopConnection(" + error + ") was ignored because the connection is already in the disconnected state.");
return;
}
if (this.connectionState === "Connecting" /* Connecting */) {
this.logger.log(LogLevel.Warning, "Call to HttpConnection.stopConnection(" + error + ") was ignored because the connection is still in the connecting state.");
throw new Error("HttpConnection.stopConnection(" + error + ") was called while the connection is still in the connecting state.");
}
if (this.connectionState === "Disconnecting" /* Disconnecting */) {
// A call to stop() induced this call to stopConnection and needs to be completed.
// Any stop() awaiters will be scheduled to continue after the onclose callback fires.
this.stopPromiseResolver();
}
if (error) {
this.logger.log(LogLevel.Error, "Connection disconnected with error '" + error + "'.");
}
else {
this.logger.log(LogLevel.Information, "Connection disconnected.");
}
if (this.sendQueue) {
this.sendQueue.stop().catch(function (e) {
_this.logger.log(LogLevel.Error, "TransportSendQueue.stop() threw error '" + e + "'.");
});
this.sendQueue = undefined;
}
this.connectionId = undefined;
this.connectionState = "Disconnected" /* Disconnected */;
if (this.connectionStarted) {
this.connectionStarted = false;
try {
if (this.onclose) {
this.onclose(error);
}
}
catch (e) {
this.logger.log(LogLevel.Error, "HttpConnection.onclose(" + error + ") threw error '" + e + "'.");
}
}
};
HttpConnection.prototype.resolveUrl = function (url) {
// startsWith is not supported in IE
if (url.lastIndexOf("https://", 0) === 0 || url.lastIndexOf("http://", 0) === 0) {
return url;
}
if (!Platform.isBrowser || !window.document) {
throw new Error("Cannot resolve '" + url + "'.");
}
// Setting the url to the href propery of an anchor tag handles normalization
// for us. There are 3 main cases.
// 1. Relative path normalization e.g "b" -> "http://localhost:5000/a/b"
// 2. Absolute path normalization e.g "/a/b" -> "http://localhost:5000/a/b"
// 3. Networkpath reference normalization e.g "//localhost:5000/a/b" -> "http://localhost:5000/a/b"
var aTag = window.document.createElement("a");
aTag.href = url;
this.logger.log(LogLevel.Information, "Normalizing '" + url + "' to '" + aTag.href + "'.");
return aTag.href;
};
HttpConnection.prototype.resolveNegotiateUrl = function (url) {
var index = url.indexOf("?");
var negotiateUrl = url.substring(0, index === -1 ? url.length : index);
if (negotiateUrl[negotiateUrl.length - 1] !== "/") {
negotiateUrl += "/";
}
negotiateUrl += "negotiate";
negotiateUrl += index === -1 ? "" : url.substring(index);
if (negotiateUrl.indexOf("negotiateVersion") === -1) {
negotiateUrl += index === -1 ? "?" : "&";
negotiateUrl += "negotiateVersion=" + this.negotiateVersion;
}
return negotiateUrl;
};
return HttpConnection;
}());
export { HttpConnection };
function transportMatches(requestedTransport, actualTransport) {
return !requestedTransport || ((actualTransport & requestedTransport) !== 0);
}
/** @private */
var TransportSendQueue = /** @class */ (function () {
function TransportSendQueue(transport) {
this.transport = transport;
this.buffer = [];
this.executing = true;
this.sendBufferedData = new PromiseSource();
this.transportResult = new PromiseSource();
this.sendLoopPromise = this.sendLoop();
}
TransportSendQueue.prototype.send = function (data) {
this.bufferData(data);
if (!this.transportResult) {
this.transportResult = new PromiseSource();
}
return this.transportResult.promise;
};
TransportSendQueue.prototype.stop = function () {
this.executing = false;
this.sendBufferedData.resolve();
return this.sendLoopPromise;
};
TransportSendQueue.prototype.bufferData = function (data) {
if (this.buffer.length && typeof (this.buffer[0]) !== typeof (data)) {
throw new Error("Expected data to be of type " + typeof (this.buffer) + " but was of type " + typeof (data));
}
this.buffer.push(data);
this.sendBufferedData.resolve();
};
TransportSendQueue.prototype.sendLoop = function () {
return __awaiter(this, void 0, void 0, function () {
var transportResult, data, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (!true) return [3 /*break*/, 6];
return [4 /*yield*/, this.sendBufferedData.promise];
case 1:
_a.sent();
if (!this.executing) {
if (this.transportResult) {
this.transportResult.reject("Connection stopped.");
}
return [3 /*break*/, 6];
}
this.sendBufferedData = new PromiseSource();
transportResult = this.transportResult;
this.transportResult = undefined;
data = typeof (this.buffer[0]) === "string" ?
this.buffer.join("") :
TransportSendQueue.concatBuffers(this.buffer);
this.buffer.length = 0;
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
return [4 /*yield*/, this.transport.send(data)];
case 3:
_a.sent();
transportResult.resolve();
return [3 /*break*/, 5];
case 4:
error_1 = _a.sent();
transportResult.reject(error_1);
return [3 /*break*/, 5];
case 5: return [3 /*break*/, 0];
case 6: return [2 /*return*/];
}
});
});
};
TransportSendQueue.concatBuffers = function (arrayBuffers) {
var totalLength = arrayBuffers.map(function (b) { return b.byteLength; }).reduce(function (a, b) { return a + b; });
var result = new Uint8Array(totalLength);
var offset = 0;
for (var _i = 0, arrayBuffers_1 = arrayBuffers; _i < arrayBuffers_1.length; _i++) {
var item = arrayBuffers_1[_i];
result.set(new Uint8Array(item), offset);
offset += item.byteLength;
}
return result.buffer;
};
return TransportSendQueue;
}());
export { TransportSendQueue };
var PromiseSource = /** @class */ (function () {
function PromiseSource() {
var _this = this;
this.promise = new Promise(function (resolve, reject) {
var _a;
return _a = [resolve, reject], _this.resolver = _a[0], _this.rejecter = _a[1], _a;
});
}
PromiseSource.prototype.resolve = function () {
this.resolver();
};
PromiseSource.prototype.reject = function (reason) {
this.rejecter(reason);
};
return PromiseSource;
}());
//# sourceMappingURL=HttpConnection.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,174 @@
import { IStreamResult } from "./Stream";
/** Describes the current state of the {@link HubConnection} to the server. */
export declare enum HubConnectionState {
/** The hub connection is disconnected. */
Disconnected = "Disconnected",
/** The hub connection is connecting. */
Connecting = "Connecting",
/** The hub connection is connected. */
Connected = "Connected",
/** The hub connection is disconnecting. */
Disconnecting = "Disconnecting",
/** The hub connection is reconnecting. */
Reconnecting = "Reconnecting"
}
/** Represents a connection to a SignalR Hub. */
export declare class HubConnection {
private readonly cachedPingMessage;
private readonly connection;
private readonly logger;
private readonly reconnectPolicy?;
private protocol;
private handshakeProtocol;
private callbacks;
private methods;
private invocationId;
private closedCallbacks;
private reconnectingCallbacks;
private reconnectedCallbacks;
private receivedHandshakeResponse;
private handshakeResolver;
private handshakeRejecter;
private stopDuringStartError?;
private connectionState;
private connectionStarted;
private startPromise?;
private stopPromise?;
private nextKeepAlive;
private reconnectDelayHandle?;
private timeoutHandle?;
private pingServerHandle?;
/** The server timeout in milliseconds.
*
* If this timeout elapses without receiving any messages from the server, the connection will be terminated with an error.
* The default timeout value is 30,000 milliseconds (30 seconds).
*/
serverTimeoutInMilliseconds: number;
/** Default interval at which to ping the server.
*
* The default value is 15,000 milliseconds (15 seconds).
* Allows the server to detect hard disconnects (like when a client unplugs their computer).
* The ping will happen at most as often as the server pings.
* If the server pings every 5 seconds, a value lower than 5 will ping every 5 seconds.
*/
keepAliveIntervalInMilliseconds: number;
private constructor();
/** Indicates the state of the {@link HubConnection} to the server. */
readonly state: HubConnectionState;
/** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either
* in the disconnected state or if the negotiation step was skipped.
*/
readonly connectionId: string | null;
/** Indicates the url of the {@link HubConnection} to the server. */
/**
* Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or
* Reconnecting states.
* @param {string} url The url to connect to.
*/
baseUrl: string;
/** Starts the connection.
*
* @returns {Promise<void>} A Promise that resolves when the connection has been successfully established, or rejects with an error.
*/
start(): Promise<void>;
private startWithStateTransitions;
private startInternal;
/** Stops the connection.
*
* @returns {Promise<void>} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.
*/
stop(): Promise<void>;
private stopInternal;
/** Invokes a streaming hub method on the server using the specified name and arguments.
*
* @typeparam T The type of the items returned by the server.
* @param {string} methodName The name of the server method to invoke.
* @param {any[]} args The arguments used to invoke the server method.
* @returns {IStreamResult<T>} An object that yields results from the server as they are received.
*/
stream<T = any>(methodName: string, ...args: any[]): IStreamResult<T>;
private sendMessage;
/**
* Sends a js object to the server.
* @param message The js object to serialize and send.
*/
private sendWithProtocol;
/** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.
*
* The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still
* be processing the invocation.
*
* @param {string} methodName The name of the server method to invoke.
* @param {any[]} args The arguments used to invoke the server method.
* @returns {Promise<void>} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.
*/
send(methodName: string, ...args: any[]): Promise<void>;
/** Invokes a hub method on the server using the specified name and arguments.
*
* The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise
* resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of
* resolving the Promise.
*
* @typeparam T The expected return type.
* @param {string} methodName The name of the server method to invoke.
* @param {any[]} args The arguments used to invoke the server method.
* @returns {Promise<T>} A Promise that resolves with the result of the server method (if any), or rejects with an error.
*/
invoke<T = any>(methodName: string, ...args: any[]): Promise<T>;
/** Registers a handler that will be invoked when the hub method with the specified method name is invoked.
*
* @param {string} methodName The name of the hub method to define.
* @param {Function} newMethod The handler that will be raised when the hub method is invoked.
*/
on(methodName: string, newMethod: (...args: any[]) => void): void;
/** Removes all handlers for the specified hub method.
*
* @param {string} methodName The name of the method to remove handlers for.
*/
off(methodName: string): void;
/** Removes the specified handler for the specified hub method.
*
* You must pass the exact same Function instance as was previously passed to {@link @microsoft/signalr.HubConnection.on}. Passing a different instance (even if the function
* body is the same) will not remove the handler.
*
* @param {string} methodName The name of the method to remove handlers for.
* @param {Function} method The handler to remove. This must be the same Function instance as the one passed to {@link @microsoft/signalr.HubConnection.on}.
*/
off(methodName: string, method: (...args: any[]) => void): void;
/** Registers a handler that will be invoked when the connection is closed.
*
* @param {Function} callback The handler that will be invoked when the connection is closed. Optionally receives a single argument containing the error that caused the connection to close (if any).
*/
onclose(callback: (error?: Error) => void): void;
/** Registers a handler that will be invoked when the connection starts reconnecting.
*
* @param {Function} callback The handler that will be invoked when the connection starts reconnecting. Optionally receives a single argument containing the error that caused the connection to start reconnecting (if any).
*/
onreconnecting(callback: (error?: Error) => void): void;
/** Registers a handler that will be invoked when the connection successfully reconnects.
*
* @param {Function} callback The handler that will be invoked when the connection successfully reconnects.
*/
onreconnected(callback: (connectionId?: string) => void): void;
private processIncomingData;
private processHandshakeResponse;
private resetKeepAliveInterval;
private resetTimeoutPeriod;
private serverTimeout;
private invokeClientMethod;
private connectionClosed;
private completeClose;
private reconnect;
private getNextRetryDelay;
private cancelCallbacksWithError;
private cleanupPingTimer;
private cleanupTimeout;
private createInvocation;
private launchStreams;
private replaceStreamingParams;
private isObservable;
private createStreamInvocation;
private createCancelInvocation;
private createStreamItemMessage;
private createCompletionMessage;
}

View File

@ -0,0 +1,966 @@
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (_) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { HandshakeProtocol } from "./HandshakeProtocol";
import { MessageType } from "./IHubProtocol";
import { LogLevel } from "./ILogger";
import { Subject } from "./Subject";
import { Arg } from "./Utils";
var DEFAULT_TIMEOUT_IN_MS = 30 * 1000;
var DEFAULT_PING_INTERVAL_IN_MS = 15 * 1000;
/** Describes the current state of the {@link HubConnection} to the server. */
export var HubConnectionState;
(function (HubConnectionState) {
/** The hub connection is disconnected. */
HubConnectionState["Disconnected"] = "Disconnected";
/** The hub connection is connecting. */
HubConnectionState["Connecting"] = "Connecting";
/** The hub connection is connected. */
HubConnectionState["Connected"] = "Connected";
/** The hub connection is disconnecting. */
HubConnectionState["Disconnecting"] = "Disconnecting";
/** The hub connection is reconnecting. */
HubConnectionState["Reconnecting"] = "Reconnecting";
})(HubConnectionState || (HubConnectionState = {}));
/** Represents a connection to a SignalR Hub. */
var HubConnection = /** @class */ (function () {
function HubConnection(connection, logger, protocol, reconnectPolicy) {
var _this = this;
this.nextKeepAlive = 0;
Arg.isRequired(connection, "connection");
Arg.isRequired(logger, "logger");
Arg.isRequired(protocol, "protocol");
this.serverTimeoutInMilliseconds = DEFAULT_TIMEOUT_IN_MS;
this.keepAliveIntervalInMilliseconds = DEFAULT_PING_INTERVAL_IN_MS;
this.logger = logger;
this.protocol = protocol;
this.connection = connection;
this.reconnectPolicy = reconnectPolicy;
this.handshakeProtocol = new HandshakeProtocol();
this.connection.onreceive = function (data) { return _this.processIncomingData(data); };
this.connection.onclose = function (error) { return _this.connectionClosed(error); };
this.callbacks = {};
this.methods = {};
this.closedCallbacks = [];
this.reconnectingCallbacks = [];
this.reconnectedCallbacks = [];
this.invocationId = 0;
this.receivedHandshakeResponse = false;
this.connectionState = HubConnectionState.Disconnected;
this.connectionStarted = false;
this.cachedPingMessage = this.protocol.writeMessage({ type: MessageType.Ping });
}
/** @internal */
// Using a public static factory method means we can have a private constructor and an _internal_
// create method that can be used by HubConnectionBuilder. An "internal" constructor would just
// be stripped away and the '.d.ts' file would have no constructor, which is interpreted as a
// public parameter-less constructor.
HubConnection.create = function (connection, logger, protocol, reconnectPolicy) {
return new HubConnection(connection, logger, protocol, reconnectPolicy);
};
Object.defineProperty(HubConnection.prototype, "state", {
/** Indicates the state of the {@link HubConnection} to the server. */
get: function () {
return this.connectionState;
},
enumerable: true,
configurable: true
});
Object.defineProperty(HubConnection.prototype, "connectionId", {
/** Represents the connection id of the {@link HubConnection} on the server. The connection id will be null when the connection is either
* in the disconnected state or if the negotiation step was skipped.
*/
get: function () {
return this.connection ? (this.connection.connectionId || null) : null;
},
enumerable: true,
configurable: true
});
Object.defineProperty(HubConnection.prototype, "baseUrl", {
/** Indicates the url of the {@link HubConnection} to the server. */
get: function () {
return this.connection.baseUrl || "";
},
/**
* Sets a new url for the HubConnection. Note that the url can only be changed when the connection is in either the Disconnected or
* Reconnecting states.
* @param {string} url The url to connect to.
*/
set: function (url) {
if (this.connectionState !== HubConnectionState.Disconnected && this.connectionState !== HubConnectionState.Reconnecting) {
throw new Error("The HubConnection must be in the Disconnected or Reconnecting state to change the url.");
}
if (!url) {
throw new Error("The HubConnection url must be a valid url.");
}
this.connection.baseUrl = url;
},
enumerable: true,
configurable: true
});
/** Starts the connection.
*
* @returns {Promise<void>} A Promise that resolves when the connection has been successfully established, or rejects with an error.
*/
HubConnection.prototype.start = function () {
this.startPromise = this.startWithStateTransitions();
return this.startPromise;
};
HubConnection.prototype.startWithStateTransitions = function () {
return __awaiter(this, void 0, void 0, function () {
var e_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
if (this.connectionState !== HubConnectionState.Disconnected) {
return [2 /*return*/, Promise.reject(new Error("Cannot start a HubConnection that is not in the 'Disconnected' state."))];
}
this.connectionState = HubConnectionState.Connecting;
this.logger.log(LogLevel.Debug, "Starting HubConnection.");
_a.label = 1;
case 1:
_a.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.startInternal()];
case 2:
_a.sent();
this.connectionState = HubConnectionState.Connected;
this.connectionStarted = true;
this.logger.log(LogLevel.Debug, "HubConnection connected successfully.");
return [3 /*break*/, 4];
case 3:
e_1 = _a.sent();
this.connectionState = HubConnectionState.Disconnected;
this.logger.log(LogLevel.Debug, "HubConnection failed to start successfully because of error '" + e_1 + "'.");
return [2 /*return*/, Promise.reject(e_1)];
case 4: return [2 /*return*/];
}
});
});
};
HubConnection.prototype.startInternal = function () {
return __awaiter(this, void 0, void 0, function () {
var handshakePromise, handshakeRequest, e_2;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
this.stopDuringStartError = undefined;
this.receivedHandshakeResponse = false;
handshakePromise = new Promise(function (resolve, reject) {
_this.handshakeResolver = resolve;
_this.handshakeRejecter = reject;
});
return [4 /*yield*/, this.connection.start(this.protocol.transferFormat)];
case 1:
_a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 5, , 7]);
handshakeRequest = {
protocol: this.protocol.name,
version: this.protocol.version,
};
this.logger.log(LogLevel.Debug, "Sending handshake request.");
return [4 /*yield*/, this.sendMessage(this.handshakeProtocol.writeHandshakeRequest(handshakeRequest))];
case 3:
_a.sent();
this.logger.log(LogLevel.Information, "Using HubProtocol '" + this.protocol.name + "'.");
// defensively cleanup timeout in case we receive a message from the server before we finish start
this.cleanupTimeout();
this.resetTimeoutPeriod();
this.resetKeepAliveInterval();
return [4 /*yield*/, handshakePromise];
case 4:
_a.sent();
// It's important to check the stopDuringStartError instead of just relying on the handshakePromise
// being rejected on close, because this continuation can run after both the handshake completed successfully
// and the connection was closed.
if (this.stopDuringStartError) {
// It's important to throw instead of returning a rejected promise, because we don't want to allow any state
// transitions to occur between now and the calling code observing the exceptions. Returning a rejected promise
// will cause the calling continuation to get scheduled to run later.
throw this.stopDuringStartError;
}
return [3 /*break*/, 7];
case 5:
e_2 = _a.sent();
this.logger.log(LogLevel.Debug, "Hub handshake failed with error '" + e_2 + "' during start(). Stopping HubConnection.");
this.cleanupTimeout();
this.cleanupPingTimer();
// HttpConnection.stop() should not complete until after the onclose callback is invoked.
// This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.
return [4 /*yield*/, this.connection.stop(e_2)];
case 6:
// HttpConnection.stop() should not complete until after the onclose callback is invoked.
// This will transition the HubConnection to the disconnected state before HttpConnection.stop() completes.
_a.sent();
throw e_2;
case 7: return [2 /*return*/];
}
});
});
};
/** Stops the connection.
*
* @returns {Promise<void>} A Promise that resolves when the connection has been successfully terminated, or rejects with an error.
*/
HubConnection.prototype.stop = function () {
return __awaiter(this, void 0, void 0, function () {
var startPromise, e_3;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
startPromise = this.startPromise;
this.stopPromise = this.stopInternal();
return [4 /*yield*/, this.stopPromise];
case 1:
_a.sent();
_a.label = 2;
case 2:
_a.trys.push([2, 4, , 5]);
// Awaiting undefined continues immediately
return [4 /*yield*/, startPromise];
case 3:
// Awaiting undefined continues immediately
_a.sent();
return [3 /*break*/, 5];
case 4:
e_3 = _a.sent();
return [3 /*break*/, 5];
case 5: return [2 /*return*/];
}
});
});
};
HubConnection.prototype.stopInternal = function (error) {
if (this.connectionState === HubConnectionState.Disconnected) {
this.logger.log(LogLevel.Debug, "Call to HubConnection.stop(" + error + ") ignored because it is already in the disconnected state.");
return Promise.resolve();
}
if (this.connectionState === HubConnectionState.Disconnecting) {
this.logger.log(LogLevel.Debug, "Call to HttpConnection.stop(" + error + ") ignored because the connection is already in the disconnecting state.");
return this.stopPromise;
}
this.connectionState = HubConnectionState.Disconnecting;
this.logger.log(LogLevel.Debug, "Stopping HubConnection.");
if (this.reconnectDelayHandle) {
// We're in a reconnect delay which means the underlying connection is currently already stopped.
// Just clear the handle to stop the reconnect loop (which no one is waiting on thankfully) and
// fire the onclose callbacks.
this.logger.log(LogLevel.Debug, "Connection stopped during reconnect delay. Done reconnecting.");
clearTimeout(this.reconnectDelayHandle);
this.reconnectDelayHandle = undefined;
this.completeClose();
return Promise.resolve();
}
this.cleanupTimeout();
this.cleanupPingTimer();
this.stopDuringStartError = error || new Error("The connection was stopped before the hub handshake could complete.");
// HttpConnection.stop() should not complete until after either HttpConnection.start() fails
// or the onclose callback is invoked. The onclose callback will transition the HubConnection
// to the disconnected state if need be before HttpConnection.stop() completes.
return this.connection.stop(error);
};
/** Invokes a streaming hub method on the server using the specified name and arguments.
*
* @typeparam T The type of the items returned by the server.
* @param {string} methodName The name of the server method to invoke.
* @param {any[]} args The arguments used to invoke the server method.
* @returns {IStreamResult<T>} An object that yields results from the server as they are received.
*/
HubConnection.prototype.stream = function (methodName) {
var _this = this;
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var _a = this.replaceStreamingParams(args), streams = _a[0], streamIds = _a[1];
var invocationDescriptor = this.createStreamInvocation(methodName, args, streamIds);
var promiseQueue;
var subject = new Subject();
subject.cancelCallback = function () {
var cancelInvocation = _this.createCancelInvocation(invocationDescriptor.invocationId);
delete _this.callbacks[invocationDescriptor.invocationId];
return promiseQueue.then(function () {
return _this.sendWithProtocol(cancelInvocation);
});
};
this.callbacks[invocationDescriptor.invocationId] = function (invocationEvent, error) {
if (error) {
subject.error(error);
return;
}
else if (invocationEvent) {
// invocationEvent will not be null when an error is not passed to the callback
if (invocationEvent.type === MessageType.Completion) {
if (invocationEvent.error) {
subject.error(new Error(invocationEvent.error));
}
else {
subject.complete();
}
}
else {
subject.next((invocationEvent.item));
}
}
};
promiseQueue = this.sendWithProtocol(invocationDescriptor)
.catch(function (e) {
subject.error(e);
delete _this.callbacks[invocationDescriptor.invocationId];
});
this.launchStreams(streams, promiseQueue);
return subject;
};
HubConnection.prototype.sendMessage = function (message) {
this.resetKeepAliveInterval();
return this.connection.send(message);
};
/**
* Sends a js object to the server.
* @param message The js object to serialize and send.
*/
HubConnection.prototype.sendWithProtocol = function (message) {
return this.sendMessage(this.protocol.writeMessage(message));
};
/** Invokes a hub method on the server using the specified name and arguments. Does not wait for a response from the receiver.
*
* The Promise returned by this method resolves when the client has sent the invocation to the server. The server may still
* be processing the invocation.
*
* @param {string} methodName The name of the server method to invoke.
* @param {any[]} args The arguments used to invoke the server method.
* @returns {Promise<void>} A Promise that resolves when the invocation has been successfully sent, or rejects with an error.
*/
HubConnection.prototype.send = function (methodName) {
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var _a = this.replaceStreamingParams(args), streams = _a[0], streamIds = _a[1];
var sendPromise = this.sendWithProtocol(this.createInvocation(methodName, args, true, streamIds));
this.launchStreams(streams, sendPromise);
return sendPromise;
};
/** Invokes a hub method on the server using the specified name and arguments.
*
* The Promise returned by this method resolves when the server indicates it has finished invoking the method. When the promise
* resolves, the server has finished invoking the method. If the server method returns a result, it is produced as the result of
* resolving the Promise.
*
* @typeparam T The expected return type.
* @param {string} methodName The name of the server method to invoke.
* @param {any[]} args The arguments used to invoke the server method.
* @returns {Promise<T>} A Promise that resolves with the result of the server method (if any), or rejects with an error.
*/
HubConnection.prototype.invoke = function (methodName) {
var _this = this;
var args = [];
for (var _i = 1; _i < arguments.length; _i++) {
args[_i - 1] = arguments[_i];
}
var _a = this.replaceStreamingParams(args), streams = _a[0], streamIds = _a[1];
var invocationDescriptor = this.createInvocation(methodName, args, false, streamIds);
var p = new Promise(function (resolve, reject) {
// invocationId will always have a value for a non-blocking invocation
_this.callbacks[invocationDescriptor.invocationId] = function (invocationEvent, error) {
if (error) {
reject(error);
return;
}
else if (invocationEvent) {
// invocationEvent will not be null when an error is not passed to the callback
if (invocationEvent.type === MessageType.Completion) {
if (invocationEvent.error) {
reject(new Error(invocationEvent.error));
}
else {
resolve(invocationEvent.result);
}
}
else {
reject(new Error("Unexpected message type: " + invocationEvent.type));
}
}
};
var promiseQueue = _this.sendWithProtocol(invocationDescriptor)
.catch(function (e) {
reject(e);
// invocationId will always have a value for a non-blocking invocation
delete _this.callbacks[invocationDescriptor.invocationId];
});
_this.launchStreams(streams, promiseQueue);
});
return p;
};
/** Registers a handler that will be invoked when the hub method with the specified method name is invoked.
*
* @param {string} methodName The name of the hub method to define.
* @param {Function} newMethod The handler that will be raised when the hub method is invoked.
*/
HubConnection.prototype.on = function (methodName, newMethod) {
if (!methodName || !newMethod) {
return;
}
methodName = methodName.toLowerCase();
if (!this.methods[methodName]) {
this.methods[methodName] = [];
}
// Preventing adding the same handler multiple times.
if (this.methods[methodName].indexOf(newMethod) !== -1) {
return;
}
this.methods[methodName].push(newMethod);
};
HubConnection.prototype.off = function (methodName, method) {
if (!methodName) {
return;
}
methodName = methodName.toLowerCase();
var handlers = this.methods[methodName];
if (!handlers) {
return;
}
if (method) {
var removeIdx = handlers.indexOf(method);
if (removeIdx !== -1) {
handlers.splice(removeIdx, 1);
if (handlers.length === 0) {
delete this.methods[methodName];
}
}
}
else {
delete this.methods[methodName];
}
};
/** Registers a handler that will be invoked when the connection is closed.
*
* @param {Function} callback The handler that will be invoked when the connection is closed. Optionally receives a single argument containing the error that caused the connection to close (if any).
*/
HubConnection.prototype.onclose = function (callback) {
if (callback) {
this.closedCallbacks.push(callback);
}
};
/** Registers a handler that will be invoked when the connection starts reconnecting.
*
* @param {Function} callback The handler that will be invoked when the connection starts reconnecting. Optionally receives a single argument containing the error that caused the connection to start reconnecting (if any).
*/
HubConnection.prototype.onreconnecting = function (callback) {
if (callback) {
this.reconnectingCallbacks.push(callback);
}
};
/** Registers a handler that will be invoked when the connection successfully reconnects.
*
* @param {Function} callback The handler that will be invoked when the connection successfully reconnects.
*/
HubConnection.prototype.onreconnected = function (callback) {
if (callback) {
this.reconnectedCallbacks.push(callback);
}
};
HubConnection.prototype.processIncomingData = function (data) {
this.cleanupTimeout();
if (!this.receivedHandshakeResponse) {
data = this.processHandshakeResponse(data);
this.receivedHandshakeResponse = true;
}
// Data may have all been read when processing handshake response
if (data) {
// Parse the messages
var messages = this.protocol.parseMessages(data, this.logger);
for (var _i = 0, messages_1 = messages; _i < messages_1.length; _i++) {
var message = messages_1[_i];
switch (message.type) {
case MessageType.Invocation:
this.invokeClientMethod(message);
break;
case MessageType.StreamItem:
case MessageType.Completion:
var callback = this.callbacks[message.invocationId];
if (callback) {
if (message.type === MessageType.Completion) {
delete this.callbacks[message.invocationId];
}
callback(message);
}
break;
case MessageType.Ping:
// Don't care about pings
break;
case MessageType.Close:
this.logger.log(LogLevel.Information, "Close message received from server.");
var error = message.error ? new Error("Server returned an error on close: " + message.error) : undefined;
if (message.allowReconnect === true) {
// It feels wrong not to await connection.stop() here, but processIncomingData is called as part of an onreceive callback which is not async,
// this is already the behavior for serverTimeout(), and HttpConnection.Stop() should catch and log all possible exceptions.
// tslint:disable-next-line:no-floating-promises
this.connection.stop(error);
}
else {
// We cannot await stopInternal() here, but subsequent calls to stop() will await this if stopInternal() is still ongoing.
this.stopPromise = this.stopInternal(error);
}
break;
default:
this.logger.log(LogLevel.Warning, "Invalid message type: " + message.type + ".");
break;
}
}
}
this.resetTimeoutPeriod();
};
HubConnection.prototype.processHandshakeResponse = function (data) {
var _a;
var responseMessage;
var remainingData;
try {
_a = this.handshakeProtocol.parseHandshakeResponse(data), remainingData = _a[0], responseMessage = _a[1];
}
catch (e) {
var message = "Error parsing handshake response: " + e;
this.logger.log(LogLevel.Error, message);
var error = new Error(message);
this.handshakeRejecter(error);
throw error;
}
if (responseMessage.error) {
var message = "Server returned handshake error: " + responseMessage.error;
this.logger.log(LogLevel.Error, message);
var error = new Error(message);
this.handshakeRejecter(error);
throw error;
}
else {
this.logger.log(LogLevel.Debug, "Server handshake complete.");
}
this.handshakeResolver();
return remainingData;
};
HubConnection.prototype.resetKeepAliveInterval = function () {
if (this.connection.features.inherentKeepAlive) {
return;
}
// Set the time we want the next keep alive to be sent
// Timer will be setup on next message receive
this.nextKeepAlive = new Date().getTime() + this.keepAliveIntervalInMilliseconds;
this.cleanupPingTimer();
};
HubConnection.prototype.resetTimeoutPeriod = function () {
var _this = this;
if (!this.connection.features || !this.connection.features.inherentKeepAlive) {
// Set the timeout timer
this.timeoutHandle = setTimeout(function () { return _this.serverTimeout(); }, this.serverTimeoutInMilliseconds);
// Set keepAlive timer if there isn't one
if (this.pingServerHandle === undefined) {
var nextPing = this.nextKeepAlive - new Date().getTime();
if (nextPing < 0) {
nextPing = 0;
}
// The timer needs to be set from a networking callback to avoid Chrome timer throttling from causing timers to run once a minute
this.pingServerHandle = setTimeout(function () { return __awaiter(_this, void 0, void 0, function () {
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
if (!(this.connectionState === HubConnectionState.Connected)) return [3 /*break*/, 4];
_b.label = 1;
case 1:
_b.trys.push([1, 3, , 4]);
return [4 /*yield*/, this.sendMessage(this.cachedPingMessage)];
case 2:
_b.sent();
return [3 /*break*/, 4];
case 3:
_a = _b.sent();
// We don't care about the error. It should be seen elsewhere in the client.
// The connection is probably in a bad or closed state now, cleanup the timer so it stops triggering
this.cleanupPingTimer();
return [3 /*break*/, 4];
case 4: return [2 /*return*/];
}
});
}); }, nextPing);
}
}
};
HubConnection.prototype.serverTimeout = function () {
// The server hasn't talked to us in a while. It doesn't like us anymore ... :(
// Terminate the connection, but we don't need to wait on the promise. This could trigger reconnecting.
// tslint:disable-next-line:no-floating-promises
this.connection.stop(new Error("Server timeout elapsed without receiving a message from the server."));
};
HubConnection.prototype.invokeClientMethod = function (invocationMessage) {
var _this = this;
var methods = this.methods[invocationMessage.target.toLowerCase()];
if (methods) {
try {
methods.forEach(function (m) { return m.apply(_this, invocationMessage.arguments); });
}
catch (e) {
this.logger.log(LogLevel.Error, "A callback for the method " + invocationMessage.target.toLowerCase() + " threw error '" + e + "'.");
}
if (invocationMessage.invocationId) {
// This is not supported in v1. So we return an error to avoid blocking the server waiting for the response.
var message = "Server requested a response, which is not supported in this version of the client.";
this.logger.log(LogLevel.Error, message);
// We don't want to wait on the stop itself.
this.stopPromise = this.stopInternal(new Error(message));
}
}
else {
this.logger.log(LogLevel.Warning, "No client method with the name '" + invocationMessage.target + "' found.");
}
};
HubConnection.prototype.connectionClosed = function (error) {
this.logger.log(LogLevel.Debug, "HubConnection.connectionClosed(" + error + ") called while in state " + this.connectionState + ".");
// Triggering this.handshakeRejecter is insufficient because it could already be resolved without the continuation having run yet.
this.stopDuringStartError = this.stopDuringStartError || error || new Error("The underlying connection was closed before the hub handshake could complete.");
// If the handshake is in progress, start will be waiting for the handshake promise, so we complete it.
// If it has already completed, this should just noop.
if (this.handshakeResolver) {
this.handshakeResolver();
}
this.cancelCallbacksWithError(error || new Error("Invocation canceled due to the underlying connection being closed."));
this.cleanupTimeout();
this.cleanupPingTimer();
if (this.connectionState === HubConnectionState.Disconnecting) {
this.completeClose(error);
}
else if (this.connectionState === HubConnectionState.Connected && this.reconnectPolicy) {
// tslint:disable-next-line:no-floating-promises
this.reconnect(error);
}
else if (this.connectionState === HubConnectionState.Connected) {
this.completeClose(error);
}
// If none of the above if conditions were true were called the HubConnection must be in either:
// 1. The Connecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail it.
// 2. The Reconnecting state in which case the handshakeResolver will complete it and stopDuringStartError will fail the current reconnect attempt
// and potentially continue the reconnect() loop.
// 3. The Disconnected state in which case we're already done.
};
HubConnection.prototype.completeClose = function (error) {
var _this = this;
if (this.connectionStarted) {
this.connectionState = HubConnectionState.Disconnected;
this.connectionStarted = false;
try {
this.closedCallbacks.forEach(function (c) { return c.apply(_this, [error]); });
}
catch (e) {
this.logger.log(LogLevel.Error, "An onclose callback called with error '" + error + "' threw error '" + e + "'.");
}
}
};
HubConnection.prototype.reconnect = function (error) {
return __awaiter(this, void 0, void 0, function () {
var reconnectStartTime, previousReconnectAttempts, retryError, nextRetryDelay, e_4;
var _this = this;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
reconnectStartTime = Date.now();
previousReconnectAttempts = 0;
retryError = error !== undefined ? error : new Error("Attempting to reconnect due to a unknown error.");
nextRetryDelay = this.getNextRetryDelay(previousReconnectAttempts++, 0, retryError);
if (nextRetryDelay === null) {
this.logger.log(LogLevel.Debug, "Connection not reconnecting because the IRetryPolicy returned null on the first reconnect attempt.");
this.completeClose(error);
return [2 /*return*/];
}
this.connectionState = HubConnectionState.Reconnecting;
if (error) {
this.logger.log(LogLevel.Information, "Connection reconnecting because of error '" + error + "'.");
}
else {
this.logger.log(LogLevel.Information, "Connection reconnecting.");
}
if (this.onreconnecting) {
try {
this.reconnectingCallbacks.forEach(function (c) { return c.apply(_this, [error]); });
}
catch (e) {
this.logger.log(LogLevel.Error, "An onreconnecting callback called with error '" + error + "' threw error '" + e + "'.");
}
// Exit early if an onreconnecting callback called connection.stop().
if (this.connectionState !== HubConnectionState.Reconnecting) {
this.logger.log(LogLevel.Debug, "Connection left the reconnecting state in onreconnecting callback. Done reconnecting.");
return [2 /*return*/];
}
}
_a.label = 1;
case 1:
if (!(nextRetryDelay !== null)) return [3 /*break*/, 7];
this.logger.log(LogLevel.Information, "Reconnect attempt number " + previousReconnectAttempts + " will start in " + nextRetryDelay + " ms.");
return [4 /*yield*/, new Promise(function (resolve) {
_this.reconnectDelayHandle = setTimeout(resolve, nextRetryDelay);
})];
case 2:
_a.sent();
this.reconnectDelayHandle = undefined;
if (this.connectionState !== HubConnectionState.Reconnecting) {
this.logger.log(LogLevel.Debug, "Connection left the reconnecting state during reconnect delay. Done reconnecting.");
return [2 /*return*/];
}
_a.label = 3;
case 3:
_a.trys.push([3, 5, , 6]);
return [4 /*yield*/, this.startInternal()];
case 4:
_a.sent();
this.connectionState = HubConnectionState.Connected;
this.logger.log(LogLevel.Information, "HubConnection reconnected successfully.");
if (this.onreconnected) {
try {
this.reconnectedCallbacks.forEach(function (c) { return c.apply(_this, [_this.connection.connectionId]); });
}
catch (e) {
this.logger.log(LogLevel.Error, "An onreconnected callback called with connectionId '" + this.connection.connectionId + "; threw error '" + e + "'.");
}
}
return [2 /*return*/];
case 5:
e_4 = _a.sent();
this.logger.log(LogLevel.Information, "Reconnect attempt failed because of error '" + e_4 + "'.");
if (this.connectionState !== HubConnectionState.Reconnecting) {
this.logger.log(LogLevel.Debug, "Connection moved to the '" + this.connectionState + "' from the reconnecting state during reconnect attempt. Done reconnecting.");
// The TypeScript compiler thinks that connectionState must be Connected here. The TypeScript compiler is wrong.
if (this.connectionState === HubConnectionState.Disconnecting) {
this.completeClose();
}
return [2 /*return*/];
}
retryError = e_4 instanceof Error ? e_4 : new Error(e_4.toString());
nextRetryDelay = this.getNextRetryDelay(previousReconnectAttempts++, Date.now() - reconnectStartTime, retryError);
return [3 /*break*/, 6];
case 6: return [3 /*break*/, 1];
case 7:
this.logger.log(LogLevel.Information, "Reconnect retries have been exhausted after " + (Date.now() - reconnectStartTime) + " ms and " + previousReconnectAttempts + " failed attempts. Connection disconnecting.");
this.completeClose();
return [2 /*return*/];
}
});
});
};
HubConnection.prototype.getNextRetryDelay = function (previousRetryCount, elapsedMilliseconds, retryReason) {
try {
return this.reconnectPolicy.nextRetryDelayInMilliseconds({
elapsedMilliseconds: elapsedMilliseconds,
previousRetryCount: previousRetryCount,
retryReason: retryReason,
});
}
catch (e) {
this.logger.log(LogLevel.Error, "IRetryPolicy.nextRetryDelayInMilliseconds(" + previousRetryCount + ", " + elapsedMilliseconds + ") threw error '" + e + "'.");
return null;
}
};
HubConnection.prototype.cancelCallbacksWithError = function (error) {
var callbacks = this.callbacks;
this.callbacks = {};
Object.keys(callbacks)
.forEach(function (key) {
var callback = callbacks[key];
callback(null, error);
});
};
HubConnection.prototype.cleanupPingTimer = function () {
if (this.pingServerHandle) {
clearTimeout(this.pingServerHandle);
this.pingServerHandle = undefined;
}
};
HubConnection.prototype.cleanupTimeout = function () {
if (this.timeoutHandle) {
clearTimeout(this.timeoutHandle);
}
};
HubConnection.prototype.createInvocation = function (methodName, args, nonblocking, streamIds) {
if (nonblocking) {
if (streamIds.length !== 0) {
return {
arguments: args,
streamIds: streamIds,
target: methodName,
type: MessageType.Invocation,
};
}
else {
return {
arguments: args,
target: methodName,
type: MessageType.Invocation,
};
}
}
else {
var invocationId = this.invocationId;
this.invocationId++;
if (streamIds.length !== 0) {
return {
arguments: args,
invocationId: invocationId.toString(),
streamIds: streamIds,
target: methodName,
type: MessageType.Invocation,
};
}
else {
return {
arguments: args,
invocationId: invocationId.toString(),
target: methodName,
type: MessageType.Invocation,
};
}
}
};
HubConnection.prototype.launchStreams = function (streams, promiseQueue) {
var _this = this;
if (streams.length === 0) {
return;
}
// Synchronize stream data so they arrive in-order on the server
if (!promiseQueue) {
promiseQueue = Promise.resolve();
}
var _loop_1 = function (streamId) {
streams[streamId].subscribe({
complete: function () {
promiseQueue = promiseQueue.then(function () { return _this.sendWithProtocol(_this.createCompletionMessage(streamId)); });
},
error: function (err) {
var message;
if (err instanceof Error) {
message = err.message;
}
else if (err && err.toString) {
message = err.toString();
}
else {
message = "Unknown error";
}
promiseQueue = promiseQueue.then(function () { return _this.sendWithProtocol(_this.createCompletionMessage(streamId, message)); });
},
next: function (item) {
promiseQueue = promiseQueue.then(function () { return _this.sendWithProtocol(_this.createStreamItemMessage(streamId, item)); });
},
});
};
// We want to iterate over the keys, since the keys are the stream ids
// tslint:disable-next-line:forin
for (var streamId in streams) {
_loop_1(streamId);
}
};
HubConnection.prototype.replaceStreamingParams = function (args) {
var streams = [];
var streamIds = [];
for (var i = 0; i < args.length; i++) {
var argument = args[i];
if (this.isObservable(argument)) {
var streamId = this.invocationId;
this.invocationId++;
// Store the stream for later use
streams[streamId] = argument;
streamIds.push(streamId.toString());
// remove stream from args
args.splice(i, 1);
}
}
return [streams, streamIds];
};
HubConnection.prototype.isObservable = function (arg) {
// This allows other stream implementations to just work (like rxjs)
return arg && arg.subscribe && typeof arg.subscribe === "function";
};
HubConnection.prototype.createStreamInvocation = function (methodName, args, streamIds) {
var invocationId = this.invocationId;
this.invocationId++;
if (streamIds.length !== 0) {
return {
arguments: args,
invocationId: invocationId.toString(),
streamIds: streamIds,
target: methodName,
type: MessageType.StreamInvocation,
};
}
else {
return {
arguments: args,
invocationId: invocationId.toString(),
target: methodName,
type: MessageType.StreamInvocation,
};
}
};
HubConnection.prototype.createCancelInvocation = function (id) {
return {
invocationId: id,
type: MessageType.CancelInvocation,
};
};
HubConnection.prototype.createStreamItemMessage = function (id, item) {
return {
invocationId: id,
item: item,
type: MessageType.StreamItem,
};
};
HubConnection.prototype.createCompletionMessage = function (id, error, result) {
if (error) {
return {
error: error,
invocationId: id,
type: MessageType.Completion,
};
}
return {
invocationId: id,
result: result,
type: MessageType.Completion,
};
};
return HubConnection;
}());
export { HubConnection };
//# sourceMappingURL=HubConnection.js.map

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,81 @@
import { HubConnection } from "./HubConnection";
import { IHttpConnectionOptions } from "./IHttpConnectionOptions";
import { IHubProtocol } from "./IHubProtocol";
import { ILogger, LogLevel } from "./ILogger";
import { IRetryPolicy } from "./IRetryPolicy";
import { HttpTransportType } from "./ITransport";
/** A builder for configuring {@link @microsoft/signalr.HubConnection} instances. */
export declare class HubConnectionBuilder {
/** Configures console logging for the {@link @microsoft/signalr.HubConnection}.
*
* @param {LogLevel} logLevel The minimum level of messages to log. Anything at this level, or a more severe level, will be logged.
* @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.
*/
configureLogging(logLevel: LogLevel): HubConnectionBuilder;
/** Configures custom logging for the {@link @microsoft/signalr.HubConnection}.
*
* @param {ILogger} logger An object implementing the {@link @microsoft/signalr.ILogger} interface, which will be used to write all log messages.
* @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.
*/
configureLogging(logger: ILogger): HubConnectionBuilder;
/** Configures custom logging for the {@link @microsoft/signalr.HubConnection}.
*
* @param {string} logLevel A string representing a LogLevel setting a minimum level of messages to log.
* See {@link https://docs.microsoft.com/aspnet/core/signalr/configuration#configure-logging|the documentation for client logging configuration} for more details.
*/
configureLogging(logLevel: string): HubConnectionBuilder;
/** Configures custom logging for the {@link @microsoft/signalr.HubConnection}.
*
* @param {LogLevel | string | ILogger} logging A {@link @microsoft/signalr.LogLevel}, a string representing a LogLevel, or an object implementing the {@link @microsoft/signalr.ILogger} interface.
* See {@link https://docs.microsoft.com/aspnet/core/signalr/configuration#configure-logging|the documentation for client logging configuration} for more details.
* @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.
*/
configureLogging(logging: LogLevel | string | ILogger): HubConnectionBuilder;
/** Configures the {@link @microsoft/signalr.HubConnection} to use HTTP-based transports to connect to the specified URL.
*
* The transport will be selected automatically based on what the server and client support.
*
* @param {string} url The URL the connection will use.
* @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.
*/
withUrl(url: string): HubConnectionBuilder;
/** Configures the {@link @microsoft/signalr.HubConnection} to use the specified HTTP-based transport to connect to the specified URL.
*
* @param {string} url The URL the connection will use.
* @param {HttpTransportType} transportType The specific transport to use.
* @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.
*/
withUrl(url: string, transportType: HttpTransportType): HubConnectionBuilder;
/** Configures the {@link @microsoft/signalr.HubConnection} to use HTTP-based transports to connect to the specified URL.
*
* @param {string} url The URL the connection will use.
* @param {IHttpConnectionOptions} options An options object used to configure the connection.
* @returns The {@link @microsoft/signalr.HubConnectionBuilder} instance, for chaining.
*/
withUrl(url: string, options: IHttpConnectionOptions): HubConnectionBuilder;
/** Configures the {@link @microsoft/signalr.HubConnection} to use the specified Hub Protocol.
*
* @param {IHubProtocol} protocol The {@link @microsoft/signalr.IHubProtocol} implementation to use.
*/
withHubProtocol(protocol: IHubProtocol): HubConnectionBuilder;
/** Configures the {@link @microsoft/signalr.HubConnection} to automatically attempt to reconnect if the connection is lost.
* By default, the client will wait 0, 2, 10 and 30 seconds respectively before trying up to 4 reconnect attempts.
*/
withAutomaticReconnect(): HubConnectionBuilder;
/** Configures the {@link @microsoft/signalr.HubConnection} to automatically attempt to reconnect if the connection is lost.
*
* @param {number[]} retryDelays An array containing the delays in milliseconds before trying each reconnect attempt.
* The length of the array represents how many failed reconnect attempts it takes before the client will stop attempting to reconnect.
*/
withAutomaticReconnect(retryDelays: number[]): HubConnectionBuilder;
/** Configures the {@link @microsoft/signalr.HubConnection} to automatically attempt to reconnect if the connection is lost.
*
* @param {IRetryPolicy} reconnectPolicy An {@link @microsoft/signalR.IRetryPolicy} that controls the timing and number of reconnect attempts.
*/
withAutomaticReconnect(reconnectPolicy: IRetryPolicy): HubConnectionBuilder;
/** Creates a {@link @microsoft/signalr.HubConnection} from the configuration options specified in this builder.
*
* @returns {HubConnection} The configured {@link @microsoft/signalr.HubConnection}.
*/
build(): HubConnection;
}

Some files were not shown because too many files have changed in this diff Show More