msw 0.35.0 → 0.36.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/lib/esm/RequestHandler-deps.js +387 -65
  2. package/lib/esm/errors-deps.js +15 -1
  3. package/lib/esm/fetch-deps.js +9 -5
  4. package/lib/esm/graphql-deps.js +14 -9
  5. package/lib/esm/graphql.js +1 -0
  6. package/lib/esm/index-deps.js +2 -1
  7. package/lib/esm/index.js +61 -4263
  8. package/lib/esm/index2.js +1 -1
  9. package/lib/esm/mockServiceWorker.js +5 -5
  10. package/lib/esm/rest-deps.js +7 -15
  11. package/lib/esm/rest.js +1 -0
  12. package/lib/iife/index.js +2 -2
  13. package/lib/iife/mockServiceWorker.js +5 -5
  14. package/lib/types/context/data.d.ts +2 -3
  15. package/lib/types/context/extensions.d.ts +8 -0
  16. package/lib/types/context/index.d.ts +1 -0
  17. package/lib/types/graphql.d.ts +2 -1
  18. package/lib/types/handlers/GraphQLHandler.d.ts +7 -6
  19. package/lib/types/handlers/RequestHandler.d.ts +8 -8
  20. package/lib/types/handlers/RestHandler.d.ts +10 -12
  21. package/lib/types/index.d.ts +17 -7
  22. package/lib/types/native/index.d.ts +1 -1
  23. package/lib/types/node/index.d.ts +1 -1
  24. package/lib/types/node/setupServer.d.ts +1 -1
  25. package/lib/types/rest.d.ts +10 -9
  26. package/lib/types/setupWorker/glossary.d.ts +12 -12
  27. package/lib/types/setupWorker/start/utils/prepareStartHandler.d.ts +3 -3
  28. package/lib/types/sharedOptions.d.ts +1 -1
  29. package/lib/types/typeUtils.d.ts +5 -3
  30. package/lib/types/utils/getResponse.d.ts +1 -1
  31. package/lib/types/utils/handleRequest.d.ts +5 -5
  32. package/lib/types/utils/internal/getCallFrame.d.ts +1 -1
  33. package/lib/types/utils/internal/jsonParse.d.ts +2 -2
  34. package/lib/types/utils/internal/requestHandlerUtils.d.ts +1 -1
  35. package/lib/types/utils/logging/prepareResponse.d.ts +1 -1
  36. package/lib/types/utils/matching/matchRequestUrl.d.ts +12 -2
  37. package/lib/types/utils/matching/normalizePath.d.ts +1 -1
  38. package/lib/types/utils/request/onUnhandledRequest.d.ts +1 -2
  39. package/lib/types/utils/request/parseBody.d.ts +2 -2
  40. package/lib/types/utils/request/parseWorkerRequest.d.ts +2 -2
  41. package/lib/types/utils/worker/createFallbackRequestListener.d.ts +2 -1
  42. package/lib/types/utils/worker/createRequestListener.d.ts +2 -1
  43. package/lib/umd/index.js +547 -134
  44. package/lib/umd/mockServiceWorker.js +5 -5
  45. package/native/lib/index.js +474 -517
  46. package/node/lib/index.js +476 -519
  47. package/package.json +19 -19
package/lib/esm/index.js CHANGED
@@ -1,16 +1,20 @@
1
1
  export { i as context } from './index-deps.js';
2
- import { c as commonjsGlobal, p as parse_1, l as lib$4, a as lib$6, j as jsonParse } from './fetch-deps.js';
3
- import { _ as __awaiter$3, d as devUtils, p as parseBody, g as getPublicUrlFromRequest, N as NetworkError, l as lib$5, a as getCleanUrl } from './RequestHandler-deps.js';
4
- export { R as RequestHandler, f as compose, c as createResponseComposition, e as defaultContext, b as defaultResponse, m as matchRequestUrl, r as response } from './RequestHandler-deps.js';
2
+ import { c as commonjsGlobal, p as parse_1, l as lib$2, a as lib$3, j as jsonParse } from './fetch-deps.js';
3
+ import { _ as __awaiter, d as devUtils, p as parseBody, g as getPublicUrlFromRequest, N as NetworkError } from './RequestHandler-deps.js';
4
+ export { R as RequestHandler, f as cleanUrl, e as compose, c as createResponseComposition, b as defaultContext, a as defaultResponse, m as matchRequestUrl, r as response } from './RequestHandler-deps.js';
5
+ import { store } from '@mswjs/cookies';
5
6
  import { i as isStringEqual, R as RestHandler } from './rest-deps.js';
6
7
  export { a as RESTMethods, R as RestHandler, r as rest, b as restContext } from './rest-deps.js';
7
8
  import { t as tryCatch, p as parseGraphQLRequest, G as GraphQLHandler } from './graphql-deps.js';
8
9
  export { G as GraphQLHandler, g as graphql, a as graphqlContext } from './graphql-deps.js';
9
10
  import { m as mergeRight } from './errors-deps.js';
10
- import require$$3 from 'debug';
11
+ import { createInterceptor } from '@mswjs/interceptors';
12
+ import { interceptFetch } from '@mswjs/interceptors/lib/interceptors/fetch';
13
+ import { interceptXMLHttpRequest } from '@mswjs/interceptors/lib/interceptors/XMLHttpRequest';
11
14
  import './xml-deps.js';
15
+ import '@mswjs/interceptors/lib/utils/getCleanUrl';
12
16
 
13
- var lib$3 = {};
17
+ var lib$1 = {};
14
18
 
15
19
  var StrictEventEmitter$1 = {};
16
20
 
@@ -490,7 +494,7 @@ function eventTargetAgnosticAddListener(emitter, name, listener, flags) {
490
494
  }
491
495
  }
492
496
 
493
- var __extends$1 = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
497
+ var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
494
498
  var extendStatics = function (d, b) {
495
499
  extendStatics = Object.setPrototypeOf ||
496
500
  ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
@@ -514,7 +518,7 @@ StrictEventEmitter$1.__esModule = true;
514
518
  StrictEventEmitter$1.StrictEventEmitter = void 0;
515
519
  var events_1 = events.exports;
516
520
  var StrictEventEmitter = /** @class */ (function (_super) {
517
- __extends$1(StrictEventEmitter, _super);
521
+ __extends(StrictEventEmitter, _super);
518
522
  function StrictEventEmitter() {
519
523
  return _super.call(this) || this;
520
524
  }
@@ -556,9 +560,9 @@ exports.__esModule = true;
556
560
  exports.StrictEventEmitter = void 0;
557
561
  var StrictEventEmitter_1 = StrictEventEmitter$1;
558
562
  __createBinding(exports, StrictEventEmitter_1, "StrictEventEmitter");
559
- }(lib$3));
563
+ }(lib$1));
560
564
 
561
- var lib$2 = {};
565
+ var lib = {};
562
566
 
563
567
  var until$1 = {};
564
568
 
@@ -580,9 +584,9 @@ until$1.until = async (promise) => {
580
584
  }
581
585
  };
582
586
 
583
- Object.defineProperty(lib$2, "__esModule", { value: true });
584
- var until_1$1 = until$1;
585
- var until = lib$2.until = until_1$1.until;
587
+ Object.defineProperty(lib, "__esModule", { value: true });
588
+ var until_1 = until$1;
589
+ var until = lib.until = until_1.until;
586
590
 
587
591
  /**
588
592
  * Attempts to resolve a Service Worker instance from a given registration,
@@ -613,7 +617,7 @@ function getAbsoluteWorkerUrl(relativeUrl) {
613
617
  * Returns an active Service Worker instance.
614
618
  * When not found, registers a new Service Worker.
615
619
  */
616
- const getWorkerInstance = (url, options = {}, findWorker) => __awaiter$3(void 0, void 0, void 0, function* () {
620
+ const getWorkerInstance = (url, options = {}, findWorker) => __awaiter(void 0, void 0, void 0, function* () {
617
621
  // Resolve the absolute Service Worker URL.
618
622
  const absoluteWorkerUrl = getAbsoluteWorkerUrl(url);
619
623
  const mockRegistrations = yield navigator.serviceWorker
@@ -639,7 +643,7 @@ const getWorkerInstance = (url, options = {}, findWorker) => __awaiter$3(void 0,
639
643
  });
640
644
  }
641
645
  // When the Service Worker wasn't found, register it anew and return the reference.
642
- const [error, instance] = yield until(() => __awaiter$3(void 0, void 0, void 0, function* () {
646
+ const [error, instance] = yield until(() => __awaiter(void 0, void 0, void 0, function* () {
643
647
  const registration = yield navigator.serviceWorker.register(url, options);
644
648
  return [
645
649
  // Compare existing worker registration by its worker URL,
@@ -686,7 +690,7 @@ function printStartMessage(args = {}) {
686
690
  * Signals the worker to enable the interception of requests.
687
691
  */
688
692
  function enableMocking(context, options) {
689
- return __awaiter$3(this, void 0, void 0, function* () {
693
+ return __awaiter(this, void 0, void 0, function* () {
690
694
  context.workerChannel.send('MOCK_ACTIVATE');
691
695
  return context.events.once('MOCKING_ENABLED').then(() => {
692
696
  printStartMessage({ quiet: options.quiet });
@@ -712,379 +716,6 @@ const createBroadcastChannel = (event) => {
712
716
  };
713
717
  };
714
718
 
715
- var lib$1 = {};
716
-
717
- var CookieStore = {};
718
-
719
- var setCookie = {exports: {}};
720
-
721
- var defaultParseOptions = {
722
- decodeValues: true,
723
- map: false,
724
- silent: false,
725
- };
726
-
727
- function isNonEmptyString(str) {
728
- return typeof str === "string" && !!str.trim();
729
- }
730
-
731
- function parseString(setCookieValue, options) {
732
- var parts = setCookieValue.split(";").filter(isNonEmptyString);
733
- var nameValue = parts.shift().split("=");
734
- var name = nameValue.shift();
735
- var value = nameValue.join("="); // everything after the first =, joined by a "=" if there was more than one part
736
-
737
- options = options
738
- ? Object.assign({}, defaultParseOptions, options)
739
- : defaultParseOptions;
740
-
741
- try {
742
- value = options.decodeValues ? decodeURIComponent(value) : value; // decode cookie value
743
- } catch (e) {
744
- console.error(
745
- "set-cookie-parser encountered an error while decoding a cookie with value '" +
746
- value +
747
- "'. Set options.decodeValues to false to disable this feature.",
748
- e
749
- );
750
- }
751
-
752
- var cookie = {
753
- name: name, // grab everything before the first =
754
- value: value,
755
- };
756
-
757
- parts.forEach(function (part) {
758
- var sides = part.split("=");
759
- var key = sides.shift().trimLeft().toLowerCase();
760
- var value = sides.join("=");
761
- if (key === "expires") {
762
- cookie.expires = new Date(value);
763
- } else if (key === "max-age") {
764
- cookie.maxAge = parseInt(value, 10);
765
- } else if (key === "secure") {
766
- cookie.secure = true;
767
- } else if (key === "httponly") {
768
- cookie.httpOnly = true;
769
- } else if (key === "samesite") {
770
- cookie.sameSite = value;
771
- } else {
772
- cookie[key] = value;
773
- }
774
- });
775
-
776
- return cookie;
777
- }
778
-
779
- function parse$1(input, options) {
780
- options = options
781
- ? Object.assign({}, defaultParseOptions, options)
782
- : defaultParseOptions;
783
-
784
- if (!input) {
785
- if (!options.map) {
786
- return [];
787
- } else {
788
- return {};
789
- }
790
- }
791
-
792
- if (input.headers && input.headers["set-cookie"]) {
793
- // fast-path for node.js (which automatically normalizes header names to lower-case
794
- input = input.headers["set-cookie"];
795
- } else if (input.headers) {
796
- // slow-path for other environments - see #25
797
- var sch =
798
- input.headers[
799
- Object.keys(input.headers).find(function (key) {
800
- return key.toLowerCase() === "set-cookie";
801
- })
802
- ];
803
- // warn if called on a request-like object with a cookie header rather than a set-cookie header - see #34, 36
804
- if (!sch && input.headers.cookie && !options.silent) {
805
- console.warn(
806
- "Warning: set-cookie-parser appears to have been called on a request object. It is designed to parse Set-Cookie headers from responses, not Cookie headers from requests. Set the option {silent: true} to suppress this warning."
807
- );
808
- }
809
- input = sch;
810
- }
811
- if (!Array.isArray(input)) {
812
- input = [input];
813
- }
814
-
815
- options = options
816
- ? Object.assign({}, defaultParseOptions, options)
817
- : defaultParseOptions;
818
-
819
- if (!options.map) {
820
- return input.filter(isNonEmptyString).map(function (str) {
821
- return parseString(str, options);
822
- });
823
- } else {
824
- var cookies = {};
825
- return input.filter(isNonEmptyString).reduce(function (cookies, str) {
826
- var cookie = parseString(str, options);
827
- cookies[cookie.name] = cookie;
828
- return cookies;
829
- }, cookies);
830
- }
831
- }
832
-
833
- /*
834
- Set-Cookie header field-values are sometimes comma joined in one string. This splits them without choking on commas
835
- that are within a single set-cookie field-value, such as in the Expires portion.
836
-
837
- This is uncommon, but explicitly allowed - see https://tools.ietf.org/html/rfc2616#section-4.2
838
- Node.js does this for every header *except* set-cookie - see https://github.com/nodejs/node/blob/d5e363b77ebaf1caf67cd7528224b651c86815c1/lib/_http_incoming.js#L128
839
- React Native's fetch does this for *every* header, including set-cookie.
840
-
841
- Based on: https://github.com/google/j2objc/commit/16820fdbc8f76ca0c33472810ce0cb03d20efe25
842
- Credits to: https://github.com/tomball for original and https://github.com/chrusart for JavaScript implementation
843
- */
844
- function splitCookiesString(cookiesString) {
845
- if (Array.isArray(cookiesString)) {
846
- return cookiesString;
847
- }
848
- if (typeof cookiesString !== "string") {
849
- return [];
850
- }
851
-
852
- var cookiesStrings = [];
853
- var pos = 0;
854
- var start;
855
- var ch;
856
- var lastComma;
857
- var nextStart;
858
- var cookiesSeparatorFound;
859
-
860
- function skipWhitespace() {
861
- while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) {
862
- pos += 1;
863
- }
864
- return pos < cookiesString.length;
865
- }
866
-
867
- function notSpecialChar() {
868
- ch = cookiesString.charAt(pos);
869
-
870
- return ch !== "=" && ch !== ";" && ch !== ",";
871
- }
872
-
873
- while (pos < cookiesString.length) {
874
- start = pos;
875
- cookiesSeparatorFound = false;
876
-
877
- while (skipWhitespace()) {
878
- ch = cookiesString.charAt(pos);
879
- if (ch === ",") {
880
- // ',' is a cookie separator if we have later first '=', not ';' or ','
881
- lastComma = pos;
882
- pos += 1;
883
-
884
- skipWhitespace();
885
- nextStart = pos;
886
-
887
- while (pos < cookiesString.length && notSpecialChar()) {
888
- pos += 1;
889
- }
890
-
891
- // currently special character
892
- if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
893
- // we found cookies separator
894
- cookiesSeparatorFound = true;
895
- // pos is inside the next cookie, so back up and return it.
896
- pos = nextStart;
897
- cookiesStrings.push(cookiesString.substring(start, lastComma));
898
- start = pos;
899
- } else {
900
- // in param ',' or param separator ';',
901
- // we continue from that comma
902
- pos = lastComma + 1;
903
- }
904
- } else {
905
- pos += 1;
906
- }
907
- }
908
-
909
- if (!cookiesSeparatorFound || pos >= cookiesString.length) {
910
- cookiesStrings.push(cookiesString.substring(start, cookiesString.length));
911
- }
912
- }
913
-
914
- return cookiesStrings;
915
- }
916
-
917
- setCookie.exports = parse$1;
918
- setCookie.exports.parse = parse$1;
919
- setCookie.exports.parseString = parseString;
920
- setCookie.exports.splitCookiesString = splitCookiesString;
921
-
922
- (function (exports) {
923
- var __rest = (commonjsGlobal && commonjsGlobal.__rest) || function (s, e) {
924
- var t = {};
925
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
926
- t[p] = s[p];
927
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
928
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
929
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
930
- t[p[i]] = s[p[i]];
931
- }
932
- return t;
933
- };
934
- Object.defineProperty(exports, "__esModule", { value: true });
935
- exports.PERSISTENCY_KEY = void 0;
936
- const set_cookie_parser_1 = setCookie.exports;
937
- exports.PERSISTENCY_KEY = 'MSW_COOKIE_STORE';
938
- const SUPPORTS_LOCAL_STORAGE = typeof localStorage !== 'undefined';
939
- class CookieStore {
940
- constructor() {
941
- this.store = new Map();
942
- }
943
- /**
944
- * Sets the given request cookies into the store.
945
- * Respects the `request.credentials` policy.
946
- */
947
- add(request, response) {
948
- if (request.credentials === 'omit') {
949
- return;
950
- }
951
- const requestUrl = new URL(request.url);
952
- const responseCookies = response.headers.get('set-cookie');
953
- if (!responseCookies) {
954
- return;
955
- }
956
- const now = Date.now();
957
- const parsedResponseCookies = set_cookie_parser_1.parse(responseCookies).map((_a) => {
958
- var { maxAge } = _a, cookie = __rest(_a, ["maxAge"]);
959
- return (Object.assign(Object.assign({}, cookie), { expires: maxAge === undefined ? cookie.expires : new Date(now + maxAge * 1000), maxAge }));
960
- });
961
- const prevCookies = this.store.get(requestUrl.origin) || new Map();
962
- parsedResponseCookies.forEach((cookie) => {
963
- this.store.set(requestUrl.origin, prevCookies.set(cookie.name, cookie));
964
- });
965
- }
966
- /**
967
- * Returns cookies relevant to the given request
968
- * and its `request.credentials` policy.
969
- */
970
- get(request) {
971
- this.deleteExpiredCookies();
972
- const requestUrl = new URL(request.url);
973
- const originCookies = this.store.get(requestUrl.origin) || new Map();
974
- switch (request.credentials) {
975
- case 'include': {
976
- const documentCookies = set_cookie_parser_1.parse(document.cookie);
977
- documentCookies.forEach((cookie) => {
978
- originCookies.set(cookie.name, cookie);
979
- });
980
- return originCookies;
981
- }
982
- case 'same-origin': {
983
- return originCookies;
984
- }
985
- default:
986
- return new Map();
987
- }
988
- }
989
- /**
990
- * Returns a collection of all stored cookies.
991
- */
992
- getAll() {
993
- this.deleteExpiredCookies();
994
- return this.store;
995
- }
996
- /**
997
- * Deletes all cookies associated with the given request.
998
- */
999
- deleteAll(request) {
1000
- const requestUrl = new URL(request.url);
1001
- this.store.delete(requestUrl.origin);
1002
- }
1003
- /**
1004
- * Clears the entire cookie store.
1005
- */
1006
- clear() {
1007
- this.store.clear();
1008
- }
1009
- /**
1010
- * Hydrates the virtual cookie store from the `localStorage` if defined.
1011
- */
1012
- hydrate() {
1013
- if (!SUPPORTS_LOCAL_STORAGE) {
1014
- return;
1015
- }
1016
- const persistedCookies = localStorage.getItem(exports.PERSISTENCY_KEY);
1017
- if (persistedCookies) {
1018
- try {
1019
- const parsedCookies = JSON.parse(persistedCookies);
1020
- parsedCookies.forEach(([origin, cookies]) => {
1021
- this.store.set(origin, new Map(cookies.map((_a) => {
1022
- var [token, _b] = _a, { expires } = _b, cookie = __rest(_b, ["expires"]);
1023
- return [
1024
- token,
1025
- expires === undefined
1026
- ? cookie
1027
- : Object.assign(Object.assign({}, cookie), { expires: new Date(expires) }),
1028
- ];
1029
- })));
1030
- });
1031
- }
1032
- catch (error) {
1033
- console.warn(`
1034
- [virtual-cookie] Failed to parse a stored cookie from the localStorage (key "${exports.PERSISTENCY_KEY}").
1035
-
1036
- Stored value:
1037
- ${localStorage.getItem(exports.PERSISTENCY_KEY)}
1038
-
1039
- Thrown exception:
1040
- ${error}
1041
-
1042
- Invalid value has been removed from localStorage to prevent subsequent failed parsing attempts.`);
1043
- localStorage.removeItem(exports.PERSISTENCY_KEY);
1044
- }
1045
- }
1046
- }
1047
- /**
1048
- * Persists the current virtual cookies into the `localStorage` if defined,
1049
- * so they are available on the next page load.
1050
- */
1051
- persist() {
1052
- if (!SUPPORTS_LOCAL_STORAGE) {
1053
- return;
1054
- }
1055
- const serializedCookies = Array.from(this.store.entries()).map(([origin, cookies]) => {
1056
- return [origin, Array.from(cookies.entries())];
1057
- });
1058
- localStorage.setItem(exports.PERSISTENCY_KEY, JSON.stringify(serializedCookies));
1059
- }
1060
- deleteExpiredCookies() {
1061
- const now = Date.now();
1062
- this.store.forEach((originCookies, origin) => {
1063
- originCookies.forEach(({ expires, name }) => {
1064
- if (expires !== undefined && expires.getTime() <= now) {
1065
- originCookies.delete(name);
1066
- }
1067
- });
1068
- if (originCookies.size === 0) {
1069
- this.store.delete(origin);
1070
- }
1071
- });
1072
- }
1073
- }
1074
- exports.default = new CookieStore();
1075
- }(CookieStore));
1076
-
1077
- (function (exports) {
1078
- var __importDefault = (commonjsGlobal && commonjsGlobal.__importDefault) || function (mod) {
1079
- return (mod && mod.__esModule) ? mod : { "default": mod };
1080
- };
1081
- Object.defineProperty(exports, "__esModule", { value: true });
1082
- exports.PERSISTENCY_KEY = exports.store = void 0;
1083
- var CookieStore_1 = CookieStore;
1084
- Object.defineProperty(exports, "store", { enumerable: true, get: function () { return __importDefault(CookieStore_1).default; } });
1085
- Object.defineProperty(exports, "PERSISTENCY_KEY", { enumerable: true, get: function () { return CookieStore_1.PERSISTENCY_KEY; } });
1086
- }(lib$1));
1087
-
1088
719
  function getAllCookies() {
1089
720
  return parse_1(document.cookie);
1090
721
  }
@@ -1095,7 +726,7 @@ function getRequestCookies(request) {
1095
726
  /**
1096
727
  * @note No cookies persist on the document in Node.js: no document.
1097
728
  */
1098
- if (typeof location === 'undefined') {
729
+ if (typeof document === 'undefined' || typeof location === 'undefined') {
1099
730
  return {};
1100
731
  }
1101
732
  switch (request.credentials) {
@@ -1116,8 +747,8 @@ function getRequestCookies(request) {
1116
747
 
1117
748
  function setRequestCookies(request) {
1118
749
  var _a;
1119
- lib$1.store.hydrate();
1120
- request.cookies = Object.assign(Object.assign({}, getRequestCookies(request)), Array.from((_a = lib$1.store.get(Object.assign(Object.assign({}, request), { url: request.url.toString() }))) === null || _a === void 0 ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => Object.assign(cookies, { [name]: value }), {}));
750
+ store.hydrate();
751
+ request.cookies = Object.assign(Object.assign({}, getRequestCookies(request)), Array.from((_a = store.get(Object.assign(Object.assign({}, request), { url: request.url.toString() }))) === null || _a === void 0 ? void 0 : _a.entries()).reduce((cookies, [name, { value }]) => Object.assign(cookies, { [name]: value }), {}));
1121
752
  request.headers.set('cookie', Object.entries(request.cookies)
1122
753
  .map(([name, value]) => `${name}=${value}`)
1123
754
  .join('; '));
@@ -1157,7 +788,7 @@ function parseWorkerRequest(rawRequest) {
1157
788
  destination: rawRequest.destination,
1158
789
  body: pruneGetRequestBody(rawRequest),
1159
790
  bodyUsed: rawRequest.bodyUsed,
1160
- headers: new lib$4.Headers(rawRequest.headers),
791
+ headers: new lib$2.Headers(rawRequest.headers),
1161
792
  };
1162
793
  // Set document cookies on the request.
1163
794
  setRequestCookies(request);
@@ -1169,7 +800,7 @@ function parseWorkerRequest(rawRequest) {
1169
800
  /**
1170
801
  * Returns a mocked response for a given request using following request handlers.
1171
802
  */
1172
- const getResponse = (request, handlers, resolutionContext) => __awaiter$3(void 0, void 0, void 0, function* () {
803
+ const getResponse = (request, handlers, resolutionContext) => __awaiter(void 0, void 0, void 0, function* () {
1173
804
  const relevantHandlers = handlers.filter((handler) => {
1174
805
  return handler.test(request, resolutionContext);
1175
806
  });
@@ -1179,7 +810,7 @@ const getResponse = (request, handlers, resolutionContext) => __awaiter$3(void 0
1179
810
  response: undefined,
1180
811
  };
1181
812
  }
1182
- const result = yield relevantHandlers.reduce((executionResult, handler) => __awaiter$3(void 0, void 0, void 0, function* () {
813
+ const result = yield relevantHandlers.reduce((executionResult, handler) => __awaiter(void 0, void 0, void 0, function* () {
1183
814
  const previousResults = yield executionResult;
1184
815
  if (!!(previousResults === null || previousResults === void 0 ? void 0 : previousResults.response)) {
1185
816
  return executionResult;
@@ -1339,10 +970,10 @@ function groupHandlersByType(handlers) {
1339
970
  graphql: [],
1340
971
  });
1341
972
  }
1342
- function getScoreForRestHandler() {
973
+ function getRestHandlerScore() {
1343
974
  return (request, handler) => {
1344
975
  const { path, method } = handler.info;
1345
- if (path instanceof RegExp) {
976
+ if (path instanceof RegExp || method instanceof RegExp) {
1346
977
  return Infinity;
1347
978
  }
1348
979
  const hasSameMethod = isStringEqual(request.method, method);
@@ -1353,12 +984,15 @@ function getScoreForRestHandler() {
1353
984
  return score - methodScoreDelta;
1354
985
  };
1355
986
  }
1356
- function getScoreForGraphQLHandler(parsedQuery) {
987
+ function getGraphQLHandlerScore(parsedQuery) {
1357
988
  return (_, handler) => {
1358
989
  if (typeof parsedQuery.operationName === 'undefined') {
1359
990
  return Infinity;
1360
991
  }
1361
992
  const { operationType, operationName } = handler.info;
993
+ if (typeof operationName !== 'string') {
994
+ return Infinity;
995
+ }
1362
996
  const hasSameOperationType = parsedQuery.operationType === operationType;
1363
997
  // Always treat a handler with the same operation type as a more similar one.
1364
998
  const operationTypeScoreDelta = hasSameOperationType ? TYPE_MATCH_DELTA : 0;
@@ -1368,16 +1002,12 @@ function getScoreForGraphQLHandler(parsedQuery) {
1368
1002
  }
1369
1003
  function getSuggestedHandler(request, handlers, getScore) {
1370
1004
  const suggestedHandlers = handlers
1371
- .reduce((acc, handler) => {
1005
+ .reduce((suggestions, handler) => {
1372
1006
  const score = getScore(request, handler);
1373
- return acc.concat([[score, handler]]);
1007
+ return suggestions.concat([[score, handler]]);
1374
1008
  }, [])
1375
- .sort(([leftScore], [rightScore]) => {
1376
- return leftScore - rightScore;
1377
- })
1378
- .filter(([score]) => {
1379
- return score <= MAX_MATCH_SCORE;
1380
- })
1009
+ .sort(([leftScore], [rightScore]) => leftScore - rightScore)
1010
+ .filter(([score]) => score <= MAX_MATCH_SCORE)
1381
1011
  .slice(0, MAX_SUGGESTION_COUNT)
1382
1012
  .map(([, handler]) => handler);
1383
1013
  return suggestedHandlers;
@@ -1407,8 +1037,8 @@ function onUnhandledRequest(request, handlers, strategy = 'warn') {
1407
1037
  ? handlerGroups.graphql
1408
1038
  : handlerGroups.rest;
1409
1039
  const suggestedHandlers = getSuggestedHandler(request, relevantHandlers, parsedGraphQLQuery
1410
- ? getScoreForGraphQLHandler(parsedGraphQLQuery)
1411
- : getScoreForRestHandler());
1040
+ ? getGraphQLHandlerScore(parsedGraphQLQuery)
1041
+ : getRestHandlerScore());
1412
1042
  const handlerSuggestion = suggestedHandlers.length > 0
1413
1043
  ? getSuggestedHandlersMessage(suggestedHandlers)
1414
1044
  : '';
@@ -1431,7 +1061,7 @@ Read more: https://mswjs.io/docs/getting-started/mocks\
1431
1061
  // Print a developer-friendly error.
1432
1062
  devUtils.error('Error: %s', message);
1433
1063
  // Throw an exception to halt request processing and not perform the original request.
1434
- throw new Error('Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.');
1064
+ throw new Error(devUtils.formatMessage('Cannot bypass a request when using the "error" strategy for the "onUnhandledRequest" option.'));
1435
1065
  }
1436
1066
  case 'warn': {
1437
1067
  devUtils.warn('Warning: %s', message);
@@ -1445,13 +1075,13 @@ Read more: https://mswjs.io/docs/getting-started/mocks\
1445
1075
  }
1446
1076
 
1447
1077
  function readResponseCookies(request, response) {
1448
- lib$1.store.add(Object.assign(Object.assign({}, request), { url: request.url.toString() }), response);
1449
- lib$1.store.persist();
1078
+ store.add(Object.assign(Object.assign({}, request), { url: request.url.toString() }), response);
1079
+ store.persist();
1450
1080
  }
1451
1081
 
1452
1082
  function handleRequest(request, handlers, options, emitter, handleRequestOptions) {
1453
1083
  var _a, _b, _c;
1454
- return __awaiter$3(this, void 0, void 0, function* () {
1084
+ return __awaiter(this, void 0, void 0, function* () {
1455
1085
  emitter.emit('request:start', request);
1456
1086
  // Perform bypassed requests (i.e. issued via "ctx.fetch") as-is.
1457
1087
  if (request.headers.get('x-msw-bypass')) {
@@ -1474,7 +1104,12 @@ function handleRequest(request, handlers, options, emitter, handleRequestOptions
1474
1104
  // When the handled request returned no mocked response, warn the developer,
1475
1105
  // as it may be an oversight on their part. Perform the request as-is.
1476
1106
  if (!response) {
1477
- devUtils.warn('Expected a mocking resolver function to return a mocked response Object, but got: %s. Original response is going to be used instead.', response);
1107
+ devUtils.warn(`\
1108
+ Expected response resolver to return a mocked response Object, but got %s. The original response is going to be used instead.\
1109
+ \n
1110
+ \u2022 %s
1111
+ %s\
1112
+ `, response, handler.info.header, handler.info.callFrame);
1478
1113
  emitter.emit('request:end', request);
1479
1114
  (_c = handleRequestOptions === null || handleRequestOptions === void 0 ? void 0 : handleRequestOptions.onBypassResponse) === null || _c === void 0 ? void 0 : _c.call(handleRequestOptions, request);
1480
1115
  return;
@@ -1499,7 +1134,7 @@ function handleRequest(request, handlers, options, emitter, handleRequestOptions
1499
1134
  }
1500
1135
 
1501
1136
  const createRequestListener = (context, options) => {
1502
- return (event, message) => __awaiter$3(void 0, void 0, void 0, function* () {
1137
+ return (event, message) => __awaiter(void 0, void 0, void 0, function* () {
1503
1138
  const channel = createBroadcastChannel(event);
1504
1139
  try {
1505
1140
  const request = parseWorkerRequest(message.payload);
@@ -1555,14 +1190,14 @@ const createRequestListener = (context, options) => {
1555
1190
  };
1556
1191
 
1557
1192
  function requestIntegrityCheck(context, serviceWorker) {
1558
- return __awaiter$3(this, void 0, void 0, function* () {
1193
+ return __awaiter(this, void 0, void 0, function* () {
1559
1194
  // Signal Service Worker to report back its integrity
1560
1195
  context.workerChannel.send('INTEGRITY_CHECK_REQUEST');
1561
1196
  const { payload: actualChecksum } = yield context.events.once('INTEGRITY_CHECK_RESPONSE');
1562
1197
  // Compare the response from the Service Worker and the
1563
1198
  // global variable set by Rollup during the build.
1564
- if (actualChecksum !== "f0a916b13c8acc2b526a03a6d26df85f") {
1565
- throw new Error(`Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"f0a916b13c8acc2b526a03a6d26df85f"}).`);
1199
+ if (actualChecksum !== "02f4ad4a2797f85668baf196e553d929") {
1200
+ throw new Error(`Currently active Service Worker (${actualChecksum}) is behind the latest published one (${"02f4ad4a2797f85668baf196e553d929"}).`);
1566
1201
  }
1567
1202
  return serviceWorker;
1568
1203
  });
@@ -1586,7 +1221,7 @@ function deferNetworkRequestsUntil(predicatePromise) {
1586
1221
  };
1587
1222
  // Defer any `fetch` requests until the Service Worker is ready.
1588
1223
  const originalFetch = window.fetch;
1589
- window.fetch = (...args) => __awaiter$3(this, void 0, void 0, function* () {
1224
+ window.fetch = (...args) => __awaiter(this, void 0, void 0, function* () {
1590
1225
  yield until(() => predicatePromise);
1591
1226
  window.fetch = originalFetch;
1592
1227
  return window.fetch(...args);
@@ -1631,7 +1266,7 @@ Cannot intercept requests on this page because it's outside of the worker's scop
1631
1266
 
1632
1267
  const createStartHandler = (context) => {
1633
1268
  return function start(options, customOptions) {
1634
- const startWorkerInstance = () => __awaiter$3(this, void 0, void 0, function* () {
1269
+ const startWorkerInstance = () => __awaiter(this, void 0, void 0, function* () {
1635
1270
  // Remove all previously existing event listeners.
1636
1271
  // This way none of the listeners persists between Fast refresh
1637
1272
  // of the application's code.
@@ -1762,3849 +1397,12 @@ function prepareStartHandler(handler, context) {
1762
1397
  };
1763
1398
  }
1764
1399
 
1765
- var lib = {};
1766
-
1767
- var createInterceptor$1 = {};
1768
-
1769
- Object.defineProperty(createInterceptor$1, "__esModule", { value: true });
1770
- createInterceptor$1.createInterceptor = void 0;
1771
- var strict_event_emitter_1$1 = lib$3;
1772
- function createInterceptor(options) {
1773
- var observer = new strict_event_emitter_1$1.StrictEventEmitter();
1774
- var cleanupFns = [];
1775
- return {
1776
- apply: function () {
1777
- cleanupFns = options.modules.map(function (interceptor) {
1778
- return interceptor(observer, options.resolver);
1779
- });
1780
- },
1781
- on: function (event, listener) {
1782
- observer.addListener(event, listener);
1783
- },
1784
- restore: function () {
1785
- observer.removeAllListeners();
1786
- if (cleanupFns.length === 0) {
1787
- throw new Error("Failed to restore patched modules: no patches found. Did you forget to run \".apply()\"?");
1788
- }
1789
- cleanupFns.forEach(function (restore) { return restore(); });
1790
- },
1791
- };
1792
- }
1793
- createInterceptor$1.createInterceptor = createInterceptor;
1794
-
1795
- var remote = {};
1796
-
1797
- var toIsoResponse$1 = {};
1798
-
1799
- Object.defineProperty(toIsoResponse$1, "__esModule", { value: true });
1800
- toIsoResponse$1.toIsoResponse = void 0;
1801
- var headers_utils_1$3 = lib$4;
1802
- /**
1803
- * Converts a given mocked response object into an isomorphic response.
1804
- */
1805
- function toIsoResponse(response) {
1806
- return {
1807
- status: response.status || 200,
1808
- statusText: response.statusText || 'OK',
1809
- headers: headers_utils_1$3.objectToHeaders(response.headers || {}),
1810
- body: response.body,
1811
- };
1812
- }
1813
- toIsoResponse$1.toIsoResponse = toIsoResponse;
1814
-
1815
- var __assign$1 = (commonjsGlobal && commonjsGlobal.__assign) || function () {
1816
- __assign$1 = Object.assign || function(t) {
1817
- for (var s, i = 1, n = arguments.length; i < n; i++) {
1818
- s = arguments[i];
1819
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
1820
- t[p] = s[p];
1821
- }
1822
- return t;
1823
- };
1824
- return __assign$1.apply(this, arguments);
1825
- };
1826
- var __awaiter$2 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
1827
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
1828
- return new (P || (P = Promise))(function (resolve, reject) {
1829
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
1830
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
1831
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
1832
- step((generator = generator.apply(thisArg, _arguments || [])).next());
1833
- });
1834
- };
1835
- var __generator$2 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
1836
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
1837
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
1838
- function verb(n) { return function (v) { return step([n, v]); }; }
1839
- function step(op) {
1840
- if (f) throw new TypeError("Generator is already executing.");
1841
- while (_) try {
1842
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
1843
- if (y = 0, t) op = [op[0] & 2, t.value];
1844
- switch (op[0]) {
1845
- case 0: case 1: t = op; break;
1846
- case 4: _.label++; return { value: op[1], done: false };
1847
- case 5: _.label++; y = op[1]; op = [0]; continue;
1848
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
1849
- default:
1850
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
1851
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
1852
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
1853
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
1854
- if (t[2]) _.ops.pop();
1855
- _.trys.pop(); continue;
1856
- }
1857
- op = body.call(thisArg, _);
1858
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
1859
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
1860
- }
1861
- };
1862
- var __read$1 = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
1863
- var m = typeof Symbol === "function" && o[Symbol.iterator];
1864
- if (!m) return o;
1865
- var i = m.call(o), r, ar = [], e;
1866
- try {
1867
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
1868
- }
1869
- catch (error) { e = { error: error }; }
1870
- finally {
1871
- try {
1872
- if (r && !r.done && (m = i["return"])) m.call(i);
1873
- }
1874
- finally { if (e) throw e.error; }
1875
- }
1876
- return ar;
1877
- };
1878
- Object.defineProperty(remote, "__esModule", { value: true });
1879
- remote.createRemoteResolver = remote.createRemoteInterceptor = void 0;
1880
- var headers_utils_1$2 = lib$4;
1881
- var outvariant_1 = lib$5;
1882
- var strict_event_emitter_1 = lib$3;
1883
- var createInterceptor_1 = createInterceptor$1;
1884
- var toIsoResponse_1$2 = toIsoResponse$1;
1885
- function requestReviver(key, value) {
1886
- switch (key) {
1887
- case 'url':
1888
- return new URL(value);
1889
- case 'headers':
1890
- return new headers_utils_1$2.Headers(value);
1891
- default:
1892
- return value;
1893
- }
1894
- }
1895
- /**
1896
- * Creates a remote request interceptor that delegates
1897
- * the mocked response resolution to the parent process.
1898
- * The parent process must establish a remote resolver
1899
- * by calling `createRemoteResolver` function.
1900
- */
1901
- function createRemoteInterceptor(options) {
1902
- outvariant_1.invariant(process.connected, "Failed to create a remote interceptor: the current process (%s) does not have a parent. Please make sure you're spawning this process as a child process in order to use remote request interception.", process.pid);
1903
- if (typeof process.send === 'undefined') {
1904
- throw new Error("Failed to create a remote interceptor: the current process (" + process.pid + ") does not have the IPC enabled. Please make sure you're spawning this process with the \"ipc\" stdio value set:\n\nspawn('node', ['module.js'], { stdio: ['ipc'] })");
1905
- }
1906
- var handleParentMessage;
1907
- var interceptor = createInterceptor_1.createInterceptor(__assign$1(__assign$1({}, options), { resolver: function (request) {
1908
- var _a;
1909
- var serializedRequest = JSON.stringify(request);
1910
- (_a = process.send) === null || _a === void 0 ? void 0 : _a.call(process, "request:" + serializedRequest);
1911
- return new Promise(function (resolve) {
1912
- handleParentMessage = function (message) {
1913
- if (typeof message !== 'string') {
1914
- return;
1915
- }
1916
- if (message.startsWith("response:" + request.id)) {
1917
- var _a = __read$1(message.match(/^response:.+?:(.+)$/) || [], 2), responseString = _a[1];
1918
- if (!responseString) {
1919
- return resolve();
1920
- }
1921
- var mockedResponse = JSON.parse(responseString);
1922
- return resolve(mockedResponse);
1923
- }
1924
- };
1925
- process.addListener('message', handleParentMessage);
1926
- });
1927
- } }));
1928
- return __assign$1(__assign$1({}, interceptor), { restore: function () {
1929
- interceptor.restore();
1930
- process.removeListener('message', handleParentMessage);
1931
- } });
1932
- }
1933
- remote.createRemoteInterceptor = createRemoteInterceptor;
1934
- /**
1935
- * Creates a response resolver function attached to the given `ChildProcess`.
1936
- * The child process must establish a remote interceptor by calling `createRemoteInterceptor` function.
1937
- */
1938
- function createRemoteResolver(options) {
1939
- var _this = this;
1940
- var observer = new strict_event_emitter_1.StrictEventEmitter();
1941
- var handleChildMessage = function (message) { return __awaiter$2(_this, void 0, void 0, function () {
1942
- var _a, requestString, isoRequest_1, mockedResponse_1, serializedResponse;
1943
- return __generator$2(this, function (_b) {
1944
- switch (_b.label) {
1945
- case 0:
1946
- if (typeof message !== 'string') {
1947
- return [2 /*return*/];
1948
- }
1949
- if (!message.startsWith('request:')) return [3 /*break*/, 2];
1950
- _a = __read$1(message.match(/^request:(.+)$/) || [], 2), requestString = _a[1];
1951
- if (!requestString) {
1952
- return [2 /*return*/];
1953
- }
1954
- isoRequest_1 = JSON.parse(requestString, requestReviver);
1955
- observer.emit('request', isoRequest_1);
1956
- return [4 /*yield*/, options.resolver(isoRequest_1, undefined)
1957
- // Send the mocked response to the child process.
1958
- ];
1959
- case 1:
1960
- mockedResponse_1 = _b.sent();
1961
- serializedResponse = JSON.stringify(mockedResponse_1);
1962
- options.process.send("response:" + isoRequest_1.id + ":" + serializedResponse, function (error) {
1963
- if (error) {
1964
- return;
1965
- }
1966
- if (mockedResponse_1) {
1967
- // Emit an optimisting "response" event at this point,
1968
- // not to rely on the back-and-forth signaling for the sake of the event.
1969
- observer.emit('response', isoRequest_1, toIsoResponse_1$2.toIsoResponse(mockedResponse_1));
1970
- }
1971
- });
1972
- _b.label = 2;
1973
- case 2: return [2 /*return*/];
1974
- }
1975
- });
1976
- }); };
1977
- var cleanup = function () {
1978
- options.process.removeListener('message', handleChildMessage);
1979
- };
1980
- options.process.addListener('message', handleChildMessage);
1981
- options.process.addListener('disconnect', cleanup);
1982
- options.process.addListener('error', cleanup);
1983
- options.process.addListener('exit', cleanup);
1984
- return {
1985
- on: function (event, listener) {
1986
- observer.addListener(event, listener);
1987
- },
1988
- };
1989
- }
1990
- remote.createRemoteResolver = createRemoteResolver;
1991
-
1992
- (function (exports) {
1993
- var __createBinding = (commonjsGlobal && commonjsGlobal.__createBinding) || (Object.create ? (function(o, m, k, k2) {
1994
- if (k2 === undefined) k2 = k;
1995
- Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
1996
- }) : (function(o, m, k, k2) {
1997
- if (k2 === undefined) k2 = k;
1998
- o[k2] = m[k];
1999
- }));
2000
- var __exportStar = (commonjsGlobal && commonjsGlobal.__exportStar) || function(m, exports) {
2001
- for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
2002
- };
2003
- Object.defineProperty(exports, "__esModule", { value: true });
2004
- exports.getCleanUrl = void 0;
2005
- __exportStar(createInterceptor$1, exports);
2006
- __exportStar(remote, exports);
2007
- /* Utils */
2008
- var getCleanUrl_1 = getCleanUrl;
2009
- Object.defineProperty(exports, "getCleanUrl", { enumerable: true, get: function () { return getCleanUrl_1.getCleanUrl; } });
2010
-
2011
- }(lib));
2012
-
2013
- var fetch = {};
2014
-
2015
- var uuid = {};
2016
-
2017
- Object.defineProperty(uuid, "__esModule", { value: true });
2018
- uuid.uuidv4 = void 0;
2019
- function uuidv4$1() {
2020
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
2021
- var r = (Math.random() * 16) | 0;
2022
- var v = c == 'x' ? r : (r & 0x3) | 0x8;
2023
- return v.toString(16);
2024
- });
2025
- }
2026
- uuid.uuidv4 = uuidv4$1;
2027
-
2028
- var __assign = (commonjsGlobal && commonjsGlobal.__assign) || function () {
2029
- __assign = Object.assign || function(t) {
2030
- for (var s, i = 1, n = arguments.length; i < n; i++) {
2031
- s = arguments[i];
2032
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
2033
- t[p] = s[p];
2034
- }
2035
- return t;
2036
- };
2037
- return __assign.apply(this, arguments);
2038
- };
2039
- var __awaiter$1 = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
2040
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
2041
- return new (P || (P = Promise))(function (resolve, reject) {
2042
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
2043
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
2044
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
2045
- step((generator = generator.apply(thisArg, _arguments || [])).next());
2046
- });
2047
- };
2048
- var __generator$1 = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
2049
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
2050
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
2051
- function verb(n) { return function (v) { return step([n, v]); }; }
2052
- function step(op) {
2053
- if (f) throw new TypeError("Generator is already executing.");
2054
- while (_) try {
2055
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
2056
- if (y = 0, t) op = [op[0] & 2, t.value];
2057
- switch (op[0]) {
2058
- case 0: case 1: t = op; break;
2059
- case 4: _.label++; return { value: op[1], done: false };
2060
- case 5: _.label++; y = op[1]; op = [0]; continue;
2061
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
2062
- default:
2063
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
2064
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
2065
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
2066
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
2067
- if (t[2]) _.ops.pop();
2068
- _.trys.pop(); continue;
2069
- }
2070
- op = body.call(thisArg, _);
2071
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
2072
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
2073
- }
2074
- };
2075
- Object.defineProperty(fetch, "__esModule", { value: true });
2076
- var interceptFetch_1 = fetch.interceptFetch = void 0;
2077
- var headers_utils_1$1 = lib$4;
2078
- var toIsoResponse_1$1 = toIsoResponse$1;
2079
- var uuid_1$1 = uuid;
2080
- var debug$1 = require$$3('fetch');
2081
- var interceptFetch = function (observer, resolver) {
2082
- var pureFetch = window.fetch;
2083
- debug$1('replacing "window.fetch"...');
2084
- window.fetch = function (input, init) { return __awaiter$1(void 0, void 0, void 0, function () {
2085
- var ref, url, method, isoRequest, response, isomorphicResponse;
2086
- var _a;
2087
- return __generator$1(this, function (_b) {
2088
- switch (_b.label) {
2089
- case 0:
2090
- ref = new Request(input, init);
2091
- url = typeof input === 'string' ? input : input.url;
2092
- method = (init === null || init === void 0 ? void 0 : init.method) || 'GET';
2093
- debug$1('[%s] %s', method, url);
2094
- _a = {
2095
- id: uuid_1$1.uuidv4(),
2096
- url: new URL(url, location.origin),
2097
- method: method,
2098
- headers: new headers_utils_1$1.Headers((init === null || init === void 0 ? void 0 : init.headers) || {})
2099
- };
2100
- return [4 /*yield*/, ref.text()];
2101
- case 1:
2102
- isoRequest = (_a.body = _b.sent(),
2103
- _a);
2104
- debug$1('isomorphic request', isoRequest);
2105
- observer.emit('request', isoRequest);
2106
- debug$1('awaiting for the mocked response...');
2107
- return [4 /*yield*/, resolver(isoRequest, ref)];
2108
- case 2:
2109
- response = _b.sent();
2110
- debug$1('mocked response', response);
2111
- if (response) {
2112
- isomorphicResponse = toIsoResponse_1$1.toIsoResponse(response);
2113
- debug$1('derived isomorphic response', isomorphicResponse);
2114
- observer.emit('response', isoRequest, isomorphicResponse);
2115
- return [2 /*return*/, new Response(response.body, __assign(__assign({}, isomorphicResponse), {
2116
- // `Response.headers` cannot be instantiated with the `Headers` polyfill.
2117
- // Apparently, it halts if the `Headers` class contains unknown properties
2118
- // (i.e. the internal `Headers.map`).
2119
- headers: headers_utils_1$1.flattenHeadersObject(response.headers || {}) }))];
2120
- }
2121
- debug$1('no mocked response found, bypassing...');
2122
- return [2 /*return*/, pureFetch(input, init).then(function (response) { return __awaiter$1(void 0, void 0, void 0, function () {
2123
- var _a, _b, _c;
2124
- return __generator$1(this, function (_d) {
2125
- switch (_d.label) {
2126
- case 0:
2127
- debug$1('original fetch performed', response);
2128
- _b = (_a = observer).emit;
2129
- _c = ['response',
2130
- isoRequest];
2131
- return [4 /*yield*/, normalizeFetchResponse(response)];
2132
- case 1:
2133
- _b.apply(_a, _c.concat([_d.sent()]));
2134
- return [2 /*return*/, response];
2135
- }
2136
- });
2137
- }); })];
2138
- }
2139
- });
2140
- }); };
2141
- return function () {
2142
- debug$1('restoring modules...');
2143
- window.fetch = pureFetch;
2144
- };
2145
- };
2146
- interceptFetch_1 = fetch.interceptFetch = interceptFetch;
2147
- function normalizeFetchResponse(response) {
2148
- return __awaiter$1(this, void 0, void 0, function () {
2149
- var _a;
2150
- return __generator$1(this, function (_b) {
2151
- switch (_b.label) {
2152
- case 0:
2153
- _a = {
2154
- status: response.status,
2155
- statusText: response.statusText,
2156
- headers: headers_utils_1$1.objectToHeaders(headers_utils_1$1.headersToObject(response.headers))
2157
- };
2158
- return [4 /*yield*/, response.text()];
2159
- case 1: return [2 /*return*/, (_a.body = _b.sent(),
2160
- _a)];
2161
- }
2162
- });
2163
- });
2164
- }
2165
-
2166
- var XMLHttpRequest = {};
2167
-
2168
- var XMLHttpRequestOverride = {};
2169
-
2170
- var domParser = {};
2171
-
2172
- var conventions$2 = {};
2173
-
2174
- /**
2175
- * "Shallow freezes" an object to render it immutable.
2176
- * Uses `Object.freeze` if available,
2177
- * otherwise the immutability is only in the type.
2178
- *
2179
- * Is used to create "enum like" objects.
2180
- *
2181
- * @template T
2182
- * @param {T} object the object to freeze
2183
- * @param {Pick<ObjectConstructor, 'freeze'> = Object} oc `Object` by default,
2184
- * allows to inject custom object constructor for tests
2185
- * @returns {Readonly<T>}
2186
- *
2187
- * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze
2188
- */
2189
- function freeze(object, oc) {
2190
- if (oc === undefined) {
2191
- oc = Object;
2192
- }
2193
- return oc && typeof oc.freeze === 'function' ? oc.freeze(object) : object
2194
- }
2195
-
2196
- /**
2197
- * All mime types that are allowed as input to `DOMParser.parseFromString`
2198
- *
2199
- * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02 MDN
2200
- * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#domparsersupportedtype WHATWG HTML Spec
2201
- * @see DOMParser.prototype.parseFromString
2202
- */
2203
- var MIME_TYPE = freeze({
2204
- /**
2205
- * `text/html`, the only mime type that triggers treating an XML document as HTML.
2206
- *
2207
- * @see DOMParser.SupportedType.isHTML
2208
- * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
2209
- * @see https://en.wikipedia.org/wiki/HTML Wikipedia
2210
- * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
2211
- * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring WHATWG HTML Spec
2212
- */
2213
- HTML: 'text/html',
2214
-
2215
- /**
2216
- * Helper method to check a mime type if it indicates an HTML document
2217
- *
2218
- * @param {string} [value]
2219
- * @returns {boolean}
2220
- *
2221
- * @see https://www.iana.org/assignments/media-types/text/html IANA MimeType registration
2222
- * @see https://en.wikipedia.org/wiki/HTML Wikipedia
2223
- * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString MDN
2224
- * @see https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-domparser-parsefromstring */
2225
- isHTML: function (value) {
2226
- return value === MIME_TYPE.HTML
2227
- },
2228
-
2229
- /**
2230
- * `application/xml`, the standard mime type for XML documents.
2231
- *
2232
- * @see https://www.iana.org/assignments/media-types/application/xml IANA MimeType registration
2233
- * @see https://tools.ietf.org/html/rfc7303#section-9.1 RFC 7303
2234
- * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
2235
- */
2236
- XML_APPLICATION: 'application/xml',
2237
-
2238
- /**
2239
- * `text/html`, an alias for `application/xml`.
2240
- *
2241
- * @see https://tools.ietf.org/html/rfc7303#section-9.2 RFC 7303
2242
- * @see https://www.iana.org/assignments/media-types/text/xml IANA MimeType registration
2243
- * @see https://en.wikipedia.org/wiki/XML_and_MIME Wikipedia
2244
- */
2245
- XML_TEXT: 'text/xml',
2246
-
2247
- /**
2248
- * `application/xhtml+xml`, indicates an XML document that has the default HTML namespace,
2249
- * but is parsed as an XML document.
2250
- *
2251
- * @see https://www.iana.org/assignments/media-types/application/xhtml+xml IANA MimeType registration
2252
- * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument WHATWG DOM Spec
2253
- * @see https://en.wikipedia.org/wiki/XHTML Wikipedia
2254
- */
2255
- XML_XHTML_APPLICATION: 'application/xhtml+xml',
2256
-
2257
- /**
2258
- * `image/svg+xml`,
2259
- *
2260
- * @see https://www.iana.org/assignments/media-types/image/svg+xml IANA MimeType registration
2261
- * @see https://www.w3.org/TR/SVG11/ W3C SVG 1.1
2262
- * @see https://en.wikipedia.org/wiki/Scalable_Vector_Graphics Wikipedia
2263
- */
2264
- XML_SVG_IMAGE: 'image/svg+xml',
2265
- });
2266
-
2267
- /**
2268
- * Namespaces that are used in this code base.
2269
- *
2270
- * @see http://www.w3.org/TR/REC-xml-names
2271
- */
2272
- var NAMESPACE$3 = freeze({
2273
- /**
2274
- * The XHTML namespace.
2275
- *
2276
- * @see http://www.w3.org/1999/xhtml
2277
- */
2278
- HTML: 'http://www.w3.org/1999/xhtml',
2279
-
2280
- /**
2281
- * Checks if `uri` equals `NAMESPACE.HTML`.
2282
- *
2283
- * @param {string} [uri]
2284
- *
2285
- * @see NAMESPACE.HTML
2286
- */
2287
- isHTML: function (uri) {
2288
- return uri === NAMESPACE$3.HTML
2289
- },
2290
-
2291
- /**
2292
- * The SVG namespace.
2293
- *
2294
- * @see http://www.w3.org/2000/svg
2295
- */
2296
- SVG: 'http://www.w3.org/2000/svg',
2297
-
2298
- /**
2299
- * The `xml:` namespace.
2300
- *
2301
- * @see http://www.w3.org/XML/1998/namespace
2302
- */
2303
- XML: 'http://www.w3.org/XML/1998/namespace',
2304
-
2305
- /**
2306
- * The `xmlns:` namespace
2307
- *
2308
- * @see https://www.w3.org/2000/xmlns/
2309
- */
2310
- XMLNS: 'http://www.w3.org/2000/xmlns/',
2311
- });
2312
-
2313
- conventions$2.freeze = freeze;
2314
- conventions$2.MIME_TYPE = MIME_TYPE;
2315
- conventions$2.NAMESPACE = NAMESPACE$3;
2316
-
2317
- var entities$1 = {};
2318
-
2319
- (function (exports) {
2320
- var freeze = conventions$2.freeze;
2321
-
2322
- /**
2323
- * The entities that are predefined in every XML document.
2324
- *
2325
- * @see https://www.w3.org/TR/2006/REC-xml11-20060816/#sec-predefined-ent W3C XML 1.1
2326
- * @see https://www.w3.org/TR/2008/REC-xml-20081126/#sec-predefined-ent W3C XML 1.0
2327
- * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Predefined_entities_in_XML Wikipedia
2328
- */
2329
- exports.XML_ENTITIES = freeze({amp:'&', apos:"'", gt:'>', lt:'<', quot:'"'});
2330
-
2331
- /**
2332
- * A map of currently 241 entities that are detected in an HTML document.
2333
- * They contain all entries from `XML_ENTITIES`.
2334
- *
2335
- * @see XML_ENTITIES
2336
- * @see DOMParser.parseFromString
2337
- * @see DOMImplementation.prototype.createHTMLDocument
2338
- * @see https://html.spec.whatwg.org/#named-character-references WHATWG HTML(5) Spec
2339
- * @see https://www.w3.org/TR/xml-entity-names/ W3C XML Entity Names
2340
- * @see https://www.w3.org/TR/html4/sgml/entities.html W3C HTML4/SGML
2341
- * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Character_entity_references_in_HTML Wikipedia (HTML)
2342
- * @see https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references#Entities_representing_special_characters_in_XHTML Wikpedia (XHTML)
2343
- */
2344
- exports.HTML_ENTITIES = freeze({
2345
- lt: '<',
2346
- gt: '>',
2347
- amp: '&',
2348
- quot: '"',
2349
- apos: "'",
2350
- Agrave: "À",
2351
- Aacute: "Á",
2352
- Acirc: "Â",
2353
- Atilde: "Ã",
2354
- Auml: "Ä",
2355
- Aring: "Å",
2356
- AElig: "Æ",
2357
- Ccedil: "Ç",
2358
- Egrave: "È",
2359
- Eacute: "É",
2360
- Ecirc: "Ê",
2361
- Euml: "Ë",
2362
- Igrave: "Ì",
2363
- Iacute: "Í",
2364
- Icirc: "Î",
2365
- Iuml: "Ï",
2366
- ETH: "Ð",
2367
- Ntilde: "Ñ",
2368
- Ograve: "Ò",
2369
- Oacute: "Ó",
2370
- Ocirc: "Ô",
2371
- Otilde: "Õ",
2372
- Ouml: "Ö",
2373
- Oslash: "Ø",
2374
- Ugrave: "Ù",
2375
- Uacute: "Ú",
2376
- Ucirc: "Û",
2377
- Uuml: "Ü",
2378
- Yacute: "Ý",
2379
- THORN: "Þ",
2380
- szlig: "ß",
2381
- agrave: "à",
2382
- aacute: "á",
2383
- acirc: "â",
2384
- atilde: "ã",
2385
- auml: "ä",
2386
- aring: "å",
2387
- aelig: "æ",
2388
- ccedil: "ç",
2389
- egrave: "è",
2390
- eacute: "é",
2391
- ecirc: "ê",
2392
- euml: "ë",
2393
- igrave: "ì",
2394
- iacute: "í",
2395
- icirc: "î",
2396
- iuml: "ï",
2397
- eth: "ð",
2398
- ntilde: "ñ",
2399
- ograve: "ò",
2400
- oacute: "ó",
2401
- ocirc: "ô",
2402
- otilde: "õ",
2403
- ouml: "ö",
2404
- oslash: "ø",
2405
- ugrave: "ù",
2406
- uacute: "ú",
2407
- ucirc: "û",
2408
- uuml: "ü",
2409
- yacute: "ý",
2410
- thorn: "þ",
2411
- yuml: "ÿ",
2412
- nbsp: "\u00a0",
2413
- iexcl: "¡",
2414
- cent: "¢",
2415
- pound: "£",
2416
- curren: "¤",
2417
- yen: "¥",
2418
- brvbar: "¦",
2419
- sect: "§",
2420
- uml: "¨",
2421
- copy: "©",
2422
- ordf: "ª",
2423
- laquo: "«",
2424
- not: "¬",
2425
- shy: "­­",
2426
- reg: "®",
2427
- macr: "¯",
2428
- deg: "°",
2429
- plusmn: "±",
2430
- sup2: "²",
2431
- sup3: "³",
2432
- acute: "´",
2433
- micro: "µ",
2434
- para: "¶",
2435
- middot: "·",
2436
- cedil: "¸",
2437
- sup1: "¹",
2438
- ordm: "º",
2439
- raquo: "»",
2440
- frac14: "¼",
2441
- frac12: "½",
2442
- frac34: "¾",
2443
- iquest: "¿",
2444
- times: "×",
2445
- divide: "÷",
2446
- forall: "∀",
2447
- part: "∂",
2448
- exist: "∃",
2449
- empty: "∅",
2450
- nabla: "∇",
2451
- isin: "∈",
2452
- notin: "∉",
2453
- ni: "∋",
2454
- prod: "∏",
2455
- sum: "∑",
2456
- minus: "−",
2457
- lowast: "∗",
2458
- radic: "√",
2459
- prop: "∝",
2460
- infin: "∞",
2461
- ang: "∠",
2462
- and: "∧",
2463
- or: "∨",
2464
- cap: "∩",
2465
- cup: "∪",
2466
- 'int': "∫",
2467
- there4: "∴",
2468
- sim: "∼",
2469
- cong: "≅",
2470
- asymp: "≈",
2471
- ne: "≠",
2472
- equiv: "≡",
2473
- le: "≤",
2474
- ge: "≥",
2475
- sub: "⊂",
2476
- sup: "⊃",
2477
- nsub: "⊄",
2478
- sube: "⊆",
2479
- supe: "⊇",
2480
- oplus: "⊕",
2481
- otimes: "⊗",
2482
- perp: "⊥",
2483
- sdot: "⋅",
2484
- Alpha: "Α",
2485
- Beta: "Β",
2486
- Gamma: "Γ",
2487
- Delta: "Δ",
2488
- Epsilon: "Ε",
2489
- Zeta: "Ζ",
2490
- Eta: "Η",
2491
- Theta: "Θ",
2492
- Iota: "Ι",
2493
- Kappa: "Κ",
2494
- Lambda: "Λ",
2495
- Mu: "Μ",
2496
- Nu: "Ν",
2497
- Xi: "Ξ",
2498
- Omicron: "Ο",
2499
- Pi: "Π",
2500
- Rho: "Ρ",
2501
- Sigma: "Σ",
2502
- Tau: "Τ",
2503
- Upsilon: "Υ",
2504
- Phi: "Φ",
2505
- Chi: "Χ",
2506
- Psi: "Ψ",
2507
- Omega: "Ω",
2508
- alpha: "α",
2509
- beta: "β",
2510
- gamma: "γ",
2511
- delta: "δ",
2512
- epsilon: "ε",
2513
- zeta: "ζ",
2514
- eta: "η",
2515
- theta: "θ",
2516
- iota: "ι",
2517
- kappa: "κ",
2518
- lambda: "λ",
2519
- mu: "μ",
2520
- nu: "ν",
2521
- xi: "ξ",
2522
- omicron: "ο",
2523
- pi: "π",
2524
- rho: "ρ",
2525
- sigmaf: "ς",
2526
- sigma: "σ",
2527
- tau: "τ",
2528
- upsilon: "υ",
2529
- phi: "φ",
2530
- chi: "χ",
2531
- psi: "ψ",
2532
- omega: "ω",
2533
- thetasym: "ϑ",
2534
- upsih: "ϒ",
2535
- piv: "ϖ",
2536
- OElig: "Œ",
2537
- oelig: "œ",
2538
- Scaron: "Š",
2539
- scaron: "š",
2540
- Yuml: "Ÿ",
2541
- fnof: "ƒ",
2542
- circ: "ˆ",
2543
- tilde: "˜",
2544
- ensp: " ",
2545
- emsp: " ",
2546
- thinsp: " ",
2547
- zwnj: "‌",
2548
- zwj: "‍",
2549
- lrm: "‎",
2550
- rlm: "‏",
2551
- ndash: "–",
2552
- mdash: "—",
2553
- lsquo: "‘",
2554
- rsquo: "’",
2555
- sbquo: "‚",
2556
- ldquo: "“",
2557
- rdquo: "”",
2558
- bdquo: "„",
2559
- dagger: "†",
2560
- Dagger: "‡",
2561
- bull: "•",
2562
- hellip: "…",
2563
- permil: "‰",
2564
- prime: "′",
2565
- Prime: "″",
2566
- lsaquo: "‹",
2567
- rsaquo: "›",
2568
- oline: "‾",
2569
- euro: "€",
2570
- trade: "™",
2571
- larr: "←",
2572
- uarr: "↑",
2573
- rarr: "→",
2574
- darr: "↓",
2575
- harr: "↔",
2576
- crarr: "↵",
2577
- lceil: "⌈",
2578
- rceil: "⌉",
2579
- lfloor: "⌊",
2580
- rfloor: "⌋",
2581
- loz: "◊",
2582
- spades: "♠",
2583
- clubs: "♣",
2584
- hearts: "♥",
2585
- diams: "♦"
2586
- });
2587
-
2588
- /**
2589
- * @deprecated use `HTML_ENTITIES` instead
2590
- * @see HTML_ENTITIES
2591
- */
2592
- exports.entityMap = exports.HTML_ENTITIES;
2593
- }(entities$1));
2594
-
2595
- var sax$1 = {};
2596
-
2597
- var NAMESPACE$2 = conventions$2.NAMESPACE;
2598
-
2599
- //[4] NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] | [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] | [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] | [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] | [#x10000-#xEFFFF]
2600
- //[4a] NameChar ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] | [#x203F-#x2040]
2601
- //[5] Name ::= NameStartChar (NameChar)*
2602
- var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/;//\u10000-\uEFFFF
2603
- var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\\u00B7\\u0300-\\u036F\\u203F-\\u2040]");
2604
- var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$');
2605
- //var tagNamePattern = /^[a-zA-Z_][\w\-\.]*(?:\:[a-zA-Z_][\w\-\.]*)?$/
2606
- //var handlers = 'resolveEntity,getExternalSubset,characters,endDocument,endElement,endPrefixMapping,ignorableWhitespace,processingInstruction,setDocumentLocator,skippedEntity,startDocument,startElement,startPrefixMapping,notationDecl,unparsedEntityDecl,error,fatalError,warning,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,comment,endCDATA,endDTD,endEntity,startCDATA,startDTD,startEntity'.split(',')
2607
-
2608
- //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
2609
- //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
2610
- var S_TAG = 0;//tag name offerring
2611
- var S_ATTR = 1;//attr name offerring
2612
- var S_ATTR_SPACE=2;//attr name end and space offer
2613
- var S_EQ = 3;//=space?
2614
- var S_ATTR_NOQUOT_VALUE = 4;//attr value(no quot value only)
2615
- var S_ATTR_END = 5;//attr value end and no space(quot end)
2616
- var S_TAG_SPACE = 6;//(attr value end || tag end ) && (space offer)
2617
- var S_TAG_CLOSE = 7;//closed el<el />
2618
-
2619
- /**
2620
- * Creates an error that will not be caught by XMLReader aka the SAX parser.
2621
- *
2622
- * @param {string} message
2623
- * @param {any?} locator Optional, can provide details about the location in the source
2624
- * @constructor
2625
- */
2626
- function ParseError$1(message, locator) {
2627
- this.message = message;
2628
- this.locator = locator;
2629
- if(Error.captureStackTrace) Error.captureStackTrace(this, ParseError$1);
2630
- }
2631
- ParseError$1.prototype = new Error();
2632
- ParseError$1.prototype.name = ParseError$1.name;
2633
-
2634
- function XMLReader$1(){
2635
-
2636
- }
2637
-
2638
- XMLReader$1.prototype = {
2639
- parse:function(source,defaultNSMap,entityMap){
2640
- var domBuilder = this.domBuilder;
2641
- domBuilder.startDocument();
2642
- _copy(defaultNSMap ,defaultNSMap = {});
2643
- parse(source,defaultNSMap,entityMap,
2644
- domBuilder,this.errorHandler);
2645
- domBuilder.endDocument();
2646
- }
2647
- };
2648
- function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){
2649
- function fixedFromCharCode(code) {
2650
- // String.prototype.fromCharCode does not supports
2651
- // > 2 bytes unicode chars directly
2652
- if (code > 0xffff) {
2653
- code -= 0x10000;
2654
- var surrogate1 = 0xd800 + (code >> 10)
2655
- , surrogate2 = 0xdc00 + (code & 0x3ff);
2656
-
2657
- return String.fromCharCode(surrogate1, surrogate2);
2658
- } else {
2659
- return String.fromCharCode(code);
2660
- }
2661
- }
2662
- function entityReplacer(a){
2663
- var k = a.slice(1,-1);
2664
- if(k in entityMap){
2665
- return entityMap[k];
2666
- }else if(k.charAt(0) === '#'){
2667
- return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x')))
2668
- }else {
2669
- errorHandler.error('entity not found:'+a);
2670
- return a;
2671
- }
2672
- }
2673
- function appendText(end){//has some bugs
2674
- if(end>start){
2675
- var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer);
2676
- locator&&position(start);
2677
- domBuilder.characters(xt,0,end-start);
2678
- start = end;
2679
- }
2680
- }
2681
- function position(p,m){
2682
- while(p>=lineEnd && (m = linePattern.exec(source))){
2683
- lineStart = m.index;
2684
- lineEnd = lineStart + m[0].length;
2685
- locator.lineNumber++;
2686
- //console.log('line++:',locator,startPos,endPos)
2687
- }
2688
- locator.columnNumber = p-lineStart+1;
2689
- }
2690
- var lineStart = 0;
2691
- var lineEnd = 0;
2692
- var linePattern = /.*(?:\r\n?|\n)|.*$/g;
2693
- var locator = domBuilder.locator;
2694
-
2695
- var parseStack = [{currentNSMap:defaultNSMapCopy}];
2696
- var closeMap = {};
2697
- var start = 0;
2698
- while(true){
2699
- try{
2700
- var tagStart = source.indexOf('<',start);
2701
- if(tagStart<0){
2702
- if(!source.substr(start).match(/^\s*$/)){
2703
- var doc = domBuilder.doc;
2704
- var text = doc.createTextNode(source.substr(start));
2705
- doc.appendChild(text);
2706
- domBuilder.currentElement = text;
2707
- }
2708
- return;
2709
- }
2710
- if(tagStart>start){
2711
- appendText(tagStart);
2712
- }
2713
- switch(source.charAt(tagStart+1)){
2714
- case '/':
2715
- var end = source.indexOf('>',tagStart+3);
2716
- var tagName = source.substring(tagStart + 2, end).replace(/[ \t\n\r]+$/g, '');
2717
- var config = parseStack.pop();
2718
- if(end<0){
2719
-
2720
- tagName = source.substring(tagStart+2).replace(/[\s<].*/,'');
2721
- errorHandler.error("end tag name: "+tagName+' is not complete:'+config.tagName);
2722
- end = tagStart+1+tagName.length;
2723
- }else if(tagName.match(/\s</)){
2724
- tagName = tagName.replace(/[\s<].*/,'');
2725
- errorHandler.error("end tag name: "+tagName+' maybe not complete');
2726
- end = tagStart+1+tagName.length;
2727
- }
2728
- var localNSMap = config.localNSMap;
2729
- var endMatch = config.tagName == tagName;
2730
- var endIgnoreCaseMach = endMatch || config.tagName&&config.tagName.toLowerCase() == tagName.toLowerCase();
2731
- if(endIgnoreCaseMach){
2732
- domBuilder.endElement(config.uri,config.localName,tagName);
2733
- if(localNSMap){
2734
- for(var prefix in localNSMap){
2735
- domBuilder.endPrefixMapping(prefix) ;
2736
- }
2737
- }
2738
- if(!endMatch){
2739
- errorHandler.fatalError("end tag name: "+tagName+' is not match the current start tagName:'+config.tagName ); // No known test case
2740
- }
2741
- }else {
2742
- parseStack.push(config);
2743
- }
2744
-
2745
- end++;
2746
- break;
2747
- // end elment
2748
- case '?':// <?...?>
2749
- locator&&position(tagStart);
2750
- end = parseInstruction(source,tagStart,domBuilder);
2751
- break;
2752
- case '!':// <!doctype,<![CDATA,<!--
2753
- locator&&position(tagStart);
2754
- end = parseDCC(source,tagStart,domBuilder,errorHandler);
2755
- break;
2756
- default:
2757
- locator&&position(tagStart);
2758
- var el = new ElementAttributes();
2759
- var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
2760
- //elStartEnd
2761
- var end = parseElementStartPart(source,tagStart,el,currentNSMap,entityReplacer,errorHandler);
2762
- var len = el.length;
2763
-
2764
-
2765
- if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){
2766
- el.closed = true;
2767
- if(!entityMap.nbsp){
2768
- errorHandler.warning('unclosed xml attribute');
2769
- }
2770
- }
2771
- if(locator && len){
2772
- var locator2 = copyLocator(locator,{});
2773
- //try{//attribute position fixed
2774
- for(var i = 0;i<len;i++){
2775
- var a = el[i];
2776
- position(a.offset);
2777
- a.locator = copyLocator(locator,{});
2778
- }
2779
- domBuilder.locator = locator2;
2780
- if(appendElement$1(el,domBuilder,currentNSMap)){
2781
- parseStack.push(el);
2782
- }
2783
- domBuilder.locator = locator;
2784
- }else {
2785
- if(appendElement$1(el,domBuilder,currentNSMap)){
2786
- parseStack.push(el);
2787
- }
2788
- }
2789
-
2790
- if (NAMESPACE$2.isHTML(el.uri) && !el.closed) {
2791
- end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder);
2792
- } else {
2793
- end++;
2794
- }
2795
- }
2796
- }catch(e){
2797
- if (e instanceof ParseError$1) {
2798
- throw e;
2799
- }
2800
- errorHandler.error('element parse error: '+e);
2801
- end = -1;
2802
- }
2803
- if(end>start){
2804
- start = end;
2805
- }else {
2806
- //TODO: 这里有可能sax回退,有位置错误风险
2807
- appendText(Math.max(tagStart,start)+1);
2808
- }
2809
- }
2810
- }
2811
- function copyLocator(f,t){
2812
- t.lineNumber = f.lineNumber;
2813
- t.columnNumber = f.columnNumber;
2814
- return t;
2815
- }
2816
-
2817
- /**
2818
- * @see #appendElement(source,elStartEnd,el,selfClosed,entityReplacer,domBuilder,parseStack);
2819
- * @return end of the elementStartPart(end of elementEndPart for selfClosed el)
2820
- */
2821
- function parseElementStartPart(source,start,el,currentNSMap,entityReplacer,errorHandler){
2822
-
2823
- /**
2824
- * @param {string} qname
2825
- * @param {string} value
2826
- * @param {number} startIndex
2827
- */
2828
- function addAttribute(qname, value, startIndex) {
2829
- if (qname in el.attributeNames) errorHandler.fatalError('Attribute ' + qname + ' redefined');
2830
- el.addValue(qname, value, startIndex);
2831
- }
2832
- var attrName;
2833
- var value;
2834
- var p = ++start;
2835
- var s = S_TAG;//status
2836
- while(true){
2837
- var c = source.charAt(p);
2838
- switch(c){
2839
- case '=':
2840
- if(s === S_ATTR){//attrName
2841
- attrName = source.slice(start,p);
2842
- s = S_EQ;
2843
- }else if(s === S_ATTR_SPACE){
2844
- s = S_EQ;
2845
- }else {
2846
- //fatalError: equal must after attrName or space after attrName
2847
- throw new Error('attribute equal must after attrName'); // No known test case
2848
- }
2849
- break;
2850
- case '\'':
2851
- case '"':
2852
- if(s === S_EQ || s === S_ATTR //|| s == S_ATTR_SPACE
2853
- ){//equal
2854
- if(s === S_ATTR){
2855
- errorHandler.warning('attribute value must after "="');
2856
- attrName = source.slice(start,p);
2857
- }
2858
- start = p+1;
2859
- p = source.indexOf(c,start);
2860
- if(p>0){
2861
- value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
2862
- addAttribute(attrName, value, start-1);
2863
- s = S_ATTR_END;
2864
- }else {
2865
- //fatalError: no end quot match
2866
- throw new Error('attribute value no end \''+c+'\' match');
2867
- }
2868
- }else if(s == S_ATTR_NOQUOT_VALUE){
2869
- value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
2870
- //console.log(attrName,value,start,p)
2871
- addAttribute(attrName, value, start);
2872
- //console.dir(el)
2873
- errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!');
2874
- start = p+1;
2875
- s = S_ATTR_END;
2876
- }else {
2877
- //fatalError: no equal before
2878
- throw new Error('attribute value must after "="'); // No known test case
2879
- }
2880
- break;
2881
- case '/':
2882
- switch(s){
2883
- case S_TAG:
2884
- el.setTagName(source.slice(start,p));
2885
- case S_ATTR_END:
2886
- case S_TAG_SPACE:
2887
- case S_TAG_CLOSE:
2888
- s =S_TAG_CLOSE;
2889
- el.closed = true;
2890
- case S_ATTR_NOQUOT_VALUE:
2891
- case S_ATTR:
2892
- case S_ATTR_SPACE:
2893
- break;
2894
- //case S_EQ:
2895
- default:
2896
- throw new Error("attribute invalid close char('/')") // No known test case
2897
- }
2898
- break;
2899
- case ''://end document
2900
- errorHandler.error('unexpected end of input');
2901
- if(s == S_TAG){
2902
- el.setTagName(source.slice(start,p));
2903
- }
2904
- return p;
2905
- case '>':
2906
- switch(s){
2907
- case S_TAG:
2908
- el.setTagName(source.slice(start,p));
2909
- case S_ATTR_END:
2910
- case S_TAG_SPACE:
2911
- case S_TAG_CLOSE:
2912
- break;//normal
2913
- case S_ATTR_NOQUOT_VALUE://Compatible state
2914
- case S_ATTR:
2915
- value = source.slice(start,p);
2916
- if(value.slice(-1) === '/'){
2917
- el.closed = true;
2918
- value = value.slice(0,-1);
2919
- }
2920
- case S_ATTR_SPACE:
2921
- if(s === S_ATTR_SPACE){
2922
- value = attrName;
2923
- }
2924
- if(s == S_ATTR_NOQUOT_VALUE){
2925
- errorHandler.warning('attribute "'+value+'" missed quot(")!');
2926
- addAttribute(attrName, value.replace(/&#?\w+;/g,entityReplacer), start);
2927
- }else {
2928
- if(!NAMESPACE$2.isHTML(currentNSMap['']) || !value.match(/^(?:disabled|checked|selected)$/i)){
2929
- errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!');
2930
- }
2931
- addAttribute(value, value, start);
2932
- }
2933
- break;
2934
- case S_EQ:
2935
- throw new Error('attribute value missed!!');
2936
- }
2937
- // console.log(tagName,tagNamePattern,tagNamePattern.test(tagName))
2938
- return p;
2939
- /*xml space '\x20' | #x9 | #xD | #xA; */
2940
- case '\u0080':
2941
- c = ' ';
2942
- default:
2943
- if(c<= ' '){//space
2944
- switch(s){
2945
- case S_TAG:
2946
- el.setTagName(source.slice(start,p));//tagName
2947
- s = S_TAG_SPACE;
2948
- break;
2949
- case S_ATTR:
2950
- attrName = source.slice(start,p);
2951
- s = S_ATTR_SPACE;
2952
- break;
2953
- case S_ATTR_NOQUOT_VALUE:
2954
- var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer);
2955
- errorHandler.warning('attribute "'+value+'" missed quot(")!!');
2956
- addAttribute(attrName, value, start);
2957
- case S_ATTR_END:
2958
- s = S_TAG_SPACE;
2959
- break;
2960
- //case S_TAG_SPACE:
2961
- //case S_EQ:
2962
- //case S_ATTR_SPACE:
2963
- // void();break;
2964
- //case S_TAG_CLOSE:
2965
- //ignore warning
2966
- }
2967
- }else {//not space
2968
- //S_TAG, S_ATTR, S_EQ, S_ATTR_NOQUOT_VALUE
2969
- //S_ATTR_SPACE, S_ATTR_END, S_TAG_SPACE, S_TAG_CLOSE
2970
- switch(s){
2971
- //case S_TAG:void();break;
2972
- //case S_ATTR:void();break;
2973
- //case S_ATTR_NOQUOT_VALUE:void();break;
2974
- case S_ATTR_SPACE:
2975
- el.tagName;
2976
- if (!NAMESPACE$2.isHTML(currentNSMap['']) || !attrName.match(/^(?:disabled|checked|selected)$/i)) {
2977
- errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead2!!');
2978
- }
2979
- addAttribute(attrName, attrName, start);
2980
- start = p;
2981
- s = S_ATTR;
2982
- break;
2983
- case S_ATTR_END:
2984
- errorHandler.warning('attribute space is required"'+attrName+'"!!');
2985
- case S_TAG_SPACE:
2986
- s = S_ATTR;
2987
- start = p;
2988
- break;
2989
- case S_EQ:
2990
- s = S_ATTR_NOQUOT_VALUE;
2991
- start = p;
2992
- break;
2993
- case S_TAG_CLOSE:
2994
- throw new Error("elements closed character '/' and '>' must be connected to");
2995
- }
2996
- }
2997
- }//end outer switch
2998
- //console.log('p++',p)
2999
- p++;
3000
- }
3001
- }
3002
- /**
3003
- * @return true if has new namespace define
3004
- */
3005
- function appendElement$1(el,domBuilder,currentNSMap){
3006
- var tagName = el.tagName;
3007
- var localNSMap = null;
3008
- //var currentNSMap = parseStack[parseStack.length-1].currentNSMap;
3009
- var i = el.length;
3010
- while(i--){
3011
- var a = el[i];
3012
- var qName = a.qName;
3013
- var value = a.value;
3014
- var nsp = qName.indexOf(':');
3015
- if(nsp>0){
3016
- var prefix = a.prefix = qName.slice(0,nsp);
3017
- var localName = qName.slice(nsp+1);
3018
- var nsPrefix = prefix === 'xmlns' && localName;
3019
- }else {
3020
- localName = qName;
3021
- prefix = null;
3022
- nsPrefix = qName === 'xmlns' && '';
3023
- }
3024
- //can not set prefix,because prefix !== ''
3025
- a.localName = localName ;
3026
- //prefix == null for no ns prefix attribute
3027
- if(nsPrefix !== false){//hack!!
3028
- if(localNSMap == null){
3029
- localNSMap = {};
3030
- //console.log(currentNSMap,0)
3031
- _copy(currentNSMap,currentNSMap={});
3032
- //console.log(currentNSMap,1)
3033
- }
3034
- currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value;
3035
- a.uri = NAMESPACE$2.XMLNS;
3036
- domBuilder.startPrefixMapping(nsPrefix, value);
3037
- }
3038
- }
3039
- var i = el.length;
3040
- while(i--){
3041
- a = el[i];
3042
- var prefix = a.prefix;
3043
- if(prefix){//no prefix attribute has no namespace
3044
- if(prefix === 'xml'){
3045
- a.uri = NAMESPACE$2.XML;
3046
- }if(prefix !== 'xmlns'){
3047
- a.uri = currentNSMap[prefix || ''];
3048
-
3049
- //{console.log('###'+a.qName,domBuilder.locator.systemId+'',currentNSMap,a.uri)}
3050
- }
3051
- }
3052
- }
3053
- var nsp = tagName.indexOf(':');
3054
- if(nsp>0){
3055
- prefix = el.prefix = tagName.slice(0,nsp);
3056
- localName = el.localName = tagName.slice(nsp+1);
3057
- }else {
3058
- prefix = null;//important!!
3059
- localName = el.localName = tagName;
3060
- }
3061
- //no prefix element has default namespace
3062
- var ns = el.uri = currentNSMap[prefix || ''];
3063
- domBuilder.startElement(ns,localName,tagName,el);
3064
- //endPrefixMapping and startPrefixMapping have not any help for dom builder
3065
- //localNSMap = null
3066
- if(el.closed){
3067
- domBuilder.endElement(ns,localName,tagName);
3068
- if(localNSMap){
3069
- for(prefix in localNSMap){
3070
- domBuilder.endPrefixMapping(prefix);
3071
- }
3072
- }
3073
- }else {
3074
- el.currentNSMap = currentNSMap;
3075
- el.localNSMap = localNSMap;
3076
- //parseStack.push(el);
3077
- return true;
3078
- }
3079
- }
3080
- function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){
3081
- if(/^(?:script|textarea)$/i.test(tagName)){
3082
- var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd);
3083
- var text = source.substring(elStartEnd+1,elEndStart);
3084
- if(/[&<]/.test(text)){
3085
- if(/^script$/i.test(tagName)){
3086
- //if(!/\]\]>/.test(text)){
3087
- //lexHandler.startCDATA();
3088
- domBuilder.characters(text,0,text.length);
3089
- //lexHandler.endCDATA();
3090
- return elEndStart;
3091
- //}
3092
- }//}else{//text area
3093
- text = text.replace(/&#?\w+;/g,entityReplacer);
3094
- domBuilder.characters(text,0,text.length);
3095
- return elEndStart;
3096
- //}
3097
-
3098
- }
3099
- }
3100
- return elStartEnd+1;
3101
- }
3102
- function fixSelfClosed(source,elStartEnd,tagName,closeMap){
3103
- //if(tagName in closeMap){
3104
- var pos = closeMap[tagName];
3105
- if(pos == null){
3106
- //console.log(tagName)
3107
- pos = source.lastIndexOf('</'+tagName+'>');
3108
- if(pos<elStartEnd){//忘记闭合
3109
- pos = source.lastIndexOf('</'+tagName);
3110
- }
3111
- closeMap[tagName] =pos;
3112
- }
3113
- return pos<elStartEnd;
3114
- //}
3115
- }
3116
- function _copy(source,target){
3117
- for(var n in source){target[n] = source[n];}
3118
- }
3119
- function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!'
3120
- var next= source.charAt(start+2);
3121
- switch(next){
3122
- case '-':
3123
- if(source.charAt(start + 3) === '-'){
3124
- var end = source.indexOf('-->',start+4);
3125
- //append comment source.substring(4,end)//<!--
3126
- if(end>start){
3127
- domBuilder.comment(source,start+4,end-start-4);
3128
- return end+3;
3129
- }else {
3130
- errorHandler.error("Unclosed comment");
3131
- return -1;
3132
- }
3133
- }else {
3134
- //error
3135
- return -1;
3136
- }
3137
- default:
3138
- if(source.substr(start+3,6) == 'CDATA['){
3139
- var end = source.indexOf(']]>',start+9);
3140
- domBuilder.startCDATA();
3141
- domBuilder.characters(source,start+9,end-start-9);
3142
- domBuilder.endCDATA();
3143
- return end+3;
3144
- }
3145
- //<!DOCTYPE
3146
- //startDTD(java.lang.String name, java.lang.String publicId, java.lang.String systemId)
3147
- var matchs = split(source,start);
3148
- var len = matchs.length;
3149
- if(len>1 && /!doctype/i.test(matchs[0][0])){
3150
- var name = matchs[1][0];
3151
- var pubid = false;
3152
- var sysid = false;
3153
- if(len>3){
3154
- if(/^public$/i.test(matchs[2][0])){
3155
- pubid = matchs[3][0];
3156
- sysid = len>4 && matchs[4][0];
3157
- }else if(/^system$/i.test(matchs[2][0])){
3158
- sysid = matchs[3][0];
3159
- }
3160
- }
3161
- var lastMatch = matchs[len-1];
3162
- domBuilder.startDTD(name, pubid, sysid);
3163
- domBuilder.endDTD();
3164
-
3165
- return lastMatch.index+lastMatch[0].length
3166
- }
3167
- }
3168
- return -1;
3169
- }
3170
-
3171
-
3172
-
3173
- function parseInstruction(source,start,domBuilder){
3174
- var end = source.indexOf('?>',start);
3175
- if(end){
3176
- var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/);
3177
- if(match){
3178
- match[0].length;
3179
- domBuilder.processingInstruction(match[1], match[2]) ;
3180
- return end+2;
3181
- }else {//error
3182
- return -1;
3183
- }
3184
- }
3185
- return -1;
3186
- }
3187
-
3188
- function ElementAttributes(){
3189
- this.attributeNames = {};
3190
- }
3191
- ElementAttributes.prototype = {
3192
- setTagName:function(tagName){
3193
- if(!tagNamePattern.test(tagName)){
3194
- throw new Error('invalid tagName:'+tagName)
3195
- }
3196
- this.tagName = tagName;
3197
- },
3198
- addValue:function(qName, value, offset) {
3199
- if(!tagNamePattern.test(qName)){
3200
- throw new Error('invalid attribute:'+qName)
3201
- }
3202
- this.attributeNames[qName] = this.length;
3203
- this[this.length++] = {qName:qName,value:value,offset:offset};
3204
- },
3205
- length:0,
3206
- getLocalName:function(i){return this[i].localName},
3207
- getLocator:function(i){return this[i].locator},
3208
- getQName:function(i){return this[i].qName},
3209
- getURI:function(i){return this[i].uri},
3210
- getValue:function(i){return this[i].value}
3211
- // ,getIndex:function(uri, localName)){
3212
- // if(localName){
3213
- //
3214
- // }else{
3215
- // var qName = uri
3216
- // }
3217
- // },
3218
- // getValue:function(){return this.getValue(this.getIndex.apply(this,arguments))},
3219
- // getType:function(uri,localName){}
3220
- // getType:function(i){},
3221
- };
3222
-
3223
-
3224
-
3225
- function split(source,start){
3226
- var match;
3227
- var buf = [];
3228
- var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g;
3229
- reg.lastIndex = start;
3230
- reg.exec(source);//skip <
3231
- while(match = reg.exec(source)){
3232
- buf.push(match);
3233
- if(match[1])return buf;
3234
- }
3235
- }
3236
-
3237
- sax$1.XMLReader = XMLReader$1;
3238
- sax$1.ParseError = ParseError$1;
3239
-
3240
- var dom = {};
3241
-
3242
- var conventions$1 = conventions$2;
3243
-
3244
- var NAMESPACE$1 = conventions$1.NAMESPACE;
3245
-
3246
- /**
3247
- * A prerequisite for `[].filter`, to drop elements that are empty
3248
- * @param {string} input
3249
- * @returns {boolean}
3250
- */
3251
- function notEmptyString (input) {
3252
- return input !== ''
3253
- }
3254
- /**
3255
- * @see https://infra.spec.whatwg.org/#split-on-ascii-whitespace
3256
- * @see https://infra.spec.whatwg.org/#ascii-whitespace
3257
- *
3258
- * @param {string} input
3259
- * @returns {string[]} (can be empty)
3260
- */
3261
- function splitOnASCIIWhitespace(input) {
3262
- // U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, U+0020 SPACE
3263
- return input ? input.split(/[\t\n\f\r ]+/).filter(notEmptyString) : []
3264
- }
3265
-
3266
- /**
3267
- * Adds element as a key to current if it is not already present.
3268
- *
3269
- * @param {Record<string, boolean | undefined>} current
3270
- * @param {string} element
3271
- * @returns {Record<string, boolean | undefined>}
3272
- */
3273
- function orderedSetReducer (current, element) {
3274
- if (!current.hasOwnProperty(element)) {
3275
- current[element] = true;
3276
- }
3277
- return current;
3278
- }
3279
-
3280
- /**
3281
- * @see https://infra.spec.whatwg.org/#ordered-set
3282
- * @param {string} input
3283
- * @returns {string[]}
3284
- */
3285
- function toOrderedSet(input) {
3286
- if (!input) return [];
3287
- var list = splitOnASCIIWhitespace(input);
3288
- return Object.keys(list.reduce(orderedSetReducer, {}))
3289
- }
3290
-
3291
- /**
3292
- * Uses `list.indexOf` to implement something like `Array.prototype.includes`,
3293
- * which we can not rely on being available.
3294
- *
3295
- * @param {any[]} list
3296
- * @returns {function(any): boolean}
3297
- */
3298
- function arrayIncludes (list) {
3299
- return function(element) {
3300
- return list && list.indexOf(element) !== -1;
3301
- }
3302
- }
3303
-
3304
- function copy(src,dest){
3305
- for(var p in src){
3306
- dest[p] = src[p];
3307
- }
3308
- }
3309
-
3310
- /**
3311
- ^\w+\.prototype\.([_\w]+)\s*=\s*((?:.*\{\s*?[\r\n][\s\S]*?^})|\S.*?(?=[;\r\n]));?
3312
- ^\w+\.prototype\.([_\w]+)\s*=\s*(\S.*?(?=[;\r\n]));?
3313
- */
3314
- function _extends(Class,Super){
3315
- var pt = Class.prototype;
3316
- if(!(pt instanceof Super)){
3317
- function t(){} t.prototype = Super.prototype;
3318
- t = new t();
3319
- copy(pt,t);
3320
- Class.prototype = pt = t;
3321
- }
3322
- if(pt.constructor != Class){
3323
- if(typeof Class != 'function'){
3324
- console.error("unknow Class:"+Class);
3325
- }
3326
- pt.constructor = Class;
3327
- }
3328
- }
3329
-
3330
- // Node Types
3331
- var NodeType = {};
3332
- var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1;
3333
- var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2;
3334
- var TEXT_NODE = NodeType.TEXT_NODE = 3;
3335
- var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4;
3336
- var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5;
3337
- var ENTITY_NODE = NodeType.ENTITY_NODE = 6;
3338
- var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7;
3339
- var COMMENT_NODE = NodeType.COMMENT_NODE = 8;
3340
- var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9;
3341
- var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10;
3342
- var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11;
3343
- var NOTATION_NODE = NodeType.NOTATION_NODE = 12;
3344
-
3345
- // ExceptionCode
3346
- var ExceptionCode = {};
3347
- var ExceptionMessage = {};
3348
- ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1);
3349
- ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2);
3350
- var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3);
3351
- ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4);
3352
- ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5);
3353
- ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6);
3354
- ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7);
3355
- var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8);
3356
- ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9);
3357
- var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10);
3358
- //level2
3359
- ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11);
3360
- ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12);
3361
- ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13);
3362
- ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14);
3363
- ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15);
3364
-
3365
- /**
3366
- * DOM Level 2
3367
- * Object DOMException
3368
- * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/ecma-script-binding.html
3369
- * @see http://www.w3.org/TR/REC-DOM-Level-1/ecma-script-language-binding.html
3370
- */
3371
- function DOMException(code, message) {
3372
- if(message instanceof Error){
3373
- var error = message;
3374
- }else {
3375
- error = this;
3376
- Error.call(this, ExceptionMessage[code]);
3377
- this.message = ExceptionMessage[code];
3378
- if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException);
3379
- }
3380
- error.code = code;
3381
- if(message) this.message = this.message + ": " + message;
3382
- return error;
3383
- }DOMException.prototype = Error.prototype;
3384
- copy(ExceptionCode,DOMException);
3385
-
3386
- /**
3387
- * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-536297177
3388
- * The NodeList interface provides the abstraction of an ordered collection of nodes, without defining or constraining how this collection is implemented. NodeList objects in the DOM are live.
3389
- * The items in the NodeList are accessible via an integral index, starting from 0.
3390
- */
3391
- function NodeList() {
3392
- }NodeList.prototype = {
3393
- /**
3394
- * The number of nodes in the list. The range of valid child node indices is 0 to length-1 inclusive.
3395
- * @standard level1
3396
- */
3397
- length:0,
3398
- /**
3399
- * Returns the indexth item in the collection. If index is greater than or equal to the number of nodes in the list, this returns null.
3400
- * @standard level1
3401
- * @param index unsigned long
3402
- * Index into the collection.
3403
- * @return Node
3404
- * The node at the indexth position in the NodeList, or null if that is not a valid index.
3405
- */
3406
- item: function(index) {
3407
- return this[index] || null;
3408
- },
3409
- toString:function(isHTML,nodeFilter){
3410
- for(var buf = [], i = 0;i<this.length;i++){
3411
- serializeToString(this[i],buf,isHTML,nodeFilter);
3412
- }
3413
- return buf.join('');
3414
- }
3415
- };
3416
-
3417
- function LiveNodeList(node,refresh){
3418
- this._node = node;
3419
- this._refresh = refresh;
3420
- _updateLiveList(this);
3421
- }
3422
- function _updateLiveList(list){
3423
- var inc = list._node._inc || list._node.ownerDocument._inc;
3424
- if(list._inc != inc){
3425
- var ls = list._refresh(list._node);
3426
- //console.log(ls.length)
3427
- __set__(list,'length',ls.length);
3428
- copy(ls,list);
3429
- list._inc = inc;
3430
- }
3431
- }
3432
- LiveNodeList.prototype.item = function(i){
3433
- _updateLiveList(this);
3434
- return this[i];
3435
- };
3436
-
3437
- _extends(LiveNodeList,NodeList);
3438
-
3439
- /**
3440
- * Objects implementing the NamedNodeMap interface are used
3441
- * to represent collections of nodes that can be accessed by name.
3442
- * Note that NamedNodeMap does not inherit from NodeList;
3443
- * NamedNodeMaps are not maintained in any particular order.
3444
- * Objects contained in an object implementing NamedNodeMap may also be accessed by an ordinal index,
3445
- * but this is simply to allow convenient enumeration of the contents of a NamedNodeMap,
3446
- * and does not imply that the DOM specifies an order to these Nodes.
3447
- * NamedNodeMap objects in the DOM are live.
3448
- * used for attributes or DocumentType entities
3449
- */
3450
- function NamedNodeMap() {
3451
- }
3452
- function _findNodeIndex(list,node){
3453
- var i = list.length;
3454
- while(i--){
3455
- if(list[i] === node){return i}
3456
- }
3457
- }
3458
-
3459
- function _addNamedNode(el,list,newAttr,oldAttr){
3460
- if(oldAttr){
3461
- list[_findNodeIndex(list,oldAttr)] = newAttr;
3462
- }else {
3463
- list[list.length++] = newAttr;
3464
- }
3465
- if(el){
3466
- newAttr.ownerElement = el;
3467
- var doc = el.ownerDocument;
3468
- if(doc){
3469
- oldAttr && _onRemoveAttribute(doc,el,oldAttr);
3470
- _onAddAttribute(doc,el,newAttr);
3471
- }
3472
- }
3473
- }
3474
- function _removeNamedNode(el,list,attr){
3475
- //console.log('remove attr:'+attr)
3476
- var i = _findNodeIndex(list,attr);
3477
- if(i>=0){
3478
- var lastIndex = list.length-1;
3479
- while(i<lastIndex){
3480
- list[i] = list[++i];
3481
- }
3482
- list.length = lastIndex;
3483
- if(el){
3484
- var doc = el.ownerDocument;
3485
- if(doc){
3486
- _onRemoveAttribute(doc,el,attr);
3487
- attr.ownerElement = null;
3488
- }
3489
- }
3490
- }else {
3491
- throw DOMException(NOT_FOUND_ERR,new Error(el.tagName+'@'+attr))
3492
- }
3493
- }
3494
- NamedNodeMap.prototype = {
3495
- length:0,
3496
- item:NodeList.prototype.item,
3497
- getNamedItem: function(key) {
3498
- // if(key.indexOf(':')>0 || key == 'xmlns'){
3499
- // return null;
3500
- // }
3501
- //console.log()
3502
- var i = this.length;
3503
- while(i--){
3504
- var attr = this[i];
3505
- //console.log(attr.nodeName,key)
3506
- if(attr.nodeName == key){
3507
- return attr;
3508
- }
3509
- }
3510
- },
3511
- setNamedItem: function(attr) {
3512
- var el = attr.ownerElement;
3513
- if(el && el!=this._ownerElement){
3514
- throw new DOMException(INUSE_ATTRIBUTE_ERR);
3515
- }
3516
- var oldAttr = this.getNamedItem(attr.nodeName);
3517
- _addNamedNode(this._ownerElement,this,attr,oldAttr);
3518
- return oldAttr;
3519
- },
3520
- /* returns Node */
3521
- setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR
3522
- var el = attr.ownerElement, oldAttr;
3523
- if(el && el!=this._ownerElement){
3524
- throw new DOMException(INUSE_ATTRIBUTE_ERR);
3525
- }
3526
- oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName);
3527
- _addNamedNode(this._ownerElement,this,attr,oldAttr);
3528
- return oldAttr;
3529
- },
3530
-
3531
- /* returns Node */
3532
- removeNamedItem: function(key) {
3533
- var attr = this.getNamedItem(key);
3534
- _removeNamedNode(this._ownerElement,this,attr);
3535
- return attr;
3536
-
3537
-
3538
- },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR
3539
-
3540
- //for level2
3541
- removeNamedItemNS:function(namespaceURI,localName){
3542
- var attr = this.getNamedItemNS(namespaceURI,localName);
3543
- _removeNamedNode(this._ownerElement,this,attr);
3544
- return attr;
3545
- },
3546
- getNamedItemNS: function(namespaceURI, localName) {
3547
- var i = this.length;
3548
- while(i--){
3549
- var node = this[i];
3550
- if(node.localName == localName && node.namespaceURI == namespaceURI){
3551
- return node;
3552
- }
3553
- }
3554
- return null;
3555
- }
3556
- };
3557
-
3558
- /**
3559
- * The DOMImplementation interface represents an object providing methods
3560
- * which are not dependent on any particular document.
3561
- * Such an object is returned by the `Document.implementation` property.
3562
- *
3563
- * __The individual methods describe the differences compared to the specs.__
3564
- *
3565
- * @constructor
3566
- *
3567
- * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation MDN
3568
- * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-102161490 DOM Level 1 Core (Initial)
3569
- * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#ID-102161490 DOM Level 2 Core
3570
- * @see https://www.w3.org/TR/DOM-Level-3-Core/core.html#ID-102161490 DOM Level 3 Core
3571
- * @see https://dom.spec.whatwg.org/#domimplementation DOM Living Standard
3572
- */
3573
- function DOMImplementation$1() {
3574
- }
3575
-
3576
- DOMImplementation$1.prototype = {
3577
- /**
3578
- * The DOMImplementation.hasFeature() method returns a Boolean flag indicating if a given feature is supported.
3579
- * The different implementations fairly diverged in what kind of features were reported.
3580
- * The latest version of the spec settled to force this method to always return true, where the functionality was accurate and in use.
3581
- *
3582
- * @deprecated It is deprecated and modern browsers return true in all cases.
3583
- *
3584
- * @param {string} feature
3585
- * @param {string} [version]
3586
- * @returns {boolean} always true
3587
- *
3588
- * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/hasFeature MDN
3589
- * @see https://www.w3.org/TR/REC-DOM-Level-1/level-one-core.html#ID-5CED94D7 DOM Level 1 Core
3590
- * @see https://dom.spec.whatwg.org/#dom-domimplementation-hasfeature DOM Living Standard
3591
- */
3592
- hasFeature: function(feature, version) {
3593
- return true;
3594
- },
3595
- /**
3596
- * Creates an XML Document object of the specified type with its document element.
3597
- *
3598
- * __It behaves slightly different from the description in the living standard__:
3599
- * - There is no interface/class `XMLDocument`, it returns a `Document` instance.
3600
- * - `contentType`, `encoding`, `mode`, `origin`, `url` fields are currently not declared.
3601
- * - this implementation is not validating names or qualified names
3602
- * (when parsing XML strings, the SAX parser takes care of that)
3603
- *
3604
- * @param {string|null} namespaceURI
3605
- * @param {string} qualifiedName
3606
- * @param {DocumentType=null} doctype
3607
- * @returns {Document}
3608
- *
3609
- * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocument MDN
3610
- * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocument DOM Level 2 Core (initial)
3611
- * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocument DOM Level 2 Core
3612
- *
3613
- * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
3614
- * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
3615
- * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
3616
- */
3617
- createDocument: function(namespaceURI, qualifiedName, doctype){
3618
- var doc = new Document();
3619
- doc.implementation = this;
3620
- doc.childNodes = new NodeList();
3621
- doc.doctype = doctype || null;
3622
- if (doctype){
3623
- doc.appendChild(doctype);
3624
- }
3625
- if (qualifiedName){
3626
- var root = doc.createElementNS(namespaceURI, qualifiedName);
3627
- doc.appendChild(root);
3628
- }
3629
- return doc;
3630
- },
3631
- /**
3632
- * Returns a doctype, with the given `qualifiedName`, `publicId`, and `systemId`.
3633
- *
3634
- * __This behavior is slightly different from the in the specs__:
3635
- * - this implementation is not validating names or qualified names
3636
- * (when parsing XML strings, the SAX parser takes care of that)
3637
- *
3638
- * @param {string} qualifiedName
3639
- * @param {string} [publicId]
3640
- * @param {string} [systemId]
3641
- * @returns {DocumentType} which can either be used with `DOMImplementation.createDocument` upon document creation
3642
- * or can be put into the document via methods like `Node.insertBefore()` or `Node.replaceChild()`
3643
- *
3644
- * @see https://developer.mozilla.org/en-US/docs/Web/API/DOMImplementation/createDocumentType MDN
3645
- * @see https://www.w3.org/TR/DOM-Level-2-Core/core.html#Level-2-Core-DOM-createDocType DOM Level 2 Core
3646
- * @see https://dom.spec.whatwg.org/#dom-domimplementation-createdocumenttype DOM Living Standard
3647
- *
3648
- * @see https://dom.spec.whatwg.org/#validate-and-extract DOM: Validate and extract
3649
- * @see https://www.w3.org/TR/xml/#NT-NameStartChar XML Spec: Names
3650
- * @see https://www.w3.org/TR/xml-names/#ns-qualnames XML Namespaces: Qualified names
3651
- */
3652
- createDocumentType: function(qualifiedName, publicId, systemId){
3653
- var node = new DocumentType();
3654
- node.name = qualifiedName;
3655
- node.nodeName = qualifiedName;
3656
- node.publicId = publicId || '';
3657
- node.systemId = systemId || '';
3658
-
3659
- return node;
3660
- }
3661
- };
3662
-
3663
-
3664
- /**
3665
- * @see http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html#ID-1950641247
3666
- */
3667
-
3668
- function Node() {
3669
- }
3670
- Node.prototype = {
3671
- firstChild : null,
3672
- lastChild : null,
3673
- previousSibling : null,
3674
- nextSibling : null,
3675
- attributes : null,
3676
- parentNode : null,
3677
- childNodes : null,
3678
- ownerDocument : null,
3679
- nodeValue : null,
3680
- namespaceURI : null,
3681
- prefix : null,
3682
- localName : null,
3683
- // Modified in DOM Level 2:
3684
- insertBefore:function(newChild, refChild){//raises
3685
- return _insertBefore(this,newChild,refChild);
3686
- },
3687
- replaceChild:function(newChild, oldChild){//raises
3688
- this.insertBefore(newChild,oldChild);
3689
- if(oldChild){
3690
- this.removeChild(oldChild);
3691
- }
3692
- },
3693
- removeChild:function(oldChild){
3694
- return _removeChild(this,oldChild);
3695
- },
3696
- appendChild:function(newChild){
3697
- return this.insertBefore(newChild,null);
3698
- },
3699
- hasChildNodes:function(){
3700
- return this.firstChild != null;
3701
- },
3702
- cloneNode:function(deep){
3703
- return cloneNode(this.ownerDocument||this,this,deep);
3704
- },
3705
- // Modified in DOM Level 2:
3706
- normalize:function(){
3707
- var child = this.firstChild;
3708
- while(child){
3709
- var next = child.nextSibling;
3710
- if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){
3711
- this.removeChild(next);
3712
- child.appendData(next.data);
3713
- }else {
3714
- child.normalize();
3715
- child = next;
3716
- }
3717
- }
3718
- },
3719
- // Introduced in DOM Level 2:
3720
- isSupported:function(feature, version){
3721
- return this.ownerDocument.implementation.hasFeature(feature,version);
3722
- },
3723
- // Introduced in DOM Level 2:
3724
- hasAttributes:function(){
3725
- return this.attributes.length>0;
3726
- },
3727
- lookupPrefix:function(namespaceURI){
3728
- var el = this;
3729
- while(el){
3730
- var map = el._nsMap;
3731
- //console.dir(map)
3732
- if(map){
3733
- for(var n in map){
3734
- if(map[n] == namespaceURI){
3735
- return n;
3736
- }
3737
- }
3738
- }
3739
- el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
3740
- }
3741
- return null;
3742
- },
3743
- // Introduced in DOM Level 3:
3744
- lookupNamespaceURI:function(prefix){
3745
- var el = this;
3746
- while(el){
3747
- var map = el._nsMap;
3748
- //console.dir(map)
3749
- if(map){
3750
- if(prefix in map){
3751
- return map[prefix] ;
3752
- }
3753
- }
3754
- el = el.nodeType == ATTRIBUTE_NODE?el.ownerDocument : el.parentNode;
3755
- }
3756
- return null;
3757
- },
3758
- // Introduced in DOM Level 3:
3759
- isDefaultNamespace:function(namespaceURI){
3760
- var prefix = this.lookupPrefix(namespaceURI);
3761
- return prefix == null;
3762
- }
3763
- };
3764
-
3765
-
3766
- function _xmlEncoder(c){
3767
- return c == '<' && '&lt;' ||
3768
- c == '>' && '&gt;' ||
3769
- c == '&' && '&amp;' ||
3770
- c == '"' && '&quot;' ||
3771
- '&#'+c.charCodeAt()+';'
3772
- }
3773
-
3774
-
3775
- copy(NodeType,Node);
3776
- copy(NodeType,Node.prototype);
3777
-
3778
- /**
3779
- * @param callback return true for continue,false for break
3780
- * @return boolean true: break visit;
3781
- */
3782
- function _visitNode(node,callback){
3783
- if(callback(node)){
3784
- return true;
3785
- }
3786
- if(node = node.firstChild){
3787
- do{
3788
- if(_visitNode(node,callback)){return true}
3789
- }while(node=node.nextSibling)
3790
- }
3791
- }
3792
-
3793
-
3794
-
3795
- function Document(){
3796
- }
3797
-
3798
- function _onAddAttribute(doc,el,newAttr){
3799
- doc && doc._inc++;
3800
- var ns = newAttr.namespaceURI ;
3801
- if(ns === NAMESPACE$1.XMLNS){
3802
- //update namespace
3803
- el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value;
3804
- }
3805
- }
3806
-
3807
- function _onRemoveAttribute(doc,el,newAttr,remove){
3808
- doc && doc._inc++;
3809
- var ns = newAttr.namespaceURI ;
3810
- if(ns === NAMESPACE$1.XMLNS){
3811
- //update namespace
3812
- delete el._nsMap[newAttr.prefix?newAttr.localName:''];
3813
- }
3814
- }
3815
-
3816
- function _onUpdateChild(doc,el,newChild){
3817
- if(doc && doc._inc){
3818
- doc._inc++;
3819
- //update childNodes
3820
- var cs = el.childNodes;
3821
- if(newChild){
3822
- cs[cs.length++] = newChild;
3823
- }else {
3824
- //console.log(1)
3825
- var child = el.firstChild;
3826
- var i = 0;
3827
- while(child){
3828
- cs[i++] = child;
3829
- child =child.nextSibling;
3830
- }
3831
- cs.length = i;
3832
- }
3833
- }
3834
- }
3835
-
3836
- /**
3837
- * attributes;
3838
- * children;
3839
- *
3840
- * writeable properties:
3841
- * nodeValue,Attr:value,CharacterData:data
3842
- * prefix
3843
- */
3844
- function _removeChild(parentNode,child){
3845
- var previous = child.previousSibling;
3846
- var next = child.nextSibling;
3847
- if(previous){
3848
- previous.nextSibling = next;
3849
- }else {
3850
- parentNode.firstChild = next;
3851
- }
3852
- if(next){
3853
- next.previousSibling = previous;
3854
- }else {
3855
- parentNode.lastChild = previous;
3856
- }
3857
- _onUpdateChild(parentNode.ownerDocument,parentNode);
3858
- return child;
3859
- }
3860
- /**
3861
- * preformance key(refChild == null)
3862
- */
3863
- function _insertBefore(parentNode,newChild,nextChild){
3864
- var cp = newChild.parentNode;
3865
- if(cp){
3866
- cp.removeChild(newChild);//remove and update
3867
- }
3868
- if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
3869
- var newFirst = newChild.firstChild;
3870
- if (newFirst == null) {
3871
- return newChild;
3872
- }
3873
- var newLast = newChild.lastChild;
3874
- }else {
3875
- newFirst = newLast = newChild;
3876
- }
3877
- var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild;
3878
-
3879
- newFirst.previousSibling = pre;
3880
- newLast.nextSibling = nextChild;
3881
-
3882
-
3883
- if(pre){
3884
- pre.nextSibling = newFirst;
3885
- }else {
3886
- parentNode.firstChild = newFirst;
3887
- }
3888
- if(nextChild == null){
3889
- parentNode.lastChild = newLast;
3890
- }else {
3891
- nextChild.previousSibling = newLast;
3892
- }
3893
- do{
3894
- newFirst.parentNode = parentNode;
3895
- }while(newFirst !== newLast && (newFirst= newFirst.nextSibling))
3896
- _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode);
3897
- //console.log(parentNode.lastChild.nextSibling == null)
3898
- if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) {
3899
- newChild.firstChild = newChild.lastChild = null;
3900
- }
3901
- return newChild;
3902
- }
3903
- function _appendSingleChild(parentNode,newChild){
3904
- var cp = newChild.parentNode;
3905
- if(cp){
3906
- var pre = parentNode.lastChild;
3907
- cp.removeChild(newChild);//remove and update
3908
- var pre = parentNode.lastChild;
3909
- }
3910
- var pre = parentNode.lastChild;
3911
- newChild.parentNode = parentNode;
3912
- newChild.previousSibling = pre;
3913
- newChild.nextSibling = null;
3914
- if(pre){
3915
- pre.nextSibling = newChild;
3916
- }else {
3917
- parentNode.firstChild = newChild;
3918
- }
3919
- parentNode.lastChild = newChild;
3920
- _onUpdateChild(parentNode.ownerDocument,parentNode,newChild);
3921
- return newChild;
3922
- //console.log("__aa",parentNode.lastChild.nextSibling == null)
3923
- }
3924
- Document.prototype = {
3925
- //implementation : null,
3926
- nodeName : '#document',
3927
- nodeType : DOCUMENT_NODE,
3928
- doctype : null,
3929
- documentElement : null,
3930
- _inc : 1,
3931
-
3932
- insertBefore : function(newChild, refChild){//raises
3933
- if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){
3934
- var child = newChild.firstChild;
3935
- while(child){
3936
- var next = child.nextSibling;
3937
- this.insertBefore(child,refChild);
3938
- child = next;
3939
- }
3940
- return newChild;
3941
- }
3942
- if(this.documentElement == null && newChild.nodeType == ELEMENT_NODE){
3943
- this.documentElement = newChild;
3944
- }
3945
-
3946
- return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild;
3947
- },
3948
- removeChild : function(oldChild){
3949
- if(this.documentElement == oldChild){
3950
- this.documentElement = null;
3951
- }
3952
- return _removeChild(this,oldChild);
3953
- },
3954
- // Introduced in DOM Level 2:
3955
- importNode : function(importedNode,deep){
3956
- return importNode(this,importedNode,deep);
3957
- },
3958
- // Introduced in DOM Level 2:
3959
- getElementById : function(id){
3960
- var rtv = null;
3961
- _visitNode(this.documentElement,function(node){
3962
- if(node.nodeType == ELEMENT_NODE){
3963
- if(node.getAttribute('id') == id){
3964
- rtv = node;
3965
- return true;
3966
- }
3967
- }
3968
- });
3969
- return rtv;
3970
- },
3971
-
3972
- /**
3973
- * The `getElementsByClassName` method of `Document` interface returns an array-like object
3974
- * of all child elements which have **all** of the given class name(s).
3975
- *
3976
- * Returns an empty list if `classeNames` is an empty string or only contains HTML white space characters.
3977
- *
3978
- *
3979
- * Warning: This is a live LiveNodeList.
3980
- * Changes in the DOM will reflect in the array as the changes occur.
3981
- * If an element selected by this array no longer qualifies for the selector,
3982
- * it will automatically be removed. Be aware of this for iteration purposes.
3983
- *
3984
- * @param {string} classNames is a string representing the class name(s) to match; multiple class names are separated by (ASCII-)whitespace
3985
- *
3986
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName
3987
- * @see https://dom.spec.whatwg.org/#concept-getelementsbyclassname
3988
- */
3989
- getElementsByClassName: function(classNames) {
3990
- var classNamesSet = toOrderedSet(classNames);
3991
- return new LiveNodeList(this, function(base) {
3992
- var ls = [];
3993
- if (classNamesSet.length > 0) {
3994
- _visitNode(base.documentElement, function(node) {
3995
- if(node !== base && node.nodeType === ELEMENT_NODE) {
3996
- var nodeClassNames = node.getAttribute('class');
3997
- // can be null if the attribute does not exist
3998
- if (nodeClassNames) {
3999
- // before splitting and iterating just compare them for the most common case
4000
- var matches = classNames === nodeClassNames;
4001
- if (!matches) {
4002
- var nodeClassNamesSet = toOrderedSet(nodeClassNames);
4003
- matches = classNamesSet.every(arrayIncludes(nodeClassNamesSet));
4004
- }
4005
- if(matches) {
4006
- ls.push(node);
4007
- }
4008
- }
4009
- }
4010
- });
4011
- }
4012
- return ls;
4013
- });
4014
- },
4015
-
4016
- //document factory method:
4017
- createElement : function(tagName){
4018
- var node = new Element();
4019
- node.ownerDocument = this;
4020
- node.nodeName = tagName;
4021
- node.tagName = tagName;
4022
- node.localName = tagName;
4023
- node.childNodes = new NodeList();
4024
- var attrs = node.attributes = new NamedNodeMap();
4025
- attrs._ownerElement = node;
4026
- return node;
4027
- },
4028
- createDocumentFragment : function(){
4029
- var node = new DocumentFragment();
4030
- node.ownerDocument = this;
4031
- node.childNodes = new NodeList();
4032
- return node;
4033
- },
4034
- createTextNode : function(data){
4035
- var node = new Text();
4036
- node.ownerDocument = this;
4037
- node.appendData(data);
4038
- return node;
4039
- },
4040
- createComment : function(data){
4041
- var node = new Comment();
4042
- node.ownerDocument = this;
4043
- node.appendData(data);
4044
- return node;
4045
- },
4046
- createCDATASection : function(data){
4047
- var node = new CDATASection();
4048
- node.ownerDocument = this;
4049
- node.appendData(data);
4050
- return node;
4051
- },
4052
- createProcessingInstruction : function(target,data){
4053
- var node = new ProcessingInstruction();
4054
- node.ownerDocument = this;
4055
- node.tagName = node.target = target;
4056
- node.nodeValue= node.data = data;
4057
- return node;
4058
- },
4059
- createAttribute : function(name){
4060
- var node = new Attr();
4061
- node.ownerDocument = this;
4062
- node.name = name;
4063
- node.nodeName = name;
4064
- node.localName = name;
4065
- node.specified = true;
4066
- return node;
4067
- },
4068
- createEntityReference : function(name){
4069
- var node = new EntityReference();
4070
- node.ownerDocument = this;
4071
- node.nodeName = name;
4072
- return node;
4073
- },
4074
- // Introduced in DOM Level 2:
4075
- createElementNS : function(namespaceURI,qualifiedName){
4076
- var node = new Element();
4077
- var pl = qualifiedName.split(':');
4078
- var attrs = node.attributes = new NamedNodeMap();
4079
- node.childNodes = new NodeList();
4080
- node.ownerDocument = this;
4081
- node.nodeName = qualifiedName;
4082
- node.tagName = qualifiedName;
4083
- node.namespaceURI = namespaceURI;
4084
- if(pl.length == 2){
4085
- node.prefix = pl[0];
4086
- node.localName = pl[1];
4087
- }else {
4088
- //el.prefix = null;
4089
- node.localName = qualifiedName;
4090
- }
4091
- attrs._ownerElement = node;
4092
- return node;
4093
- },
4094
- // Introduced in DOM Level 2:
4095
- createAttributeNS : function(namespaceURI,qualifiedName){
4096
- var node = new Attr();
4097
- var pl = qualifiedName.split(':');
4098
- node.ownerDocument = this;
4099
- node.nodeName = qualifiedName;
4100
- node.name = qualifiedName;
4101
- node.namespaceURI = namespaceURI;
4102
- node.specified = true;
4103
- if(pl.length == 2){
4104
- node.prefix = pl[0];
4105
- node.localName = pl[1];
4106
- }else {
4107
- //el.prefix = null;
4108
- node.localName = qualifiedName;
4109
- }
4110
- return node;
4111
- }
4112
- };
4113
- _extends(Document,Node);
4114
-
4115
-
4116
- function Element() {
4117
- this._nsMap = {};
4118
- }Element.prototype = {
4119
- nodeType : ELEMENT_NODE,
4120
- hasAttribute : function(name){
4121
- return this.getAttributeNode(name)!=null;
4122
- },
4123
- getAttribute : function(name){
4124
- var attr = this.getAttributeNode(name);
4125
- return attr && attr.value || '';
4126
- },
4127
- getAttributeNode : function(name){
4128
- return this.attributes.getNamedItem(name);
4129
- },
4130
- setAttribute : function(name, value){
4131
- var attr = this.ownerDocument.createAttribute(name);
4132
- attr.value = attr.nodeValue = "" + value;
4133
- this.setAttributeNode(attr);
4134
- },
4135
- removeAttribute : function(name){
4136
- var attr = this.getAttributeNode(name);
4137
- attr && this.removeAttributeNode(attr);
4138
- },
4139
-
4140
- //four real opeartion method
4141
- appendChild:function(newChild){
4142
- if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){
4143
- return this.insertBefore(newChild,null);
4144
- }else {
4145
- return _appendSingleChild(this,newChild);
4146
- }
4147
- },
4148
- setAttributeNode : function(newAttr){
4149
- return this.attributes.setNamedItem(newAttr);
4150
- },
4151
- setAttributeNodeNS : function(newAttr){
4152
- return this.attributes.setNamedItemNS(newAttr);
4153
- },
4154
- removeAttributeNode : function(oldAttr){
4155
- //console.log(this == oldAttr.ownerElement)
4156
- return this.attributes.removeNamedItem(oldAttr.nodeName);
4157
- },
4158
- //get real attribute name,and remove it by removeAttributeNode
4159
- removeAttributeNS : function(namespaceURI, localName){
4160
- var old = this.getAttributeNodeNS(namespaceURI, localName);
4161
- old && this.removeAttributeNode(old);
4162
- },
4163
-
4164
- hasAttributeNS : function(namespaceURI, localName){
4165
- return this.getAttributeNodeNS(namespaceURI, localName)!=null;
4166
- },
4167
- getAttributeNS : function(namespaceURI, localName){
4168
- var attr = this.getAttributeNodeNS(namespaceURI, localName);
4169
- return attr && attr.value || '';
4170
- },
4171
- setAttributeNS : function(namespaceURI, qualifiedName, value){
4172
- var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName);
4173
- attr.value = attr.nodeValue = "" + value;
4174
- this.setAttributeNode(attr);
4175
- },
4176
- getAttributeNodeNS : function(namespaceURI, localName){
4177
- return this.attributes.getNamedItemNS(namespaceURI, localName);
4178
- },
4179
-
4180
- getElementsByTagName : function(tagName){
4181
- return new LiveNodeList(this,function(base){
4182
- var ls = [];
4183
- _visitNode(base,function(node){
4184
- if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){
4185
- ls.push(node);
4186
- }
4187
- });
4188
- return ls;
4189
- });
4190
- },
4191
- getElementsByTagNameNS : function(namespaceURI, localName){
4192
- return new LiveNodeList(this,function(base){
4193
- var ls = [];
4194
- _visitNode(base,function(node){
4195
- if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){
4196
- ls.push(node);
4197
- }
4198
- });
4199
- return ls;
4200
-
4201
- });
4202
- }
4203
- };
4204
- Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName;
4205
- Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS;
4206
-
4207
-
4208
- _extends(Element,Node);
4209
- function Attr() {
4210
- }Attr.prototype.nodeType = ATTRIBUTE_NODE;
4211
- _extends(Attr,Node);
4212
-
4213
-
4214
- function CharacterData() {
4215
- }CharacterData.prototype = {
4216
- data : '',
4217
- substringData : function(offset, count) {
4218
- return this.data.substring(offset, offset+count);
4219
- },
4220
- appendData: function(text) {
4221
- text = this.data+text;
4222
- this.nodeValue = this.data = text;
4223
- this.length = text.length;
4224
- },
4225
- insertData: function(offset,text) {
4226
- this.replaceData(offset,0,text);
4227
-
4228
- },
4229
- appendChild:function(newChild){
4230
- throw new Error(ExceptionMessage[HIERARCHY_REQUEST_ERR])
4231
- },
4232
- deleteData: function(offset, count) {
4233
- this.replaceData(offset,count,"");
4234
- },
4235
- replaceData: function(offset, count, text) {
4236
- var start = this.data.substring(0,offset);
4237
- var end = this.data.substring(offset+count);
4238
- text = start + text + end;
4239
- this.nodeValue = this.data = text;
4240
- this.length = text.length;
4241
- }
4242
- };
4243
- _extends(CharacterData,Node);
4244
- function Text() {
4245
- }Text.prototype = {
4246
- nodeName : "#text",
4247
- nodeType : TEXT_NODE,
4248
- splitText : function(offset) {
4249
- var text = this.data;
4250
- var newText = text.substring(offset);
4251
- text = text.substring(0, offset);
4252
- this.data = this.nodeValue = text;
4253
- this.length = text.length;
4254
- var newNode = this.ownerDocument.createTextNode(newText);
4255
- if(this.parentNode){
4256
- this.parentNode.insertBefore(newNode, this.nextSibling);
4257
- }
4258
- return newNode;
4259
- }
4260
- };
4261
- _extends(Text,CharacterData);
4262
- function Comment() {
4263
- }Comment.prototype = {
4264
- nodeName : "#comment",
4265
- nodeType : COMMENT_NODE
4266
- };
4267
- _extends(Comment,CharacterData);
4268
-
4269
- function CDATASection() {
4270
- }CDATASection.prototype = {
4271
- nodeName : "#cdata-section",
4272
- nodeType : CDATA_SECTION_NODE
4273
- };
4274
- _extends(CDATASection,CharacterData);
4275
-
4276
-
4277
- function DocumentType() {
4278
- }DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE;
4279
- _extends(DocumentType,Node);
4280
-
4281
- function Notation() {
4282
- }Notation.prototype.nodeType = NOTATION_NODE;
4283
- _extends(Notation,Node);
4284
-
4285
- function Entity() {
4286
- }Entity.prototype.nodeType = ENTITY_NODE;
4287
- _extends(Entity,Node);
4288
-
4289
- function EntityReference() {
4290
- }EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE;
4291
- _extends(EntityReference,Node);
4292
-
4293
- function DocumentFragment() {
4294
- }DocumentFragment.prototype.nodeName = "#document-fragment";
4295
- DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE;
4296
- _extends(DocumentFragment,Node);
4297
-
4298
-
4299
- function ProcessingInstruction() {
4300
- }
4301
- ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE;
4302
- _extends(ProcessingInstruction,Node);
4303
- function XMLSerializer(){}
4304
- XMLSerializer.prototype.serializeToString = function(node,isHtml,nodeFilter){
4305
- return nodeSerializeToString.call(node,isHtml,nodeFilter);
4306
- };
4307
- Node.prototype.toString = nodeSerializeToString;
4308
- function nodeSerializeToString(isHtml,nodeFilter){
4309
- var buf = [];
4310
- var refNode = this.nodeType == 9 && this.documentElement || this;
4311
- var prefix = refNode.prefix;
4312
- var uri = refNode.namespaceURI;
4313
-
4314
- if(uri && prefix == null){
4315
- //console.log(prefix)
4316
- var prefix = refNode.lookupPrefix(uri);
4317
- if(prefix == null){
4318
- //isHTML = true;
4319
- var visibleNamespaces=[
4320
- {namespace:uri,prefix:null}
4321
- //{namespace:uri,prefix:''}
4322
- ];
4323
- }
4324
- }
4325
- serializeToString(this,buf,isHtml,nodeFilter,visibleNamespaces);
4326
- //console.log('###',this.nodeType,uri,prefix,buf.join(''))
4327
- return buf.join('');
4328
- }
4329
-
4330
- function needNamespaceDefine(node, isHTML, visibleNamespaces) {
4331
- var prefix = node.prefix || '';
4332
- var uri = node.namespaceURI;
4333
- // According to [Namespaces in XML 1.0](https://www.w3.org/TR/REC-xml-names/#ns-using) ,
4334
- // and more specifically https://www.w3.org/TR/REC-xml-names/#nsc-NoPrefixUndecl :
4335
- // > In a namespace declaration for a prefix [...], the attribute value MUST NOT be empty.
4336
- // in a similar manner [Namespaces in XML 1.1](https://www.w3.org/TR/xml-names11/#ns-using)
4337
- // and more specifically https://www.w3.org/TR/xml-names11/#nsc-NSDeclared :
4338
- // > [...] Furthermore, the attribute value [...] must not be an empty string.
4339
- // so serializing empty namespace value like xmlns:ds="" would produce an invalid XML document.
4340
- if (!uri) {
4341
- return false;
4342
- }
4343
- if (prefix === "xml" && uri === NAMESPACE$1.XML || uri === NAMESPACE$1.XMLNS) {
4344
- return false;
4345
- }
4346
-
4347
- var i = visibleNamespaces.length;
4348
- while (i--) {
4349
- var ns = visibleNamespaces[i];
4350
- // get namespace prefix
4351
- if (ns.prefix === prefix) {
4352
- return ns.namespace !== uri;
4353
- }
4354
- }
4355
- return true;
4356
- }
4357
- /**
4358
- * Well-formed constraint: No < in Attribute Values
4359
- * The replacement text of any entity referred to directly or indirectly in an attribute value must not contain a <.
4360
- * @see https://www.w3.org/TR/xml/#CleanAttrVals
4361
- * @see https://www.w3.org/TR/xml/#NT-AttValue
4362
- */
4363
- function addSerializedAttribute(buf, qualifiedName, value) {
4364
- buf.push(' ', qualifiedName, '="', value.replace(/[<&"]/g,_xmlEncoder), '"');
4365
- }
4366
-
4367
- function serializeToString(node,buf,isHTML,nodeFilter,visibleNamespaces){
4368
- if (!visibleNamespaces) {
4369
- visibleNamespaces = [];
4370
- }
4371
-
4372
- if(nodeFilter){
4373
- node = nodeFilter(node);
4374
- if(node){
4375
- if(typeof node == 'string'){
4376
- buf.push(node);
4377
- return;
4378
- }
4379
- }else {
4380
- return;
4381
- }
4382
- //buf.sort.apply(attrs, attributeSorter);
4383
- }
4384
-
4385
- switch(node.nodeType){
4386
- case ELEMENT_NODE:
4387
- var attrs = node.attributes;
4388
- var len = attrs.length;
4389
- var child = node.firstChild;
4390
- var nodeName = node.tagName;
4391
-
4392
- isHTML = NAMESPACE$1.isHTML(node.namespaceURI) || isHTML;
4393
-
4394
- var prefixedNodeName = nodeName;
4395
- if (!isHTML && !node.prefix && node.namespaceURI) {
4396
- var defaultNS;
4397
- for (var ai = 0; ai < attrs.length; ai++) {
4398
- if (attrs.item(ai).name === 'xmlns') {
4399
- defaultNS = attrs.item(ai).value;
4400
- break
4401
- }
4402
- }
4403
- if (defaultNS !== node.namespaceURI) {
4404
- for (var nsi = visibleNamespaces.length - 1; nsi >= 0; nsi--) {
4405
- var namespace = visibleNamespaces[nsi];
4406
- if (namespace.namespace === node.namespaceURI) {
4407
- if (namespace.prefix) {
4408
- prefixedNodeName = namespace.prefix + ':' + nodeName;
4409
- }
4410
- break
4411
- }
4412
- }
4413
- }
4414
- }
4415
-
4416
- buf.push('<', prefixedNodeName);
4417
-
4418
- for(var i=0;i<len;i++){
4419
- // add namespaces for attributes
4420
- var attr = attrs.item(i);
4421
- if (attr.prefix == 'xmlns') {
4422
- visibleNamespaces.push({ prefix: attr.localName, namespace: attr.value });
4423
- }else if(attr.nodeName == 'xmlns'){
4424
- visibleNamespaces.push({ prefix: '', namespace: attr.value });
4425
- }
4426
- }
4427
-
4428
- for(var i=0;i<len;i++){
4429
- var attr = attrs.item(i);
4430
- if (needNamespaceDefine(attr,isHTML, visibleNamespaces)) {
4431
- var prefix = attr.prefix||'';
4432
- var uri = attr.namespaceURI;
4433
- addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
4434
- visibleNamespaces.push({ prefix: prefix, namespace:uri });
4435
- }
4436
- serializeToString(attr,buf,isHTML,nodeFilter,visibleNamespaces);
4437
- }
4438
-
4439
- // add namespace for current node
4440
- if (nodeName === prefixedNodeName && needNamespaceDefine(node, isHTML, visibleNamespaces)) {
4441
- var prefix = node.prefix||'';
4442
- var uri = node.namespaceURI;
4443
- addSerializedAttribute(buf, prefix ? 'xmlns:' + prefix : "xmlns", uri);
4444
- visibleNamespaces.push({ prefix: prefix, namespace:uri });
4445
- }
4446
-
4447
- if(child || isHTML && !/^(?:meta|link|img|br|hr|input)$/i.test(nodeName)){
4448
- buf.push('>');
4449
- //if is cdata child node
4450
- if(isHTML && /^script$/i.test(nodeName)){
4451
- while(child){
4452
- if(child.data){
4453
- buf.push(child.data);
4454
- }else {
4455
- serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
4456
- }
4457
- child = child.nextSibling;
4458
- }
4459
- }else
4460
- {
4461
- while(child){
4462
- serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
4463
- child = child.nextSibling;
4464
- }
4465
- }
4466
- buf.push('</',prefixedNodeName,'>');
4467
- }else {
4468
- buf.push('/>');
4469
- }
4470
- // remove added visible namespaces
4471
- //visibleNamespaces.length = startVisibleNamespaces;
4472
- return;
4473
- case DOCUMENT_NODE:
4474
- case DOCUMENT_FRAGMENT_NODE:
4475
- var child = node.firstChild;
4476
- while(child){
4477
- serializeToString(child, buf, isHTML, nodeFilter, visibleNamespaces.slice());
4478
- child = child.nextSibling;
4479
- }
4480
- return;
4481
- case ATTRIBUTE_NODE:
4482
- return addSerializedAttribute(buf, node.name, node.value);
4483
- case TEXT_NODE:
4484
- /**
4485
- * The ampersand character (&) and the left angle bracket (<) must not appear in their literal form,
4486
- * except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section.
4487
- * If they are needed elsewhere, they must be escaped using either numeric character references or the strings
4488
- * `&amp;` and `&lt;` respectively.
4489
- * The right angle bracket (>) may be represented using the string " &gt; ", and must, for compatibility,
4490
- * be escaped using either `&gt;` or a character reference when it appears in the string `]]>` in content,
4491
- * when that string is not marking the end of a CDATA section.
4492
- *
4493
- * In the content of elements, character data is any string of characters
4494
- * which does not contain the start-delimiter of any markup
4495
- * and does not include the CDATA-section-close delimiter, `]]>`.
4496
- *
4497
- * @see https://www.w3.org/TR/xml/#NT-CharData
4498
- */
4499
- return buf.push(node.data
4500
- .replace(/[<&]/g,_xmlEncoder)
4501
- .replace(/]]>/g, ']]&gt;')
4502
- );
4503
- case CDATA_SECTION_NODE:
4504
- return buf.push( '<![CDATA[',node.data,']]>');
4505
- case COMMENT_NODE:
4506
- return buf.push( "<!--",node.data,"-->");
4507
- case DOCUMENT_TYPE_NODE:
4508
- var pubid = node.publicId;
4509
- var sysid = node.systemId;
4510
- buf.push('<!DOCTYPE ',node.name);
4511
- if(pubid){
4512
- buf.push(' PUBLIC ', pubid);
4513
- if (sysid && sysid!='.') {
4514
- buf.push(' ', sysid);
4515
- }
4516
- buf.push('>');
4517
- }else if(sysid && sysid!='.'){
4518
- buf.push(' SYSTEM ', sysid, '>');
4519
- }else {
4520
- var sub = node.internalSubset;
4521
- if(sub){
4522
- buf.push(" [",sub,"]");
4523
- }
4524
- buf.push(">");
4525
- }
4526
- return;
4527
- case PROCESSING_INSTRUCTION_NODE:
4528
- return buf.push( "<?",node.target," ",node.data,"?>");
4529
- case ENTITY_REFERENCE_NODE:
4530
- return buf.push( '&',node.nodeName,';');
4531
- //case ENTITY_NODE:
4532
- //case NOTATION_NODE:
4533
- default:
4534
- buf.push('??',node.nodeName);
4535
- }
4536
- }
4537
- function importNode(doc,node,deep){
4538
- var node2;
4539
- switch (node.nodeType) {
4540
- case ELEMENT_NODE:
4541
- node2 = node.cloneNode(false);
4542
- node2.ownerDocument = doc;
4543
- //var attrs = node2.attributes;
4544
- //var len = attrs.length;
4545
- //for(var i=0;i<len;i++){
4546
- //node2.setAttributeNodeNS(importNode(doc,attrs.item(i),deep));
4547
- //}
4548
- case DOCUMENT_FRAGMENT_NODE:
4549
- break;
4550
- case ATTRIBUTE_NODE:
4551
- deep = true;
4552
- break;
4553
- //case ENTITY_REFERENCE_NODE:
4554
- //case PROCESSING_INSTRUCTION_NODE:
4555
- ////case TEXT_NODE:
4556
- //case CDATA_SECTION_NODE:
4557
- //case COMMENT_NODE:
4558
- // deep = false;
4559
- // break;
4560
- //case DOCUMENT_NODE:
4561
- //case DOCUMENT_TYPE_NODE:
4562
- //cannot be imported.
4563
- //case ENTITY_NODE:
4564
- //case NOTATION_NODE:
4565
- //can not hit in level3
4566
- //default:throw e;
4567
- }
4568
- if(!node2){
4569
- node2 = node.cloneNode(false);//false
4570
- }
4571
- node2.ownerDocument = doc;
4572
- node2.parentNode = null;
4573
- if(deep){
4574
- var child = node.firstChild;
4575
- while(child){
4576
- node2.appendChild(importNode(doc,child,deep));
4577
- child = child.nextSibling;
4578
- }
4579
- }
4580
- return node2;
4581
- }
4582
- //
4583
- //var _relationMap = {firstChild:1,lastChild:1,previousSibling:1,nextSibling:1,
4584
- // attributes:1,childNodes:1,parentNode:1,documentElement:1,doctype,};
4585
- function cloneNode(doc,node,deep){
4586
- var node2 = new node.constructor();
4587
- for(var n in node){
4588
- var v = node[n];
4589
- if(typeof v != 'object' ){
4590
- if(v != node2[n]){
4591
- node2[n] = v;
4592
- }
4593
- }
4594
- }
4595
- if(node.childNodes){
4596
- node2.childNodes = new NodeList();
4597
- }
4598
- node2.ownerDocument = doc;
4599
- switch (node2.nodeType) {
4600
- case ELEMENT_NODE:
4601
- var attrs = node.attributes;
4602
- var attrs2 = node2.attributes = new NamedNodeMap();
4603
- var len = attrs.length;
4604
- attrs2._ownerElement = node2;
4605
- for(var i=0;i<len;i++){
4606
- node2.setAttributeNode(cloneNode(doc,attrs.item(i),true));
4607
- }
4608
- break; case ATTRIBUTE_NODE:
4609
- deep = true;
4610
- }
4611
- if(deep){
4612
- var child = node.firstChild;
4613
- while(child){
4614
- node2.appendChild(cloneNode(doc,child,deep));
4615
- child = child.nextSibling;
4616
- }
4617
- }
4618
- return node2;
4619
- }
4620
-
4621
- function __set__(object,key,value){
4622
- object[key] = value;
4623
- }
4624
- //do dynamic
4625
- try{
4626
- if(Object.defineProperty){
4627
- Object.defineProperty(LiveNodeList.prototype,'length',{
4628
- get:function(){
4629
- _updateLiveList(this);
4630
- return this.$$length;
4631
- }
4632
- });
4633
-
4634
- Object.defineProperty(Node.prototype,'textContent',{
4635
- get:function(){
4636
- return getTextContent(this);
4637
- },
4638
-
4639
- set:function(data){
4640
- switch(this.nodeType){
4641
- case ELEMENT_NODE:
4642
- case DOCUMENT_FRAGMENT_NODE:
4643
- while(this.firstChild){
4644
- this.removeChild(this.firstChild);
4645
- }
4646
- if(data || String(data)){
4647
- this.appendChild(this.ownerDocument.createTextNode(data));
4648
- }
4649
- break;
4650
-
4651
- default:
4652
- this.data = data;
4653
- this.value = data;
4654
- this.nodeValue = data;
4655
- }
4656
- }
4657
- });
4658
-
4659
- function getTextContent(node){
4660
- switch(node.nodeType){
4661
- case ELEMENT_NODE:
4662
- case DOCUMENT_FRAGMENT_NODE:
4663
- var buf = [];
4664
- node = node.firstChild;
4665
- while(node){
4666
- if(node.nodeType!==7 && node.nodeType !==8){
4667
- buf.push(getTextContent(node));
4668
- }
4669
- node = node.nextSibling;
4670
- }
4671
- return buf.join('');
4672
- default:
4673
- return node.nodeValue;
4674
- }
4675
- }
4676
-
4677
- __set__ = function(object,key,value){
4678
- //console.log(value)
4679
- object['$$'+key] = value;
4680
- };
4681
- }
4682
- }catch(e){//ie8
4683
- }
4684
-
4685
- //if(typeof require == 'function'){
4686
- dom.DocumentType = DocumentType;
4687
- dom.DOMException = DOMException;
4688
- dom.DOMImplementation = DOMImplementation$1;
4689
- dom.Element = Element;
4690
- dom.Node = Node;
4691
- dom.NodeList = NodeList;
4692
- dom.XMLSerializer = XMLSerializer;
4693
-
4694
- var conventions = conventions$2;
4695
- var entities = entities$1;
4696
-
4697
- var NAMESPACE = conventions.NAMESPACE;
4698
-
4699
- function DOMParser(options){
4700
- this.options = options ||{locator:{}};
4701
- }
4702
-
4703
- DOMParser.prototype.parseFromString = function(source,mimeType){
4704
- var options = this.options;
4705
- var sax = new XMLReader();
4706
- var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler
4707
- var errorHandler = options.errorHandler;
4708
- var locator = options.locator;
4709
- var defaultNSMap = options.xmlns||{};
4710
- var isHTML = /\/x?html?$/.test(mimeType);//mimeType.toLowerCase().indexOf('html') > -1;
4711
- var entityMap = isHTML ? entities.HTML_ENTITIES : entities.XML_ENTITIES;
4712
- if(locator){
4713
- domBuilder.setDocumentLocator(locator);
4714
- }
4715
-
4716
- sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator);
4717
- sax.domBuilder = options.domBuilder || domBuilder;
4718
- if(isHTML){
4719
- defaultNSMap[''] = NAMESPACE.HTML;
4720
- }
4721
- defaultNSMap.xml = defaultNSMap.xml || NAMESPACE.XML;
4722
- if(source && typeof source === 'string'){
4723
- sax.parse(source,defaultNSMap,entityMap);
4724
- }else {
4725
- sax.errorHandler.error("invalid doc source");
4726
- }
4727
- return domBuilder.doc;
4728
- };
4729
- function buildErrorHandler(errorImpl,domBuilder,locator){
4730
- if(!errorImpl){
4731
- if(domBuilder instanceof DOMHandler){
4732
- return domBuilder;
4733
- }
4734
- errorImpl = domBuilder ;
4735
- }
4736
- var errorHandler = {};
4737
- var isCallback = errorImpl instanceof Function;
4738
- locator = locator||{};
4739
- function build(key){
4740
- var fn = errorImpl[key];
4741
- if(!fn && isCallback){
4742
- fn = errorImpl.length == 2?function(msg){errorImpl(key,msg);}:errorImpl;
4743
- }
4744
- errorHandler[key] = fn && function(msg){
4745
- fn('[xmldom '+key+']\t'+msg+_locator(locator));
4746
- }||function(){};
4747
- }
4748
- build('warning');
4749
- build('error');
4750
- build('fatalError');
4751
- return errorHandler;
4752
- }
4753
-
4754
- //console.log('#\n\n\n\n\n\n\n####')
4755
- /**
4756
- * +ContentHandler+ErrorHandler
4757
- * +LexicalHandler+EntityResolver2
4758
- * -DeclHandler-DTDHandler
4759
- *
4760
- * DefaultHandler:EntityResolver, DTDHandler, ContentHandler, ErrorHandler
4761
- * DefaultHandler2:DefaultHandler,LexicalHandler, DeclHandler, EntityResolver2
4762
- * @link http://www.saxproject.org/apidoc/org/xml/sax/helpers/DefaultHandler.html
4763
- */
4764
- function DOMHandler() {
4765
- this.cdata = false;
4766
- }
4767
- function position(locator,node){
4768
- node.lineNumber = locator.lineNumber;
4769
- node.columnNumber = locator.columnNumber;
4770
- }
4771
- /**
4772
- * @see org.xml.sax.ContentHandler#startDocument
4773
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ContentHandler.html
4774
- */
4775
- DOMHandler.prototype = {
4776
- startDocument : function() {
4777
- this.doc = new DOMImplementation().createDocument(null, null, null);
4778
- if (this.locator) {
4779
- this.doc.documentURI = this.locator.systemId;
4780
- }
4781
- },
4782
- startElement:function(namespaceURI, localName, qName, attrs) {
4783
- var doc = this.doc;
4784
- var el = doc.createElementNS(namespaceURI, qName||localName);
4785
- var len = attrs.length;
4786
- appendElement(this, el);
4787
- this.currentElement = el;
4788
-
4789
- this.locator && position(this.locator,el);
4790
- for (var i = 0 ; i < len; i++) {
4791
- var namespaceURI = attrs.getURI(i);
4792
- var value = attrs.getValue(i);
4793
- var qName = attrs.getQName(i);
4794
- var attr = doc.createAttributeNS(namespaceURI, qName);
4795
- this.locator &&position(attrs.getLocator(i),attr);
4796
- attr.value = attr.nodeValue = value;
4797
- el.setAttributeNode(attr);
4798
- }
4799
- },
4800
- endElement:function(namespaceURI, localName, qName) {
4801
- var current = this.currentElement;
4802
- current.tagName;
4803
- this.currentElement = current.parentNode;
4804
- },
4805
- startPrefixMapping:function(prefix, uri) {
4806
- },
4807
- endPrefixMapping:function(prefix) {
4808
- },
4809
- processingInstruction:function(target, data) {
4810
- var ins = this.doc.createProcessingInstruction(target, data);
4811
- this.locator && position(this.locator,ins);
4812
- appendElement(this, ins);
4813
- },
4814
- ignorableWhitespace:function(ch, start, length) {
4815
- },
4816
- characters:function(chars, start, length) {
4817
- chars = _toString.apply(this,arguments);
4818
- //console.log(chars)
4819
- if(chars){
4820
- if (this.cdata) {
4821
- var charNode = this.doc.createCDATASection(chars);
4822
- } else {
4823
- var charNode = this.doc.createTextNode(chars);
4824
- }
4825
- if(this.currentElement){
4826
- this.currentElement.appendChild(charNode);
4827
- }else if(/^\s*$/.test(chars)){
4828
- this.doc.appendChild(charNode);
4829
- //process xml
4830
- }
4831
- this.locator && position(this.locator,charNode);
4832
- }
4833
- },
4834
- skippedEntity:function(name) {
4835
- },
4836
- endDocument:function() {
4837
- this.doc.normalize();
4838
- },
4839
- setDocumentLocator:function (locator) {
4840
- if(this.locator = locator){// && !('lineNumber' in locator)){
4841
- locator.lineNumber = 0;
4842
- }
4843
- },
4844
- //LexicalHandler
4845
- comment:function(chars, start, length) {
4846
- chars = _toString.apply(this,arguments);
4847
- var comm = this.doc.createComment(chars);
4848
- this.locator && position(this.locator,comm);
4849
- appendElement(this, comm);
4850
- },
4851
-
4852
- startCDATA:function() {
4853
- //used in characters() methods
4854
- this.cdata = true;
4855
- },
4856
- endCDATA:function() {
4857
- this.cdata = false;
4858
- },
4859
-
4860
- startDTD:function(name, publicId, systemId) {
4861
- var impl = this.doc.implementation;
4862
- if (impl && impl.createDocumentType) {
4863
- var dt = impl.createDocumentType(name, publicId, systemId);
4864
- this.locator && position(this.locator,dt);
4865
- appendElement(this, dt);
4866
- }
4867
- },
4868
- /**
4869
- * @see org.xml.sax.ErrorHandler
4870
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ErrorHandler.html
4871
- */
4872
- warning:function(error) {
4873
- console.warn('[xmldom warning]\t'+error,_locator(this.locator));
4874
- },
4875
- error:function(error) {
4876
- console.error('[xmldom error]\t'+error,_locator(this.locator));
4877
- },
4878
- fatalError:function(error) {
4879
- throw new ParseError(error, this.locator);
4880
- }
4881
- };
4882
- function _locator(l){
4883
- if(l){
4884
- return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']'
4885
- }
4886
- }
4887
- function _toString(chars,start,length){
4888
- if(typeof chars == 'string'){
4889
- return chars.substr(start,length)
4890
- }else {//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)")
4891
- if(chars.length >= start+length || start){
4892
- return new java.lang.String(chars,start,length)+'';
4893
- }
4894
- return chars;
4895
- }
4896
- }
4897
-
4898
- /*
4899
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/LexicalHandler.html
4900
- * used method of org.xml.sax.ext.LexicalHandler:
4901
- * #comment(chars, start, length)
4902
- * #startCDATA()
4903
- * #endCDATA()
4904
- * #startDTD(name, publicId, systemId)
4905
- *
4906
- *
4907
- * IGNORED method of org.xml.sax.ext.LexicalHandler:
4908
- * #endDTD()
4909
- * #startEntity(name)
4910
- * #endEntity(name)
4911
- *
4912
- *
4913
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/DeclHandler.html
4914
- * IGNORED method of org.xml.sax.ext.DeclHandler
4915
- * #attributeDecl(eName, aName, type, mode, value)
4916
- * #elementDecl(name, model)
4917
- * #externalEntityDecl(name, publicId, systemId)
4918
- * #internalEntityDecl(name, value)
4919
- * @link http://www.saxproject.org/apidoc/org/xml/sax/ext/EntityResolver2.html
4920
- * IGNORED method of org.xml.sax.EntityResolver2
4921
- * #resolveEntity(String name,String publicId,String baseURI,String systemId)
4922
- * #resolveEntity(publicId, systemId)
4923
- * #getExternalSubset(name, baseURI)
4924
- * @link http://www.saxproject.org/apidoc/org/xml/sax/DTDHandler.html
4925
- * IGNORED method of org.xml.sax.DTDHandler
4926
- * #notationDecl(name, publicId, systemId) {};
4927
- * #unparsedEntityDecl(name, publicId, systemId, notationName) {};
4928
- */
4929
- "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){
4930
- DOMHandler.prototype[key] = function(){return null};
4931
- });
4932
-
4933
- /* Private static helpers treated below as private instance methods, so don't need to add these to the public API; we might use a Relator to also get rid of non-standard public properties */
4934
- function appendElement (hander,node) {
4935
- if (!hander.currentElement) {
4936
- hander.doc.appendChild(node);
4937
- } else {
4938
- hander.currentElement.appendChild(node);
4939
- }
4940
- }//appendChild and setAttributeNS are preformance key
4941
-
4942
- //if(typeof require == 'function'){
4943
- var sax = sax$1;
4944
- var XMLReader = sax.XMLReader;
4945
- var ParseError = sax.ParseError;
4946
- var DOMImplementation = domParser.DOMImplementation = dom.DOMImplementation;
4947
- domParser.XMLSerializer = dom.XMLSerializer ;
4948
- domParser.DOMParser = DOMParser;
4949
- domParser.__DOMHandler = DOMHandler;
4950
-
4951
- var parseJson$1 = {};
4952
-
4953
- Object.defineProperty(parseJson$1, "__esModule", { value: true });
4954
- parseJson$1.parseJson = void 0;
4955
- /**
4956
- * Parses a given string into JSON.
4957
- * Gracefully handles invalid JSON by returning `null`.
4958
- */
4959
- function parseJson(data) {
4960
- try {
4961
- var json = JSON.parse(data);
4962
- return json;
4963
- }
4964
- catch (_) {
4965
- return null;
4966
- }
4967
- }
4968
- parseJson$1.parseJson = parseJson;
4969
-
4970
- var bufferFrom$1 = {};
4971
-
4972
- Object.defineProperty(bufferFrom$1, "__esModule", { value: true });
4973
- bufferFrom$1.bufferFrom = void 0;
4974
- /**
4975
- * Convert a given string into a `Uint8Array`.
4976
- * We don't use `TextEncoder` because it's unavailable in some environments.
4977
- */
4978
- function bufferFrom(init) {
4979
- var encodedString = encodeURIComponent(init);
4980
- var binaryString = encodedString.replace(/%([0-9A-F]{2})/g, function (_, char) {
4981
- return String.fromCharCode(('0x' + char));
4982
- });
4983
- var buffer = new Uint8Array(binaryString.length);
4984
- Array.prototype.forEach.call(binaryString, function (char, index) {
4985
- buffer[index] = char.charCodeAt(0);
4986
- });
4987
- return buffer;
4988
- }
4989
- bufferFrom$1.bufferFrom = bufferFrom;
4990
-
4991
- var createEvent$1 = {};
4992
-
4993
- var EventPolyfill$1 = {};
4994
-
4995
- Object.defineProperty(EventPolyfill$1, "__esModule", { value: true });
4996
- EventPolyfill$1.EventPolyfill = void 0;
4997
- var EventPolyfill = /** @class */ (function () {
4998
- function EventPolyfill(type, options) {
4999
- this.AT_TARGET = 0;
5000
- this.BUBBLING_PHASE = 0;
5001
- this.CAPTURING_PHASE = 0;
5002
- this.NONE = 0;
5003
- this.type = '';
5004
- this.srcElement = null;
5005
- this.currentTarget = null;
5006
- this.eventPhase = 0;
5007
- this.isTrusted = true;
5008
- this.composed = false;
5009
- this.cancelable = true;
5010
- this.defaultPrevented = false;
5011
- this.bubbles = true;
5012
- this.lengthComputable = true;
5013
- this.loaded = 0;
5014
- this.total = 0;
5015
- this.cancelBubble = false;
5016
- this.returnValue = true;
5017
- this.type = type;
5018
- this.target = (options === null || options === void 0 ? void 0 : options.target) || null;
5019
- this.currentTarget = (options === null || options === void 0 ? void 0 : options.currentTarget) || null;
5020
- this.timeStamp = Date.now();
5021
- }
5022
- EventPolyfill.prototype.composedPath = function () {
5023
- return [];
5024
- };
5025
- EventPolyfill.prototype.initEvent = function (type, bubbles, cancelable) {
5026
- this.type = type;
5027
- this.bubbles = !!bubbles;
5028
- this.cancelable = !!cancelable;
5029
- };
5030
- EventPolyfill.prototype.preventDefault = function () {
5031
- this.defaultPrevented = true;
5032
- };
5033
- EventPolyfill.prototype.stopPropagation = function () { };
5034
- EventPolyfill.prototype.stopImmediatePropagation = function () { };
5035
- return EventPolyfill;
5036
- }());
5037
- EventPolyfill$1.EventPolyfill = EventPolyfill;
5038
-
5039
- var ProgressEventPolyfill$1 = {};
5040
-
5041
- var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
5042
- var extendStatics = function (d, b) {
5043
- extendStatics = Object.setPrototypeOf ||
5044
- ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5045
- function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
5046
- return extendStatics(d, b);
5047
- };
5048
- return function (d, b) {
5049
- if (typeof b !== "function" && b !== null)
5050
- throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
5051
- extendStatics(d, b);
5052
- function __() { this.constructor = d; }
5053
- d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
5054
- };
5055
- })();
5056
- Object.defineProperty(ProgressEventPolyfill$1, "__esModule", { value: true });
5057
- ProgressEventPolyfill$1.ProgressEventPolyfill = void 0;
5058
- var EventPolyfill_1$1 = EventPolyfill$1;
5059
- var ProgressEventPolyfill = /** @class */ (function (_super) {
5060
- __extends(ProgressEventPolyfill, _super);
5061
- function ProgressEventPolyfill(type, init) {
5062
- var _this = _super.call(this, type) || this;
5063
- _this.lengthComputable = (init === null || init === void 0 ? void 0 : init.lengthComputable) || false;
5064
- _this.composed = (init === null || init === void 0 ? void 0 : init.composed) || false;
5065
- _this.loaded = (init === null || init === void 0 ? void 0 : init.loaded) || 0;
5066
- _this.total = (init === null || init === void 0 ? void 0 : init.total) || 0;
5067
- return _this;
5068
- }
5069
- return ProgressEventPolyfill;
5070
- }(EventPolyfill_1$1.EventPolyfill));
5071
- ProgressEventPolyfill$1.ProgressEventPolyfill = ProgressEventPolyfill;
5072
-
5073
- Object.defineProperty(createEvent$1, "__esModule", { value: true });
5074
- createEvent$1.createEvent = void 0;
5075
- var EventPolyfill_1 = EventPolyfill$1;
5076
- var ProgressEventPolyfill_1 = ProgressEventPolyfill$1;
5077
- var SUPPORTS_PROGRESS_EVENT = typeof ProgressEvent !== 'undefined';
5078
- function createEvent(target, type, init) {
5079
- var progressEvents = [
5080
- 'error',
5081
- 'progress',
5082
- 'loadstart',
5083
- 'loadend',
5084
- 'load',
5085
- 'timeout',
5086
- 'abort',
5087
- ];
5088
- /**
5089
- * `ProgressEvent` is not supported in React Native.
5090
- * @see https://github.com/mswjs/interceptors/issues/40
5091
- */
5092
- var ProgressEventClass = SUPPORTS_PROGRESS_EVENT
5093
- ? ProgressEvent
5094
- : ProgressEventPolyfill_1.ProgressEventPolyfill;
5095
- var event = progressEvents.includes(type)
5096
- ? new ProgressEventClass(type, {
5097
- lengthComputable: true,
5098
- loaded: (init === null || init === void 0 ? void 0 : init.loaded) || 0,
5099
- total: (init === null || init === void 0 ? void 0 : init.total) || 0,
5100
- })
5101
- : new EventPolyfill_1.EventPolyfill(type, {
5102
- target: target,
5103
- currentTarget: target,
5104
- });
5105
- return event;
5106
- }
5107
- createEvent$1.createEvent = createEvent;
5108
-
5109
- var __awaiter = (commonjsGlobal && commonjsGlobal.__awaiter) || function (thisArg, _arguments, P, generator) {
5110
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
5111
- return new (P || (P = Promise))(function (resolve, reject) {
5112
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5113
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
5114
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
5115
- step((generator = generator.apply(thisArg, _arguments || [])).next());
5116
- });
5117
- };
5118
- var __generator = (commonjsGlobal && commonjsGlobal.__generator) || function (thisArg, body) {
5119
- var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
5120
- return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
5121
- function verb(n) { return function (v) { return step([n, v]); }; }
5122
- function step(op) {
5123
- if (f) throw new TypeError("Generator is already executing.");
5124
- while (_) try {
5125
- if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
5126
- if (y = 0, t) op = [op[0] & 2, t.value];
5127
- switch (op[0]) {
5128
- case 0: case 1: t = op; break;
5129
- case 4: _.label++; return { value: op[1], done: false };
5130
- case 5: _.label++; y = op[1]; op = [0]; continue;
5131
- case 7: op = _.ops.pop(); _.trys.pop(); continue;
5132
- default:
5133
- if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
5134
- if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
5135
- if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
5136
- if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
5137
- if (t[2]) _.ops.pop();
5138
- _.trys.pop(); continue;
5139
- }
5140
- op = body.call(thisArg, _);
5141
- } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
5142
- if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
5143
- }
5144
- };
5145
- var __values = (commonjsGlobal && commonjsGlobal.__values) || function(o) {
5146
- var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
5147
- if (m) return m.call(o);
5148
- if (o && typeof o.length === "number") return {
5149
- next: function () {
5150
- if (o && i >= o.length) o = void 0;
5151
- return { value: o && o[i++], done: !o };
5152
- }
5153
- };
5154
- throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
5155
- };
5156
- var __read = (commonjsGlobal && commonjsGlobal.__read) || function (o, n) {
5157
- var m = typeof Symbol === "function" && o[Symbol.iterator];
5158
- if (!m) return o;
5159
- var i = m.call(o), r, ar = [], e;
5160
- try {
5161
- while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
5162
- }
5163
- catch (error) { e = { error: error }; }
5164
- finally {
5165
- try {
5166
- if (r && !r.done && (m = i["return"])) m.call(i);
5167
- }
5168
- finally { if (e) throw e.error; }
5169
- }
5170
- return ar;
5171
- };
5172
- Object.defineProperty(XMLHttpRequestOverride, "__esModule", { value: true });
5173
- XMLHttpRequestOverride.createXMLHttpRequestOverride = void 0;
5174
- /**
5175
- * XMLHttpRequest override class.
5176
- * Inspired by https://github.com/marvinhagemeister/xhr-mocklet.
5177
- */
5178
- var until_1 = lib$2;
5179
- var headers_utils_1 = lib$4;
5180
- var xmldom_1 = domParser;
5181
- var parseJson_1 = parseJson$1;
5182
- var toIsoResponse_1 = toIsoResponse$1;
5183
- var uuid_1 = uuid;
5184
- var bufferFrom_1 = bufferFrom$1;
5185
- var createEvent_1 = createEvent$1;
5186
- var createDebug = require$$3;
5187
- var createXMLHttpRequestOverride = function (options) {
5188
- var _a;
5189
- var pureXMLHttpRequest = options.pureXMLHttpRequest, observer = options.observer, resolver = options.resolver;
5190
- var debug = createDebug('XHR');
5191
- return _a = /** @class */ (function () {
5192
- function XMLHttpRequestOverride() {
5193
- // Collection of events modified by `addEventListener`/`removeEventListener` calls.
5194
- this._events = [];
5195
- this.UNSENT = 0;
5196
- this.OPENED = 1;
5197
- this.HEADERS_RECEIVED = 2;
5198
- this.LOADING = 3;
5199
- this.DONE = 4;
5200
- this.onreadystatechange = null;
5201
- /* Events */
5202
- this.onabort = null;
5203
- this.onerror = null;
5204
- this.onload = null;
5205
- this.onloadend = null;
5206
- this.onloadstart = null;
5207
- this.onprogress = null;
5208
- this.ontimeout = null;
5209
- this.url = '';
5210
- this.method = 'GET';
5211
- this.readyState = this.UNSENT;
5212
- this.withCredentials = false;
5213
- this.status = 200;
5214
- this.statusText = 'OK';
5215
- this.data = '';
5216
- this.response = '';
5217
- this.responseType = 'text';
5218
- this.responseText = '';
5219
- this.responseXML = null;
5220
- this.responseURL = '';
5221
- this.upload = null;
5222
- this.timeout = 0;
5223
- this._requestHeaders = new headers_utils_1.Headers();
5224
- this._responseHeaders = new headers_utils_1.Headers();
5225
- }
5226
- XMLHttpRequestOverride.prototype.setReadyState = function (nextState) {
5227
- if (nextState === this.readyState) {
5228
- return;
5229
- }
5230
- debug('readyState change %d -> %d', this.readyState, nextState);
5231
- this.readyState = nextState;
5232
- if (nextState !== this.UNSENT) {
5233
- debug('triggerring readystate change...');
5234
- this.trigger('readystatechange');
5235
- }
5236
- };
5237
- /**
5238
- * Triggers both direct callback and attached event listeners
5239
- * for the given event.
5240
- */
5241
- XMLHttpRequestOverride.prototype.trigger = function (eventName, options) {
5242
- var e_1, _a;
5243
- debug('trigger "%s" (%d)', eventName, this.readyState);
5244
- debug('resolve listener for event "%s"', eventName);
5245
- // @ts-expect-error XMLHttpRequest class has no index signature.
5246
- var callback = this["on" + eventName];
5247
- callback === null || callback === void 0 ? void 0 : callback.call(this, createEvent_1.createEvent(this, eventName, options));
5248
- try {
5249
- for (var _b = __values(this._events), _c = _b.next(); !_c.done; _c = _b.next()) {
5250
- var event_1 = _c.value;
5251
- if (event_1.name === eventName) {
5252
- debug('calling mock event listener "%s" (%d)', eventName, this.readyState);
5253
- event_1.listener.call(this, createEvent_1.createEvent(this, eventName, options));
5254
- }
5255
- }
5256
- }
5257
- catch (e_1_1) { e_1 = { error: e_1_1 }; }
5258
- finally {
5259
- try {
5260
- if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
5261
- }
5262
- finally { if (e_1) throw e_1.error; }
5263
- }
5264
- return this;
5265
- };
5266
- XMLHttpRequestOverride.prototype.reset = function () {
5267
- debug('reset');
5268
- this.setReadyState(this.UNSENT);
5269
- this.status = 200;
5270
- this.statusText = 'OK';
5271
- this.data = '';
5272
- this.response = null;
5273
- this.responseText = null;
5274
- this.responseXML = null;
5275
- this._requestHeaders = new headers_utils_1.Headers();
5276
- this._responseHeaders = new headers_utils_1.Headers();
5277
- };
5278
- XMLHttpRequestOverride.prototype.open = function (method, url, async, user, password) {
5279
- if (async === void 0) { async = true; }
5280
- return __awaiter(this, void 0, void 0, function () {
5281
- return __generator(this, function (_a) {
5282
- debug = createDebug("XHR " + method + " " + url);
5283
- debug('open', { method: method, url: url, async: async, user: user, password: password });
5284
- this.reset();
5285
- this.setReadyState(this.OPENED);
5286
- if (typeof url === 'undefined') {
5287
- this.url = method;
5288
- this.method = 'GET';
5289
- }
5290
- else {
5291
- this.url = url;
5292
- this.method = method;
5293
- this.async = async;
5294
- this.user = user;
5295
- this.password = password;
5296
- }
5297
- return [2 /*return*/];
5298
- });
5299
- });
5300
- };
5301
- XMLHttpRequestOverride.prototype.send = function (data) {
5302
- var _this = this;
5303
- debug('send %s %s', this.method, this.url);
5304
- this.data = data || '';
5305
- var url;
5306
- try {
5307
- url = new URL(this.url);
5308
- }
5309
- catch (error) {
5310
- // Assume a relative URL, if construction of a new `URL` instance fails.
5311
- // Since `XMLHttpRequest` always executed in a DOM-like environment,
5312
- // resolve the relative request URL against the current window location.
5313
- url = new URL(this.url, window.location.href);
5314
- }
5315
- debug('request headers', this._requestHeaders);
5316
- // Create an intercepted request instance exposed to the request intercepting middleware.
5317
- var isoRequest = {
5318
- id: uuid_1.uuidv4(),
5319
- url: url,
5320
- method: this.method,
5321
- body: this.data,
5322
- headers: this._requestHeaders,
5323
- };
5324
- observer.emit('request', isoRequest);
5325
- debug('awaiting mocked response...');
5326
- Promise.resolve(until_1.until(function () { return __awaiter(_this, void 0, void 0, function () { return __generator(this, function (_a) {
5327
- return [2 /*return*/, resolver(isoRequest, this)];
5328
- }); }); })).then(function (_a) {
5329
- var _b;
5330
- var _c = __read(_a, 2), middlewareException = _c[0], mockedResponse = _c[1];
5331
- // When the request middleware throws an exception, error the request.
5332
- // This cancels the request and is similar to a network error.
5333
- if (middlewareException) {
5334
- debug('middleware function threw an exception!', middlewareException);
5335
- // No way to propagate the actual error message.
5336
- _this.trigger('error');
5337
- _this.abort();
5338
- return;
5339
- }
5340
- // Return a mocked response, if provided in the middleware.
5341
- if (mockedResponse) {
5342
- debug('received mocked response', mockedResponse);
5343
- // Trigger a loadstart event to indicate the initialization of the fetch.
5344
- _this.trigger('loadstart');
5345
- _this.status = mockedResponse.status || 200;
5346
- _this.statusText = mockedResponse.statusText || 'OK';
5347
- _this._responseHeaders = mockedResponse.headers
5348
- ? headers_utils_1.objectToHeaders(mockedResponse.headers)
5349
- : new headers_utils_1.Headers();
5350
- debug('set response status', _this.status, _this.statusText);
5351
- debug('set response headers', _this._responseHeaders);
5352
- // Mark that response headers has been received
5353
- // and trigger a ready state event to reflect received headers
5354
- // in a custom `onreadystatechange` callback.
5355
- _this.setReadyState(_this.HEADERS_RECEIVED);
5356
- debug('response type', _this.responseType);
5357
- _this.response = _this.getResponseBody(mockedResponse.body);
5358
- _this.responseText = mockedResponse.body || '';
5359
- _this.responseXML = _this.getResponseXML();
5360
- debug('set response body', _this.response);
5361
- if (mockedResponse.body && _this.response) {
5362
- _this.setReadyState(_this.LOADING);
5363
- // Presense of the mocked response implies a response body (not null).
5364
- // Presense of the coerced `this.response` implies the mocked body is valid.
5365
- var bodyBuffer = bufferFrom_1.bufferFrom(mockedResponse.body);
5366
- // Trigger a progress event based on the mocked response body.
5367
- _this.trigger('progress', {
5368
- loaded: bodyBuffer.length,
5369
- total: bodyBuffer.length,
5370
- });
5371
- }
5372
- /**
5373
- * Explicitly mark the request as done so its response never hangs.
5374
- * @see https://github.com/mswjs/interceptors/issues/13
5375
- */
5376
- _this.setReadyState(_this.DONE);
5377
- // Trigger a load event to indicate the fetch has succeeded.
5378
- _this.trigger('load');
5379
- // Trigger a loadend event to indicate the fetch has completed.
5380
- _this.trigger('loadend');
5381
- observer.emit('response', isoRequest, toIsoResponse_1.toIsoResponse(mockedResponse));
5382
- }
5383
- else {
5384
- debug('no mocked response received!');
5385
- // Perform an original request, when the request middleware returned no mocked response.
5386
- var originalRequest_1 = new pureXMLHttpRequest();
5387
- debug('opening an original request %s %s', _this.method, _this.url);
5388
- originalRequest_1.open(_this.method, _this.url, (_b = _this.async) !== null && _b !== void 0 ? _b : true, _this.user, _this.password);
5389
- // Reflect a successful state of the original request
5390
- // on the patched instance.
5391
- originalRequest_1.addEventListener('load', function () {
5392
- debug('original "onload"');
5393
- _this.status = originalRequest_1.status;
5394
- _this.statusText = originalRequest_1.statusText;
5395
- _this.responseURL = originalRequest_1.responseURL;
5396
- _this.responseType = originalRequest_1.responseType;
5397
- _this.response = originalRequest_1.response;
5398
- _this.responseText = originalRequest_1.responseText;
5399
- _this.responseXML = originalRequest_1.responseXML;
5400
- debug('set mock request readyState to DONE');
5401
- // Explicitly mark the mocked request instance as done
5402
- // so the response never hangs.
5403
- /**
5404
- * @note `readystatechange` listener is called TWICE
5405
- * in the case of unhandled request.
5406
- */
5407
- _this.setReadyState(_this.DONE);
5408
- debug('received original response', _this.status, _this.statusText);
5409
- debug('original response body:', _this.response);
5410
- var responseHeaders = originalRequest_1.getAllResponseHeaders();
5411
- debug('original response headers:\n', responseHeaders);
5412
- _this._responseHeaders = headers_utils_1.stringToHeaders(responseHeaders);
5413
- debug('original response headers (normalized)', _this._responseHeaders);
5414
- debug('original response finished');
5415
- observer.emit('response', isoRequest, {
5416
- status: originalRequest_1.status,
5417
- statusText: originalRequest_1.statusText,
5418
- headers: _this._responseHeaders,
5419
- body: originalRequest_1.response,
5420
- });
5421
- });
5422
- // Assign callbacks and event listeners from the intercepted XHR instance
5423
- // to the original XHR instance.
5424
- _this.propagateCallbacks(originalRequest_1);
5425
- _this.propagateListeners(originalRequest_1);
5426
- _this.propagateHeaders(originalRequest_1, _this._requestHeaders);
5427
- if (_this.async) {
5428
- originalRequest_1.timeout = _this.timeout;
5429
- }
5430
- debug('send', _this.data);
5431
- originalRequest_1.send(_this.data);
5432
- }
5433
- });
5434
- };
5435
- XMLHttpRequestOverride.prototype.abort = function () {
5436
- debug('abort');
5437
- if (this.readyState > this.UNSENT && this.readyState < this.DONE) {
5438
- this.setReadyState(this.UNSENT);
5439
- this.trigger('abort');
5440
- }
5441
- };
5442
- XMLHttpRequestOverride.prototype.dispatchEvent = function () {
5443
- return false;
5444
- };
5445
- XMLHttpRequestOverride.prototype.setRequestHeader = function (name, value) {
5446
- debug('set request header "%s" to "%s"', name, value);
5447
- this._requestHeaders.append(name, value);
5448
- };
5449
- XMLHttpRequestOverride.prototype.getResponseHeader = function (name) {
5450
- debug('get response header "%s"', name);
5451
- if (this.readyState < this.HEADERS_RECEIVED) {
5452
- debug('cannot return a header: headers not received (state: %s)', this.readyState);
5453
- return null;
5454
- }
5455
- var headerValue = this._responseHeaders.get(name);
5456
- debug('resolved response header "%s" to "%s"', name, headerValue, this._responseHeaders);
5457
- return headerValue;
5458
- };
5459
- XMLHttpRequestOverride.prototype.getAllResponseHeaders = function () {
5460
- debug('get all response headers');
5461
- if (this.readyState < this.HEADERS_RECEIVED) {
5462
- debug('cannot return headers: headers not received (state: %s)', this.readyState);
5463
- return '';
5464
- }
5465
- return headers_utils_1.headersToString(this._responseHeaders);
5466
- };
5467
- XMLHttpRequestOverride.prototype.addEventListener = function (name, listener) {
5468
- debug('addEventListener', name, listener);
5469
- this._events.push({
5470
- name: name,
5471
- listener: listener,
5472
- });
5473
- };
5474
- XMLHttpRequestOverride.prototype.removeEventListener = function (name, listener) {
5475
- debug('removeEventListener', name, listener);
5476
- this._events = this._events.filter(function (storedEvent) {
5477
- return storedEvent.name !== name && storedEvent.listener !== listener;
5478
- });
5479
- };
5480
- XMLHttpRequestOverride.prototype.overrideMimeType = function () { };
5481
- /**
5482
- * Resolves the response based on the `responseType` value.
5483
- */
5484
- XMLHttpRequestOverride.prototype.getResponseBody = function (body) {
5485
- // Handle an improperly set "null" value of the mocked response body.
5486
- var textBody = body !== null && body !== void 0 ? body : '';
5487
- debug('coerced response body to', textBody);
5488
- switch (this.responseType) {
5489
- case 'json': {
5490
- debug('resolving response body as JSON');
5491
- return parseJson_1.parseJson(textBody);
5492
- }
5493
- case 'blob': {
5494
- var blobType = this.getResponseHeader('content-type') || 'text/plain';
5495
- debug('resolving response body as Blob', { type: blobType });
5496
- return new Blob([textBody], {
5497
- type: blobType,
5498
- });
5499
- }
5500
- case 'arraybuffer': {
5501
- debug('resolving response body as ArrayBuffer');
5502
- var arrayBuffer = bufferFrom_1.bufferFrom(textBody);
5503
- return arrayBuffer;
5504
- }
5505
- default:
5506
- return textBody;
5507
- }
5508
- };
5509
- XMLHttpRequestOverride.prototype.getResponseXML = function () {
5510
- var contentType = this.getResponseHeader('Content-Type');
5511
- if (contentType === 'application/xml' || contentType === 'text/xml') {
5512
- return new xmldom_1.DOMParser().parseFromString(this.responseText, contentType);
5513
- }
5514
- return null;
5515
- };
5516
- /**
5517
- * Propagates mock XMLHttpRequest instance callbacks
5518
- * to the given XMLHttpRequest instance.
5519
- */
5520
- XMLHttpRequestOverride.prototype.propagateCallbacks = function (request) {
5521
- request.onabort = this.abort;
5522
- request.onerror = this.onerror;
5523
- request.ontimeout = this.ontimeout;
5524
- request.onload = this.onload;
5525
- request.onloadstart = this.onloadstart;
5526
- request.onloadend = this.onloadend;
5527
- request.onprogress = this.onprogress;
5528
- request.onreadystatechange = this.onreadystatechange;
5529
- };
5530
- /**
5531
- * Propagates the mock XMLHttpRequest instance listeners
5532
- * to the given XMLHttpRequest instance.
5533
- */
5534
- XMLHttpRequestOverride.prototype.propagateListeners = function (request) {
5535
- debug('propagating request listeners (%d) to the original request', this._events.length, this._events);
5536
- this._events.forEach(function (_a) {
5537
- var name = _a.name, listener = _a.listener;
5538
- request.addEventListener(name, listener);
5539
- });
5540
- };
5541
- XMLHttpRequestOverride.prototype.propagateHeaders = function (request, headers) {
5542
- debug('propagating request headers to the original request', headers);
5543
- // Preserve the request headers casing.
5544
- Object.entries(headers.raw()).forEach(function (_a) {
5545
- var _b = __read(_a, 2), name = _b[0], value = _b[1];
5546
- debug('setting "%s" (%s) header on the original request', name, value);
5547
- request.setRequestHeader(name, value);
5548
- });
5549
- };
5550
- return XMLHttpRequestOverride;
5551
- }()),
5552
- /* Request state */
5553
- _a.UNSENT = 0,
5554
- _a.OPENED = 1,
5555
- _a.HEADERS_RECEIVED = 2,
5556
- _a.LOADING = 3,
5557
- _a.DONE = 4,
5558
- _a;
5559
- };
5560
- XMLHttpRequestOverride.createXMLHttpRequestOverride = createXMLHttpRequestOverride;
5561
-
5562
- Object.defineProperty(XMLHttpRequest, "__esModule", { value: true });
5563
- var interceptXMLHttpRequest_1 = XMLHttpRequest.interceptXMLHttpRequest = void 0;
5564
- var XMLHttpRequestOverride_1 = XMLHttpRequestOverride;
5565
- var debug = require$$3('XHR');
5566
- var pureXMLHttpRequest =
5567
- // Although executed in node, certain processes emulate the DOM-like environment
5568
- // (i.e. `js-dom` in Jest). The `window` object would be avilable in such environments.
5569
- typeof window === 'undefined' ? undefined : window.XMLHttpRequest;
5570
- /**
5571
- * Intercepts requests issued via `XMLHttpRequest`.
5572
- */
5573
- var interceptXMLHttpRequest = function (observer, resolver) {
5574
- if (pureXMLHttpRequest) {
5575
- debug('patching "XMLHttpRequest" module...');
5576
- var XMLHttpRequestOverride = XMLHttpRequestOverride_1.createXMLHttpRequestOverride({
5577
- pureXMLHttpRequest: pureXMLHttpRequest,
5578
- observer: observer,
5579
- resolver: resolver,
5580
- });
5581
- window.XMLHttpRequest = XMLHttpRequestOverride;
5582
- }
5583
- return function () {
5584
- if (pureXMLHttpRequest) {
5585
- debug('restoring modules...');
5586
- window.XMLHttpRequest = pureXMLHttpRequest;
5587
- }
5588
- };
5589
- };
5590
- interceptXMLHttpRequest_1 = XMLHttpRequest.interceptXMLHttpRequest = interceptXMLHttpRequest;
5591
-
5592
- function uuidv4() {
5593
- return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
5594
- const r = (Math.random() * 16) | 0;
5595
- const v = c == 'x' ? r : (r & 0x3) | 0x8;
5596
- return v.toString(16);
5597
- });
5598
- }
5599
-
5600
1400
  /**
5601
1401
  * Converts a given isomorphic request to a `MockedRequest` instance.
5602
1402
  */
5603
1403
  function parseIsomorphicRequest(request) {
5604
- const requestId = uuidv4();
5605
- request.headers.set('x-msw-request-id', requestId);
5606
1404
  const mockedRequest = {
5607
- id: requestId,
1405
+ id: request.id,
5608
1406
  url: request.url,
5609
1407
  method: request.method,
5610
1408
  body: parseBody(request.body, request.headers),
@@ -5638,10 +1436,10 @@ function parseIsomorphicRequest(request) {
5638
1436
  }
5639
1437
 
5640
1438
  function createFallbackRequestListener(context, options) {
5641
- const interceptor = lib.createInterceptor({
5642
- modules: [interceptFetch_1, interceptXMLHttpRequest_1],
1439
+ const interceptor = createInterceptor({
1440
+ modules: [interceptFetch, interceptXMLHttpRequest],
5643
1441
  resolver(request) {
5644
- return __awaiter$3(this, void 0, void 0, function* () {
1442
+ return __awaiter(this, void 0, void 0, function* () {
5645
1443
  const mockedRequest = parseIsomorphicRequest(request);
5646
1444
  return handleRequest(mockedRequest, context.requestHandlers, options, context.emitter, {
5647
1445
  transformResponse(response) {
@@ -5667,7 +1465,7 @@ function createFallbackRequestListener(context, options) {
5667
1465
 
5668
1466
  function createFallbackStart(context) {
5669
1467
  return function start(options) {
5670
- return __awaiter$3(this, void 0, void 0, function* () {
1468
+ return __awaiter(this, void 0, void 0, function* () {
5671
1469
  context.fallbackInterceptor = createFallbackRequestListener(context, options);
5672
1470
  printStartMessage({
5673
1471
  message: 'Mocking enabled (fallback mode).',
@@ -5718,11 +1516,11 @@ function setupWorker(...requestHandlers) {
5718
1516
  throw new Error(devUtils.formatMessage('Failed to call "setupWorker" given an Array of request handlers (setupWorker([a, b])), expected to receive each handler individually: setupWorker(a, b).'));
5719
1517
  });
5720
1518
  // Error when attempting to run this function in a Node.js environment.
5721
- if (lib$6.exports.isNodeProcess()) {
1519
+ if (lib$3.exports.isNodeProcess()) {
5722
1520
  throw new Error(devUtils.formatMessage('Failed to execute `setupWorker` in a non-browser environment. Consider using `setupServer` for Node.js environment instead.'));
5723
1521
  }
5724
- const emitter = new lib$3.StrictEventEmitter();
5725
- const publicEmitter = new lib$3.StrictEventEmitter();
1522
+ const emitter = new lib$1.StrictEventEmitter();
1523
+ const publicEmitter = new lib$1.StrictEventEmitter();
5726
1524
  pipeEvents(emitter, publicEmitter);
5727
1525
  const context = {
5728
1526
  startOptions: undefined,