binaryjs.html 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572
  1. <script>
  2. /*! binary.js build:0.2.2, development. Copyright(c) 2012 Eric Zhang <eric@ericzhang.com> MIT Licensed */
  3. (function(exports){
  4. /*! binarypack.js build:0.0.9, production. Copyright(c) 2012 Eric Zhang <eric@ericzhang.com> MIT Licensed */(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
  5. var BufferBuilder = require('./bufferbuilder').BufferBuilder;
  6. var binaryFeatures = require('./bufferbuilder').binaryFeatures;
  7. var BinaryPack = {
  8. unpack: function(data){
  9. var unpacker = new Unpacker(data);
  10. return unpacker.unpack();
  11. },
  12. pack: function(data){
  13. var packer = new Packer();
  14. packer.pack(data);
  15. var buffer = packer.getBuffer();
  16. return buffer;
  17. }
  18. };
  19. module.exports = BinaryPack;
  20. function Unpacker (data){
  21. // Data is ArrayBuffer
  22. this.index = 0;
  23. this.dataBuffer = data;
  24. this.dataView = new Uint8Array(this.dataBuffer);
  25. this.length = this.dataBuffer.byteLength;
  26. }
  27. Unpacker.prototype.unpack = function(){
  28. var type = this.unpack_uint8();
  29. if (type < 0x80){
  30. var positive_fixnum = type;
  31. return positive_fixnum;
  32. } else if ((type ^ 0xe0) < 0x20){
  33. var negative_fixnum = (type ^ 0xe0) - 0x20;
  34. return negative_fixnum;
  35. }
  36. var size;
  37. if ((size = type ^ 0xa0) <= 0x0f){
  38. return this.unpack_raw(size);
  39. } else if ((size = type ^ 0xb0) <= 0x0f){
  40. return this.unpack_string(size);
  41. } else if ((size = type ^ 0x90) <= 0x0f){
  42. return this.unpack_array(size);
  43. } else if ((size = type ^ 0x80) <= 0x0f){
  44. return this.unpack_map(size);
  45. }
  46. switch(type){
  47. case 0xc0:
  48. return null;
  49. case 0xc1:
  50. return undefined;
  51. case 0xc2:
  52. return false;
  53. case 0xc3:
  54. return true;
  55. case 0xca:
  56. return this.unpack_float();
  57. case 0xcb:
  58. return this.unpack_double();
  59. case 0xcc:
  60. return this.unpack_uint8();
  61. case 0xcd:
  62. return this.unpack_uint16();
  63. case 0xce:
  64. return this.unpack_uint32();
  65. case 0xcf:
  66. return this.unpack_uint64();
  67. case 0xd0:
  68. return this.unpack_int8();
  69. case 0xd1:
  70. return this.unpack_int16();
  71. case 0xd2:
  72. return this.unpack_int32();
  73. case 0xd3:
  74. return this.unpack_int64();
  75. case 0xd4:
  76. return undefined;
  77. case 0xd5:
  78. return undefined;
  79. case 0xd6:
  80. return undefined;
  81. case 0xd7:
  82. return undefined;
  83. case 0xd8:
  84. size = this.unpack_uint16();
  85. return this.unpack_string(size);
  86. case 0xd9:
  87. size = this.unpack_uint32();
  88. return this.unpack_string(size);
  89. case 0xda:
  90. size = this.unpack_uint16();
  91. return this.unpack_raw(size);
  92. case 0xdb:
  93. size = this.unpack_uint32();
  94. return this.unpack_raw(size);
  95. case 0xdc:
  96. size = this.unpack_uint16();
  97. return this.unpack_array(size);
  98. case 0xdd:
  99. size = this.unpack_uint32();
  100. return this.unpack_array(size);
  101. case 0xde:
  102. size = this.unpack_uint16();
  103. return this.unpack_map(size);
  104. case 0xdf:
  105. size = this.unpack_uint32();
  106. return this.unpack_map(size);
  107. }
  108. }
  109. Unpacker.prototype.unpack_uint8 = function(){
  110. var byte = this.dataView[this.index] & 0xff;
  111. this.index++;
  112. return byte;
  113. };
  114. Unpacker.prototype.unpack_uint16 = function(){
  115. var bytes = this.read(2);
  116. var uint16 =
  117. ((bytes[0] & 0xff) * 256) + (bytes[1] & 0xff);
  118. this.index += 2;
  119. return uint16;
  120. }
  121. Unpacker.prototype.unpack_uint32 = function(){
  122. var bytes = this.read(4);
  123. var uint32 =
  124. ((bytes[0] * 256 +
  125. bytes[1]) * 256 +
  126. bytes[2]) * 256 +
  127. bytes[3];
  128. this.index += 4;
  129. return uint32;
  130. }
  131. Unpacker.prototype.unpack_uint64 = function(){
  132. var bytes = this.read(8);
  133. var uint64 =
  134. ((((((bytes[0] * 256 +
  135. bytes[1]) * 256 +
  136. bytes[2]) * 256 +
  137. bytes[3]) * 256 +
  138. bytes[4]) * 256 +
  139. bytes[5]) * 256 +
  140. bytes[6]) * 256 +
  141. bytes[7];
  142. this.index += 8;
  143. return uint64;
  144. }
  145. Unpacker.prototype.unpack_int8 = function(){
  146. var uint8 = this.unpack_uint8();
  147. return (uint8 < 0x80 ) ? uint8 : uint8 - (1 << 8);
  148. };
  149. Unpacker.prototype.unpack_int16 = function(){
  150. var uint16 = this.unpack_uint16();
  151. return (uint16 < 0x8000 ) ? uint16 : uint16 - (1 << 16);
  152. }
  153. Unpacker.prototype.unpack_int32 = function(){
  154. var uint32 = this.unpack_uint32();
  155. return (uint32 < Math.pow(2, 31) ) ? uint32 :
  156. uint32 - Math.pow(2, 32);
  157. }
  158. Unpacker.prototype.unpack_int64 = function(){
  159. var uint64 = this.unpack_uint64();
  160. return (uint64 < Math.pow(2, 63) ) ? uint64 :
  161. uint64 - Math.pow(2, 64);
  162. }
  163. Unpacker.prototype.unpack_raw = function(size){
  164. if ( this.length < this.index + size){
  165. throw new Error('BinaryPackFailure: index is out of range'
  166. + ' ' + this.index + ' ' + size + ' ' + this.length);
  167. }
  168. var buf = this.dataBuffer.slice(this.index, this.index + size);
  169. this.index += size;
  170. //buf = util.bufferToString(buf);
  171. return buf;
  172. }
  173. Unpacker.prototype.unpack_string = function(size){
  174. var bytes = this.read(size);
  175. var i = 0, str = '', c, code;
  176. while(i < size){
  177. c = bytes[i];
  178. if ( c < 128){
  179. str += String.fromCharCode(c);
  180. i++;
  181. } else if ((c ^ 0xc0) < 32){
  182. code = ((c ^ 0xc0) << 6) | (bytes[i+1] & 63);
  183. str += String.fromCharCode(code);
  184. i += 2;
  185. } else {
  186. code = ((c & 15) << 12) | ((bytes[i+1] & 63) << 6) |
  187. (bytes[i+2] & 63);
  188. str += String.fromCharCode(code);
  189. i += 3;
  190. }
  191. }
  192. this.index += size;
  193. return str;
  194. }
  195. Unpacker.prototype.unpack_array = function(size){
  196. var objects = new Array(size);
  197. for(var i = 0; i < size ; i++){
  198. objects[i] = this.unpack();
  199. }
  200. return objects;
  201. }
  202. Unpacker.prototype.unpack_map = function(size){
  203. var map = {};
  204. for(var i = 0; i < size ; i++){
  205. var key = this.unpack();
  206. var value = this.unpack();
  207. map[key] = value;
  208. }
  209. return map;
  210. }
  211. Unpacker.prototype.unpack_float = function(){
  212. var uint32 = this.unpack_uint32();
  213. var sign = uint32 >> 31;
  214. var exp = ((uint32 >> 23) & 0xff) - 127;
  215. var fraction = ( uint32 & 0x7fffff ) | 0x800000;
  216. return (sign == 0 ? 1 : -1) *
  217. fraction * Math.pow(2, exp - 23);
  218. }
  219. Unpacker.prototype.unpack_double = function(){
  220. var h32 = this.unpack_uint32();
  221. var l32 = this.unpack_uint32();
  222. var sign = h32 >> 31;
  223. var exp = ((h32 >> 20) & 0x7ff) - 1023;
  224. var hfrac = ( h32 & 0xfffff ) | 0x100000;
  225. var frac = hfrac * Math.pow(2, exp - 20) +
  226. l32 * Math.pow(2, exp - 52);
  227. return (sign == 0 ? 1 : -1) * frac;
  228. }
  229. Unpacker.prototype.read = function(length){
  230. var j = this.index;
  231. if (j + length <= this.length) {
  232. return this.dataView.subarray(j, j + length);
  233. } else {
  234. throw new Error('BinaryPackFailure: read index out of range');
  235. }
  236. }
  237. function Packer(){
  238. this.bufferBuilder = new BufferBuilder();
  239. }
  240. Packer.prototype.getBuffer = function(){
  241. return this.bufferBuilder.getBuffer();
  242. }
  243. Packer.prototype.pack = function(value){
  244. var type = typeof(value);
  245. if (type == 'string'){
  246. this.pack_string(value);
  247. } else if (type == 'number'){
  248. if (Math.floor(value) === value){
  249. this.pack_integer(value);
  250. } else{
  251. this.pack_double(value);
  252. }
  253. } else if (type == 'boolean'){
  254. if (value === true){
  255. this.bufferBuilder.append(0xc3);
  256. } else if (value === false){
  257. this.bufferBuilder.append(0xc2);
  258. }
  259. } else if (type == 'undefined'){
  260. this.bufferBuilder.append(0xc0);
  261. } else if (type == 'object'){
  262. if (value === null){
  263. this.bufferBuilder.append(0xc0);
  264. } else {
  265. var constructor = value.constructor;
  266. if (constructor == Array){
  267. this.pack_array(value);
  268. } else if (constructor == Blob || constructor == File) {
  269. this.pack_bin(value);
  270. } else if (constructor == ArrayBuffer) {
  271. if(binaryFeatures.useArrayBufferView) {
  272. this.pack_bin(new Uint8Array(value));
  273. } else {
  274. this.pack_bin(value);
  275. }
  276. } else if ('BYTES_PER_ELEMENT' in value){
  277. if(binaryFeatures.useArrayBufferView) {
  278. this.pack_bin(new Uint8Array(value.buffer));
  279. } else {
  280. this.pack_bin(value.buffer);
  281. }
  282. } else if (constructor == Object){
  283. this.pack_object(value);
  284. } else if (constructor == Date){
  285. this.pack_string(value.toString());
  286. } else if (typeof value.toBinaryPack == 'function'){
  287. this.bufferBuilder.append(value.toBinaryPack());
  288. } else {
  289. throw new Error('Type "' + constructor.toString() + '" not yet supported');
  290. }
  291. }
  292. } else {
  293. throw new Error('Type "' + type + '" not yet supported');
  294. }
  295. this.bufferBuilder.flush();
  296. }
  297. Packer.prototype.pack_bin = function(blob){
  298. var length = blob.length || blob.byteLength || blob.size;
  299. if (length <= 0x0f){
  300. this.pack_uint8(0xa0 + length);
  301. } else if (length <= 0xffff){
  302. this.bufferBuilder.append(0xda) ;
  303. this.pack_uint16(length);
  304. } else if (length <= 0xffffffff){
  305. this.bufferBuilder.append(0xdb);
  306. this.pack_uint32(length);
  307. } else{
  308. throw new Error('Invalid length');
  309. }
  310. this.bufferBuilder.append(blob);
  311. }
  312. Packer.prototype.pack_string = function(str){
  313. var length = utf8Length(str);
  314. if (length <= 0x0f){
  315. this.pack_uint8(0xb0 + length);
  316. } else if (length <= 0xffff){
  317. this.bufferBuilder.append(0xd8) ;
  318. this.pack_uint16(length);
  319. } else if (length <= 0xffffffff){
  320. this.bufferBuilder.append(0xd9);
  321. this.pack_uint32(length);
  322. } else{
  323. throw new Error('Invalid length');
  324. }
  325. this.bufferBuilder.append(str);
  326. }
  327. Packer.prototype.pack_array = function(ary){
  328. var length = ary.length;
  329. if (length <= 0x0f){
  330. this.pack_uint8(0x90 + length);
  331. } else if (length <= 0xffff){
  332. this.bufferBuilder.append(0xdc)
  333. this.pack_uint16(length);
  334. } else if (length <= 0xffffffff){
  335. this.bufferBuilder.append(0xdd);
  336. this.pack_uint32(length);
  337. } else{
  338. throw new Error('Invalid length');
  339. }
  340. for(var i = 0; i < length ; i++){
  341. this.pack(ary[i]);
  342. }
  343. }
  344. Packer.prototype.pack_integer = function(num){
  345. if ( -0x20 <= num && num <= 0x7f){
  346. this.bufferBuilder.append(num & 0xff);
  347. } else if (0x00 <= num && num <= 0xff){
  348. this.bufferBuilder.append(0xcc);
  349. this.pack_uint8(num);
  350. } else if (-0x80 <= num && num <= 0x7f){
  351. this.bufferBuilder.append(0xd0);
  352. this.pack_int8(num);
  353. } else if ( 0x0000 <= num && num <= 0xffff){
  354. this.bufferBuilder.append(0xcd);
  355. this.pack_uint16(num);
  356. } else if (-0x8000 <= num && num <= 0x7fff){
  357. this.bufferBuilder.append(0xd1);
  358. this.pack_int16(num);
  359. } else if ( 0x00000000 <= num && num <= 0xffffffff){
  360. this.bufferBuilder.append(0xce);
  361. this.pack_uint32(num);
  362. } else if (-0x80000000 <= num && num <= 0x7fffffff){
  363. this.bufferBuilder.append(0xd2);
  364. this.pack_int32(num);
  365. } else if (-0x8000000000000000 <= num && num <= 0x7FFFFFFFFFFFFFFF){
  366. this.bufferBuilder.append(0xd3);
  367. this.pack_int64(num);
  368. } else if (0x0000000000000000 <= num && num <= 0xFFFFFFFFFFFFFFFF){
  369. this.bufferBuilder.append(0xcf);
  370. this.pack_uint64(num);
  371. } else{
  372. throw new Error('Invalid integer');
  373. }
  374. }
  375. Packer.prototype.pack_double = function(num){
  376. var sign = 0;
  377. if (num < 0){
  378. sign = 1;
  379. num = -num;
  380. }
  381. var exp = Math.floor(Math.log(num) / Math.LN2);
  382. var frac0 = num / Math.pow(2, exp) - 1;
  383. var frac1 = Math.floor(frac0 * Math.pow(2, 52));
  384. var b32 = Math.pow(2, 32);
  385. var h32 = (sign << 31) | ((exp+1023) << 20) |
  386. (frac1 / b32) & 0x0fffff;
  387. var l32 = frac1 % b32;
  388. this.bufferBuilder.append(0xcb);
  389. this.pack_int32(h32);
  390. this.pack_int32(l32);
  391. }
  392. Packer.prototype.pack_object = function(obj){
  393. var keys = Object.keys(obj);
  394. var length = keys.length;
  395. if (length <= 0x0f){
  396. this.pack_uint8(0x80 + length);
  397. } else if (length <= 0xffff){
  398. this.bufferBuilder.append(0xde);
  399. this.pack_uint16(length);
  400. } else if (length <= 0xffffffff){
  401. this.bufferBuilder.append(0xdf);
  402. this.pack_uint32(length);
  403. } else{
  404. throw new Error('Invalid length');
  405. }
  406. for(var prop in obj){
  407. if (obj.hasOwnProperty(prop)){
  408. this.pack(prop);
  409. this.pack(obj[prop]);
  410. }
  411. }
  412. }
  413. Packer.prototype.pack_uint8 = function(num){
  414. this.bufferBuilder.append(num);
  415. }
  416. Packer.prototype.pack_uint16 = function(num){
  417. this.bufferBuilder.append(num >> 8);
  418. this.bufferBuilder.append(num & 0xff);
  419. }
  420. Packer.prototype.pack_uint32 = function(num){
  421. var n = num & 0xffffffff;
  422. this.bufferBuilder.append((n & 0xff000000) >>> 24);
  423. this.bufferBuilder.append((n & 0x00ff0000) >>> 16);
  424. this.bufferBuilder.append((n & 0x0000ff00) >>> 8);
  425. this.bufferBuilder.append((n & 0x000000ff));
  426. }
  427. Packer.prototype.pack_uint64 = function(num){
  428. var high = num / Math.pow(2, 32);
  429. var low = num % Math.pow(2, 32);
  430. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  431. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  432. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  433. this.bufferBuilder.append((high & 0x000000ff));
  434. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  435. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  436. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  437. this.bufferBuilder.append((low & 0x000000ff));
  438. }
  439. Packer.prototype.pack_int8 = function(num){
  440. this.bufferBuilder.append(num & 0xff);
  441. }
  442. Packer.prototype.pack_int16 = function(num){
  443. this.bufferBuilder.append((num & 0xff00) >> 8);
  444. this.bufferBuilder.append(num & 0xff);
  445. }
  446. Packer.prototype.pack_int32 = function(num){
  447. this.bufferBuilder.append((num >>> 24) & 0xff);
  448. this.bufferBuilder.append((num & 0x00ff0000) >>> 16);
  449. this.bufferBuilder.append((num & 0x0000ff00) >>> 8);
  450. this.bufferBuilder.append((num & 0x000000ff));
  451. }
  452. Packer.prototype.pack_int64 = function(num){
  453. var high = Math.floor(num / Math.pow(2, 32));
  454. var low = num % Math.pow(2, 32);
  455. this.bufferBuilder.append((high & 0xff000000) >>> 24);
  456. this.bufferBuilder.append((high & 0x00ff0000) >>> 16);
  457. this.bufferBuilder.append((high & 0x0000ff00) >>> 8);
  458. this.bufferBuilder.append((high & 0x000000ff));
  459. this.bufferBuilder.append((low & 0xff000000) >>> 24);
  460. this.bufferBuilder.append((low & 0x00ff0000) >>> 16);
  461. this.bufferBuilder.append((low & 0x0000ff00) >>> 8);
  462. this.bufferBuilder.append((low & 0x000000ff));
  463. }
  464. function _utf8Replace(m){
  465. var code = m.charCodeAt(0);
  466. if(code <= 0x7ff) return '00';
  467. if(code <= 0xffff) return '000';
  468. if(code <= 0x1fffff) return '0000';
  469. if(code <= 0x3ffffff) return '00000';
  470. return '000000';
  471. }
  472. function utf8Length(str){
  473. if (str.length > 600) {
  474. // Blob method faster for large strings
  475. return (new Blob([str])).size;
  476. } else {
  477. return str.replace(/[^\u0000-\u007F]/g, _utf8Replace).length;
  478. }
  479. }
  480. },{"./bufferbuilder":2}],2:[function(require,module,exports){
  481. var binaryFeatures = {};
  482. binaryFeatures.useBlobBuilder = (function(){
  483. try {
  484. new Blob([]);
  485. return false;
  486. } catch (e) {
  487. return true;
  488. }
  489. })();
  490. binaryFeatures.useArrayBufferView = !binaryFeatures.useBlobBuilder && (function(){
  491. try {
  492. return (new Blob([new Uint8Array([])])).size === 0;
  493. } catch (e) {
  494. return true;
  495. }
  496. })();
  497. module.exports.binaryFeatures = binaryFeatures;
  498. var BlobBuilder = module.exports.BlobBuilder;
  499. if (typeof window != 'undefined') {
  500. BlobBuilder = module.exports.BlobBuilder = window.WebKitBlobBuilder ||
  501. window.MozBlobBuilder || window.MSBlobBuilder || window.BlobBuilder;
  502. }
  503. function BufferBuilder(){
  504. this._pieces = [];
  505. this._parts = [];
  506. }
  507. BufferBuilder.prototype.append = function(data) {
  508. if(typeof data === 'number') {
  509. this._pieces.push(data);
  510. } else {
  511. this.flush();
  512. this._parts.push(data);
  513. }
  514. };
  515. BufferBuilder.prototype.flush = function() {
  516. if (this._pieces.length > 0) {
  517. var buf = new Uint8Array(this._pieces);
  518. if(!binaryFeatures.useArrayBufferView) {
  519. buf = buf.buffer;
  520. }
  521. this._parts.push(buf);
  522. this._pieces = [];
  523. }
  524. };
  525. BufferBuilder.prototype.getBuffer = function() {
  526. this.flush();
  527. if(binaryFeatures.useBlobBuilder) {
  528. var builder = new BlobBuilder();
  529. for(var i = 0, ii = this._parts.length; i < ii; i++) {
  530. builder.append(this._parts[i]);
  531. }
  532. return builder.getBlob();
  533. } else {
  534. return new Blob(this._parts);
  535. }
  536. };
  537. module.exports.BufferBuilder = BufferBuilder;
  538. },{}],3:[function(require,module,exports){
  539. var BufferBuilderExports = require('./bufferbuilder');
  540. window.BufferBuilder = BufferBuilderExports.BufferBuilder;
  541. window.binaryFeatures = BufferBuilderExports.binaryFeatures;
  542. window.BlobBuilder = BufferBuilderExports.BlobBuilder;
  543. window.BinaryPack = require('./binarypack');
  544. },{"./binarypack":1,"./bufferbuilder":2}]},{},[3]);
  545. /**
  546. * Light EventEmitter. Ported from Node.js/events.js
  547. * Eric Zhang
  548. */
  549. /**
  550. * EventEmitter class
  551. * Creates an object with event registering and firing methods
  552. */
  553. function EventEmitter() {
  554. // Initialise required storage variables
  555. this._events = {};
  556. }
  557. var isArray = Array.isArray;
  558. EventEmitter.prototype.addListener = function(type, listener, scope, once) {
  559. if ('function' !== typeof listener) {
  560. throw new Error('addListener only takes instances of Function');
  561. }
  562. // To avoid recursion in the case that type == "newListeners"! Before
  563. // adding it to the listeners, first emit "newListeners".
  564. this.emit('newListener', type, typeof listener.listener === 'function' ?
  565. listener.listener : listener);
  566. if (!this._events[type]) {
  567. // Optimize the case of one listener. Don't need the extra array object.
  568. this._events[type] = listener;
  569. } else if (isArray(this._events[type])) {
  570. // If we've already got an array, just append.
  571. this._events[type].push(listener);
  572. } else {
  573. // Adding the second element, need to change to array.
  574. this._events[type] = [this._events[type], listener];
  575. }
  576. };
  577. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  578. EventEmitter.prototype.once = function(type, listener, scope) {
  579. if ('function' !== typeof listener) {
  580. throw new Error('.once only takes instances of Function');
  581. }
  582. var self = this;
  583. function g() {
  584. self.removeListener(type, g);
  585. listener.apply(this, arguments);
  586. };
  587. g.listener = listener;
  588. self.on(type, g);
  589. return this;
  590. };
  591. EventEmitter.prototype.removeListener = function(type, listener, scope) {
  592. if ('function' !== typeof listener) {
  593. throw new Error('removeListener only takes instances of Function');
  594. }
  595. // does not use listeners(), so no side effect of creating _events[type]
  596. if (!this._events[type]) return this;
  597. var list = this._events[type];
  598. if (isArray(list)) {
  599. var position = -1;
  600. for (var i = 0, length = list.length; i < length; i++) {
  601. if (list[i] === listener ||
  602. (list[i].listener && list[i].listener === listener))
  603. {
  604. position = i;
  605. break;
  606. }
  607. }
  608. if (position < 0) return this;
  609. list.splice(position, 1);
  610. if (list.length == 0)
  611. delete this._events[type];
  612. } else if (list === listener ||
  613. (list.listener && list.listener === listener))
  614. {
  615. delete this._events[type];
  616. }
  617. return this;
  618. };
  619. EventEmitter.prototype.off = EventEmitter.prototype.removeListener;
  620. EventEmitter.prototype.removeAllListeners = function(type) {
  621. if (arguments.length === 0) {
  622. this._events = {};
  623. return this;
  624. }
  625. // does not use listeners(), so no side effect of creating _events[type]
  626. if (type && this._events && this._events[type]) this._events[type] = null;
  627. return this;
  628. };
  629. EventEmitter.prototype.listeners = function(type) {
  630. if (!this._events[type]) this._events[type] = [];
  631. if (!isArray(this._events[type])) {
  632. this._events[type] = [this._events[type]];
  633. }
  634. return this._events[type];
  635. };
  636. EventEmitter.prototype.emit = function(type) {
  637. var type = arguments[0];
  638. var handler = this._events[type];
  639. if (!handler) return false;
  640. if (typeof handler == 'function') {
  641. switch (arguments.length) {
  642. // fast cases
  643. case 1:
  644. handler.call(this);
  645. break;
  646. case 2:
  647. handler.call(this, arguments[1]);
  648. break;
  649. case 3:
  650. handler.call(this, arguments[1], arguments[2]);
  651. break;
  652. // slower
  653. default:
  654. var l = arguments.length;
  655. var args = new Array(l - 1);
  656. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  657. handler.apply(this, args);
  658. }
  659. return true;
  660. } else if (isArray(handler)) {
  661. var l = arguments.length;
  662. var args = new Array(l - 1);
  663. for (var i = 1; i < l; i++) args[i - 1] = arguments[i];
  664. var listeners = handler.slice();
  665. for (var i = 0, l = listeners.length; i < l; i++) {
  666. listeners[i].apply(this, args);
  667. }
  668. return true;
  669. } else {
  670. return false;
  671. }
  672. };
  673. var util = {
  674. inherits: function(ctor, superCtor) {
  675. ctor.super_ = superCtor;
  676. ctor.prototype = Object.create(superCtor.prototype, {
  677. constructor: {
  678. value: ctor,
  679. enumerable: false,
  680. writable: true,
  681. configurable: true
  682. }
  683. });
  684. },
  685. extend: function(dest, source) {
  686. for(var key in source) {
  687. if(source.hasOwnProperty(key)) {
  688. dest[key] = source[key];
  689. }
  690. }
  691. return dest;
  692. },
  693. pack: BinaryPack.pack,
  694. unpack: BinaryPack.unpack,
  695. setZeroTimeout: (function(global) {
  696. var timeouts = [];
  697. var messageName = 'zero-timeout-message';
  698. // Like setTimeout, but only takes a function argument. There's
  699. // no time argument (always zero) and no arguments (you have to
  700. // use a closure).
  701. function setZeroTimeoutPostMessage(fn) {
  702. timeouts.push(fn);
  703. global.postMessage(messageName, '*');
  704. }
  705. function handleMessage(event) {
  706. if (event.source == global && event.data == messageName) {
  707. if (event.stopPropagation) {
  708. event.stopPropagation();
  709. }
  710. if (timeouts.length) {
  711. timeouts.shift()();
  712. }
  713. }
  714. }
  715. if (global.addEventListener) {
  716. global.addEventListener('message', handleMessage, true);
  717. } else if (global.attachEvent) {
  718. global.attachEvent('onmessage', handleMessage);
  719. }
  720. return setZeroTimeoutPostMessage;
  721. }(this))
  722. };
  723. exports.util = util;
  724. function Stream() {
  725. EventEmitter.call(this);
  726. }
  727. util.inherits(Stream, EventEmitter);
  728. Stream.prototype.pipe = function(dest, options) {
  729. var source = this;
  730. function ondata(chunk) {
  731. if (dest.writable) {
  732. if (false === dest.write(chunk) && source.pause) {
  733. source.pause();
  734. }
  735. }
  736. }
  737. source.on('data', ondata);
  738. function ondrain() {
  739. if (source.readable && source.resume) {
  740. source.resume();
  741. }
  742. }
  743. dest.on('drain', ondrain);
  744. // If the 'end' option is not supplied, dest.end() will be called when
  745. // source gets the 'end' or 'close' events. Only dest.end() once.
  746. if (!dest._isStdio && (!options || options.end !== false)) {
  747. source.on('end', onend);
  748. source.on('close', onclose);
  749. }
  750. var didOnEnd = false;
  751. function onend() {
  752. if (didOnEnd) return;
  753. didOnEnd = true;
  754. dest.end();
  755. }
  756. function onclose() {
  757. if (didOnEnd) return;
  758. didOnEnd = true;
  759. dest.destroy();
  760. }
  761. // don't leave dangling pipes when there are errors.
  762. function onerror(er) {
  763. cleanup();
  764. if (this.listeners('error').length === 0) {
  765. throw er; // Unhandled stream error in pipe.
  766. }
  767. }
  768. source.on('error', onerror);
  769. dest.on('error', onerror);
  770. // remove all the event listeners that were added.
  771. function cleanup() {
  772. source.removeListener('data', ondata);
  773. dest.removeListener('drain', ondrain);
  774. source.removeListener('end', onend);
  775. source.removeListener('close', onclose);
  776. source.removeListener('error', onerror);
  777. dest.removeListener('error', onerror);
  778. source.removeListener('end', cleanup);
  779. source.removeListener('close', cleanup);
  780. dest.removeListener('end', cleanup);
  781. dest.removeListener('close', cleanup);
  782. }
  783. source.on('end', cleanup);
  784. source.on('close', cleanup);
  785. dest.on('end', cleanup);
  786. dest.on('close', cleanup);
  787. dest.emit('pipe', source);
  788. // Allow for unix-like usage: A.pipe(B).pipe(C)
  789. return dest;
  790. };
  791. exports.Stream = Stream;
  792. function BlobReadStream(source, options){
  793. Stream.call(this);
  794. options = util.extend({
  795. readDelay: 0,
  796. paused: false
  797. }, options);
  798. this._source = source;
  799. this._start = 0;
  800. this._readChunkSize = options.chunkSize || source.size;
  801. this._readDelay = options.readDelay;
  802. this.readable = true;
  803. this.paused = options.paused;
  804. this._read();
  805. }
  806. util.inherits(BlobReadStream, Stream);
  807. BlobReadStream.prototype.pause = function(){
  808. this.paused = true;
  809. };
  810. BlobReadStream.prototype.resume = function(){
  811. this.paused = false;
  812. this._read();
  813. };
  814. BlobReadStream.prototype.destroy = function(){
  815. this.readable = false;
  816. clearTimeout(this._timeoutId);
  817. };
  818. BlobReadStream.prototype._read = function(){
  819. var self = this;
  820. function emitReadChunk(){
  821. self._emitReadChunk();
  822. }
  823. var readDelay = this._readDelay;
  824. if (readDelay !== 0){
  825. this._timeoutId = setTimeout(emitReadChunk, readDelay);
  826. } else {
  827. util.setZeroTimeout(emitReadChunk);
  828. }
  829. };
  830. BlobReadStream.prototype._emitReadChunk = function(){
  831. if(this.paused || !this.readable) return;
  832. var chunkSize = Math.min(this._source.size - this._start, this._readChunkSize);
  833. if(chunkSize === 0){
  834. this.readable = false;
  835. this.emit("end");
  836. return;
  837. }
  838. var sourceEnd = this._start + chunkSize;
  839. var chunk = (this._source.slice || this._source.webkitSlice || this._source.mozSlice).call(this._source, this._start, sourceEnd);
  840. this._start = sourceEnd;
  841. this._read();
  842. this.emit("data", chunk);
  843. };
  844. /*
  845. function BlobWriteStream(options){
  846. stream.Stream.call(this);
  847. options = _.extend({
  848. onFull: onFull,
  849. onEnd: function(){},
  850. minBlockAllocSize: 0,
  851. drainDelay:0
  852. }, options);
  853. this._onFull = options.onFull;
  854. this._onEnd = options.onEnd;
  855. this._onWrite = options.onWrite;
  856. this._minBlockAllocSize = options.minBlockAllocSize;
  857. this._maxBlockAllocSize = options.maxBlockAllocSize;
  858. this._drainDelay = options.drainDelay;
  859. this._buffer = new Buffer(options.minBlockAllocSize);
  860. this._destination = this._buffer;
  861. this._destinationPos = 0;
  862. this._writeQueue = [];
  863. this._pendingOnFull = false;
  864. this._pendingQueueDrain = false;
  865. this.writable = true;
  866. this.bytesWritten = 0;
  867. }
  868. util.inherits(BlobWriteStream, stream.Stream);
  869. BlobWriteStream.prototype.getBuffer = function(){
  870. return this._buffer;
  871. };
  872. BlobWriteStream.prototype.write = function(data, encoding){
  873. if(!this.writable){
  874. throw new Error("stream is not writable");
  875. }
  876. if(!Buffer.isBuffer(data)){
  877. data = new Buffer(data, encoding);
  878. }
  879. if(data.length){
  880. this._writeQueue.push(data);
  881. }
  882. this._commit();
  883. return this._writeQueue.length === 0;
  884. };
  885. BlobWriteStream.prototype._commit = function(){
  886. var self = this;
  887. var destination = this._destination;
  888. var writeQueue = this._writeQueue;
  889. var startDestinationPos = this._destinationPos;
  890. while(writeQueue.length && destination.length){
  891. var head = writeQueue[0];
  892. var copySize = Math.min(destination.length, head.length);
  893. head.copy(destination, 0, 0, copySize);
  894. head = head.slice(copySize);
  895. destination = destination.slice(copySize);
  896. this.bytesWritten += copySize;
  897. this._destinationPos += copySize;
  898. if(head.length === 0){
  899. writeQueue.shift();
  900. }
  901. else{
  902. writeQueue[0] = head;
  903. }
  904. }
  905. this._destination = destination;
  906. bytesCommitted = this._destinationPos - startDestinationPos;
  907. if(bytesCommitted){
  908. if(this._onWrite){
  909. if(writeQueue.length){
  910. this._pendingQueueDrain = true;
  911. }
  912. // By locking destination the buffer is frozen and the onWrite
  913. // callback cannot miss any write commits
  914. this._destination = emptyBuffer;
  915. var consumer = this._onWrite;
  916. this._onWrite = null;
  917. consumer.call(this, function(nextCallback){
  918. util.setZeroTimeout(function(){
  919. self._destination = destination;
  920. self._onWrite = nextCallback;
  921. self._commit();
  922. });
  923. }, consumer);
  924. return;
  925. }
  926. }
  927. if(writeQueue.length){
  928. this._pendingQueueDrain = true;
  929. this._growBuffer();
  930. }
  931. else if(this._pendingQueueDrain){
  932. this._pendingQueueDrain = false;
  933. if(this._drainDelay !== 0){
  934. setTimeout(function(){
  935. self.emit("drain");
  936. }, this._drainDelay);
  937. }
  938. else{
  939. util.setZeroTimeout(function(){
  940. self.emit("drain");
  941. });
  942. }
  943. }
  944. };
  945. BlobWriteStream.prototype._growBuffer = function(){
  946. var self = this;
  947. var writeQueue = this._writeQueue;
  948. var requestSize = this._minBlockAllocSize;
  949. var maxBlockAllocSize = this._maxBlockAllocSize;
  950. var add = (maxBlockAllocSize === undefined ? function(a, b){return a + b;} : function(a, b){return Math.min(a + b, maxBlockAllocSize);});
  951. for(var i = 0, queueLength = writeQueue.length; i < queueLength; i++){
  952. requestSize = add(requestSize, writeQueue[i].length);
  953. }
  954. // Prevent concurrent onFull callbacks
  955. if(this._pendingOnFull){
  956. return;
  957. }
  958. this._pendingOnFull = true;
  959. this._onFull(this._buffer, requestSize, function(buffer, destination){
  960. util.setZeroTimeout(function(){
  961. self._pendingOnFull = false;
  962. if(!destination){
  963. if(self.writable){
  964. self.emit("error", new Error("buffer is full"));
  965. }
  966. self.destroy();
  967. return;
  968. }
  969. self._buffer = buffer;
  970. self._destination = destination;
  971. self._commit();
  972. });
  973. });
  974. };
  975. BlobWriteStream.prototype.end = function(data, encoding){
  976. var self = this;
  977. function _end(){
  978. self.writable = false;
  979. self._onEnd();
  980. }
  981. if(data){
  982. if(this.write(data, encoding)){
  983. _end();
  984. }else{
  985. self.writable = false;
  986. this.once("drain", _end);
  987. }
  988. }
  989. else{
  990. _end();
  991. }
  992. };
  993. BlobWriteStream.prototype.destroy = function(){
  994. this.writable = false;
  995. this._pendingQueueDrain = false;
  996. this._writeQueue = [];
  997. };
  998. BlobWriteStream.prototype.consume = function(consume){
  999. this._buffer = this._buffer.slice(consume);
  1000. this._destinationPos -= consume;
  1001. };
  1002. BlobWriteStream.prototype.getCommittedSlice = function(){
  1003. return this._buffer.slice(0, this._destinationPos);
  1004. };
  1005. function onFull(buffer, extraSize, callback){
  1006. var newBuffer = new Buffer(buffer.length + extraSize);
  1007. buffer.copy(newBuffer);
  1008. callback(newBuffer, newBuffer.slice(buffer.length));
  1009. }
  1010. */
  1011. exports.BlobReadStream = BlobReadStream;
  1012. function BinaryStream(socket, id, create, meta) {
  1013. if (!(this instanceof BinaryStream)) return new BinaryStream(options);
  1014. var self = this;
  1015. Stream.call(this);
  1016. this.id = id;
  1017. this._socket = socket;
  1018. this.writable = true;
  1019. this.readable = true;
  1020. this.paused = false;
  1021. this._closed = false;
  1022. this._ended = false;
  1023. if(create) {
  1024. // This is a stream we are creating
  1025. this._write(1, meta, this.id);
  1026. }
  1027. }
  1028. util.inherits(BinaryStream, Stream);
  1029. BinaryStream.prototype._onDrain = function() {
  1030. if(!this.paused) {
  1031. this.emit('drain');
  1032. }
  1033. };
  1034. BinaryStream.prototype._onClose = function() {
  1035. // Emit close event
  1036. if (this._closed) {
  1037. return;
  1038. }
  1039. this.readable = false;
  1040. this.writable = false;
  1041. this._closed = true;
  1042. this.emit('close');
  1043. };
  1044. BinaryStream.prototype._onError = function(error){
  1045. this.readable = false;
  1046. this.writable = false;
  1047. this.emit('error', error);
  1048. };
  1049. // Write stream
  1050. BinaryStream.prototype._onPause = function() {
  1051. // Emit pause event
  1052. this.paused = true;
  1053. this.emit('pause');
  1054. };
  1055. BinaryStream.prototype._onResume = function() {
  1056. // Emit resume event
  1057. this.paused = false;
  1058. this.emit('resume');
  1059. this.emit('drain');
  1060. };
  1061. BinaryStream.prototype._write = function(code, data, bonus) {
  1062. if (this._socket.readyState !== this._socket.constructor.OPEN) {
  1063. return false;
  1064. }
  1065. var message = util.pack([code, data, bonus]);
  1066. return this._socket.send(message) !== false;
  1067. };
  1068. BinaryStream.prototype.write = function(data) {
  1069. if(this.writable) {
  1070. var out = this._write(2, data, this.id);
  1071. return !this.paused && out;
  1072. } else {
  1073. this.emit('error', new Error('Stream is not writable'));
  1074. return false;
  1075. }
  1076. };
  1077. BinaryStream.prototype.end = function() {
  1078. this._ended = true;
  1079. this.readable = false;
  1080. this._write(5, null, this.id);
  1081. };
  1082. BinaryStream.prototype.destroy = BinaryStream.prototype.destroySoon = function() {
  1083. this._onClose();
  1084. this._write(6, null, this.id);
  1085. };
  1086. // Read stream
  1087. BinaryStream.prototype._onEnd = function() {
  1088. if(this._ended) {
  1089. return;
  1090. }
  1091. this._ended = true;
  1092. this.readable = false;
  1093. this.emit('end');
  1094. };
  1095. BinaryStream.prototype._onData = function(data) {
  1096. // Dispatch
  1097. this.emit('data', data);
  1098. };
  1099. BinaryStream.prototype.pause = function() {
  1100. this._onPause();
  1101. this._write(3, null, this.id);
  1102. };
  1103. BinaryStream.prototype.resume = function() {
  1104. this._onResume();
  1105. this._write(4, null, this.id);
  1106. };
  1107. function BinaryClient(socket, options) {
  1108. if (!(this instanceof BinaryClient)) return new BinaryClient(socket, options);
  1109. EventEmitter.call(this);
  1110. var self = this;
  1111. this._options = util.extend({
  1112. chunkSize: 40960
  1113. }, options);
  1114. this.streams = {};
  1115. if(typeof socket === 'string') {
  1116. this._nextId = 0;
  1117. this._socket = new WebSocket(socket);
  1118. } else {
  1119. // Use odd numbered ids for server originated streams
  1120. this._nextId = 1;
  1121. this._socket = socket;
  1122. }
  1123. this._socket.binaryType = 'arraybuffer';
  1124. this._socket.addEventListener('open', function(){
  1125. self.emit('open');
  1126. });
  1127. this._socket.addEventListener('error', function(error){
  1128. var ids = Object.keys(self.streams);
  1129. for (var i = 0, ii = ids.length; i < ii; i++) {
  1130. self.streams[ids[i]]._onError(error);
  1131. }
  1132. self.emit('error', error);
  1133. });
  1134. this._socket.addEventListener('close', function(code, message){
  1135. var ids = Object.keys(self.streams);
  1136. for (var i = 0, ii = ids.length; i < ii; i++) {
  1137. self.streams[ids[i]]._onClose();
  1138. }
  1139. self.emit('close', code, message);
  1140. });
  1141. this._socket.addEventListener('message', function(data, flags){
  1142. util.setZeroTimeout(function(){
  1143. // Message format
  1144. // [type, payload, bonus ]
  1145. //
  1146. // Reserved
  1147. // [ 0 , X , X ]
  1148. //
  1149. //
  1150. // New stream
  1151. // [ 1 , Meta , new streamId ]
  1152. //
  1153. //
  1154. // Data
  1155. // [ 2 , Data , streamId ]
  1156. //
  1157. //
  1158. // Pause
  1159. // [ 3 , null , streamId ]
  1160. //
  1161. //
  1162. // Resume
  1163. // [ 4 , null , streamId ]
  1164. //
  1165. //
  1166. // End
  1167. // [ 5 , null , streamId ]
  1168. //
  1169. //
  1170. // Close
  1171. // [ 6 , null , streamId ]
  1172. //
  1173. data = data.data;
  1174. try {
  1175. data = util.unpack(data);
  1176. } catch (ex) {
  1177. return self.emit('error', new Error('Received unparsable message: ' + ex));
  1178. }
  1179. if (!(data instanceof Array))
  1180. return self.emit('error', new Error('Received non-array message'));
  1181. if (data.length != 3)
  1182. return self.emit('error', new Error('Received message with wrong part count: ' + data.length));
  1183. if ('number' != typeof data[0])
  1184. return self.emit('error', new Error('Received message with non-number type: ' + data[0]));
  1185. switch(data[0]) {
  1186. case 0:
  1187. // Reserved
  1188. break;
  1189. case 1:
  1190. var meta = data[1];
  1191. var streamId = data[2];
  1192. var binaryStream = self._receiveStream(streamId);
  1193. self.emit('stream', binaryStream, meta);
  1194. break;
  1195. case 2:
  1196. var payload = data[1];
  1197. var streamId = data[2];
  1198. var binaryStream = self.streams[streamId];
  1199. if(binaryStream) {
  1200. binaryStream._onData(payload);
  1201. } else {
  1202. self.emit('error', new Error('Received `data` message for unknown stream: ' + streamId));
  1203. }
  1204. break;
  1205. case 3:
  1206. var streamId = data[2];
  1207. var binaryStream = self.streams[streamId];
  1208. if(binaryStream) {
  1209. binaryStream._onPause();
  1210. } else {
  1211. self.emit('error', new Error('Received `pause` message for unknown stream: ' + streamId));
  1212. }
  1213. break;
  1214. case 4:
  1215. var streamId = data[2];
  1216. var binaryStream = self.streams[streamId];
  1217. if(binaryStream) {
  1218. binaryStream._onResume();
  1219. } else {
  1220. self.emit('error', new Error('Received `resume` message for unknown stream: ' + streamId));
  1221. }
  1222. break;
  1223. case 5:
  1224. var streamId = data[2];
  1225. var binaryStream = self.streams[streamId];
  1226. if(binaryStream) {
  1227. binaryStream._onEnd();
  1228. } else {
  1229. self.emit('error', new Error('Received `end` message for unknown stream: ' + streamId));
  1230. }
  1231. break;
  1232. case 6:
  1233. var streamId = data[2];
  1234. var binaryStream = self.streams[streamId];
  1235. if(binaryStream) {
  1236. binaryStream._onClose();
  1237. } else {
  1238. self.emit('error', new Error('Received `close` message for unknown stream: ' + streamId));
  1239. }
  1240. break;
  1241. default:
  1242. self.emit('error', new Error('Unrecognized message type received: ' + data[0]));
  1243. }
  1244. });
  1245. });
  1246. }
  1247. util.inherits(BinaryClient, EventEmitter);
  1248. BinaryClient.prototype.send = function(data, meta){
  1249. var stream = this.createStream(meta);
  1250. if(data instanceof Stream) {
  1251. data.pipe(stream);
  1252. } else if (util.isNode === true) {
  1253. if(Buffer.isBuffer(data)) {
  1254. (new BufferReadStream(data, {chunkSize: this._options.chunkSize})).pipe(stream);
  1255. } else {
  1256. stream.write(data);
  1257. }
  1258. } else if (util.isNode !== true) {
  1259. if(data.constructor == Blob || data.constructor == File) {
  1260. (new BlobReadStream(data, {chunkSize: this._options.chunkSize})).pipe(stream);
  1261. } else if (data.constructor == ArrayBuffer) {
  1262. var blob;
  1263. if(binaryFeatures.useArrayBufferView) {
  1264. data = new Uint8Array(data);
  1265. }
  1266. if(binaryFeatures.useBlobBuilder) {
  1267. var builder = new BlobBuilder();
  1268. builder.append(data);
  1269. blob = builder.getBlob()
  1270. } else {
  1271. blob = new Blob([data]);
  1272. }
  1273. (new BlobReadStream(blob, {chunkSize: this._options.chunkSize})).pipe(stream);
  1274. } else if (typeof data === 'object' && 'BYTES_PER_ELEMENT' in data) {
  1275. var blob;
  1276. if(!binaryFeatures.useArrayBufferView) {
  1277. // Warn
  1278. data = data.buffer;
  1279. }
  1280. if(binaryFeatures.useBlobBuilder) {
  1281. var builder = new BlobBuilder();
  1282. builder.append(data);
  1283. blob = builder.getBlob()
  1284. } else {
  1285. blob = new Blob([data]);
  1286. }
  1287. (new BlobReadStream(blob, {chunkSize: this._options.chunkSize})).pipe(stream);
  1288. } else {
  1289. stream.write(data);
  1290. }
  1291. }
  1292. return stream;
  1293. };
  1294. BinaryClient.prototype._receiveStream = function(streamId){
  1295. var self = this;
  1296. var binaryStream = new BinaryStream(this._socket, streamId, false);
  1297. binaryStream.on('close', function(){
  1298. delete self.streams[streamId];
  1299. });
  1300. this.streams[streamId] = binaryStream;
  1301. return binaryStream;
  1302. };
  1303. BinaryClient.prototype.createStream = function(meta){
  1304. if(this._socket.readyState !== WebSocket.OPEN) {
  1305. throw new Error('Client is not yet connected or has closed');
  1306. return;
  1307. }
  1308. var self = this;
  1309. var streamId = this._nextId;
  1310. this._nextId += 2;
  1311. var binaryStream = new BinaryStream(this._socket, streamId, true, meta);
  1312. binaryStream.on('close', function(){
  1313. delete self.streams[streamId];
  1314. });
  1315. this.streams[streamId] = binaryStream;
  1316. return binaryStream;
  1317. };
  1318. BinaryClient.prototype.close = BinaryClient.prototype.destroy = function() {
  1319. this._socket.close();
  1320. };
  1321. exports.BinaryClient = BinaryClient;
  1322. })(this);
  1323. </script>