13693261870
2022-09-16 354b3dbfbffb3df45212a2a44dbbf48b4acc2594
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <title>The source code</title>
  <link href="../resources/prettify/prettify.css" type="text/css" rel="stylesheet" />
  <script type="text/javascript" src="../resources/prettify/prettify.js"></script>
  <style type="text/css">
    .highlight { display: block; background-color: #ddd; }
  </style>
  <script type="text/javascript">
    function highlight() {
      document.getElementById(location.hash.replace(/#/, "")).className = "highlight";
    }
  </script>
</head>
<body onload="prettyPrint(); highlight();">
  <pre class="prettyprint lang-js">// @tag enterprise
<span id='Ext-data-amf-Encoder'>/**
</span> * @class Ext.data.amf.Encoder
 * This class serializes data in the Action Message Format (AMF) format.
 * It can write simple and complex objects, to be used in conjunction with an
 * AMF-compliant server.
 * To encode a byte array, first construct an Encoder, optionally setting the format:
 *
 *     var encoder = Ext.create('Ext.data.amf.Encoder', {
 *       format: 3
 *     });
 *
 * Then use the writer methods to out data to the :
 *
 *     encoder.writeObject(1);
 *
 * And access the data through the #bytes property:
 *     encoder.bytes;
 *
 * You can also reset the class to start a new byte array:
 *
 *     encoder.clear();
 *
 * Current limitations:
 * AMF3 format (format:3)
 * - writeObject will write out XML object, not legacy XMLDocument objects. A
 *   writeXmlDocument method is provided for explicitly writing XMLDocument
 *   objects.
 * - Each object is written out explicitly, not using the reference tables
 *   supported by the AMF format. This means the function does NOT support
 *   circular reference objects.
 * - Array objects: only the numbered indices and data will be written out.
 *   Associative values will be ignored.
 * - Objects that aren't Arrays, Dates, Strings, Document (XML) or primitive
 *   values will be written out as anonymous objects with dynamic data.
 * - There's no JavaScript equivalent to the ByteArray type in ActionScript,
 *   hence data will never be searialized as ByteArrays by the writeObject
 *   function. A writeByteArray method is provided for writing out ByteArray objects.
 *
 * AMF0 format (format:0)
 * - Each object is written out explicitly, not using the reference tables
 *   supported by the AMF format. This means the function does NOT support
 *   circular reference objects.
 * - Array objects: the function always writes an associative array (following
 *   the behavior of flex).
 * - Objects that aren't Arrays, Dates, Strings, Document (XML) or primitive
 *   values will be written out as anonymous objects.
 *
 * For more information on working with AMF data please refer to the
 * [AMF Guide](#/guide/amf).
 */
Ext.define('Ext.data.amf.Encoder', {
 
    alias: 'data.amf.Encoder',
 
    config: {
<span id='Ext-data-amf-Encoder-cfg-format'>        format: 3
</span>    },
 
<span id='Ext-data-amf-Encoder-property-bytes'>    /**
</span>     * @property {Array} bytes
     * @readonly
     * The constructed byte array.
     */
    bytes: [],
 
<span id='Ext-data-amf-Encoder-method-constructor'>    /**
</span>     * Creates new Encoder.
     * @param {Object} config Configuration options
     */
    constructor: function(config) {
        this.initConfig(config);
        this.clear();
    },
 
<span id='Ext-data-amf-Encoder-method-clear'>    /**
</span>     * Reset all class states and starts a new empty array for encoding data.
     * The method generates a new array for encoding, so it's safe to keep a
     * reference to the old one.
     */
    clear: function() {
        this.bytes = [];
    },
 
<span id='Ext-data-amf-Encoder-method-applyFormat'>    /**
</span>     * Sets the functions that will correctly serialize for the relevant
     * protocol version.
     * @param {Number} protocol_version the protocol version to support
     */
    applyFormat: function(protocol_version) {
        var funcs = {
            0: {
                writeUndefined: this.write0Undefined,
                writeNull: this.write0Null,
                writeBoolean: this.write0Boolean,
                writeNumber: this.write0Number,
                writeString: this.write0String,
                writeXml: this.write0Xml,
                writeDate: this.write0Date,
                writeArray: this.write0Array,
                writeGenericObject: this.write0GenericObject
            },
 
            3: {
                writeUndefined: this.write3Undefined,
                writeNull: this.write3Null,
                writeBoolean: this.write3Boolean,
                writeNumber: this.write3Number,
                writeString: this.write3String,
                writeXml: this.write3Xml,
                writeDate: this.write3Date,
                writeArray: this.write3Array,
                writeGenericObject: this.write3GenericObject
            }
 
        }[protocol_version];
        if (funcs) {
            Ext.apply(this, funcs);
            return protocol_version;
        } else {
            //&lt;debug&gt;
            Ext.Error.raise(&quot;Unsupported AMF format: &quot; + protocol_version + &quot;. Only '3' (AMF3) is supported at this point.&quot;);
            //&lt;/debug&gt;
            return; // return nothing
        }
    },
 
<span id='Ext-data-amf-Encoder-method-writeObject'>    /**
</span>     * Write the appropriate data items to the byte array. Supported types:
     * - undefined
     * - null
     * - boolean
     * - integer (if AMF3 - limited by 29-bit int, otherwise passed as double)
     * - double
     * - UTF-8 string
     * - XML Document (identified by being instaneof Document. Can be generated with: new DOMParser()).parseFromString(xml, &quot;text/xml&quot;);
     * @param {Object} item A primitive or object to write to the stream
     */
    writeObject: function(item) {
        var t = typeof(item);
        //Ext.log(&quot;Writing &quot; + item + &quot; of type &quot; + t);
        if (t === &quot;undefined&quot;) {
            this.writeUndefined();
        } else if (item === null) { // can't check type since typeof(null) returns &quot;object&quot;
            this.writeNull();
        } else if (Ext.isBoolean(item)) {
            this.writeBoolean(item);
        } else if (Ext.isString(item)) {
            this.writeString(item);
        } else if (t === &quot;number&quot; || item instanceof Number) { // Can't use Ext.isNumeric since it accepts strings as well
            this.writeNumber(item);
        } else if (t === &quot;object&quot;) {
            // Figure out which object this is
            if (item instanceof Date) {
                this.writeDate(item);
            } else if (Ext.isArray(item)) { // this won't catch associative arrays deserialized by the Packet class!
                this.writeArray(item);
            } else if (this.isXmlDocument(item)) {
                this.writeXml(item);
            } else {
                // Treat this as a generic object with name/value pairs of data.
                this.writeGenericObject(item);
            }
        } else {
            //&lt;debug&gt;
            Ext.log.warn(&quot;AMF Encoder: Unknown item type &quot; + t + &quot; can't be written to stream: &quot; + item);
            //&lt;/debug&gt;
        }
    },
 
<span id='Ext-data-amf-Encoder-method-write3Undefined'>    /**
</span>     * Writes the AMF3 undefined value to the byte array.
     * @private
     */
    write3Undefined: function() {
        this.writeByte(0x00); // AMF3 undefined
    },
 
<span id='Ext-data-amf-Encoder-method-write0Undefined'>    /**
</span>     * Writes the AMF0 undefined value to the byte array.
     * @private
     */
    write0Undefined: function() {
        this.writeByte(0x06); // AMF0 undefined
    },
 
<span id='Ext-data-amf-Encoder-method-write3Null'>    /**
</span>     * Writes the AMF3 null value to the byte array.
     * @private
     */
    write3Null: function() {
        this.writeByte(0x01); // AMF3 null
    },
 
<span id='Ext-data-amf-Encoder-method-write0Null'>    /**
</span>     * Writes the AMF0 null value to the byte array.
     * @private
     */
    write0Null: function() {
        this.writeByte(0x05); // AMF0 null
    },
 
<span id='Ext-data-amf-Encoder-method-write3Boolean'>    /**
</span>     * Writes the appropriate AMF3 boolean value to the byte array.
     * @param {boolean} item The value to write
     * @private
     */
    write3Boolean: function(item) {
        //&lt;debug&gt;
        if (typeof(item) !== &quot;boolean&quot;) {
            Ext.log.warn(&quot;Encoder: writeBoolean argument is not a boolean. Coercing.&quot;);
        }
        // &lt;/debug&gt;
        if (item) {
            this.writeByte(0x03); // AMF3 true
        } else {
            this.writeByte(0x02); // AMF3 false
        }
    },
 
<span id='Ext-data-amf-Encoder-method-write0Boolean'>    /**
</span>     * Writes the appropriate AMF0 boolean value to the byte array.
     * @param {boolean} item The value to write
     * @private
     */
    write0Boolean: function(item) {
        //&lt;debug&gt;
        if (typeof(item) !== &quot;boolean&quot;) {
            Ext.log.warn(&quot;Encoder: writeBoolean argument is not a boolean. Coercing.&quot;);
        }
        // &lt;/debug&gt;
        this.writeByte(0x01); // AMF0 boolean marker
        if (item) {
            this.writeByte(0x01); // AMF0 true
        } else {
            this.writeByte(0x00); // AMF0 false
        }
    },
 
<span id='Ext-data-amf-Encoder-method-encode29Int'>    /**
</span>     * Encodes a U29 int, returning a byte array with the encoded number.
     * @param item - unsigned int value
     * @private
     */
    encode29Int: function(item) {
        var data = [], // prepare the bytes, then send them to the array
            num = item,
            nibble,
            i;
        if (num == 0) {
            return [0]; // no other data
        }
        // we have a special case if the number is 4-nibbles in U29 encoding
        if (num &gt; 0x001fffff) {
            // last nibble is an 8-bit value
            nibble = num &amp; 0xff;
            data.unshift(nibble);
            num = num &gt;&gt; 8;
        }
        // get all the 7-bit parts ready
        while (num &gt; 0) {
            nibble = num &amp; 0x7f; // 7 bits
            data.unshift(nibble);
            num = num &gt;&gt; 7;
        }
        // now we need to mark each MSb of a 7-bit byte with a 1, except the absolute last one which has a 0.
        // If there's an 8-bit byte, the 7-bit byte before it is marked with 1 as well.
        for (i = 0; i &lt; data.length - 1; i++) {
            data[i] = data[i] | 0x80;
        }
        return data;
    },
 
<span id='Ext-data-amf-Encoder-method-write3Number'>    /**
</span>     * Writes a numberic value to the byte array in AMF3 format
     * @param item A native numeric value, Number instance or one of Infinity, -Infinity or NaN
     * @private
     */
    write3Number: function(item) {
        var data;
        var maxInt = 0x1fffffff,
            minSignedInt = -0xfffffff;
        //&lt;debug&gt;
        if (typeof(item) !== &quot;number&quot; &amp;&amp; !(item instanceof Number)) {
            Ext.log.warn(&quot;Encoder: writeNumber argument is not numeric. Can't coerce.&quot;);
        }
        // &lt;/debug&gt;
 
        // switch to the primitive value for handling:
        if (item instanceof Number) {
            item = item.valueOf();
        }
        // First we need to determine if this is an integer or a float.
        // AMF3 allows integers between -2^28 &lt; item &lt; 2^29, else they need to be passed as doubles.
        if (item % 1 === 0 &amp;&amp; item &gt;= minSignedInt &amp;&amp; item &lt;= maxInt) {
            // The number has no decimal point and is within bounds. Let's encode it.
            item = item &amp; maxInt; // get an unsigned value to work with - we only care about 29 bits.
            data = this.encode29Int(item);
            // And , mark it as an integer
            data.unshift(0x04); // AMF3 integer marker
            // write it!
            this.writeBytes(data);
 
        } else {
            data = this.encodeDouble(item);
            data.unshift(0x05); // AMF3 double marker
            this.writeBytes(data);
        }
    },
 
<span id='Ext-data-amf-Encoder-method-write0Number'>    /**
</span>     * Writes a numberic value to the byte array in AMF0 format
     * @param item A native numeric value, Number instance or one of Infinity, -Infinity or NaN
     * @private
     */
    write0Number: function(item) {
        var data;
        //&lt;debug&gt;
        if (typeof(item) !== &quot;number&quot; &amp;&amp; !(item instanceof Number)) {
            Ext.log.warn(&quot;Encoder: writeNumber argument is not numeric. Can't coerce.&quot;);
        }
        // &lt;/debug&gt;
 
        // switch to the primitive value for handling:
        if (item instanceof Number) {
            item = item.valueOf();
        }
        //In AMF0 numbers are always serialized as double-float values.
        data = this.encodeDouble(item);
        data.unshift(0x00); // AMF0 double marker
        this.writeBytes(data);
    },
 
<span id='Ext-data-amf-Encoder-method-encodeUtf8Char'>    /**
</span>     * Convert a UTF 16 char to a UTF 8 char
     * @param {Number} c char 16-bit code to convert
     * @return {Array} byte array with the UTF 8 values
     */
    encodeUtf8Char: function(c) {
        var data = [],
            val, b, i,
            marker;
        //&lt;debug&gt;
        if (c &gt; 0x10FFFF) {
            //&lt;debug&gt;
            Ext.Error.raise(&quot;UTF 8 char out of bounds&quot;);
            //&lt;/debug&gt;
        }
        //&lt;/debug&gt;
        if (c &lt;= 0x7F) {
            // One byte UTF8
            data.push(c);
        } else {
            // Multi-byte UTF8. Figure out how many bytes:
            if (c &lt;= 0x7ff) {
                b = 2;
            } else if (c &lt;= 0xffff) {
                b = 3;
            } else {
                b = 4;
            }
            // encode LSBs of value
            marker = 0x80; // MSB marker
            for (i = 1; i &lt; b; i++) {
                val = (c &amp; 0x3F) | 0x80; // lowest 6 bits of number, plus a flag to mark the byte
                data.unshift(val);
                c = c &gt;&gt; 6; // drop 6 LSbs
                marker = (marker &gt;&gt; 1) | 0x80; // add one more bit for every byte
            }
            // the final byte is now ready, but we need to mark it to show how many other bytes follow
            val = c | marker;
            data.unshift(val);
        }
        return data;
    },
 
<span id='Ext-data-amf-Encoder-method-encodeUtf8String'>    /**
</span>     * Accepts a string and returns a byte array encoded in UTF-8
     * @param {String} str String to encode
     * @return {Array} byte array with string encoded in UTF-8 format
     * @private
     */
    encodeUtf8String: function(str) {
        var i,
            utf8Data = [];
        for (i = 0; i &lt; str.length; i++) {
            var data = this.encodeUtf8Char(str.charCodeAt(i));
            Ext.Array.push(utf8Data, data);
        }
        return utf8Data;
 
        // quicker conversion, doesn't work in IE:
        //          utf8String = unescape(encodeURIComponent(str)),
        //          utf8Data = [];
 
 
    },
 
<span id='Ext-data-amf-Encoder-method-encode3Utf8StringLen'>    /**
</span>     * Encode the length of a UTF-8 string in AMF3 format.
     * @param {Array} utf8Data byte array with the encoded data
     * @return {Array} byte array encoding of length
     *
     * @private
     */
    encode3Utf8StringLen: function(utf8Data) {
        var len = utf8Data.length,
            data = [];
        if (len &lt;= 0xFFFFFFF) {
            // String is under max allowed length in AMF3
            // AMF3 strings use the LSb to mark whether it's a string reference or a string value. For now we only pass values:
            len = len &lt;&lt; 1;
            len = len | 1; // mark as value
            // push length value to the array
            data =this.encode29Int(len);
        } else {
            //&lt;debug&gt;
            Ext.Error.raise(&quot;UTF8 encoded string too long to serialize to AMF: &quot; + len);
            //&lt;/debug&gt;
        }
        return data;
    },
 
<span id='Ext-data-amf-Encoder-method-write3String'>    /**
</span>     * Write an AMF3 UTF-8 string to the byte array
     * @param {String} item The string to write
     * @private
     */
    write3String: function(item) {
        //&lt;debug&gt;
        if (!Ext.isString(item)) {
            Ext.log.warn(&quot;Encoder: writString argument is not a string.&quot;);
        }
        // &lt;/debug&gt;
        if (item == &quot;&quot;) { // special case for the empty string
            this.writeByte(0x06); // AMF3 string marker
            this.writeByte(0x01); // zero length string
        } else {
            // first encode string to UTF-8.
            var utf8Data = this.encodeUtf8String(item);
            var lenData = this.encode3Utf8StringLen(utf8Data);
            // only write encoding once we got here, i.e. length of string is legal
            this.writeByte(0x06); // AMF3 string marker, only if we can actually write a string
            this.writeBytes(lenData);
            this.writeBytes(utf8Data);
        }
    },
 
<span id='Ext-data-amf-Encoder-method-encodeXInt'>    /**
</span>     * Encode 16- or 32-bit integers into big-endian (network order) bytes
     * @param {Number} value the number to encode.
     * @param {Number} byte_count 2 or 4 byte encoding
     * @return {Array} byte array with encoded number
     */
    encodeXInt: function(value, byte_count) {
        var data = [],
            i;
        for (i = 0; i &lt; byte_count; i++) {
            data.unshift(value &amp; 0xff);
            value = value &gt;&gt; 8;
        }
        return data;
    },
 
<span id='Ext-data-amf-Encoder-method-write0String'>    /**
</span>     * Write an AMF0 UTF-8 string to the byte array
     * @param {String} item The string to write
     * @private
     */
    write0String: function(item) {
        //&lt;debug&gt;
        if (!Ext.isString(item)) {
            Ext.log.warn(&quot;Encoder: writString argument is not a string.&quot;);
        }
        // &lt;/debug&gt;
        if (item == &quot;&quot;) { // special case for the empty string
            this.writeByte(0x02); // AMF0 short string marker
            this.writeBytes([0x00, 0x00]); // zero length string
        } else {
            // first encode string to UTF-8.
            var utf8Data = this.encodeUtf8String(item);
            var encoding;
            var lenData;
            if (utf8Data.length &lt;= 0xffff) {
                // short string
                encoding = 0x02; // short string
                lenData = this.encodeXInt(utf8Data.length, 2);
            } else {
                // long string
                encoding = 0x0C; // long string
                lenData = this.encodeXInt(utf8Data.length, 4);
            }
            this.writeByte(encoding); // Approperiate AMF0 string marker
            this.writeBytes(lenData);
            this.writeBytes(utf8Data);
        }
    },
 
<span id='Ext-data-amf-Encoder-method-write3XmlWithType'>    /**
</span>     * Writes an XML document in AMF3 format.
     * @param {Object} xml XML document (type Document typically)
     * @param {number} amfType Either 0x07 or 0x0B - the AMF3 object type to use
     * @private
     */
    write3XmlWithType: function(xml, amfType) {
        //&lt;debug&gt;
        // We accept XML Documents, or strings
        if (amfType !== 0x07 &amp;&amp; amfType !== 0x0B) {
            Ext.Error.raise(&quot;write XML with unknown AMF3 code: &quot; + amfType);
        }
        if (!this.isXmlDocument(xml)) {
            Ext.log.warn(&quot;Encoder: write3XmlWithType argument is not an xml document.&quot;);
        }
        // &lt;/debug&gt;
        var xmlStr = this.convertXmlToString(xml);
        if (xmlStr == &quot;&quot;) { // special case for the empty string
            this.writeByte(amfType); // AMF3 XML marker
            this.writeByte(0x01); // zero length string
        } else {
            // first encode string to UTF-8.
            var utf8Data = this.encodeUtf8String(xmlStr);
            var lenData = this.encode3Utf8StringLen(utf8Data);
            // only write encoding once we got here, i.e. length of string is legal
            this.writeByte(amfType); // AMF3 XML marker, only if we can actually write the string
            this.writeBytes(lenData);
            this.writeBytes(utf8Data);
        }
    },
 
<span id='Ext-data-amf-Encoder-method-write3XmlDocument'>    /**
</span>     * Writes an Legacy XMLDocument (ActionScript Legacy XML object) in AMF3
     * format. Must be called explicitly.
     * The writeObject method will call writeXml and not writeXmlDocument.
     * @param {Object} xml XML document (type Document typically) to write
     */
    write3XmlDocument: function(xml) {
        this.write3XmlWithType(xml, 0x07);
    },
 
<span id='Ext-data-amf-Encoder-method-write3Xml'>    /**
</span>     * Writes an XML object (ActionScript 3 new XML object) in AMF3 format.
     * @param {Object} xml XML document (type Document typically) to write
     * @private
     */
    write3Xml: function(xml) {
        this.write3XmlWithType(xml, 0x0B);
    },
 
<span id='Ext-data-amf-Encoder-method-write0Xml'>    /**
</span>     * Writes an XMLDocument in AMF0 format.
     * @param {Object} xml XML document (type Document typically) to write
     * @private
     */
    write0Xml: function(xml) {
        //&lt;debug&gt;
        // We accept XML Documents, or strings
        if (!this.isXmlDocument(xml)) {
            Ext.log.warn(&quot;Encoder: write0Xml argument is not an xml document.&quot;);
        }
        // &lt;/debug&gt;
        var xmlStr = this.convertXmlToString(xml);
        this.writeByte(0x0F); // AMF0 XML marker
 
        // Always encoded as a long string
        var utf8Data = this.encodeUtf8String(xmlStr);
        var lenData = this.encodeXInt(utf8Data.length, 4);
        this.writeBytes(lenData);
        this.writeBytes(utf8Data);
 
    },
 
<span id='Ext-data-amf-Encoder-method-write3Date'>    /**
</span>     * Writes a date in AMF3 format.
     * @param {Date} date the date object
     * @private
     */
    write3Date: function(date) {
 
        //&lt;debug&gt;
        if (!(date instanceof Date)) {
            Ext.Error.raise(&quot;Serializing a non-date object as date: &quot; + date);
        }
        //&lt;/debug&gt;
        // For now, we don't use object references to just encode the date.
        this.writeByte(0x08); // AMF3 date marker
        this.writeBytes(this.encode29Int(0x1)); // mark this as a date value - we don't support references yet
        this.writeBytes(this.encodeDouble(new Number(date)));
    },
 
<span id='Ext-data-amf-Encoder-method-write0Date'>    /**
</span>     * Writes a date in AMF0 format.
     * @param {Date} date the date object
     * @private
     */
    write0Date: function(date) {
 
        //&lt;debug&gt;
        if (!(date instanceof Date)) {
            Ext.Error.raise(&quot;Serializing a non-date object as date: &quot; + date);
        }
        //&lt;/debug&gt;
        // For now, we don't use object references to just encode the date.
        this.writeByte(0x0B); // AMF0 date marker
        this.writeBytes(this.encodeDouble(new Number(date)));
        this.writeBytes([0x00, 0x00]); // placeholder for timezone, standard says to keep 0, flash actually writes data here
    },
 
<span id='Ext-data-amf-Encoder-method-write3Array'>    /**
</span>     * Writes an array in AMF3 format. Only the ordered part of the array use handled.
     * Unordered parts are ignored (e.g. a[&quot;hello&quot;] will not be encoded).
     * @param {Array} arr the array to serialize.
     * @private
     */
    write3Array: function(arr) {
 
        //&lt;debug&gt;
        if (!Ext.isArray(arr)) {
            Ext.Error.raise(&quot;Serializing a non-array object as array: &quot; + arr);
        }
        if (arr.length &gt; 0xFFFFFFF) {
            Ext.Error.raise(&quot;Array size too long to encode in AMF3: &quot; + arr.length);
        }
        //&lt;/debug&gt;
        // For now, we don't use object references to just encode the array.
        this.writeByte(0x09); // AMF3 array marker
 
        // encode ordered part of array's length
        var len = arr.length;
        len = len &lt;&lt; 1; // right-most bit marks this as size
        len = len | 0x1; // mark it a size
        this.writeBytes(this.encode29Int(len));
 
        // The associative part of the array is ignored, so mark it as empty
        this.writeByte(0x01); // equivalent to an empty UTF-8 string
 
        // now iterate over the array, writing each element
        Ext.each(arr, function(x) {this.writeObject(x);}, this);
    },
 
<span id='Ext-data-amf-Encoder-method-write0ObjectProperty'>    /**
</span>     * Writes a key-value pair in AMF0 format.
     * @param {String} key the name of the property
     * @param {Object} value to write in AMF0 format
     */
    write0ObjectProperty: function(key, value) {
        if (!(key instanceof String) &amp;&amp; (typeof(key) !== &quot;string&quot;)) {
            // coerce to a string
            key = key + &quot;&quot;;
        }
        // first encode the key to a short UTF-8.
        var utf8Data = this.encodeUtf8String(key);
        var lenData;
        lenData = this.encodeXInt(utf8Data.length, 2);
        this.writeBytes(lenData);
        this.writeBytes(utf8Data);
        // and now write out the object
        this.writeObject(value);
    },
 
<span id='Ext-data-amf-Encoder-method-write0Array'>    /**
</span>     * Writes an associative array in AMF0 format.
     * @param {Array} arr the array to serialize.
     * @private
     */
    write0Array: function(arr) {
        var key;
        //&lt;debug&gt;
        if (!Ext.isArray(arr)) {
            Ext.Error.raise(&quot;Serializing a non-array object as array: &quot; + arr);
        }
        //&lt;/debug&gt;
 
        /* This writes a strict array, but it seems Flex always writes out associative arrays, so mimic behavior
 
         // For now, we don't use object references to just encode the array.
         this.writeByte(0x0A); // AMF0 strict array marker
 
         // encode ordered part of array's length
         var len = arr.length;
         this.writeBytes(this.encodeXInt(len, 4));
 
         // now iterate over the array, writing each element
         Ext.each(arr, function(x) {this.writeObject(x);}, this);
         */
        // Use ECMA (associative) array type
        this.writeByte(0x08); // AMF0 ECMA-array marker
        // we need to know the length of the array before we write the serialized data
        // to the array. Better to traverse it twice than to copy all the byte data afterwards
        var total = 0;
        for (key in arr) {
            total++;
        }
        // Now write out the length of the array
        this.writeBytes(this.encodeXInt(total, 4));
        // then write out the data
        for (key in arr) {
            Ext.Array.push(this.write0ObjectProperty(key, arr[key]));
        }
        // And finally the object end marker
        this.writeBytes([0x00, 0x00, 0x09]);
    },
 
<span id='Ext-data-amf-Encoder-method-write0StrictArray'>    /**
</span>     * Writes a strict-array in AMF0 format. Unordered parts are ignored (e.g.
     * a[&quot;hello&quot;] will not be encoded). This function is included for
     * completeness and will never be called by writeObject.
     * @param {Array} arr the array to serialize.
     */
    write0StrictArray: function(arr) {
 
        //&lt;debug&gt;
        if (!Ext.isArray(arr)) {
            Ext.Error.raise(&quot;Serializing a non-array object as array: &quot; + arr);
        }
        //&lt;/debug&gt;
 
        // For now, we don't use object references to just encode the array.
        this.writeByte(0x0A); // AMF0 strict array marker
 
        // encode ordered part of array's length
        var len = arr.length;
        this.writeBytes(this.encodeXInt(len, 4));
 
        // now iterate over the array, writing each element
        Ext.each(arr, function(x) {this.writeObject(x);}, this);
    },
 
 
<span id='Ext-data-amf-Encoder-method-write3ByteArray'>    /**
</span>     * Write a byte array in AMF3 format. This function is never called directly
     * by writeObject since there's no way to distinguish a regular array from a
     * byte array.
     * @param {Array} arr the object to serialize.
     */
    write3ByteArray: function(arr) {
 
        //&lt;debug&gt;
        if (!Ext.isArray(arr)) {
            Ext.Error.raise(&quot;Serializing a non-array object as array: &quot; + arr);
        }
        if (arr.length &gt; 0xFFFFFFF) {
            Ext.Error.raise(&quot;Array size too long to encode in AMF3: &quot; + arr.length);
        }
        //&lt;/debug&gt;
        this.writeByte(0x0c); // Byte array marker
 
        // for now no support for references, so just dump the length and data
 
        // encode array's length
        var len = arr.length;
        len = len &lt;&lt; 1; // right-most bit marks this as size
        len = len | 0x1; // mark it a size
        this.writeBytes(this.encode29Int(len));
        // and finally, dump the byte data
        this.writeBytes(arr);
    },
 
<span id='Ext-data-amf-Encoder-method-write3GenericObject'>    /**
</span>     * Write an object to the byte array in AMF3 format.
     * Since we don't have the class information form Flex, the object
     * is written as an anonymous object.
     * @param {Array} obj the object to serialize.
     * @private
     */
    write3GenericObject: function(obj) {
        var name;
 
        //&lt;debug&gt;
        if (!Ext.isObject(obj)) {
            Ext.Error.raise(&quot;Serializing a non-object object: &quot; + obj);
        }
        //&lt;/debug&gt;
        // For now, we don't use object references so just encode the object.
        this.writeByte(0x0A); // AMF3 object marker
        // The following 29-int is marked as follows (LSb to MSb) to signify a
        // &quot;U29O-traits&quot;:
        // 1 - LSb marks an object value (1) or an object reference (0) which
        //     is not yet supported.
        // 1 - trait values (1) or trait references (0) which are not supported
        //     yet.
        // 0 - AMF3 format (0) or externalizable, i.e. object handles own
        //     serialization (1) which is not supported.
        // 1 - dynamic (1) or not dynamic (0) object which is not relevant since
        //     we pass all data as dynamic fields.
        // The reset of the bits signify how many sealed traits the object has.
        //     we pass 0 since all data is passed as dynamic fields
        var oType = 0x0b; // binary 1011
        this.writeByte(oType);
        // Next we pass the class name, which is the empty string for anonymous
        // objects
        this.writeByte(0x01);
        // Next are the sealed traits (of which we have none)
        // And now the name / value pairs of dynamic fields
        for (name in obj) {
            // Ensure that name is actually a string
            var newName = new String(name).valueOf();
            if (newName == &quot;&quot;) {
                //&lt;debug&gt;
                Ext.Error.raise(&quot;Can't encode non-string field name: &quot; + name);
                //&lt;/debug&gt;
            }
            var nameData = (this.encodeUtf8String(name));
            this.writeBytes(this.encode3Utf8StringLen(name));
            this.writeBytes(nameData);
            this.writeObject(obj[name]);
        }
        // And mark the end of the dynamic field section with the empty string
        this.writeByte(0x01);
    },
 
<span id='Ext-data-amf-Encoder-method-write0GenericObject'>    /**
</span>     * Write an object to the byte array in AMF0 format.
     * Since we don't have the class information form Flex, the object
     * is written as an anonymous object.
     * @param {Array} obj the object to serialize.
     * @private
     */
    write0GenericObject: function(obj) {
        var typed, amfType, key;
        //&lt;debug&gt;
        if (!Ext.isObject(obj)) {
            Ext.Error.raise(&quot;Serializing a non-object object: &quot; + obj);
        }
        //&lt;/debug&gt;
        // For now, we don't use object references so just encode the object.
        // if the object is typed, the ID changes and we need to send the type ahead of the data
        typed = !!obj.$flexType;
        amfType = typed ? 0x10 : 0x03; // typed vs. untyped object
        this.writeByte(amfType); // AMF0 object marker
        // if typed, send object type
        if (typed) {
            this.write0ShortUtf8String(obj.$flexType);
        }
        // then write out the data. There's no counter, but other than that it's the same as an ECMA array
        for (key in obj) {
            if (key != &quot;$flexType&quot;) {
                Ext.Array.push(this.write0ObjectProperty(key, obj[key]));
            }
        }
        // And finally the object end marker
        this.writeBytes([0x00, 0x00, 0x09]);
    },
 
<span id='Ext-data-amf-Encoder-method-writeByte'>    /**
</span>     * Writes a byte to the byte array
     * @param {number} b Byte to write to the array
     * @private
     */
    writeByte: function(b) {
 
        //&lt;debug&gt;
        if (b &lt; 0 || b &gt; 255) {
            Ex.Error.raise('ERROR: Value being written outside byte range: ' + b);
        }
        //&lt;/debug&gt;
        Ext.Array.push(this.bytes, b);
    },
 
<span id='Ext-data-amf-Encoder-method-writeBytes'>    /**
</span>     * Writes a byte array to the byte array
     * @param {number} b Byte array to append to the array
     * @private
     */
    writeBytes: function(b) {
        var i;
        //&lt;debug&gt;
        if (!Ext.isArray(b)) {
            Ext.Error.raise(&quot;Decoder: writeBytes parameter is not an array: &quot; + b);
        }
        for (i = 0; i &lt; b.length; i++) {
            if (b[i] &lt; 0 || b[i] &gt; 255 || !Ext.isNumber(b[i])) {
                Ext.Error.raise(&quot;ERROR: Value &quot; + i + &quot; being written outside byte range: &quot; + b[i]);
            }
        }
        //&lt;/debug&gt;
        Ext.Array.push(this.bytes, b);
    },
 
<span id='Ext-data-amf-Encoder-method-convertXmlToString'>    /**
</span>     * Converts an XML Document object to a string.
     * @param {Object} xml XML document (type Document typically) to convert
     * @return {String} A string representing the document
     * @private
     */
    convertXmlToString: function(xml) {
        var str;
        if (window.XMLSerializer) {
            // this is not IE, so:
            str = new window.XMLSerializer().serializeToString(xml);
        } else {
            //no XMLSerializer, might be an old version of IE
            str = xml.xml;
        }
        return str;
    },
 
 
<span id='Ext-data-amf-Encoder-method-isXmlDocument'>    /**
</span>     * Tries to determine if an object is an XML document
     * @param {Object} item to identify
     * @return {Boolean} true if it's an XML document, false otherwise
     */
    isXmlDocument: function(item) {
        // We can't test if Document is defined since IE just throws an exception. Instead rely on the DOMParser object
        if (window.DOMParser) {
            if (Ext.isDefined(item.doctype)) {
                return true;
            }
        }
        // Otherwise, check if it has an XML field
        if (Ext.isString(item.xml)) {
            // and we can get the xml
            return true;
        }
        return false;
    },
 
    /*
     * The encodeDouble function is derived from code from the typedarray.js library by Linden Research, Inc.
     *
 
     Copyright (c) 2010, Linden Research, Inc.
 
     Permission is hereby granted, free of charge, to any person obtaining a copy
     of this software and associated documentation files (the &quot;Software&quot;), to deal
     in the Software without restriction, including without limitation the rights
     to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     copies of the Software, and to permit persons to whom the Software is
     furnished to do so, subject to the following conditions:
 
     The above copyright notice and this permission notice shall be included in
     all copies or substantial portions of the Software.
 
     THE SOFTWARE IS PROVIDED &quot;AS IS&quot;, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
     IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
     FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
     AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
     LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
     OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
     THE SOFTWARE.
     */
 
<span id='Ext-data-amf-Encoder-method-encodeDouble'>    /**
</span>     * Encodes an IEEE-754 double-precision number.
     * @param {Number} num the number to encode
     * @return {Array} byte array containing the encoded number
     * @private
     */
    encodeDouble: function(v) {
        var ebits = 11, fbits = 52; // double
        var bias = (1 &lt;&lt; (ebits - 1)) - 1,
            s, e, f, ln,
            i, bits, str, data = [];
 
        // Precalculated values
        var K_INFINITY=[127,240,0,0,0,0,0,0],
            K_NINFINITY=[255,240,0,0,0,0,0,0],
            K_NAN=[255,248,0,0,0,0,0,0];
 
 
        // Compute sign, exponent, fraction
        if (isNaN(v)) {
            data = K_NAN;
        } else if (v === Infinity) {
            data = K_INFINITY;
        } else if (v == -Infinity) {
            data = K_NINFINITY;
        } else {
            // not a special case, so encode
            if (v === 0) {
                e = 0; f = 0; s = (1 / v === -Infinity) ? 1 : 0;
            }
            else {
                s = v &lt; 0;
                v = Math.abs(v);
 
                if (v &gt;= Math.pow(2, 1 - bias)) {
                    // Normalized
                    ln = Math.min(Math.floor(Math.log(v) / Math.LN2), bias);
                    e = ln + bias;
                    f = Math.round(v * Math.pow(2, fbits - ln) - Math.pow(2, fbits));
                }
                else {
                    // Denormalized
                    e = 0;
                    f = Math.round(v / Math.pow(2, 1 - bias - fbits));
                }
            }
 
            // Pack sign, exponent, fraction
            bits = [];
            for (i = fbits; i; i -= 1) { bits.push(f % 2 ? 1 : 0); f = Math.floor(f / 2); }
            for (i = ebits; i; i -= 1) { bits.push(e % 2 ? 1 : 0); e = Math.floor(e / 2); }
            bits.push(s ? 1 : 0);
            bits.reverse();
            str = bits.join('');
 
            // Bits to bytes
            data = [];
            while (str.length) {
                data.push(parseInt(str.substring(0, 8), 2));
                str = str.substring(8);
            }
        }
        return data;
    },
 
<span id='Ext-data-amf-Encoder-method-write0ShortUtf8String'>    /**
</span>     * Writes a short UTF8 string preceded with a 16-bit length.
     * @param {String} str the string to write
     */
    write0ShortUtf8String: function(str) {
        var utf8Data = this.encodeUtf8String(str),
            lenData;
        lenData = this.encodeXInt(utf8Data.length, 2);
        this.writeBytes(lenData);
        this.writeBytes(utf8Data);
    },
 
<span id='Ext-data-amf-Encoder-method-writeAmfPacket'>    /**
</span>     * Writes an AMF packet to the byte array
     * @param {Array} headers the headers to serialize. Each item in the array
     *                should be an object with three fields:
     *                name, mustUnderstand, value
     * @param {Array} messages the messages to serialize. Each item in the array
     *                should be an object with three fields:
     *                targetUri, responseUri, body
     */
    writeAmfPacket: function(headers, messages) {
        var i;
        //&lt;debug&gt;
        if (this.config.format != 0) {
            Ext.Error.raise (&quot;Trying to write a packet on an AMF3 Encoder. Only AMF0 is supported!&quot;);
        }
        if (!Ext.isArray(headers)) {
            Ext.Error.raise(&quot;headers is not an array: &quot; + headers);
        }
        if (!Ext.isArray(messages)) {
            Ext.Error.raise(&quot;messages is not an array: &quot; + messages);
        }
        //&lt;/debug&gt;
        // Write Packet marker
        this.writeBytes([0x00, 0x00]); // AMF 0 version for this packet.
        // Write header count
        this.writeBytes(this.encodeXInt(headers.length, 2));
        // And actual headers
        for (i in headers) {
            this.writeAmfHeader(headers[i].name, headers[i].mustUnderstand, headers[i].value);
        }
        // Write message count
        this.writeBytes(this.encodeXInt(messages.length, 2));
        // And actual messages
        for (i in messages) {
            this.writeAmfMessage(messages[i].targetUri, messages[i].responseUri, messages[i].body);
        }
    },
 
<span id='Ext-data-amf-Encoder-method-writeAmfHeader'>    /**
</span>     * Write an AMF header to the byte array. AMF headers are always encoded in AMF0.
     * @param {String} headerName the header name
     * @param {Boolean} mustUnderstand true if the receiver must understand this header or else reject it, false otherwise
     * @param {Object} value the value to serialize. Must be an object that can be serialized by AMF
     * @private
     */
    writeAmfHeader: function(headerName, mustUnderstand, value) {
        //&lt;debug&gt;
        if (this.config.format != 0) {
            Ext.Error.raise (&quot;Trying to write a header on an AMF3 Encoder. Only AMF0 is supported!&quot;);
        }
        if (!Ext.isString(headerName)) {
            Ext.Error.raise(&quot;targetURI is not a string: &quot; + targetUri);
        }
        if ((typeof(mustUnderstand) !== &quot;boolean&quot;) &amp;&amp; !Ext.isBoolean(mustUnderstand)) {
            Ext.Error.raise(&quot;mustUnderstand is not a boolean value: &quot; + mustUnderstand);
        }
        //&lt;/debug&gt;
        // write header name
        this.write0ShortUtf8String(headerName);
        // write must understand byte
        var mu = mustUnderstand ? 0x01 : 0x00;
        this.writeByte(mu);
        // next write the header length of -1 (undetermined) to the stream
        this.writeBytes(this.encodeXInt(-1, 4));
        // write value
        this.writeObject(value);
    },
 
<span id='Ext-data-amf-Encoder-method-writeAmfMessage'>    /**
</span>     * Writes an AMF message to the byte array. AMF messages are always encoded in AMF0.
     * @param {String} targetUri the class / method to call
     * @param {String} responseUri the response should call here
     * @param {Array} body the parameters to pass to the called method, wrapped in an array
     * @private
     */
    writeAmfMessage: function(targetUri, responseUri, body) {
        //&lt;debug&gt;
        if (this.config.format != 0) {
            Ext.Error.raise (&quot;Trying to write a message on an AMF3 Encoder. Only AMF0 is supported!&quot;);
        }
        if (!Ext.isString(targetUri)) {
            Ext.Error.raise(&quot;targetURI is not a string: &quot; + targetUri);
        }
        if (!Ext.isString(responseUri)) {
            Ext.Error.raise(&quot;targetURI is not a string: &quot; + responseUri);
        }
        if (!Ext.isArray(body)) {
            Ext.Error.raise(&quot;body is not an array: &quot; + typeof(body));
        }
        //&lt;/debug&gt;
        // write target URI
        this.write0ShortUtf8String(targetUri);
        // write response URI
        this.write0ShortUtf8String(responseUri);
        // next write the message length of -1 (undetermined) to the stream
        this.writeBytes(this.encodeXInt(-1, 4));
        // write the paramters
        this.write0StrictArray(body);
    }
 
});</pre>
</body>
</html>