buildModuleUrl-14bfe498.js 171 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573
  1. /**
  2. * Cesium - https://github.com/AnalyticalGraphicsInc/cesium
  3. *
  4. * Copyright 2011-2017 Cesium Contributors
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. *
  18. * Columbus View (Pat. Pend.)
  19. *
  20. * Portions licensed separately.
  21. * See https://github.com/AnalyticalGraphicsInc/cesium/blob/master/LICENSE.md for full licensing details.
  22. */
  23. define(['exports', './when-8d13db60', './Check-70bec281', './RuntimeError-ba10bc3e'], function (exports, when, Check, RuntimeError) { 'use strict';
  24. /**
  25. * @license
  26. *
  27. * Grauw URI utilities
  28. *
  29. * See: http://hg.grauw.nl/grauw-lib/file/tip/src/uri.js
  30. *
  31. * @author Laurens Holst (http://www.grauw.nl/)
  32. *
  33. * Copyright 2012 Laurens Holst
  34. *
  35. * Licensed under the Apache License, Version 2.0 (the "License");
  36. * you may not use this file except in compliance with the License.
  37. * You may obtain a copy of the License at
  38. *
  39. * http://www.apache.org/licenses/LICENSE-2.0
  40. *
  41. * Unless required by applicable law or agreed to in writing, software
  42. * distributed under the License is distributed on an "AS IS" BASIS,
  43. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  44. * See the License for the specific language governing permissions and
  45. * limitations under the License.
  46. *
  47. */
  48. /**
  49. * Constructs a URI object.
  50. * @constructor
  51. * @class Implementation of URI parsing and base URI resolving algorithm in RFC 3986.
  52. * @param {string|URI} uri A string or URI object to create the object from.
  53. */
  54. function URI(uri) {
  55. if (uri instanceof URI) { // copy constructor
  56. this.scheme = uri.scheme;
  57. this.authority = uri.authority;
  58. this.path = uri.path;
  59. this.query = uri.query;
  60. this.fragment = uri.fragment;
  61. } else if (uri) { // uri is URI string or cast to string
  62. var c = parseRegex.exec(uri);
  63. this.scheme = c[1];
  64. this.authority = c[2];
  65. this.path = c[3];
  66. this.query = c[4];
  67. this.fragment = c[5];
  68. }
  69. }
  70. // Initial values on the prototype
  71. URI.prototype.scheme = null;
  72. URI.prototype.authority = null;
  73. URI.prototype.path = '';
  74. URI.prototype.query = null;
  75. URI.prototype.fragment = null;
  76. // Regular expression from RFC 3986 appendix B
  77. var parseRegex = new RegExp('^(?:([^:/?#]+):)?(?://([^/?#]*))?([^?#]*)(?:\\?([^#]*))?(?:#(.*))?$');
  78. /**
  79. * Returns the scheme part of the URI.
  80. * In "http://example.com:80/a/b?x#y" this is "http".
  81. */
  82. URI.prototype.getScheme = function() {
  83. return this.scheme;
  84. };
  85. /**
  86. * Returns the authority part of the URI.
  87. * In "http://example.com:80/a/b?x#y" this is "example.com:80".
  88. */
  89. URI.prototype.getAuthority = function() {
  90. return this.authority;
  91. };
  92. /**
  93. * Returns the path part of the URI.
  94. * In "http://example.com:80/a/b?x#y" this is "/a/b".
  95. * In "mailto:mike@example.com" this is "mike@example.com".
  96. */
  97. URI.prototype.getPath = function() {
  98. return this.path;
  99. };
  100. /**
  101. * Returns the query part of the URI.
  102. * In "http://example.com:80/a/b?x#y" this is "x".
  103. */
  104. URI.prototype.getQuery = function() {
  105. return this.query;
  106. };
  107. /**
  108. * Returns the fragment part of the URI.
  109. * In "http://example.com:80/a/b?x#y" this is "y".
  110. */
  111. URI.prototype.getFragment = function() {
  112. return this.fragment;
  113. };
  114. /**
  115. * Tests whether the URI is an absolute URI.
  116. * See RFC 3986 section 4.3.
  117. */
  118. URI.prototype.isAbsolute = function() {
  119. return !!this.scheme && !this.fragment;
  120. };
  121. ///**
  122. //* Extensive validation of the URI against the ABNF in RFC 3986
  123. //*/
  124. //URI.prototype.validate
  125. /**
  126. * Tests whether the URI is a same-document reference.
  127. * See RFC 3986 section 4.4.
  128. *
  129. * To perform more thorough comparison, you can normalise the URI objects.
  130. */
  131. URI.prototype.isSameDocumentAs = function(uri) {
  132. return uri.scheme == this.scheme &&
  133. uri.authority == this.authority &&
  134. uri.path == this.path &&
  135. uri.query == this.query;
  136. };
  137. /**
  138. * Simple String Comparison of two URIs.
  139. * See RFC 3986 section 6.2.1.
  140. *
  141. * To perform more thorough comparison, you can normalise the URI objects.
  142. */
  143. URI.prototype.equals = function(uri) {
  144. return this.isSameDocumentAs(uri) && uri.fragment == this.fragment;
  145. };
  146. /**
  147. * Normalizes the URI using syntax-based normalization.
  148. * This includes case normalization, percent-encoding normalization and path segment normalization.
  149. * XXX: Percent-encoding normalization does not escape characters that need to be escaped.
  150. * (Although that would not be a valid URI in the first place. See validate().)
  151. * See RFC 3986 section 6.2.2.
  152. */
  153. URI.prototype.normalize = function() {
  154. this.removeDotSegments();
  155. if (this.scheme)
  156. this.scheme = this.scheme.toLowerCase();
  157. if (this.authority)
  158. this.authority = this.authority.replace(authorityRegex, replaceAuthority).
  159. replace(caseRegex, replaceCase);
  160. if (this.path)
  161. this.path = this.path.replace(caseRegex, replaceCase);
  162. if (this.query)
  163. this.query = this.query.replace(caseRegex, replaceCase);
  164. if (this.fragment)
  165. this.fragment = this.fragment.replace(caseRegex, replaceCase);
  166. };
  167. var caseRegex = /%[0-9a-z]{2}/gi;
  168. var percentRegex = /[a-zA-Z0-9\-\._~]/;
  169. var authorityRegex = /(.*@)?([^@:]*)(:.*)?/;
  170. function replaceCase(str) {
  171. var dec = unescape(str);
  172. return percentRegex.test(dec) ? dec : str.toUpperCase();
  173. }
  174. function replaceAuthority(str, p1, p2, p3) {
  175. return (p1 || '') + p2.toLowerCase() + (p3 || '');
  176. }
  177. /**
  178. * Resolve a relative URI (this) against a base URI.
  179. * The base URI must be an absolute URI.
  180. * See RFC 3986 section 5.2
  181. */
  182. URI.prototype.resolve = function(baseURI) {
  183. var uri = new URI();
  184. if (this.scheme) {
  185. uri.scheme = this.scheme;
  186. uri.authority = this.authority;
  187. uri.path = this.path;
  188. uri.query = this.query;
  189. } else {
  190. uri.scheme = baseURI.scheme;
  191. if (this.authority) {
  192. uri.authority = this.authority;
  193. uri.path = this.path;
  194. uri.query = this.query;
  195. } else {
  196. uri.authority = baseURI.authority;
  197. if (this.path == '') {
  198. uri.path = baseURI.path;
  199. uri.query = this.query || baseURI.query;
  200. } else {
  201. if (this.path.charAt(0) == '/') {
  202. uri.path = this.path;
  203. uri.removeDotSegments();
  204. } else {
  205. if (baseURI.authority && baseURI.path == '') {
  206. uri.path = '/' + this.path;
  207. } else {
  208. uri.path = baseURI.path.substring(0, baseURI.path.lastIndexOf('/') + 1) + this.path;
  209. }
  210. uri.removeDotSegments();
  211. }
  212. uri.query = this.query;
  213. }
  214. }
  215. }
  216. uri.fragment = this.fragment;
  217. return uri;
  218. };
  219. /**
  220. * Remove dot segments from path.
  221. * See RFC 3986 section 5.2.4
  222. * @private
  223. */
  224. URI.prototype.removeDotSegments = function() {
  225. var input = this.path.split('/'),
  226. output = [],
  227. segment,
  228. absPath = input[0] == '';
  229. if (absPath)
  230. input.shift();
  231. var sFirst = input[0] == '' ? input.shift() : null;
  232. while (input.length) {
  233. segment = input.shift();
  234. if (segment == '..') {
  235. output.pop();
  236. } else if (segment != '.') {
  237. output.push(segment);
  238. }
  239. }
  240. if (segment == '.' || segment == '..')
  241. output.push('');
  242. if (absPath)
  243. output.unshift('');
  244. this.path = output.join('/');
  245. };
  246. // We don't like this function because it builds up a cache that is never cleared.
  247. // /**
  248. // * Resolves a relative URI against an absolute base URI.
  249. // * Convenience method.
  250. // * @param {String} uri the relative URI to resolve
  251. // * @param {String} baseURI the base URI (must be absolute) to resolve against
  252. // */
  253. // URI.resolve = function(sURI, sBaseURI) {
  254. // var uri = cache[sURI] || (cache[sURI] = new URI(sURI));
  255. // var baseURI = cache[sBaseURI] || (cache[sBaseURI] = new URI(sBaseURI));
  256. // return uri.resolve(baseURI).toString();
  257. // };
  258. // var cache = {};
  259. /**
  260. * Serialises the URI to a string.
  261. */
  262. URI.prototype.toString = function() {
  263. var result = '';
  264. if (this.scheme)
  265. result += this.scheme + ':';
  266. if (this.authority)
  267. result += '//' + this.authority;
  268. result += this.path;
  269. if (this.query)
  270. result += '?' + this.query;
  271. if (this.fragment)
  272. result += '#' + this.fragment;
  273. return result;
  274. };
  275. /**
  276. * @private
  277. */
  278. function appendForwardSlash(url) {
  279. if (url.length === 0 || url[url.length - 1] !== '/') {
  280. url = url + '/';
  281. }
  282. return url;
  283. }
  284. /**
  285. * Clones an object, returning a new object containing the same properties.
  286. *
  287. * @exports clone
  288. *
  289. * @param {Object} object The object to clone.
  290. * @param {Boolean} [deep=false] If true, all properties will be deep cloned recursively.
  291. * @returns {Object} The cloned object.
  292. */
  293. function clone(object, deep) {
  294. if (object === null || typeof object !== 'object') {
  295. return object;
  296. }
  297. deep = when.defaultValue(deep, false);
  298. var result = new object.constructor();
  299. for ( var propertyName in object) {
  300. if (object.hasOwnProperty(propertyName)) {
  301. var value = object[propertyName];
  302. if (deep) {
  303. value = clone(value, deep);
  304. }
  305. result[propertyName] = value;
  306. }
  307. }
  308. return result;
  309. }
  310. /**
  311. * Merges two objects, copying their properties onto a new combined object. When two objects have the same
  312. * property, the value of the property on the first object is used. If either object is undefined,
  313. * it will be treated as an empty object.
  314. *
  315. * @example
  316. * var object1 = {
  317. * propOne : 1,
  318. * propTwo : {
  319. * value1 : 10
  320. * }
  321. * }
  322. * var object2 = {
  323. * propTwo : 2
  324. * }
  325. * var final = Cesium.combine(object1, object2);
  326. *
  327. * // final === {
  328. * // propOne : 1,
  329. * // propTwo : {
  330. * // value1 : 10
  331. * // }
  332. * // }
  333. *
  334. * @param {Object} [object1] The first object to merge.
  335. * @param {Object} [object2] The second object to merge.
  336. * @param {Boolean} [deep=false] Perform a recursive merge.
  337. * @returns {Object} The combined object containing all properties from both objects.
  338. *
  339. * @exports combine
  340. */
  341. function combine(object1, object2, deep) {
  342. deep = when.defaultValue(deep, false);
  343. var result = {};
  344. var object1Defined = when.defined(object1);
  345. var object2Defined = when.defined(object2);
  346. var property;
  347. var object1Value;
  348. var object2Value;
  349. if (object1Defined) {
  350. for (property in object1) {
  351. if (object1.hasOwnProperty(property)) {
  352. object1Value = object1[property];
  353. if (object2Defined && deep && typeof object1Value === 'object' && object2.hasOwnProperty(property)) {
  354. object2Value = object2[property];
  355. if (typeof object2Value === 'object') {
  356. result[property] = combine(object1Value, object2Value, deep);
  357. } else {
  358. result[property] = object1Value;
  359. }
  360. } else {
  361. result[property] = object1Value;
  362. }
  363. }
  364. }
  365. }
  366. if (object2Defined) {
  367. for (property in object2) {
  368. if (object2.hasOwnProperty(property) && !result.hasOwnProperty(property)) {
  369. object2Value = object2[property];
  370. result[property] = object2Value;
  371. }
  372. }
  373. }
  374. return result;
  375. }
  376. /**
  377. * Given a relative Uri and a base Uri, returns the absolute Uri of the relative Uri.
  378. * @exports getAbsoluteUri
  379. *
  380. * @param {String} relative The relative Uri.
  381. * @param {String} [base] The base Uri.
  382. * @returns {String} The absolute Uri of the given relative Uri.
  383. *
  384. * @example
  385. * //absolute Uri will be "https://test.com/awesome.png";
  386. * var absoluteUri = Cesium.getAbsoluteUri('awesome.png', 'https://test.com');
  387. */
  388. function getAbsoluteUri(relative, base) {
  389. var documentObject;
  390. if (typeof document !== 'undefined') {
  391. documentObject = document;
  392. }
  393. return getAbsoluteUri._implementation(relative, base, documentObject);
  394. }
  395. getAbsoluteUri._implementation = function(relative, base, documentObject) {
  396. //>>includeStart('debug', pragmas.debug);
  397. if (!when.defined(relative)) {
  398. throw new Check.DeveloperError('relative uri is required.');
  399. }
  400. //>>includeEnd('debug');
  401. if (!when.defined(base)) {
  402. if (typeof documentObject === 'undefined') {
  403. return relative;
  404. }
  405. base = when.defaultValue(documentObject.baseURI, documentObject.location.href);
  406. }
  407. var baseUri = new URI(base);
  408. var relativeUri = new URI(relative);
  409. return relativeUri.resolve(baseUri).toString();
  410. };
  411. /**
  412. * Given a URI, returns the base path of the URI.
  413. * @exports getBaseUri
  414. *
  415. * @param {String} uri The Uri.
  416. * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
  417. * @returns {String} The base path of the Uri.
  418. *
  419. * @example
  420. * // basePath will be "/Gallery/";
  421. * var basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false');
  422. *
  423. * // basePath will be "/Gallery/?value=true&example=false";
  424. * var basePath = Cesium.getBaseUri('/Gallery/simple.czml?value=true&example=false', true);
  425. */
  426. function getBaseUri(uri, includeQuery) {
  427. //>>includeStart('debug', pragmas.debug);
  428. if (!when.defined(uri)) {
  429. throw new Check.DeveloperError('uri is required.');
  430. }
  431. //>>includeEnd('debug');
  432. var basePath = '';
  433. var i = uri.lastIndexOf('/');
  434. if (i !== -1) {
  435. basePath = uri.substring(0, i + 1);
  436. }
  437. if (!includeQuery) {
  438. return basePath;
  439. }
  440. uri = new URI(uri);
  441. if (when.defined(uri.query)) {
  442. basePath += '?' + uri.query;
  443. }
  444. if (when.defined(uri.fragment)){
  445. basePath += '#' + uri.fragment;
  446. }
  447. return basePath;
  448. }
  449. /**
  450. * Given a URI, returns the extension of the URI.
  451. * @exports getExtensionFromUri
  452. *
  453. * @param {String} uri The Uri.
  454. * @returns {String} The extension of the Uri.
  455. *
  456. * @example
  457. * //extension will be "czml";
  458. * var extension = Cesium.getExtensionFromUri('/Gallery/simple.czml?value=true&example=false');
  459. */
  460. function getExtensionFromUri(uri) {
  461. //>>includeStart('debug', pragmas.debug);
  462. if (!when.defined(uri)) {
  463. throw new Check.DeveloperError('uri is required.');
  464. }
  465. //>>includeEnd('debug');
  466. var uriObject = new URI(uri);
  467. uriObject.normalize();
  468. var path = uriObject.path;
  469. var index = path.lastIndexOf('/');
  470. if (index !== -1) {
  471. path = path.substr(index + 1);
  472. }
  473. index = path.lastIndexOf('.');
  474. if (index === -1) {
  475. path = '';
  476. } else {
  477. path = path.substr(index + 1);
  478. }
  479. return path;
  480. }
  481. var blobUriRegex = /^blob:/i;
  482. /**
  483. * Determines if the specified uri is a blob uri.
  484. *
  485. * @exports isBlobUri
  486. *
  487. * @param {String} uri The uri to test.
  488. * @returns {Boolean} true when the uri is a blob uri; otherwise, false.
  489. *
  490. * @private
  491. */
  492. function isBlobUri(uri) {
  493. //>>includeStart('debug', pragmas.debug);
  494. Check.Check.typeOf.string('uri', uri);
  495. //>>includeEnd('debug');
  496. return blobUriRegex.test(uri);
  497. }
  498. var a;
  499. /**
  500. * Given a URL, determine whether that URL is considered cross-origin to the current page.
  501. *
  502. * @private
  503. */
  504. function isCrossOriginUrl(url) {
  505. if (!when.defined(a)) {
  506. a = document.createElement('a');
  507. }
  508. // copy window location into the anchor to get consistent results
  509. // when the port is default for the protocol (e.g. 80 for HTTP)
  510. a.href = window.location.href;
  511. // host includes both hostname and port if the port is not standard
  512. var host = a.host;
  513. var protocol = a.protocol;
  514. a.href = url;
  515. // IE only absolutizes href on get, not set
  516. a.href = a.href; // eslint-disable-line no-self-assign
  517. return protocol !== a.protocol || host !== a.host;
  518. }
  519. var dataUriRegex = /^data:/i;
  520. /**
  521. * Determines if the specified uri is a data uri.
  522. *
  523. * @exports isDataUri
  524. *
  525. * @param {String} uri The uri to test.
  526. * @returns {Boolean} true when the uri is a data uri; otherwise, false.
  527. *
  528. * @private
  529. */
  530. function isDataUri(uri) {
  531. //>>includeStart('debug', pragmas.debug);
  532. Check.Check.typeOf.string('uri', uri);
  533. //>>includeEnd('debug');
  534. return dataUriRegex.test(uri);
  535. }
  536. /**
  537. * @private
  538. */
  539. function loadAndExecuteScript(url) {
  540. var deferred = when.when.defer();
  541. var script = document.createElement('script');
  542. script.async = true;
  543. script.src = url;
  544. var head = document.getElementsByTagName('head')[0];
  545. script.onload = function() {
  546. script.onload = undefined;
  547. head.removeChild(script);
  548. deferred.resolve();
  549. };
  550. script.onerror = function(e) {
  551. deferred.reject(e);
  552. };
  553. head.appendChild(script);
  554. return deferred.promise;
  555. }
  556. /**
  557. * Converts an object representing a set of name/value pairs into a query string,
  558. * with names and values encoded properly for use in a URL. Values that are arrays
  559. * will produce multiple values with the same name.
  560. * @exports objectToQuery
  561. *
  562. * @param {Object} obj The object containing data to encode.
  563. * @returns {String} An encoded query string.
  564. *
  565. *
  566. * @example
  567. * var str = Cesium.objectToQuery({
  568. * key1 : 'some value',
  569. * key2 : 'a/b',
  570. * key3 : ['x', 'y']
  571. * });
  572. *
  573. * @see queryToObject
  574. * // str will be:
  575. * // 'key1=some%20value&key2=a%2Fb&key3=x&key3=y'
  576. */
  577. function objectToQuery(obj, donotEncodeSpecialCharacters) {
  578. //>>includeStart('debug', pragmas.debug);
  579. if (!when.defined(obj)) {
  580. throw new Check.DeveloperError('obj is required.');
  581. }
  582. //>>includeEnd('debug');
  583. var result = '';
  584. for ( var propName in obj) {
  585. if (obj.hasOwnProperty(propName)) {
  586. var value = obj[propName];
  587. var part = encodeURIComponent(propName) + '=';
  588. if (Array.isArray(value)) {
  589. for (var i = 0, len = value.length; i < len; ++i) {
  590. if (donotEncodeSpecialCharacters === true) {
  591. result += part + encodeURI(value[i]) + '&';
  592. } else {
  593. result += part + encodeURIComponent(value[i]) + '&';
  594. }
  595. }
  596. } else {
  597. if (donotEncodeSpecialCharacters === true) {
  598. result += part + encodeURI(value) + '&';
  599. } else {
  600. result += part + encodeURIComponent(value) + '&';
  601. }
  602. }
  603. }
  604. }
  605. // trim last &
  606. result = result.slice(0, -1);
  607. // This function used to replace %20 with + which is more compact and readable.
  608. // However, some servers didn't properly handle + as a space.
  609. // https://github.com/CesiumGS/cesium/issues/2192
  610. return result;
  611. }
  612. /**
  613. * Parses a query string into an object, where the keys and values of the object are the
  614. * name/value pairs from the query string, decoded. If a name appears multiple times,
  615. * the value in the object will be an array of values.
  616. * @exports queryToObject
  617. *
  618. * @param {String} queryString The query string.
  619. * @returns {Object} An object containing the parameters parsed from the query string.
  620. *
  621. *
  622. * @example
  623. * var obj = Cesium.queryToObject('key1=some%20value&key2=a%2Fb&key3=x&key3=y');
  624. * // obj will be:
  625. * // {
  626. * // key1 : 'some value',
  627. * // key2 : 'a/b',
  628. * // key3 : ['x', 'y']
  629. * // }
  630. *
  631. * @see objectToQuery
  632. */
  633. function queryToObject(queryString) {
  634. //>>includeStart('debug', pragmas.debug);
  635. if (!when.defined(queryString)) {
  636. throw new Check.DeveloperError('queryString is required.');
  637. }
  638. //>>includeEnd('debug');
  639. var result = {};
  640. if (queryString === '') {
  641. return result;
  642. }
  643. var parts = queryString.replace(/\+/g, '%20').split(/[&;]/);
  644. for (var i = 0, len = parts.length; i < len; ++i) {
  645. var subparts = parts[i].split('=');
  646. if (subparts.length > 2) {
  647. var index = parts[i].indexOf("=");
  648. var key = parts[i].substring(0, index);
  649. var strvalue = parts[i].substring(index + 1, parts[i].length);
  650. subparts = [key, strvalue];
  651. }
  652. var name = decodeURIComponent(subparts[0]);
  653. var value = subparts[1];
  654. if (when.defined(value)) {
  655. value = decodeURIComponent(value);
  656. } else {
  657. value = '';
  658. }
  659. var resultValue = result[name];
  660. if (typeof resultValue === 'string') {
  661. // expand the single value to an array
  662. result[name] = [resultValue, value];
  663. } else if (Array.isArray(resultValue)) {
  664. resultValue.push(value);
  665. } else {
  666. result[name] = value;
  667. }
  668. }
  669. return result;
  670. }
  671. /**
  672. * State of the request.
  673. *
  674. * @exports RequestState
  675. */
  676. var RequestState = {
  677. /**
  678. * Initial unissued state.
  679. *
  680. * @type Number
  681. * @constant
  682. */
  683. UNISSUED : 0,
  684. /**
  685. * Issued but not yet active. Will become active when open slots are available.
  686. *
  687. * @type Number
  688. * @constant
  689. */
  690. ISSUED : 1,
  691. /**
  692. * Actual http request has been sent.
  693. *
  694. * @type Number
  695. * @constant
  696. */
  697. ACTIVE : 2,
  698. /**
  699. * Request completed successfully.
  700. *
  701. * @type Number
  702. * @constant
  703. */
  704. RECEIVED : 3,
  705. /**
  706. * Request was cancelled, either explicitly or automatically because of low priority.
  707. *
  708. * @type Number
  709. * @constant
  710. */
  711. CANCELLED : 4,
  712. /**
  713. * Request failed.
  714. *
  715. * @type Number
  716. * @constant
  717. */
  718. FAILED : 5
  719. };
  720. var RequestState$1 = Object.freeze(RequestState);
  721. /**
  722. * An enum identifying the type of request. Used for finer grained logging and priority sorting.
  723. *
  724. * @exports RequestType
  725. */
  726. var RequestType = {
  727. /**
  728. * Terrain request.
  729. *
  730. * @type Number
  731. * @constant
  732. */
  733. TERRAIN : 0,
  734. /**
  735. * Imagery request.
  736. *
  737. * @type Number
  738. * @constant
  739. */
  740. IMAGERY : 1,
  741. /**
  742. * 3D Tiles request.
  743. *
  744. * @type Number
  745. * @constant
  746. */
  747. TILES3D : 2,
  748. /**
  749. * Other request.
  750. *
  751. * @type Number
  752. * @constant
  753. */
  754. OTHER : 3,
  755. PACK : 4,
  756. BLOCK : 5,
  757. BLOCKPACK : 6
  758. };
  759. var RequestType$1 = Object.freeze(RequestType);
  760. /**
  761. * Stores information for making a request. In general this does not need to be constructed directly.
  762. *
  763. * @alias Request
  764. * @constructor
  765. * @namespace
  766. * @exports Request
  767. * @param {Object} [options] An object with the following properties:
  768. * @param {String} [options.url] The url to request.
  769. * @param {Request~RequestCallback} [options.requestFunction] The function that makes the actual data request.
  770. * @param {Request~CancelCallback} [options.cancelFunction] The function that is called when the request is cancelled.
  771. * @param {Request~PriorityCallback} [options.priorityFunction] The function that is called to update the request's priority, which occurs once per frame.
  772. * @param {Number} [options.priority=0.0] The initial priority of the request.
  773. * @param {Boolean} [options.throttle=false] Whether to throttle and prioritize the request. If false, the request will be sent immediately. If true, the request will be throttled and sent based on priority.
  774. * @param {Boolean} [options.throttleByServer=false] Whether to throttle the request by server.
  775. * @param {RequestType} [options.type=RequestType.OTHER] The type of request.
  776. */
  777. function Request(options) {
  778. options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
  779. var throttleByServer = when.defaultValue(options.throttleByServer, false);
  780. var throttle = when.defaultValue(options.throttle, false);
  781. /**
  782. * The URL to request.
  783. *
  784. * @type {String}
  785. */
  786. this.url = options.url;
  787. /**
  788. * The function that makes the actual data request.
  789. *
  790. * @type {Request~RequestCallback}
  791. */
  792. this.requestFunction = options.requestFunction;
  793. /**
  794. * The function that is called when the request is cancelled.
  795. *
  796. * @type {Request~CancelCallback}
  797. */
  798. this.cancelFunction = options.cancelFunction;
  799. /**
  800. * The function that is called to update the request's priority, which occurs once per frame.
  801. *
  802. * @type {Request~PriorityCallback}
  803. */
  804. this.priorityFunction = options.priorityFunction;
  805. /**
  806. * Priority is a unit-less value where lower values represent higher priority.
  807. * For world-based objects, this is usually the distance from the camera.
  808. * A request that does not have a priority function defaults to a priority of 0.
  809. *
  810. * If priorityFunction is defined, this value is updated every frame with the result of that call.
  811. *
  812. * @type {Number}
  813. * @default 0.0
  814. */
  815. this.priority = when.defaultValue(options.priority, 0.0);
  816. /**
  817. * Whether to throttle and prioritize the request. If false, the request will be sent immediately. If true, the
  818. * request will be throttled and sent based on priority.
  819. *
  820. * @type {Boolean}
  821. * @readonly
  822. *
  823. * @default false
  824. */
  825. this.throttle = throttle;
  826. /**
  827. * Whether to throttle the request by server. Browsers typically support about 6-8 parallel connections
  828. * for HTTP/1 servers, and an unlimited amount of connections for HTTP/2 servers. Setting this value
  829. * to <code>true</code> is preferable for requests going through HTTP/1 servers.
  830. *
  831. * @type {Boolean}
  832. * @readonly
  833. *
  834. * @default false
  835. */
  836. this.throttleByServer = throttleByServer;
  837. /**
  838. * Type of request.
  839. *
  840. * @type {RequestType}
  841. * @readonly
  842. *
  843. * @default RequestType.OTHER
  844. */
  845. this.type = when.defaultValue(options.type, RequestType$1.OTHER);
  846. /**
  847. * A key used to identify the server that a request is going to. It is derived from the url's authority and scheme.
  848. *
  849. * @type {String}
  850. *
  851. * @private
  852. */
  853. this.serverKey = undefined;
  854. /**
  855. * The current state of the request.
  856. *
  857. * @type {RequestState}
  858. * @readonly
  859. */
  860. this.state = RequestState$1.UNISSUED;
  861. /**
  862. * The requests's deferred promise.
  863. *
  864. * @type {Object}
  865. *
  866. * @private
  867. */
  868. this.deferred = undefined;
  869. /**
  870. * Whether the request was explicitly cancelled.
  871. *
  872. * @type {Boolean}
  873. *
  874. * @private
  875. */
  876. this.cancelled = false;
  877. }
  878. /**
  879. * Mark the request as cancelled.
  880. *
  881. * @private
  882. */
  883. Request.prototype.cancel = function() {
  884. this.cancelled = true;
  885. };
  886. /**
  887. * Duplicates a Request instance.
  888. *
  889. * @param {Request} [result] The object onto which to store the result.
  890. *
  891. * @returns {Request} The modified result parameter or a new Resource instance if one was not provided.
  892. */
  893. Request.prototype.clone = function(result) {
  894. if (!when.defined(result)) {
  895. return new Request(this);
  896. }
  897. result.url = this.url;
  898. result.requestFunction = this.requestFunction;
  899. result.cancelFunction = this.cancelFunction;
  900. result.priorityFunction = this.priorityFunction;
  901. result.priority = this.priority;
  902. result.throttle = this.throttle;
  903. result.throttleByServer = this.throttleByServer;
  904. result.type = this.type;
  905. result.serverKey = this.serverKey;
  906. // These get defaulted because the cloned request hasn't been issued
  907. result.state = this.RequestState.UNISSUED;
  908. result.deferred = undefined;
  909. result.cancelled = false;
  910. return result;
  911. };
  912. /**
  913. * Parses the result of XMLHttpRequest's getAllResponseHeaders() method into
  914. * a dictionary.
  915. *
  916. * @exports parseResponseHeaders
  917. *
  918. * @param {String} headerString The header string returned by getAllResponseHeaders(). The format is
  919. * described here: http://www.w3.org/TR/XMLHttpRequest/#the-getallresponseheaders()-method
  920. * @returns {Object} A dictionary of key/value pairs, where each key is the name of a header and the corresponding value
  921. * is that header's value.
  922. *
  923. * @private
  924. */
  925. function parseResponseHeaders(headerString) {
  926. var headers = {};
  927. if (!headerString) {
  928. return headers;
  929. }
  930. var headerPairs = headerString.split('\u000d\u000a');
  931. for (var i = 0; i < headerPairs.length; ++i) {
  932. var headerPair = headerPairs[i];
  933. // Can't use split() here because it does the wrong thing
  934. // if the header value has the string ": " in it.
  935. var index = headerPair.indexOf('\u003a\u0020');
  936. if (index > 0) {
  937. var key = headerPair.substring(0, index);
  938. var val = headerPair.substring(index + 2);
  939. headers[key] = val;
  940. }
  941. }
  942. return headers;
  943. }
  944. /**
  945. * An event that is raised when a request encounters an error.
  946. *
  947. * @constructor
  948. * @alias RequestErrorEvent
  949. *
  950. * @param {Number} [statusCode] The HTTP error status code, such as 404.
  951. * @param {Object} [response] The response included along with the error.
  952. * @param {String|Object} [responseHeaders] The response headers, represented either as an object literal or as a
  953. * string in the format returned by XMLHttpRequest's getAllResponseHeaders() function.
  954. */
  955. function RequestErrorEvent(statusCode, response, responseHeaders) {
  956. /**
  957. * The HTTP error status code, such as 404. If the error does not have a particular
  958. * HTTP code, this property will be undefined.
  959. *
  960. * @type {Number}
  961. */
  962. this.statusCode = statusCode;
  963. /**
  964. * The response included along with the error. If the error does not include a response,
  965. * this property will be undefined.
  966. *
  967. * @type {Object}
  968. */
  969. this.response = response;
  970. /**
  971. * The headers included in the response, represented as an object literal of key/value pairs.
  972. * If the error does not include any headers, this property will be undefined.
  973. *
  974. * @type {Object}
  975. */
  976. this.responseHeaders = responseHeaders;
  977. if (typeof this.responseHeaders === 'string') {
  978. this.responseHeaders = parseResponseHeaders(this.responseHeaders);
  979. }
  980. }
  981. /**
  982. * Creates a string representing this RequestErrorEvent.
  983. * @memberof RequestErrorEvent
  984. *
  985. * @returns {String} A string representing the provided RequestErrorEvent.
  986. */
  987. RequestErrorEvent.prototype.toString = function() {
  988. var str = 'Request has failed.';
  989. if (when.defined(this.statusCode)) {
  990. str += ' Status Code: ' + this.statusCode;
  991. }
  992. return str;
  993. };
  994. /**
  995. * A generic utility class for managing subscribers for a particular event.
  996. * This class is usually instantiated inside of a container class and
  997. * exposed as a property for others to subscribe to.
  998. *
  999. * @alias Event
  1000. * @constructor
  1001. * @example
  1002. * MyObject.prototype.myListener = function(arg1, arg2) {
  1003. * this.myArg1Copy = arg1;
  1004. * this.myArg2Copy = arg2;
  1005. * }
  1006. *
  1007. * var myObjectInstance = new MyObject();
  1008. * var evt = new Cesium.Event();
  1009. * evt.addEventListener(MyObject.prototype.myListener, myObjectInstance);
  1010. * evt.raiseEvent('1', '2');
  1011. * evt.removeEventListener(MyObject.prototype.myListener);
  1012. */
  1013. function Event() {
  1014. this._listeners = [];
  1015. this._scopes = [];
  1016. this._toRemove = [];
  1017. this._insideRaiseEvent = false;
  1018. }
  1019. Object.defineProperties(Event.prototype, {
  1020. /**
  1021. * The number of listeners currently subscribed to the event.
  1022. * @memberof Event.prototype
  1023. * @type {Number}
  1024. * @readonly
  1025. */
  1026. numberOfListeners : {
  1027. get : function() {
  1028. return this._listeners.length - this._toRemove.length;
  1029. }
  1030. }
  1031. });
  1032. /**
  1033. * Registers a callback function to be executed whenever the event is raised.
  1034. * An optional scope can be provided to serve as the <code>this</code> pointer
  1035. * in which the function will execute.
  1036. *
  1037. * @param {Function} listener The function to be executed when the event is raised.
  1038. * @param {Object} [scope] An optional object scope to serve as the <code>this</code>
  1039. * pointer in which the listener function will execute.
  1040. * @returns {Event~RemoveCallback} A function that will remove this event listener when invoked.
  1041. *
  1042. * @see Event#raiseEvent
  1043. * @see Event#removeEventListener
  1044. */
  1045. Event.prototype.addEventListener = function(listener, scope) {
  1046. //>>includeStart('debug', pragmas.debug);
  1047. Check.Check.typeOf.func('listener', listener);
  1048. //>>includeEnd('debug');
  1049. this._listeners.push(listener);
  1050. this._scopes.push(scope);
  1051. var event = this;
  1052. return function() {
  1053. event.removeEventListener(listener, scope);
  1054. };
  1055. };
  1056. /**
  1057. * Unregisters a previously registered callback.
  1058. *
  1059. * @param {Function} listener The function to be unregistered.
  1060. * @param {Object} [scope] The scope that was originally passed to addEventListener.
  1061. * @returns {Boolean} <code>true</code> if the listener was removed; <code>false</code> if the listener and scope are not registered with the event.
  1062. *
  1063. * @see Event#addEventListener
  1064. * @see Event#raiseEvent
  1065. */
  1066. Event.prototype.removeEventListener = function(listener, scope) {
  1067. //>>includeStart('debug', pragmas.debug);
  1068. Check.Check.typeOf.func('listener', listener);
  1069. //>>includeEnd('debug');
  1070. var listeners = this._listeners;
  1071. var scopes = this._scopes;
  1072. var index = -1;
  1073. for (var i = 0; i < listeners.length; i++) {
  1074. if (listeners[i] === listener && scopes[i] === scope) {
  1075. index = i;
  1076. break;
  1077. }
  1078. }
  1079. if (index !== -1) {
  1080. if (this._insideRaiseEvent) {
  1081. //In order to allow removing an event subscription from within
  1082. //a callback, we don't actually remove the items here. Instead
  1083. //remember the index they are at and undefined their value.
  1084. this._toRemove.push(index);
  1085. listeners[index] = undefined;
  1086. scopes[index] = undefined;
  1087. } else {
  1088. listeners.splice(index, 1);
  1089. scopes.splice(index, 1);
  1090. }
  1091. return true;
  1092. }
  1093. return false;
  1094. };
  1095. function compareNumber(a,b) {
  1096. return b - a;
  1097. }
  1098. /**
  1099. * Raises the event by calling each registered listener with all supplied arguments.
  1100. *
  1101. * @param {*} arguments This method takes any number of parameters and passes them through to the listener functions.
  1102. *
  1103. * @see Event#addEventListener
  1104. * @see Event#removeEventListener
  1105. */
  1106. Event.prototype.raiseEvent = function() {
  1107. this._insideRaiseEvent = true;
  1108. var i;
  1109. var listeners = this._listeners;
  1110. var scopes = this._scopes;
  1111. var length = listeners.length;
  1112. for (i = 0; i < length; i++) {
  1113. var listener = listeners[i];
  1114. if (when.defined(listener)) {
  1115. listeners[i].apply(scopes[i], arguments);
  1116. }
  1117. }
  1118. //Actually remove items removed in removeEventListener.
  1119. var toRemove = this._toRemove;
  1120. length = toRemove.length;
  1121. if (length > 0) {
  1122. toRemove.sort(compareNumber);
  1123. for (i = 0; i < length; i++) {
  1124. var index = toRemove[i];
  1125. listeners.splice(index, 1);
  1126. scopes.splice(index, 1);
  1127. }
  1128. toRemove.length = 0;
  1129. }
  1130. this._insideRaiseEvent = false;
  1131. };
  1132. /**
  1133. * Array implementation of a heap.
  1134. *
  1135. * @alias Heap
  1136. * @constructor
  1137. * @private
  1138. *
  1139. * @param {Object} options Object with the following properties:
  1140. * @param {Heap~ComparatorCallback} options.comparator The comparator to use for the heap. If comparator(a, b) is less than 0, sort a to a lower index than b, otherwise sort to a higher index.
  1141. */
  1142. function Heap(options) {
  1143. //>>includeStart('debug', pragmas.debug);
  1144. Check.Check.typeOf.object('options', options);
  1145. Check.Check.defined('options.comparator', options.comparator);
  1146. //>>includeEnd('debug');
  1147. this._comparator = options.comparator;
  1148. this._array = [];
  1149. this._length = 0;
  1150. this._maximumLength = undefined;
  1151. }
  1152. Object.defineProperties(Heap.prototype, {
  1153. /**
  1154. * Gets the length of the heap.
  1155. *
  1156. * @memberof Heap.prototype
  1157. *
  1158. * @type {Number}
  1159. * @readonly
  1160. */
  1161. length : {
  1162. get : function() {
  1163. return this._length;
  1164. }
  1165. },
  1166. /**
  1167. * Gets the internal array.
  1168. *
  1169. * @memberof Heap.prototype
  1170. *
  1171. * @type {Array}
  1172. * @readonly
  1173. */
  1174. internalArray : {
  1175. get : function() {
  1176. return this._array;
  1177. }
  1178. },
  1179. /**
  1180. * Gets and sets the maximum length of the heap.
  1181. *
  1182. * @memberof Heap.prototype
  1183. *
  1184. * @type {Number}
  1185. */
  1186. maximumLength : {
  1187. get : function() {
  1188. return this._maximumLength;
  1189. },
  1190. set : function(value) {
  1191. this._maximumLength = value;
  1192. if (this._length > value && value > 0) {
  1193. this._length = value;
  1194. this._array.length = value;
  1195. }
  1196. }
  1197. },
  1198. /**
  1199. * The comparator to use for the heap. If comparator(a, b) is less than 0, sort a to a lower index than b, otherwise sort to a higher index.
  1200. *
  1201. * @memberof Heap.prototype
  1202. *
  1203. * @type {Heap~ComparatorCallback}
  1204. */
  1205. comparator : {
  1206. get : function() {
  1207. return this._comparator;
  1208. }
  1209. }
  1210. });
  1211. function swap(array, a, b) {
  1212. var temp = array[a];
  1213. array[a] = array[b];
  1214. array[b] = temp;
  1215. }
  1216. /**
  1217. * Resizes the internal array of the heap.
  1218. *
  1219. * @param {Number} [length] The length to resize internal array to. Defaults to the current length of the heap.
  1220. */
  1221. Heap.prototype.reserve = function(length) {
  1222. length = when.defaultValue(length, this._length);
  1223. this._array.length = length;
  1224. };
  1225. /**
  1226. * Update the heap so that index and all descendants satisfy the heap property.
  1227. *
  1228. * @param {Number} [index=0] The starting index to heapify from.
  1229. */
  1230. Heap.prototype.heapify = function(index) {
  1231. index = when.defaultValue(index, 0);
  1232. var length = this._length;
  1233. var comparator = this._comparator;
  1234. var array = this._array;
  1235. var candidate = -1;
  1236. var inserting = true;
  1237. while (inserting) {
  1238. var right = 2 * (index + 1);
  1239. var left = right - 1;
  1240. if (left < length && comparator(array[left], array[index]) < 0) {
  1241. candidate = left;
  1242. } else {
  1243. candidate = index;
  1244. }
  1245. if (right < length && comparator(array[right], array[candidate]) < 0) {
  1246. candidate = right;
  1247. }
  1248. if (candidate !== index) {
  1249. swap(array, candidate, index);
  1250. index = candidate;
  1251. } else {
  1252. inserting = false;
  1253. }
  1254. }
  1255. };
  1256. /**
  1257. * Resort the heap.
  1258. */
  1259. Heap.prototype.resort = function() {
  1260. var length = this._length;
  1261. for (var i = Math.ceil(length / 2); i >= 0; --i) {
  1262. this.heapify(i);
  1263. }
  1264. };
  1265. /**
  1266. * Insert an element into the heap. If the length would grow greater than maximumLength
  1267. * of the heap, extra elements are removed.
  1268. *
  1269. * @param {*} element The element to insert
  1270. *
  1271. * @return {*} The element that was removed from the heap if the heap is at full capacity.
  1272. */
  1273. Heap.prototype.insert = function(element) {
  1274. //>>includeStart('debug', pragmas.debug);
  1275. Check.Check.defined('element', element);
  1276. //>>includeEnd('debug');
  1277. var array = this._array;
  1278. var comparator = this._comparator;
  1279. var maximumLength = this._maximumLength;
  1280. var index = this._length++;
  1281. if (index < array.length) {
  1282. array[index] = element;
  1283. } else {
  1284. array.push(element);
  1285. }
  1286. while (index !== 0) {
  1287. var parent = Math.floor((index - 1) / 2);
  1288. if (comparator(array[index], array[parent]) < 0) {
  1289. swap(array, index, parent);
  1290. index = parent;
  1291. } else {
  1292. break;
  1293. }
  1294. }
  1295. var removedElement;
  1296. if (when.defined(maximumLength) && (this._length > maximumLength)) {
  1297. removedElement = array[maximumLength];
  1298. this._length = maximumLength;
  1299. }
  1300. return removedElement;
  1301. };
  1302. /**
  1303. * Remove the element specified by index from the heap and return it.
  1304. *
  1305. * @param {Number} [index=0] The index to remove.
  1306. * @returns {*} The specified element of the heap.
  1307. */
  1308. Heap.prototype.pop = function(index) {
  1309. index = when.defaultValue(index, 0);
  1310. if (this._length === 0) {
  1311. return undefined;
  1312. }
  1313. //>>includeStart('debug', pragmas.debug);
  1314. Check.Check.typeOf.number.lessThan('index', index, this._length);
  1315. //>>includeEnd('debug');
  1316. var array = this._array;
  1317. var root = array[index];
  1318. swap(array, index, --this._length);
  1319. this.heapify(index);
  1320. return root;
  1321. };
  1322. /**
  1323. * Gets a timestamp that can be used in measuring the time between events. Timestamps
  1324. * are expressed in milliseconds, but it is not specified what the milliseconds are
  1325. * measured from. This function uses performance.now() if it is available, or Date.now()
  1326. * otherwise.
  1327. *
  1328. * @exports getTimestamp
  1329. *
  1330. * @returns {Number} The timestamp in milliseconds since some unspecified reference time.
  1331. */
  1332. var getTimestamp;
  1333. if (typeof performance !== 'undefined' && typeof performance.now === 'function' && isFinite(performance.now())) {
  1334. getTimestamp = function() {
  1335. return performance.now();
  1336. };
  1337. } else {
  1338. getTimestamp = function() {
  1339. return Date.now();
  1340. };
  1341. }
  1342. var getTimestamp$1 = getTimestamp;
  1343. function sortRequests(a, b) {
  1344. return a.priority - b.priority;
  1345. }
  1346. var statistics = {
  1347. numberOfAttemptedRequests : 0,
  1348. numberOfActiveRequests : 0,
  1349. numberOfCancelledRequests : 0,
  1350. numberOfCancelledActiveRequests : 0,
  1351. numberOfFailedRequests : 0,
  1352. numberOfActiveRequestsEver : 0,
  1353. lastNumberOfActiveRequests : 0,
  1354. totalRequestTime : 0
  1355. };
  1356. var priorityHeapLength = 20;
  1357. var requestHeap = new Heap({
  1358. comparator : sortRequests
  1359. });
  1360. requestHeap.maximumLength = priorityHeapLength;
  1361. requestHeap.reserve(priorityHeapLength);
  1362. var activeRequests = [];
  1363. var numberOfActiveRequestsByServer = {};
  1364. var pageUri = typeof document !== 'undefined' ? new URI(document.location.href) : new URI();
  1365. var requestCompletedEvent = new Event();
  1366. /**
  1367. * Tracks the number of active requests and prioritizes incoming requests.
  1368. *
  1369. * @exports RequestScheduler
  1370. *
  1371. * @private
  1372. */
  1373. function RequestScheduler() {
  1374. }
  1375. /**
  1376. * The maximum number of simultaneous active requests. Un-throttled requests do not observe this limit.
  1377. * @type {Number}
  1378. * @default 50
  1379. */
  1380. RequestScheduler.maximumRequests = 50;
  1381. /**
  1382. * The maximum number of simultaneous active requests per server. Un-throttled requests or servers specifically
  1383. * listed in requestsByServer do not observe this limit.
  1384. * @type {Number}
  1385. * @default 6
  1386. */
  1387. RequestScheduler.maximumRequestsPerServer = 6;
  1388. RequestScheduler.perPacketCount = 20;//批量下载,每帧每个包的最大请求数限制,默认是20,不超过120
  1389. /**
  1390. * A per serverKey list of overrides to use for throttling instead of maximumRequestsPerServer
  1391. */
  1392. RequestScheduler.requestsByServer = {
  1393. 'api.cesium.com:443': 18,
  1394. 'assets.cesium.com:443': 18
  1395. };
  1396. /**
  1397. * Specifies if the request scheduler should throttle incoming requests, or let the browser queue requests under its control.
  1398. * @type {Boolean}
  1399. * @default true
  1400. */
  1401. RequestScheduler.throttleRequests = true;
  1402. /**
  1403. * When true, log statistics to the console every frame
  1404. * @type {Boolean}
  1405. * @default false
  1406. */
  1407. RequestScheduler.debugShowStatistics = false;
  1408. /**
  1409. * An event that's raised when a request is completed. Event handlers are passed
  1410. * the error object if the request fails.
  1411. *
  1412. * @type {Event}
  1413. * @default Event()
  1414. */
  1415. RequestScheduler.requestCompletedEvent = requestCompletedEvent;
  1416. Object.defineProperties(RequestScheduler, {
  1417. /**
  1418. * Returns the statistics used by the request scheduler.
  1419. *
  1420. * @memberof RequestScheduler
  1421. *
  1422. * @type Object
  1423. * @readonly
  1424. */
  1425. statistics : {
  1426. get : function() {
  1427. return statistics;
  1428. }
  1429. },
  1430. /**
  1431. * The maximum size of the priority heap. This limits the number of requests that are sorted by priority. Only applies to requests that are not yet active.
  1432. *
  1433. * @memberof RequestScheduler
  1434. *
  1435. * @type {Number}
  1436. * @default 20
  1437. */
  1438. priorityHeapLength : {
  1439. get : function() {
  1440. return priorityHeapLength;
  1441. },
  1442. set : function(value) {
  1443. // If the new length shrinks the heap, need to cancel some of the requests.
  1444. // Since this value is not intended to be tweaked regularly it is fine to just cancel the high priority requests.
  1445. if (value < priorityHeapLength) {
  1446. while (requestHeap.length > value) {
  1447. var request = requestHeap.pop();
  1448. cancelRequest(request);
  1449. }
  1450. }
  1451. priorityHeapLength = value;
  1452. requestHeap.maximumLength = value;
  1453. requestHeap.reserve(value);
  1454. }
  1455. }
  1456. });
  1457. function updatePriority(request) {
  1458. if (when.defined(request.priorityFunction)) {
  1459. request.priority = request.priorityFunction();
  1460. }
  1461. }
  1462. function serverHasOpenSlots(serverKey) {
  1463. var maxRequests = when.defaultValue(RequestScheduler.requestsByServer[serverKey], RequestScheduler.maximumRequestsPerServer);
  1464. return numberOfActiveRequestsByServer[serverKey] < maxRequests;
  1465. }
  1466. RequestScheduler.packRequestGroup = {};//每帧的所有需要打包的请求 : (serverIP + provider name), value :[request, request,...]
  1467. RequestScheduler.packRequestPromise = {};//每帧打包请求的promise (serverIP + provider name) : defer
  1468. RequestScheduler.packRequestQuadKey = {};//请求包的四叉树编码 (serverIP + provider name) : (quadkey;quadkey;...)
  1469. RequestScheduler.quadKeyIndex = {};//记录当前四叉树编码数组的索引
  1470. RequestScheduler.packRequestHeap = {};//每个图层对应一个二叉堆(serverIp + provider name) : heap
  1471. RequestScheduler.blockDefer = {};
  1472. RequestScheduler.blockRequest = {};
  1473. function getRequestKey(request) {
  1474. if(when.defined(request.packKey)){
  1475. return request.packKey;
  1476. }
  1477. request.packKey = request.serverKey + '_' + request.providerName;
  1478. return request.packKey;
  1479. }
  1480. function getRequestBlockKey(request){
  1481. if(when.defined(request.blockKey)){
  1482. return request.blockKey;
  1483. }
  1484. request.blockKey = request.serverKey + '_' + request.providerName + '_' + request.quadKey;
  1485. return request.blockKey;
  1486. }
  1487. function preparePackRequest (request) {
  1488. var packKey = getRequestKey(request);
  1489. if(!when.defined(RequestScheduler.packRequestGroup[packKey])) {
  1490. RequestScheduler.packRequestGroup[packKey] = [];
  1491. }
  1492. if(!when.defined(RequestScheduler.packRequestQuadKey[packKey])) {
  1493. RequestScheduler.packRequestQuadKey[packKey] = '';
  1494. }
  1495. if(!when.defined(RequestScheduler.packRequestPromise[packKey])) {
  1496. RequestScheduler.packRequestPromise[packKey] = when.when.defer();
  1497. }
  1498. if(!when.defined(RequestScheduler.quadKeyIndex[packKey])) {
  1499. RequestScheduler.quadKeyIndex[packKey] = 0;
  1500. }
  1501. request.quadKeyIndex = RequestScheduler.quadKeyIndex[packKey]++;
  1502. request.deferred = RequestScheduler.packRequestPromise[packKey];
  1503. request.state = RequestState$1.ISSUED;
  1504. RequestScheduler.packRequestGroup[packKey].push(request);
  1505. return request.deferred.promise;
  1506. }
  1507. function prepareBlockRequest(request) {
  1508. var key = getRequestBlockKey(request);
  1509. var deferred = RequestScheduler.blockDefer[key];
  1510. if(!when.defined(deferred)) {
  1511. deferred = RequestScheduler.blockDefer[key] = when.when.defer();
  1512. RequestScheduler.blockRequest[key] = request;
  1513. }
  1514. request.deferred = deferred;
  1515. request.state = RequestState$1.ISSUED;
  1516. return request.deferred.promise;
  1517. }
  1518. function clearRequestPackets() {
  1519. RequestScheduler.packRequestGroup = {};
  1520. RequestScheduler.packRequestPromise = {};
  1521. RequestScheduler.packRequestQuadKey = {};
  1522. RequestScheduler.quadKeyIndex = {};
  1523. }
  1524. function clearBlockRequest() {
  1525. RequestScheduler.blockRequest = {};
  1526. }
  1527. function cancelAllRequests(requests) {
  1528. for(var i = 0,j = requests.length;i < j;i++) {
  1529. var request = requests[i];
  1530. request.state = RequestState$1.CANCELLED;
  1531. }
  1532. }
  1533. function combineQuadkey(reqGroup) {
  1534. var quadkeys = [];
  1535. for(var i = 0,j = reqGroup.length;i < j;i++){
  1536. quadkeys.push(reqGroup[i].quadKey);
  1537. }
  1538. return quadkeys;
  1539. }
  1540. function startPackingRequest() {
  1541. var packRequestGroup = RequestScheduler.packRequestGroup;
  1542. for(var key in packRequestGroup) {
  1543. if(packRequestGroup.hasOwnProperty(key)) {
  1544. var reqGroup = packRequestGroup[key];
  1545. if(reqGroup.length < 1) {
  1546. continue ;
  1547. }
  1548. var packRequest = reqGroup[0].clone();
  1549. var isTileMap = packRequest.url.indexOf("rest/maps") !== -1;
  1550. packRequest.serverKey = reqGroup[0].serverKey;
  1551. packRequest.state = reqGroup[0].state;
  1552. var oldUrl = packRequest.url;
  1553. if (isTileMap) {
  1554. RequestScheduler.packRequestQuadKey[key] = combineQuadkey(reqGroup).join(',');
  1555. } else {
  1556. RequestScheduler.packRequestQuadKey[key] = combineQuadkey(reqGroup).join(';');
  1557. }
  1558. var quadKey = RequestScheduler.packRequestQuadKey[key];
  1559. if (packRequest.throttleByServer && !serverHasOpenSlots(packRequest.serverKey)) {
  1560. cancelAllRequests(reqGroup);
  1561. RequestScheduler.packRequestPromise[key].reject();
  1562. continue;
  1563. }
  1564. packRequest.deferred = RequestScheduler.packRequestPromise[key];
  1565. var uri = new URI(oldUrl);
  1566. if (isTileMap) {
  1567. uri.query = when.defined(uri.query) ? uri.query + '&tiles=' + quadKey : 'tiles=' + quadKey;
  1568. } else {
  1569. uri.query = when.defined(uri.query) ? uri.query + '&extratiles=' + quadKey : 'extratiles=' + quadKey;
  1570. }
  1571. packRequest.url = uri.toString();
  1572. startRequest(packRequest, packRequest.url);
  1573. }
  1574. }
  1575. clearRequestPackets();
  1576. }
  1577. function updateBlockRequest() {
  1578. var blockRequest = RequestScheduler.blockRequest;
  1579. for(var key in blockRequest) {
  1580. if(blockRequest.hasOwnProperty(key)) {
  1581. var request = blockRequest[key];
  1582. startRequest(request);
  1583. }
  1584. }
  1585. clearBlockRequest();
  1586. }
  1587. function issueRequest(request) {
  1588. if (request.state === RequestState$1.UNISSUED) {
  1589. request.state = RequestState$1.ISSUED;
  1590. if(request.type === RequestType$1.PACK || request.type === RequestType$1.BLOCKPACK){
  1591. var packKey = getRequestKey(request);
  1592. if(!when.defined(RequestScheduler.packRequestPromise[packKey])) {
  1593. RequestScheduler.packRequestPromise[packKey] = when.when.defer();
  1594. }
  1595. request.deferred = RequestScheduler.packRequestPromise[packKey];
  1596. }
  1597. else{
  1598. request.deferred = when.when.defer();
  1599. }
  1600. }
  1601. return request.deferred.promise;
  1602. }
  1603. function getRequestReceivedFunction(request) {
  1604. return function(results) {
  1605. if (request.state === RequestState$1.CANCELLED) {
  1606. // If the data request comes back but the request is cancelled, ignore it.
  1607. return;
  1608. }
  1609. --statistics.numberOfActiveRequests;
  1610. --numberOfActiveRequestsByServer[request.serverKey];
  1611. requestCompletedEvent.raiseEvent();
  1612. request.state = RequestState$1.RECEIVED;
  1613. request.deferred.resolve(results);
  1614. request.endTime = getTimestamp$1();
  1615. if(request.type !== RequestType$1.OTHER) {
  1616. statistics.totalRequestTime += request.endTime - request.startTime;
  1617. }
  1618. if(request.type === RequestType$1.BLOCK || request.type === RequestType$1.BLOCKPACK){
  1619. var key = getRequestBlockKey(request);
  1620. if(when.defined(RequestScheduler.blockDefer[key])){
  1621. RequestScheduler.blockDefer[key] = undefined;
  1622. delete RequestScheduler.blockDefer[key];
  1623. }
  1624. }
  1625. };
  1626. }
  1627. function getRequestFailedFunction(request) {
  1628. return function(error) {
  1629. if (request.state === RequestState$1.CANCELLED) {
  1630. // If the data request comes back but the request is cancelled, ignore it.
  1631. return;
  1632. }
  1633. ++statistics.numberOfFailedRequests;
  1634. --statistics.numberOfActiveRequests;
  1635. --numberOfActiveRequestsByServer[request.serverKey];
  1636. requestCompletedEvent.raiseEvent(error);
  1637. request.state = RequestState$1.FAILED;
  1638. request.deferred.reject(error);
  1639. };
  1640. }
  1641. function startRequest(request, url) {
  1642. var promise = issueRequest(request);
  1643. request.state = RequestState$1.ACTIVE;
  1644. activeRequests.push(request);
  1645. ++statistics.numberOfActiveRequests;
  1646. ++statistics.numberOfActiveRequestsEver;
  1647. ++numberOfActiveRequestsByServer[request.serverKey];
  1648. request.startTime = getTimestamp$1();
  1649. request.requestFunction(url).then(getRequestReceivedFunction(request)).otherwise(getRequestFailedFunction(request));
  1650. return promise;
  1651. }
  1652. function cancelRequest(request) {
  1653. var active = request.state === RequestState$1.ACTIVE;
  1654. request.state = RequestState$1.CANCELLED;
  1655. ++statistics.numberOfCancelledRequests;
  1656. request.deferred.reject();
  1657. if (active) {
  1658. --statistics.numberOfActiveRequests;
  1659. --numberOfActiveRequestsByServer[request.serverKey];
  1660. ++statistics.numberOfCancelledActiveRequests;
  1661. }
  1662. if (when.defined(request.cancelFunction)) {
  1663. request.cancelFunction();
  1664. }
  1665. }
  1666. function updatePackRequestHeap() {
  1667. for(var key in RequestScheduler.packRequestHeap) {
  1668. if(RequestScheduler.packRequestHeap.hasOwnProperty(key)) {
  1669. var heap = RequestScheduler.packRequestHeap[key];
  1670. var issuedRequests = heap.internalArray;
  1671. var issuedLength = heap.length;
  1672. for (var i = 0; i < issuedLength; ++i) {
  1673. updatePriority(issuedRequests[i]);
  1674. }
  1675. heap.resort();
  1676. }
  1677. }
  1678. }
  1679. function packingRequest() {
  1680. for(var key in RequestScheduler.packRequestHeap) {
  1681. if(RequestScheduler.packRequestHeap.hasOwnProperty(key)) {
  1682. var heap = RequestScheduler.packRequestHeap[key];
  1683. while(heap.length > 0) {
  1684. var request = heap.pop();
  1685. if (request.cancelled) {
  1686. cancelRequest(request);
  1687. continue;
  1688. }
  1689. preparePackRequest(request);
  1690. }
  1691. }
  1692. }
  1693. startPackingRequest();
  1694. }
  1695. /**
  1696. * Sort requests by priority and start requests.
  1697. */
  1698. RequestScheduler.update = function() {
  1699. var i;
  1700. var request;
  1701. // Loop over all active requests. Cancelled, failed, or received requests are removed from the array to make room for new requests.
  1702. var removeCount = 0;
  1703. var activeLength = activeRequests.length;
  1704. for (i = 0; i < activeLength; ++i) {
  1705. request = activeRequests[i];
  1706. if (request.cancelled) {
  1707. // Request was explicitly cancelled
  1708. cancelRequest(request);
  1709. }
  1710. if (request.state !== RequestState$1.ACTIVE) {
  1711. // Request is no longer active, remove from array
  1712. ++removeCount;
  1713. continue;
  1714. }
  1715. if (removeCount > 0) {
  1716. // Shift back to fill in vacated slots from completed requests
  1717. activeRequests[i - removeCount] = request;
  1718. }
  1719. }
  1720. activeRequests.length -= removeCount;
  1721. // Update priority of issued requests and resort the heap
  1722. var issuedRequests = requestHeap.internalArray;
  1723. var issuedLength = requestHeap.length;
  1724. for (i = 0; i < issuedLength; ++i) {
  1725. updatePriority(issuedRequests[i]);
  1726. }
  1727. requestHeap.resort();
  1728. updatePackRequestHeap();
  1729. updateBlockRequest();
  1730. packingRequest();
  1731. // Get the number of open slots and fill with the highest priority requests.
  1732. // Un-throttled requests are automatically added to activeRequests, so activeRequests.length may exceed maximumRequests
  1733. var openSlots = Math.max(RequestScheduler.maximumRequests - activeRequests.length, 0);
  1734. var filledSlots = 0;
  1735. while (filledSlots < openSlots && requestHeap.length > 0) {
  1736. // Loop until all open slots are filled or the heap becomes empty
  1737. request = requestHeap.pop();
  1738. if (request.cancelled) {
  1739. // Request was explicitly cancelled
  1740. cancelRequest(request);
  1741. continue;
  1742. }
  1743. if (request.throttleByServer && !serverHasOpenSlots(request.serverKey)) {
  1744. // Open slots are available, but the request is throttled by its server. Cancel and try again later.
  1745. cancelRequest(request);
  1746. continue;
  1747. }
  1748. startRequest(request);
  1749. ++filledSlots;
  1750. }
  1751. updateStatistics();
  1752. };
  1753. /**
  1754. * Get the server key from a given url.
  1755. *
  1756. * @param {String} url The url.
  1757. * @returns {String} The server key.
  1758. */
  1759. RequestScheduler.getServerKey = function(url) {
  1760. //>>includeStart('debug', pragmas.debug);
  1761. Check.Check.typeOf.string('url', url);
  1762. //>>includeEnd('debug');
  1763. var uri = new URI(url).resolve(pageUri);
  1764. uri.normalize();
  1765. var serverKey = uri.authority;
  1766. if (!/:/.test(serverKey)) {
  1767. // If the authority does not contain a port number, add port 443 for https or port 80 for http
  1768. serverKey = serverKey + ':' + (uri.scheme === 'https' ? '443' : '80');
  1769. }
  1770. var length = numberOfActiveRequestsByServer[serverKey];
  1771. if (!when.defined(length)) {
  1772. numberOfActiveRequestsByServer[serverKey] = 0;
  1773. }
  1774. return serverKey;
  1775. };
  1776. function getPackRequestHeap(request) {
  1777. var packKey = getRequestKey(request);
  1778. var heap = RequestScheduler.packRequestHeap[packKey];
  1779. if(!when.defined(heap)) {
  1780. heap = RequestScheduler.packRequestHeap[packKey] = new Heap({
  1781. comparator : sortRequests
  1782. });
  1783. heap.maximumLength = RequestScheduler.perPacketCount;
  1784. heap.reserve(priorityHeapLength);
  1785. }
  1786. return heap;
  1787. }
  1788. /**
  1789. * Issue a request. If request.throttle is false, the request is sent immediately. Otherwise the request will be
  1790. * queued and sorted by priority before being sent.
  1791. *
  1792. * @param {Request} request The request object.
  1793. *
  1794. * @returns {Promise|undefined} A Promise for the requested data, or undefined if this request does not have high enough priority to be issued.
  1795. */
  1796. RequestScheduler.request = function(request) {
  1797. //>>includeStart('debug', pragmas.debug);
  1798. Check.Check.typeOf.object('request', request);
  1799. Check.Check.typeOf.string('request.url', request.url);
  1800. Check.Check.typeOf.func('request.requestFunction', request.requestFunction);
  1801. //>>includeEnd('debug');
  1802. if (isDataUri(request.url) || isBlobUri(request.url)) {
  1803. requestCompletedEvent.raiseEvent();
  1804. request.state = RequestState$1.RECEIVED;
  1805. return request.requestFunction();
  1806. }
  1807. ++statistics.numberOfAttemptedRequests;
  1808. if (!when.defined(request.serverKey)) {
  1809. request.serverKey = RequestScheduler.getServerKey(request.url);
  1810. }
  1811. if(request.type === RequestType$1.BLOCK) {
  1812. return prepareBlockRequest(request);
  1813. }
  1814. if (request.throttleByServer && !serverHasOpenSlots(request.serverKey)) {
  1815. // Server is saturated. Try again later.
  1816. return undefined;
  1817. }
  1818. if (!RequestScheduler.throttleRequests || !request.throttle) {
  1819. return startRequest(request);
  1820. }
  1821. if (activeRequests.length >= RequestScheduler.maximumRequests) {
  1822. // Active requests are saturated. Try again later.
  1823. return undefined;
  1824. }
  1825. // Insert into the priority heap and see if a request was bumped off. If this request is the lowest
  1826. // priority it will be returned.
  1827. updatePriority(request);
  1828. var removedRequest;
  1829. if(request.type === RequestType$1.PACK || request.type === RequestType$1.BLOCKPACK) {
  1830. var packRequestHeap = getPackRequestHeap(request);
  1831. var inset = true;
  1832. if(request.type === RequestType$1.BLOCKPACK){
  1833. for(var i=0; i<packRequestHeap.length; i++){
  1834. if(packRequestHeap._array[i].quadKey === request.quadKey){
  1835. request.blockRequest = packRequestHeap._array[i];
  1836. inset = false;
  1837. break;
  1838. }
  1839. }
  1840. }
  1841. if(inset){
  1842. removedRequest = packRequestHeap.insert(request);
  1843. }
  1844. }
  1845. else{
  1846. removedRequest = requestHeap.insert(request);
  1847. }
  1848. if (when.defined(removedRequest)) {
  1849. if (removedRequest === request) {
  1850. // Request does not have high enough priority to be issued
  1851. return undefined;
  1852. }
  1853. // A previously issued request has been bumped off the priority heap, so cancel it
  1854. cancelRequest(removedRequest);
  1855. }
  1856. return issueRequest(request);
  1857. };
  1858. function updateStatistics() {
  1859. if (!RequestScheduler.debugShowStatistics) {
  1860. return;
  1861. }
  1862. if (statistics.numberOfActiveRequests === 0 && statistics.lastNumberOfActiveRequests > 0) {
  1863. if (statistics.numberOfAttemptedRequests > 0) {
  1864. console.log('Number of attempted requests: ' + statistics.numberOfAttemptedRequests);
  1865. statistics.numberOfAttemptedRequests = 0;
  1866. }
  1867. if (statistics.numberOfCancelledRequests > 0) {
  1868. console.log('Number of cancelled requests: ' + statistics.numberOfCancelledRequests);
  1869. statistics.numberOfCancelledRequests = 0;
  1870. }
  1871. if (statistics.numberOfCancelledActiveRequests > 0) {
  1872. console.log('Number of cancelled active requests: ' + statistics.numberOfCancelledActiveRequests);
  1873. statistics.numberOfCancelledActiveRequests = 0;
  1874. }
  1875. if (statistics.numberOfFailedRequests > 0) {
  1876. console.log('Number of failed requests: ' + statistics.numberOfFailedRequests);
  1877. statistics.numberOfFailedRequests = 0;
  1878. }
  1879. }
  1880. statistics.lastNumberOfActiveRequests = statistics.numberOfActiveRequests;
  1881. }
  1882. /**
  1883. * For testing only. Clears any requests that may not have completed from previous tests.
  1884. *
  1885. * @private
  1886. */
  1887. RequestScheduler.clearForSpecs = function() {
  1888. while (requestHeap.length > 0) {
  1889. var request = requestHeap.pop();
  1890. cancelRequest(request);
  1891. }
  1892. var length = activeRequests.length;
  1893. for (var i = 0; i < length; ++i) {
  1894. cancelRequest(activeRequests[i]);
  1895. }
  1896. activeRequests.length = 0;
  1897. numberOfActiveRequestsByServer = {};
  1898. // Clear stats
  1899. statistics.numberOfAttemptedRequests = 0;
  1900. statistics.numberOfActiveRequests = 0;
  1901. statistics.numberOfCancelledRequests = 0;
  1902. statistics.numberOfCancelledActiveRequests = 0;
  1903. statistics.numberOfFailedRequests = 0;
  1904. statistics.numberOfActiveRequestsEver = 0;
  1905. statistics.lastNumberOfActiveRequests = 0;
  1906. statistics.totalRequestTime = 0;
  1907. };
  1908. /**
  1909. * For testing only.
  1910. *
  1911. * @private
  1912. */
  1913. RequestScheduler.numberOfActiveRequestsByServer = function(serverKey) {
  1914. return numberOfActiveRequestsByServer[serverKey];
  1915. };
  1916. /**
  1917. * For testing only.
  1918. *
  1919. * @private
  1920. */
  1921. RequestScheduler.requestHeap = requestHeap;
  1922. /**
  1923. * A singleton that contains all of the servers that are trusted. Credentials will be sent with
  1924. * any requests to these servers.
  1925. *
  1926. * @exports TrustedServers
  1927. *
  1928. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  1929. */
  1930. var TrustedServers = {};
  1931. var _servers = {};
  1932. /**
  1933. * Adds a trusted server to the registry
  1934. *
  1935. * @param {String} host The host to be added.
  1936. * @param {Number} port The port used to access the host.
  1937. *
  1938. * @example
  1939. * // Add a trusted server
  1940. * TrustedServers.add('my.server.com', 80);
  1941. */
  1942. TrustedServers.add = function(host, port) {
  1943. //>>includeStart('debug', pragmas.debug);
  1944. if (!when.defined(host)) {
  1945. throw new Check.DeveloperError('host is required.');
  1946. }
  1947. if (!when.defined(port) || port <= 0) {
  1948. throw new Check.DeveloperError('port is required to be greater than 0.');
  1949. }
  1950. //>>includeEnd('debug');
  1951. var authority = host.toLowerCase() + ':' + port;
  1952. if (!when.defined(_servers[authority])) {
  1953. _servers[authority] = true;
  1954. }
  1955. };
  1956. /**
  1957. * Removes a trusted server from the registry
  1958. *
  1959. * @param {String} host The host to be removed.
  1960. * @param {Number} port The port used to access the host.
  1961. *
  1962. * @example
  1963. * // Remove a trusted server
  1964. * TrustedServers.remove('my.server.com', 80);
  1965. */
  1966. TrustedServers.remove = function(host, port) {
  1967. //>>includeStart('debug', pragmas.debug);
  1968. if (!when.defined(host)) {
  1969. throw new Check.DeveloperError('host is required.');
  1970. }
  1971. if (!when.defined(port) || port <= 0) {
  1972. throw new Check.DeveloperError('port is required to be greater than 0.');
  1973. }
  1974. //>>includeEnd('debug');
  1975. var authority = host.toLowerCase() + ':' + port;
  1976. if (when.defined(_servers[authority])) {
  1977. delete _servers[authority];
  1978. }
  1979. };
  1980. function getAuthority(url) {
  1981. var uri = new URI(url);
  1982. uri.normalize();
  1983. // Removes username:password@ so we just have host[:port]
  1984. var authority = uri.getAuthority();
  1985. if (!when.defined(authority)) {
  1986. return undefined; // Relative URL
  1987. }
  1988. if (authority.indexOf('@') !== -1) {
  1989. var parts = authority.split('@');
  1990. authority = parts[1];
  1991. }
  1992. // If the port is missing add one based on the scheme
  1993. if (authority.indexOf(':') === -1) {
  1994. var scheme = uri.getScheme();
  1995. if (!when.defined(scheme)) {
  1996. scheme = window.location.protocol;
  1997. scheme = scheme.substring(0, scheme.length-1);
  1998. }
  1999. if (scheme === 'http') {
  2000. authority += ':80';
  2001. } else if (scheme === 'https') {
  2002. authority += ':443';
  2003. } else {
  2004. return undefined;
  2005. }
  2006. }
  2007. return authority;
  2008. }
  2009. /**
  2010. * Tests whether a server is trusted or not. The server must have been added with the port if it is included in the url.
  2011. *
  2012. * @param {String} url The url to be tested against the trusted list
  2013. *
  2014. * @returns {boolean} Returns true if url is trusted, false otherwise.
  2015. *
  2016. * @example
  2017. * // Add server
  2018. * TrustedServers.add('my.server.com', 81);
  2019. *
  2020. * // Check if server is trusted
  2021. * if (TrustedServers.contains('https://my.server.com:81/path/to/file.png')) {
  2022. * // my.server.com:81 is trusted
  2023. * }
  2024. * if (TrustedServers.contains('https://my.server.com/path/to/file.png')) {
  2025. * // my.server.com isn't trusted
  2026. * }
  2027. */
  2028. TrustedServers.contains = function(url) {
  2029. //>>includeStart('debug', pragmas.debug);
  2030. if (!when.defined(url)) {
  2031. throw new Check.DeveloperError('url is required.');
  2032. }
  2033. //>>includeEnd('debug');
  2034. var authority = getAuthority(url);
  2035. if (when.defined(authority) && when.defined(_servers[authority])) {
  2036. return true;
  2037. }
  2038. return false;
  2039. };
  2040. /**
  2041. * Clears the registry
  2042. *
  2043. * @example
  2044. * // Remove a trusted server
  2045. * TrustedServers.clear();
  2046. */
  2047. TrustedServers.clear = function() {
  2048. _servers = {};
  2049. };
  2050. var warnings = {};
  2051. /**
  2052. * Logs a one time message to the console. Use this function instead of
  2053. * <code>console.log</code> directly since this does not log duplicate messages
  2054. * unless it is called from multiple workers.
  2055. *
  2056. * @exports oneTimeWarning
  2057. *
  2058. * @param {String} identifier The unique identifier for this warning.
  2059. * @param {String} [message=identifier] The message to log to the console.
  2060. *
  2061. * @example
  2062. * for(var i=0;i<foo.length;++i) {
  2063. * if (!defined(foo[i].bar)) {
  2064. * // Something that can be recovered from but may happen a lot
  2065. * oneTimeWarning('foo.bar undefined', 'foo.bar is undefined. Setting to 0.');
  2066. * foo[i].bar = 0;
  2067. * // ...
  2068. * }
  2069. * }
  2070. *
  2071. * @private
  2072. */
  2073. function oneTimeWarning(identifier, message) {
  2074. //>>includeStart('debug', pragmas.debug);
  2075. if (!when.defined(identifier)) {
  2076. throw new Check.DeveloperError('identifier is required.');
  2077. }
  2078. //>>includeEnd('debug');
  2079. if (!when.defined(warnings[identifier])) {
  2080. warnings[identifier] = true;
  2081. console.warn(when.defaultValue(message, identifier));
  2082. }
  2083. }
  2084. oneTimeWarning.geometryOutlines = 'Entity geometry outlines are unsupported on terrain. Outlines will be disabled. To enable outlines, disable geometry terrain clamping by explicitly setting height to 0.';
  2085. oneTimeWarning.geometryZIndex = 'Entity geometry with zIndex are unsupported when height or extrudedHeight are defined. zIndex will be ignored';
  2086. oneTimeWarning.geometryHeightReference = 'Entity corridor, ellipse, polygon or rectangle with heightReference must also have a defined height. heightReference will be ignored';
  2087. oneTimeWarning.geometryExtrudedHeightReference = 'Entity corridor, ellipse, polygon or rectangle with extrudedHeightReference must also have a defined extrudedHeight. extrudedHeightReference will be ignored';
  2088. /**
  2089. * Logs a deprecation message to the console. Use this function instead of
  2090. * <code>console.log</code> directly since this does not log duplicate messages
  2091. * unless it is called from multiple workers.
  2092. *
  2093. * @exports deprecationWarning
  2094. *
  2095. * @param {String} identifier The unique identifier for this deprecated API.
  2096. * @param {String} message The message to log to the console.
  2097. *
  2098. * @example
  2099. * // Deprecated function or class
  2100. * function Foo() {
  2101. * deprecationWarning('Foo', 'Foo was deprecated in Cesium 1.01. It will be removed in 1.03. Use newFoo instead.');
  2102. * // ...
  2103. * }
  2104. *
  2105. * // Deprecated function
  2106. * Bar.prototype.func = function() {
  2107. * deprecationWarning('Bar.func', 'Bar.func() was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newFunc() instead.');
  2108. * // ...
  2109. * };
  2110. *
  2111. * // Deprecated property
  2112. * Object.defineProperties(Bar.prototype, {
  2113. * prop : {
  2114. * get : function() {
  2115. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  2116. * // ...
  2117. * },
  2118. * set : function(value) {
  2119. * deprecationWarning('Bar.prop', 'Bar.prop was deprecated in Cesium 1.01. It will be removed in 1.03. Use Bar.newProp instead.');
  2120. * // ...
  2121. * }
  2122. * }
  2123. * });
  2124. *
  2125. * @private
  2126. */
  2127. function deprecationWarning(identifier, message) {
  2128. //>>includeStart('debug', pragmas.debug);
  2129. if (!when.defined(identifier) || !when.defined(message)) {
  2130. throw new Check.DeveloperError('identifier and message are required.');
  2131. }
  2132. //>>includeEnd('debug');
  2133. oneTimeWarning(identifier, message);
  2134. }
  2135. var xhrBlobSupported = (function() {
  2136. try {
  2137. var xhr = new XMLHttpRequest();
  2138. xhr.open('GET', '#', true);
  2139. xhr.responseType = 'blob';
  2140. return xhr.responseType === 'blob';
  2141. } catch (e) {
  2142. return false;
  2143. }
  2144. })();
  2145. /**
  2146. * Parses a query string and returns the object equivalent.
  2147. *
  2148. * @param {Uri} uri The Uri with a query object.
  2149. * @param {Resource} resource The Resource that will be assigned queryParameters.
  2150. * @param {Boolean} merge If true, we'll merge with the resource's existing queryParameters. Otherwise they will be replaced.
  2151. * @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in uri will take precedence.
  2152. *
  2153. * @private
  2154. */
  2155. function parseQuery(uri, resource, merge, preserveQueryParameters) {
  2156. var queryString = uri.query;
  2157. if (!when.defined(queryString) || (queryString.length === 0)) {
  2158. return {};
  2159. }
  2160. var query;
  2161. // Special case we run into where the querystring is just a string, not key/value pairs
  2162. if (queryString.indexOf('=') === -1) {
  2163. var result = {};
  2164. result[queryString] = undefined;
  2165. query = result;
  2166. } else {
  2167. query = queryToObject(queryString);
  2168. }
  2169. if (merge) {
  2170. resource._queryParameters = combineQueryParameters(query, resource._queryParameters, preserveQueryParameters);
  2171. } else {
  2172. resource._queryParameters = query;
  2173. }
  2174. uri.query = undefined;
  2175. }
  2176. /**
  2177. * Converts a query object into a string.
  2178. *
  2179. * @param {Uri} uri The Uri object that will have the query object set.
  2180. * @param {Resource} resource The resource that has queryParameters
  2181. *
  2182. * @private
  2183. */
  2184. function stringifyQuery(uri, resource) {
  2185. var queryObject = resource._queryParameters;
  2186. var keys = Object.keys(queryObject);
  2187. // We have 1 key with an undefined value, so this is just a string, not key/value pairs
  2188. if (keys.length === 1 && !when.defined(queryObject[keys[0]])) {
  2189. uri.query = keys[0];
  2190. } else {
  2191. uri.query = objectToQuery(queryObject);
  2192. }
  2193. }
  2194. /**
  2195. * Clones a value if it is defined, otherwise returns the default value
  2196. *
  2197. * @param {*} [val] The value to clone.
  2198. * @param {*} [defaultVal] The default value.
  2199. *
  2200. * @returns {*} A clone of val or the defaultVal.
  2201. *
  2202. * @private
  2203. */
  2204. function defaultClone(val, defaultVal) {
  2205. if (!when.defined(val)) {
  2206. return defaultVal;
  2207. }
  2208. return when.defined(val.clone) ? val.clone() : clone(val);
  2209. }
  2210. /**
  2211. * Checks to make sure the Resource isn't already being requested.
  2212. *
  2213. * @param {Request} request The request to check.
  2214. *
  2215. * @private
  2216. */
  2217. function checkAndResetRequest(request) {
  2218. if (request.state === RequestState$1.ISSUED || request.state === RequestState$1.ACTIVE) {
  2219. throw new RuntimeError.RuntimeError('The Resource is already being fetched.');
  2220. }
  2221. request.state = RequestState$1.UNISSUED;
  2222. request.deferred = undefined;
  2223. }
  2224. /**
  2225. * This combines a map of query parameters.
  2226. *
  2227. * @param {Object} q1 The first map of query parameters. Values in this map will take precedence if preserveQueryParameters is false.
  2228. * @param {Object} q2 The second map of query parameters.
  2229. * @param {Boolean} preserveQueryParameters If true duplicate parameters will be concatenated into an array. If false, keys in q1 will take precedence.
  2230. *
  2231. * @returns {Object} The combined map of query parameters.
  2232. *
  2233. * @example
  2234. * var q1 = {
  2235. * a: 1,
  2236. * b: 2
  2237. * };
  2238. * var q2 = {
  2239. * a: 3,
  2240. * c: 4
  2241. * };
  2242. * var q3 = {
  2243. * b: [5, 6],
  2244. * d: 7
  2245. * }
  2246. *
  2247. * // Returns
  2248. * // {
  2249. * // a: [1, 3],
  2250. * // b: 2,
  2251. * // c: 4
  2252. * // };
  2253. * combineQueryParameters(q1, q2, true);
  2254. *
  2255. * // Returns
  2256. * // {
  2257. * // a: 1,
  2258. * // b: 2,
  2259. * // c: 4
  2260. * // };
  2261. * combineQueryParameters(q1, q2, false);
  2262. *
  2263. * // Returns
  2264. * // {
  2265. * // a: 1,
  2266. * // b: [2, 5, 6],
  2267. * // d: 7
  2268. * // };
  2269. * combineQueryParameters(q1, q3, true);
  2270. *
  2271. * // Returns
  2272. * // {
  2273. * // a: 1,
  2274. * // b: 2,
  2275. * // d: 7
  2276. * // };
  2277. * combineQueryParameters(q1, q3, false);
  2278. *
  2279. * @private
  2280. */
  2281. function combineQueryParameters(q1, q2, preserveQueryParameters) {
  2282. if (!preserveQueryParameters) {
  2283. return combine(q1, q2);
  2284. }
  2285. var result = clone(q1, true);
  2286. for (var param in q2) {
  2287. if (q2.hasOwnProperty(param)) {
  2288. var value = result[param];
  2289. var q2Value = q2[param];
  2290. if (when.defined(value)) {
  2291. if (!Array.isArray(value)) {
  2292. value = result[param] = [value];
  2293. }
  2294. result[param] = value.concat(q2Value);
  2295. } else {
  2296. result[param] = Array.isArray(q2Value) ? q2Value.slice() : q2Value;
  2297. }
  2298. }
  2299. }
  2300. return result;
  2301. }
  2302. /**
  2303. * A resource that includes the location and any other parameters we need to retrieve it or create derived resources. It also provides the ability to retry requests.
  2304. *
  2305. * @alias Resource
  2306. * @constructor
  2307. *
  2308. * @param {String|Object} options A url or an object with the following properties
  2309. * @param {String} options.url The url of the resource.
  2310. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  2311. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  2312. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  2313. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  2314. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  2315. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  2316. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  2317. *
  2318. * @example
  2319. * function refreshTokenRetryCallback(resource, error) {
  2320. * if (error.statusCode === 403) {
  2321. * // 403 status code means a new token should be generated
  2322. * return getNewAccessToken()
  2323. * .then(function(token) {
  2324. * resource.queryParameters.access_token = token;
  2325. * return true;
  2326. * })
  2327. * .otherwise(function() {
  2328. * return false;
  2329. * });
  2330. * }
  2331. *
  2332. * return false;
  2333. * }
  2334. *
  2335. * var resource = new Resource({
  2336. * url: 'http://server.com/path/to/resource.json',
  2337. * proxy: new DefaultProxy('/proxy/'),
  2338. * headers: {
  2339. * 'X-My-Header': 'valueOfHeader'
  2340. * },
  2341. * queryParameters: {
  2342. * 'access_token': '123-435-456-000'
  2343. * },
  2344. * retryCallback: refreshTokenRetryCallback,
  2345. * retryAttempts: 1
  2346. * });
  2347. */
  2348. function Resource(options) {
  2349. options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
  2350. if (typeof options === 'string') {
  2351. options = {
  2352. url: options
  2353. };
  2354. }
  2355. //>>includeStart('debug', pragmas.debug);
  2356. Check.Check.typeOf.string('options.url', options.url);
  2357. //>>includeEnd('debug');
  2358. this._url = undefined;
  2359. this._templateValues = defaultClone(options.templateValues, {});
  2360. this._queryParameters = defaultClone(options.queryParameters, {});
  2361. /**
  2362. * Additional HTTP headers that will be sent with the request.
  2363. *
  2364. * @type {Object}
  2365. */
  2366. this.headers = defaultClone(options.headers, {});
  2367. /**
  2368. * A Request object that will be used. Intended for internal use only.
  2369. *
  2370. * @type {Request}
  2371. */
  2372. this.request = when.defaultValue(options.request, new Request());
  2373. /**
  2374. * A proxy to be used when loading the resource.
  2375. *
  2376. * @type {DefaultProxy}
  2377. */
  2378. this.proxy = options.proxy;
  2379. /**
  2380. * Function to call when a request for this resource fails. If it returns true or a Promise that resolves to true, the request will be retried.
  2381. *
  2382. * @type {Function}
  2383. */
  2384. this.retryCallback = options.retryCallback;
  2385. /**
  2386. * The number of times the retryCallback should be called before giving up.
  2387. *
  2388. * @type {Number}
  2389. */
  2390. this.retryAttempts = when.defaultValue(options.retryAttempts, 0);
  2391. this._retryCount = 0;
  2392. var uri = new URI(options.url);
  2393. parseQuery(uri, this, true, true);
  2394. // Remove the fragment as it's not sent with a request
  2395. uri.fragment = undefined;
  2396. this._url = uri.toString();
  2397. }
  2398. /**
  2399. * A helper function to create a resource depending on whether we have a String or a Resource
  2400. *
  2401. * @param {Resource|String} resource A Resource or a String to use when creating a new Resource.
  2402. *
  2403. * @returns {Resource} If resource is a String, a Resource constructed with the url and options. Otherwise the resource parameter is returned.
  2404. *
  2405. * @private
  2406. */
  2407. Resource.createIfNeeded = function(resource) {
  2408. if (resource instanceof Resource) {
  2409. // Keep existing request object. This function is used internally to duplicate a Resource, so that it can't
  2410. // be modified outside of a class that holds it (eg. an imagery or terrain provider). Since the Request objects
  2411. // are managed outside of the providers, by the tile loading code, we want to keep the request property the same so if it is changed
  2412. // in the underlying tiling code the requests for this resource will use it.
  2413. return resource.getDerivedResource({
  2414. request: resource.request
  2415. });
  2416. }
  2417. if (typeof resource !== 'string') {
  2418. return resource;
  2419. }
  2420. return new Resource({
  2421. url: resource
  2422. });
  2423. };
  2424. var supportsImageBitmapOptionsPromise;
  2425. /**
  2426. * A helper function to check whether createImageBitmap supports passing ImageBitmapOptions.
  2427. *
  2428. * @returns {Promise<Boolean>} A promise that resolves to true if this browser supports creating an ImageBitmap with options.
  2429. *
  2430. * @private
  2431. */
  2432. Resource.supportsImageBitmapOptions = function() {
  2433. // Until the HTML folks figure out what to do about this, we need to actually try loading an image to
  2434. // know if this browser supports passing options to the createImageBitmap function.
  2435. // https://github.com/whatwg/html/pull/4248
  2436. if (when.defined(supportsImageBitmapOptionsPromise)) {
  2437. return supportsImageBitmapOptionsPromise;
  2438. }
  2439. if (typeof createImageBitmap !== 'function') {
  2440. supportsImageBitmapOptionsPromise = when.when.resolve(false);
  2441. return supportsImageBitmapOptionsPromise;
  2442. }
  2443. var imageDataUri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVQImWP4////fwAJ+wP9CNHoHgAAAABJRU5ErkJggg==';
  2444. supportsImageBitmapOptionsPromise = Resource.fetchBlob({
  2445. url : imageDataUri
  2446. })
  2447. .then(function(blob) {
  2448. return createImageBitmap(blob, {
  2449. imageOrientation: 'flipY',
  2450. premultiplyAlpha: 'none'
  2451. });
  2452. })
  2453. .then(function(imageBitmap) {
  2454. return true;
  2455. })
  2456. .otherwise(function() {
  2457. return false;
  2458. });
  2459. return supportsImageBitmapOptionsPromise;
  2460. };
  2461. Object.defineProperties(Resource, {
  2462. /**
  2463. * Returns true if blobs are supported.
  2464. *
  2465. * @memberof Resource
  2466. * @type {Boolean}
  2467. *
  2468. * @readonly
  2469. */
  2470. isBlobSupported : {
  2471. get : function() {
  2472. return xhrBlobSupported;
  2473. }
  2474. }
  2475. });
  2476. Object.defineProperties(Resource.prototype, {
  2477. /**
  2478. * Query parameters appended to the url.
  2479. *
  2480. * @memberof Resource.prototype
  2481. * @type {Object}
  2482. *
  2483. * @readonly
  2484. */
  2485. queryParameters: {
  2486. get: function() {
  2487. return this._queryParameters;
  2488. }
  2489. },
  2490. /**
  2491. * The key/value pairs used to replace template parameters in the url.
  2492. *
  2493. * @memberof Resource.prototype
  2494. * @type {Object}
  2495. *
  2496. * @readonly
  2497. */
  2498. templateValues: {
  2499. get: function() {
  2500. return this._templateValues;
  2501. }
  2502. },
  2503. /**
  2504. * The url to the resource with template values replaced, query string appended and encoded by proxy if one was set.
  2505. *
  2506. * @memberof Resource.prototype
  2507. * @type {String}
  2508. */
  2509. url: {
  2510. get: function() {
  2511. return this.getUrlComponent(true, true);
  2512. },
  2513. set: function(value) {
  2514. var uri = new URI(value);
  2515. parseQuery(uri, this, false);
  2516. // Remove the fragment as it's not sent with a request
  2517. uri.fragment = undefined;
  2518. this._url = uri.toString();
  2519. }
  2520. },
  2521. /**
  2522. * The file extension of the resource.
  2523. *
  2524. * @memberof Resource.prototype
  2525. * @type {String}
  2526. *
  2527. * @readonly
  2528. */
  2529. extension: {
  2530. get: function() {
  2531. return getExtensionFromUri(this._url);
  2532. }
  2533. },
  2534. /**
  2535. * True if the Resource refers to a data URI.
  2536. *
  2537. * @memberof Resource.prototype
  2538. * @type {Boolean}
  2539. */
  2540. isDataUri: {
  2541. get: function() {
  2542. return isDataUri(this._url);
  2543. }
  2544. },
  2545. /**
  2546. * True if the Resource refers to a blob URI.
  2547. *
  2548. * @memberof Resource.prototype
  2549. * @type {Boolean}
  2550. */
  2551. isBlobUri: {
  2552. get: function() {
  2553. return isBlobUri(this._url);
  2554. }
  2555. },
  2556. /**
  2557. * True if the Resource refers to a cross origin URL.
  2558. *
  2559. * @memberof Resource.prototype
  2560. * @type {Boolean}
  2561. */
  2562. isCrossOriginUrl: {
  2563. get: function() {
  2564. return isCrossOriginUrl(this._url);
  2565. }
  2566. },
  2567. /**
  2568. * True if the Resource has request headers. This is equivalent to checking if the headers property has any keys.
  2569. *
  2570. * @memberof Resource.prototype
  2571. * @type {Boolean}
  2572. */
  2573. hasHeaders: {
  2574. get: function() {
  2575. return (Object.keys(this.headers).length > 0);
  2576. }
  2577. }
  2578. });
  2579. /**
  2580. * Returns the url, optional with the query string and processed by a proxy.
  2581. *
  2582. * @param {Boolean} [query=false] If true, the query string is included.
  2583. * @param {Boolean} [proxy=false] If true, the url is processed the proxy object if defined.
  2584. *
  2585. * @returns {String} The url with all the requested components.
  2586. */
  2587. Resource.prototype.getUrlComponent = function(query, proxy) {
  2588. if(this.isDataUri) {
  2589. return this._url;
  2590. }
  2591. var uri = new URI(this._url);
  2592. if (query) {
  2593. stringifyQuery(uri, this);
  2594. }
  2595. // objectToQuery escapes the placeholders. Undo that.
  2596. var url = uri.toString().replace(/%7B/g, '{').replace(/%7D/g, '}');
  2597. var templateValues = this._templateValues;
  2598. url = url.replace(/{(.*?)}/g, function(match, key) {
  2599. var replacement = templateValues[key];
  2600. if (when.defined(replacement)) {
  2601. // use the replacement value from templateValues if there is one...
  2602. return encodeURIComponent(replacement);
  2603. }
  2604. // otherwise leave it unchanged
  2605. return match;
  2606. });
  2607. if (proxy && when.defined(this.proxy)) {
  2608. url = this.proxy.getURL(url);
  2609. }
  2610. return url;
  2611. };
  2612. /**
  2613. * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
  2614. * as opposed to adding them one at a time to the queryParameters property. If a value is already set, it will be replaced with the new value.
  2615. *
  2616. * @param {Object} params The query parameters
  2617. * @param {Boolean} [useAsDefault=false] If true the params will be used as the default values, so they will only be set if they are undefined.
  2618. */
  2619. Resource.prototype.setQueryParameters = function(params, useAsDefault) {
  2620. if (useAsDefault) {
  2621. this._queryParameters = combineQueryParameters(this._queryParameters, params, false);
  2622. } else {
  2623. this._queryParameters = combineQueryParameters(params, this._queryParameters, false);
  2624. }
  2625. };
  2626. /**
  2627. * Combines the specified object and the existing query parameters. This allows you to add many parameters at once,
  2628. * as opposed to adding them one at a time to the queryParameters property.
  2629. *
  2630. * @param {Object} params The query parameters
  2631. */
  2632. Resource.prototype.appendQueryParameters = function(params) {
  2633. this._queryParameters = combineQueryParameters(params, this._queryParameters, true);
  2634. };
  2635. /**
  2636. * Combines the specified object and the existing template values. This allows you to add many values at once,
  2637. * as opposed to adding them one at a time to the templateValues property. If a value is already set, it will become an array and the new value will be appended.
  2638. *
  2639. * @param {Object} template The template values
  2640. * @param {Boolean} [useAsDefault=false] If true the values will be used as the default values, so they will only be set if they are undefined.
  2641. */
  2642. Resource.prototype.setTemplateValues = function(template, useAsDefault) {
  2643. if (useAsDefault) {
  2644. this._templateValues = combine(this._templateValues, template);
  2645. } else {
  2646. this._templateValues = combine(template, this._templateValues);
  2647. }
  2648. };
  2649. /**
  2650. * Returns a resource relative to the current instance. All properties remain the same as the current instance unless overridden in options.
  2651. *
  2652. * @param {Object} options An object with the following properties
  2653. * @param {String} [options.url] The url that will be resolved relative to the url of the current instance.
  2654. * @param {Object} [options.queryParameters] An object containing query parameters that will be combined with those of the current instance.
  2655. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}). These will be combined with those of the current instance.
  2656. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  2657. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  2658. * @param {Resource~RetryCallback} [options.retryCallback] The function to call when loading the resource fails.
  2659. * @param {Number} [options.retryAttempts] The number of times the retryCallback should be called before giving up.
  2660. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  2661. * @param {Boolean} [options.preserveQueryParameters=false] If true, this will keep all query parameters from the current resource and derived resource. If false, derived parameters will replace those of the current resource.
  2662. *
  2663. * @returns {Resource} The resource derived from the current one.
  2664. */
  2665. Resource.prototype.getDerivedResource = function(options) {
  2666. var resource = this.clone();
  2667. resource._retryCount = 0;
  2668. if (when.defined(options.url)) {
  2669. var uri = new URI(options.url);
  2670. var preserveQueryParameters = when.defaultValue(options.preserveQueryParameters, false);
  2671. parseQuery(uri, resource, true, preserveQueryParameters);
  2672. // Remove the fragment as it's not sent with a request
  2673. uri.fragment = undefined;
  2674. resource._url = uri.resolve(new URI(getAbsoluteUri(this._url))).toString();
  2675. }
  2676. if (when.defined(options.queryParameters)) {
  2677. resource._queryParameters = combine(options.queryParameters, resource._queryParameters);
  2678. }
  2679. if (when.defined(options.templateValues)) {
  2680. resource._templateValues = combine(options.templateValues, resource.templateValues);
  2681. }
  2682. if (when.defined(options.headers)) {
  2683. resource.headers = combine(options.headers, resource.headers);
  2684. }
  2685. if (when.defined(options.proxy)) {
  2686. resource.proxy = options.proxy;
  2687. }
  2688. if (when.defined(options.request)) {
  2689. resource.request = options.request;
  2690. }
  2691. if (when.defined(options.retryCallback)) {
  2692. resource.retryCallback = options.retryCallback;
  2693. }
  2694. if (when.defined(options.retryAttempts)) {
  2695. resource.retryAttempts = options.retryAttempts;
  2696. }
  2697. return resource;
  2698. };
  2699. /**
  2700. * Called when a resource fails to load. This will call the retryCallback function if defined until retryAttempts is reached.
  2701. *
  2702. * @param {Error} [error] The error that was encountered.
  2703. *
  2704. * @returns {Promise<Boolean>} A promise to a boolean, that if true will cause the resource request to be retried.
  2705. *
  2706. * @private
  2707. */
  2708. Resource.prototype.retryOnError = function(error) {
  2709. var retryCallback = this.retryCallback;
  2710. if ((typeof retryCallback !== 'function') || (this._retryCount >= this.retryAttempts)) {
  2711. return when.when(false);
  2712. }
  2713. var that = this;
  2714. return when.when(retryCallback(this, error))
  2715. .then(function(result) {
  2716. ++that._retryCount;
  2717. return result;
  2718. });
  2719. };
  2720. /**
  2721. * Duplicates a Resource instance.
  2722. *
  2723. * @param {Resource} [result] The object onto which to store the result.
  2724. *
  2725. * @returns {Resource} The modified result parameter or a new Resource instance if one was not provided.
  2726. */
  2727. Resource.prototype.clone = function(result) {
  2728. if (!when.defined(result)) {
  2729. result = new Resource({
  2730. url : this._url
  2731. });
  2732. }
  2733. result._url = this._url;
  2734. result._queryParameters = clone(this._queryParameters);
  2735. result._templateValues = clone(this._templateValues);
  2736. result.headers = clone(this.headers);
  2737. result.proxy = this.proxy;
  2738. result.retryCallback = this.retryCallback;
  2739. result.retryAttempts = this.retryAttempts;
  2740. result._retryCount = 0;
  2741. result.request = this.request.clone();
  2742. return result;
  2743. };
  2744. /**
  2745. * Returns the base path of the Resource.
  2746. *
  2747. * @param {Boolean} [includeQuery = false] Whether or not to include the query string and fragment form the uri
  2748. *
  2749. * @returns {String} The base URI of the resource
  2750. */
  2751. Resource.prototype.getBaseUri = function(includeQuery) {
  2752. return getBaseUri(this.getUrlComponent(includeQuery), includeQuery);
  2753. };
  2754. /**
  2755. * Appends a forward slash to the URL.
  2756. */
  2757. Resource.prototype.appendForwardSlash = function() {
  2758. this._url = appendForwardSlash(this._url);
  2759. };
  2760. /**
  2761. * Asynchronously loads the resource as raw binary data. Returns a promise that will resolve to
  2762. * an ArrayBuffer once loaded, or reject if the resource failed to load. The data is loaded
  2763. * using XMLHttpRequest, which means that in order to make requests to another origin,
  2764. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  2765. *
  2766. * @returns {Promise.<ArrayBuffer>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  2767. *
  2768. * @example
  2769. * // load a single URL asynchronously
  2770. * resource.fetchArrayBuffer().then(function(arrayBuffer) {
  2771. * // use the data
  2772. * }).otherwise(function(error) {
  2773. * // an error occurred
  2774. * });
  2775. *
  2776. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  2777. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  2778. */
  2779. Resource.prototype.fetchArrayBuffer = function () {
  2780. return this.fetch({
  2781. responseType : 'arraybuffer'
  2782. });
  2783. };
  2784. /**
  2785. * Creates a Resource and calls fetchArrayBuffer() on it.
  2786. *
  2787. * @param {String|Object} options A url or an object with the following properties
  2788. * @param {String} options.url The url of the resource.
  2789. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  2790. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  2791. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  2792. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  2793. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  2794. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  2795. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  2796. * @returns {Promise.<ArrayBuffer>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  2797. */
  2798. Resource.fetchArrayBuffer = function (options) {
  2799. var resource = new Resource(options);
  2800. return resource.fetchArrayBuffer();
  2801. };
  2802. /**
  2803. * Asynchronously loads the given resource as a blob. Returns a promise that will resolve to
  2804. * a Blob once loaded, or reject if the resource failed to load. The data is loaded
  2805. * using XMLHttpRequest, which means that in order to make requests to another origin,
  2806. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  2807. *
  2808. * @returns {Promise.<Blob>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  2809. *
  2810. * @example
  2811. * // load a single URL asynchronously
  2812. * resource.fetchBlob().then(function(blob) {
  2813. * // use the data
  2814. * }).otherwise(function(error) {
  2815. * // an error occurred
  2816. * });
  2817. *
  2818. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  2819. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  2820. */
  2821. Resource.prototype.fetchBlob = function () {
  2822. return this.fetch({
  2823. responseType : 'blob'
  2824. });
  2825. };
  2826. /**
  2827. * Creates a Resource and calls fetchBlob() on it.
  2828. *
  2829. * @param {String|Object} options A url or an object with the following properties
  2830. * @param {String} options.url The url of the resource.
  2831. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  2832. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  2833. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  2834. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  2835. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  2836. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  2837. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  2838. * @returns {Promise.<Blob>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  2839. */
  2840. Resource.fetchBlob = function (options) {
  2841. var resource = new Resource(options);
  2842. return resource.fetchBlob();
  2843. };
  2844. /**
  2845. * Asynchronously loads the given image resource. Returns a promise that will resolve to
  2846. * an {@link https://developer.mozilla.org/en-US/docs/Web/API/ImageBitmap|ImageBitmap} if <code>preferImageBitmap</code> is true and the browser supports <code>createImageBitmap</code> or otherwise an
  2847. * {@link https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement|Image} once loaded, or reject if the image failed to load.
  2848. *
  2849. * @param {Object} [options] An object with the following properties.
  2850. * @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
  2851. * @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  2852. * @param {Boolean} [options.flipY=false] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
  2853. * @returns {Promise.<ImageBitmap>|Promise.<Image>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  2854. *
  2855. *
  2856. * @example
  2857. * // load a single image asynchronously
  2858. * resource.fetchImage().then(function(image) {
  2859. * // use the loaded image
  2860. * }).otherwise(function(error) {
  2861. * // an error occurred
  2862. * });
  2863. *
  2864. * // load several images in parallel
  2865. * when.all([resource1.fetchImage(), resource2.fetchImage()]).then(function(images) {
  2866. * // images is an array containing all the loaded images
  2867. * });
  2868. *
  2869. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  2870. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  2871. */
  2872. Resource.prototype.fetchImage = function (options) {
  2873. options = when.defaultValue(options, when.defaultValue.EMPTY_OBJECT);
  2874. var preferImageBitmap = when.defaultValue(options.preferImageBitmap, false);
  2875. var preferBlob = when.defaultValue(options.preferBlob, false);
  2876. var flipY = when.defaultValue(options.flipY, false);
  2877. checkAndResetRequest(this.request);
  2878. // We try to load the image normally if
  2879. // 1. Blobs aren't supported
  2880. // 2. It's a data URI
  2881. // 3. It's a blob URI
  2882. // 4. It doesn't have request headers and we preferBlob is false
  2883. if (!xhrBlobSupported || this.isDataUri || this.isBlobUri || (!this.hasHeaders && !preferBlob)) {
  2884. return fetchImage({
  2885. resource: this,
  2886. flipY: flipY,
  2887. preferImageBitmap: preferImageBitmap
  2888. });
  2889. }
  2890. var blobPromise = this.fetchBlob();
  2891. if (!when.defined(blobPromise)) {
  2892. return;
  2893. }
  2894. var supportsImageBitmap;
  2895. var useImageBitmap;
  2896. var generatedBlobResource;
  2897. var generatedBlob;
  2898. return Resource.supportsImageBitmapOptions()
  2899. .then(function(result) {
  2900. supportsImageBitmap = result;
  2901. useImageBitmap = supportsImageBitmap && preferImageBitmap;
  2902. return blobPromise;
  2903. })
  2904. .then(function(blob) {
  2905. if (!when.defined(blob)) {
  2906. return;
  2907. }
  2908. generatedBlob = blob;
  2909. if (useImageBitmap) {
  2910. return Resource.createImageBitmapFromBlob(blob, {
  2911. flipY: flipY,
  2912. premultiplyAlpha: false
  2913. });
  2914. }
  2915. var blobUrl = window.URL.createObjectURL(blob);
  2916. generatedBlobResource = new Resource({
  2917. url: blobUrl
  2918. });
  2919. return fetchImage({
  2920. resource: generatedBlobResource,
  2921. flipY: flipY,
  2922. preferImageBitmap: false
  2923. });
  2924. })
  2925. .then(function(image) {
  2926. if (!when.defined(image)) {
  2927. return;
  2928. }
  2929. // The blob object may be needed for use by a TileDiscardPolicy,
  2930. // so attach it to the image.
  2931. image.blob = generatedBlob;
  2932. if (useImageBitmap) {
  2933. return image;
  2934. }
  2935. window.URL.revokeObjectURL(generatedBlobResource.url);
  2936. return image;
  2937. })
  2938. .otherwise(function(error) {
  2939. if (when.defined(generatedBlobResource)) {
  2940. window.URL.revokeObjectURL(generatedBlobResource.url);
  2941. }
  2942. // If the blob load succeeded but the image decode failed, attach the blob
  2943. // to the error object for use by a TileDiscardPolicy.
  2944. // In particular, BingMapsImageryProvider uses this to detect the
  2945. // zero-length response that is returned when a tile is not available.
  2946. error.blob = generatedBlob;
  2947. return when.when.reject(error);
  2948. });
  2949. };
  2950. /**
  2951. * Fetches an image and returns a promise to it.
  2952. *
  2953. * @param {Object} [options] An object with the following properties.
  2954. * @param {Resource} [options.resource] Resource object that points to an image to fetch.
  2955. * @param {Boolean} [options.preferImageBitmap] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  2956. * @param {Boolean} [options.flipY] If true, image will be vertically flipped during decode. Only applies if the browser supports <code>createImageBitmap</code>.
  2957. *
  2958. * @private
  2959. */
  2960. function fetchImage(options) {
  2961. var resource = options.resource;
  2962. var flipY = options.flipY;
  2963. var preferImageBitmap = options.preferImageBitmap;
  2964. var request = resource.request;
  2965. request.url = resource.url;
  2966. request.requestFunction = function() {
  2967. var crossOrigin = false;
  2968. // data URIs can't have crossorigin set.
  2969. if (!resource.isDataUri && !resource.isBlobUri) {
  2970. crossOrigin = resource.isCrossOriginUrl;
  2971. }
  2972. var deferred = when.when.defer();
  2973. Resource._Implementations.createImage(request, crossOrigin, deferred, flipY, preferImageBitmap);
  2974. return deferred.promise;
  2975. };
  2976. var promise = RequestScheduler.request(request);
  2977. if (!when.defined(promise)) {
  2978. return;
  2979. }
  2980. return promise
  2981. .otherwise(function(e) {
  2982. // Don't retry cancelled or otherwise aborted requests
  2983. if (request.state !== RequestState$1.FAILED) {
  2984. return when.when.reject(e);
  2985. }
  2986. return resource.retryOnError(e)
  2987. .then(function(retry) {
  2988. if (retry) {
  2989. // Reset request so it can try again
  2990. request.state = RequestState$1.UNISSUED;
  2991. request.deferred = undefined;
  2992. return fetchImage({
  2993. resource: resource,
  2994. flipY: flipY,
  2995. preferImageBitmap: preferImageBitmap
  2996. });
  2997. }
  2998. return when.when.reject(e);
  2999. });
  3000. });
  3001. }
  3002. /**
  3003. * Creates a Resource and calls fetchImage() on it.
  3004. *
  3005. * @param {String|Object} options A url or an object with the following properties
  3006. * @param {String} options.url The url of the resource.
  3007. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3008. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3009. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3010. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3011. * @param {Boolean} [options.flipY=false] Whether to vertically flip the image during fetch and decode. Only applies when requesting an image and the browser supports <code>createImageBitmap</code>.
  3012. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3013. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3014. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3015. * @param {Boolean} [options.preferBlob=false] If true, we will load the image via a blob.
  3016. * @param {Boolean} [options.preferImageBitmap=false] If true, image will be decoded during fetch and an <code>ImageBitmap</code> is returned.
  3017. * @returns {Promise.<ImageBitmap>|Promise.<Image>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3018. */
  3019. Resource.fetchImage = function (options) {
  3020. var resource = new Resource(options);
  3021. return resource.fetchImage({
  3022. flipY: options.flipY,
  3023. preferBlob: options.preferBlob,
  3024. preferImageBitmap: options.preferImageBitmap
  3025. });
  3026. };
  3027. /**
  3028. * Asynchronously loads the given resource as text. Returns a promise that will resolve to
  3029. * a String once loaded, or reject if the resource failed to load. The data is loaded
  3030. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3031. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3032. *
  3033. * @returns {Promise.<String>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3034. *
  3035. * @example
  3036. * // load text from a URL, setting a custom header
  3037. * var resource = new Resource({
  3038. * url: 'http://someUrl.com/someJson.txt',
  3039. * headers: {
  3040. * 'X-Custom-Header' : 'some value'
  3041. * }
  3042. * });
  3043. * resource.fetchText().then(function(text) {
  3044. * // Do something with the text
  3045. * }).otherwise(function(error) {
  3046. * // an error occurred
  3047. * });
  3048. *
  3049. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  3050. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3051. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3052. */
  3053. Resource.prototype.fetchText = function() {
  3054. return this.fetch({
  3055. responseType : 'text'
  3056. });
  3057. };
  3058. /**
  3059. * Creates a Resource and calls fetchText() on it.
  3060. *
  3061. * @param {String|Object} options A url or an object with the following properties
  3062. * @param {String} options.url The url of the resource.
  3063. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3064. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3065. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3066. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3067. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3068. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3069. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3070. * @returns {Promise.<String>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3071. */
  3072. Resource.fetchText = function (options) {
  3073. var resource = new Resource(options);
  3074. return resource.fetchText();
  3075. };
  3076. // note: &#42;&#47;&#42; below is */* but that ends the comment block early
  3077. /**
  3078. * Asynchronously loads the given resource as JSON. Returns a promise that will resolve to
  3079. * a JSON object once loaded, or reject if the resource failed to load. The data is loaded
  3080. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3081. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. This function
  3082. * adds 'Accept: application/json,&#42;&#47;&#42;;q=0.01' to the request headers, if not
  3083. * already specified.
  3084. *
  3085. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3086. *
  3087. *
  3088. * @example
  3089. * resource.fetchJson().then(function(jsonData) {
  3090. * // Do something with the JSON object
  3091. * }).otherwise(function(error) {
  3092. * // an error occurred
  3093. * });
  3094. *
  3095. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3096. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3097. */
  3098. Resource.prototype.fetchJson = function() {
  3099. var promise = this.fetch({
  3100. responseType : 'text',
  3101. headers: {
  3102. Accept : 'application/json,*/*;q=0.01'
  3103. }
  3104. });
  3105. if (!when.defined(promise)) {
  3106. return undefined;
  3107. }
  3108. return promise
  3109. .then(function(value) {
  3110. if (!when.defined(value)) {
  3111. return;
  3112. }
  3113. return JSON.parse(value);
  3114. });
  3115. };
  3116. /**
  3117. * Creates a Resource and calls fetchJson() on it.
  3118. *
  3119. * @param {String|Object} options A url or an object with the following properties
  3120. * @param {String} options.url The url of the resource.
  3121. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3122. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3123. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3124. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3125. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3126. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3127. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3128. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3129. */
  3130. Resource.fetchJson = function (options) {
  3131. var resource = new Resource(options);
  3132. return resource.fetchJson();
  3133. };
  3134. /**
  3135. * Asynchronously loads the given resource as XML. Returns a promise that will resolve to
  3136. * an XML Document once loaded, or reject if the resource failed to load. The data is loaded
  3137. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3138. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3139. *
  3140. * @returns {Promise.<XMLDocument>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3141. *
  3142. *
  3143. * @example
  3144. * // load XML from a URL, setting a custom header
  3145. * Cesium.loadXML('http://someUrl.com/someXML.xml', {
  3146. * 'X-Custom-Header' : 'some value'
  3147. * }).then(function(document) {
  3148. * // Do something with the document
  3149. * }).otherwise(function(error) {
  3150. * // an error occurred
  3151. * });
  3152. *
  3153. * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest|XMLHttpRequest}
  3154. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3155. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3156. */
  3157. Resource.prototype.fetchXML = function() {
  3158. return this.fetch({
  3159. responseType : 'document',
  3160. overrideMimeType : 'text/xml'
  3161. });
  3162. };
  3163. /**
  3164. * Creates a Resource and calls fetchXML() on it.
  3165. *
  3166. * @param {String|Object} options A url or an object with the following properties
  3167. * @param {String} options.url The url of the resource.
  3168. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3169. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3170. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3171. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3172. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3173. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3174. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3175. * @returns {Promise.<XMLDocument>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3176. */
  3177. Resource.fetchXML = function (options) {
  3178. var resource = new Resource(options);
  3179. return resource.fetchXML();
  3180. };
  3181. /**
  3182. * Requests a resource using JSONP.
  3183. *
  3184. * @param {String} [callbackParameterName='callback'] The callback parameter name that the server expects.
  3185. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3186. *
  3187. *
  3188. * @example
  3189. * // load a data asynchronously
  3190. * resource.fetchJsonp().then(function(data) {
  3191. * // use the loaded data
  3192. * }).otherwise(function(error) {
  3193. * // an error occurred
  3194. * });
  3195. *
  3196. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3197. */
  3198. Resource.prototype.fetchJsonp = function(callbackParameterName) {
  3199. callbackParameterName = when.defaultValue(callbackParameterName, 'callback');
  3200. checkAndResetRequest(this.request);
  3201. //generate a unique function name
  3202. var functionName;
  3203. do {
  3204. functionName = 'loadJsonp' + Math.random().toString().substring(2, 8);
  3205. } while (when.defined(window[functionName]));
  3206. return fetchJsonp(this, callbackParameterName, functionName);
  3207. };
  3208. function fetchJsonp(resource, callbackParameterName, functionName) {
  3209. var callbackQuery = {};
  3210. callbackQuery[callbackParameterName] = functionName;
  3211. resource.setQueryParameters(callbackQuery);
  3212. var request = resource.request;
  3213. request.url = resource.url;
  3214. request.requestFunction = function() {
  3215. var deferred = when.when.defer();
  3216. //assign a function with that name in the global scope
  3217. window[functionName] = function(data) {
  3218. deferred.resolve(data);
  3219. try {
  3220. delete window[functionName];
  3221. } catch (e) {
  3222. window[functionName] = undefined;
  3223. }
  3224. };
  3225. Resource._Implementations.loadAndExecuteScript(resource.url, functionName, deferred);
  3226. return deferred.promise;
  3227. };
  3228. var promise = RequestScheduler.request(request);
  3229. if (!when.defined(promise)) {
  3230. return;
  3231. }
  3232. return promise
  3233. .otherwise(function(e) {
  3234. if (request.state !== RequestState$1.FAILED) {
  3235. return when.when.reject(e);
  3236. }
  3237. return resource.retryOnError(e)
  3238. .then(function(retry) {
  3239. if (retry) {
  3240. // Reset request so it can try again
  3241. request.state = RequestState$1.UNISSUED;
  3242. request.deferred = undefined;
  3243. return fetchJsonp(resource, callbackParameterName, functionName);
  3244. }
  3245. return when.when.reject(e);
  3246. });
  3247. });
  3248. }
  3249. /**
  3250. * Creates a Resource from a URL and calls fetchJsonp() on it.
  3251. *
  3252. * @param {String|Object} options A url or an object with the following properties
  3253. * @param {String} options.url The url of the resource.
  3254. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3255. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3256. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3257. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3258. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3259. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3260. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3261. * @param {String} [options.callbackParameterName='callback'] The callback parameter name that the server expects.
  3262. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3263. */
  3264. Resource.fetchJsonp = function (options) {
  3265. var resource = new Resource(options);
  3266. return resource.fetchJsonp(options.callbackParameterName);
  3267. };
  3268. /**
  3269. * @private
  3270. */
  3271. Resource.prototype._makeRequest = function(options) {
  3272. var resource = this;
  3273. checkAndResetRequest(resource.request);
  3274. var request = resource.request;
  3275. request.url = resource.url;
  3276. request.requestFunction = function(url) {
  3277. var responseType = options.responseType;
  3278. var headers = combine(options.headers, resource.headers);
  3279. var overrideMimeType = options.overrideMimeType;
  3280. var method = options.method;
  3281. var data = options.data;
  3282. var deferred = when.when.defer();
  3283. var newUrl = when.defined(url) ? url : resource.url;
  3284. var xhr = Resource._Implementations.loadWithXhr(newUrl, responseType, method, data, headers, deferred, overrideMimeType);
  3285. if (when.defined(xhr) && when.defined(xhr.abort)) {
  3286. request.cancelFunction = function() {
  3287. xhr.abort();
  3288. };
  3289. }
  3290. return deferred.promise;
  3291. };
  3292. var promise = RequestScheduler.request(request);
  3293. if (!when.defined(promise)) {
  3294. return;
  3295. }
  3296. return promise
  3297. .then(function(data) {
  3298. return data;
  3299. })
  3300. .otherwise(function(e) {
  3301. if (request.state !== RequestState$1.FAILED) {
  3302. return when.when.reject(e);
  3303. }
  3304. return resource.retryOnError(e)
  3305. .then(function(retry) {
  3306. if (retry) {
  3307. // Reset request so it can try again
  3308. request.state = RequestState$1.UNISSUED;
  3309. request.deferred = undefined;
  3310. return resource.fetch(options);
  3311. }
  3312. return when.when.reject(e);
  3313. });
  3314. });
  3315. };
  3316. var dataUriRegex$1 = /^data:(.*?)(;base64)?,(.*)$/;
  3317. function decodeDataUriText(isBase64, data) {
  3318. var result = decodeURIComponent(data);
  3319. if (isBase64) {
  3320. return atob(result);
  3321. }
  3322. return result;
  3323. }
  3324. function decodeDataUriArrayBuffer(isBase64, data) {
  3325. var byteString = decodeDataUriText(isBase64, data);
  3326. var buffer = new ArrayBuffer(byteString.length);
  3327. var view = new Uint8Array(buffer);
  3328. for (var i = 0; i < byteString.length; i++) {
  3329. view[i] = byteString.charCodeAt(i);
  3330. }
  3331. return buffer;
  3332. }
  3333. function decodeDataUri(dataUriRegexResult, responseType) {
  3334. responseType = when.defaultValue(responseType, '');
  3335. var mimeType = dataUriRegexResult[1];
  3336. var isBase64 = !!dataUriRegexResult[2];
  3337. var data = dataUriRegexResult[3];
  3338. switch (responseType) {
  3339. case '':
  3340. case 'text':
  3341. return decodeDataUriText(isBase64, data);
  3342. case 'arraybuffer':
  3343. return decodeDataUriArrayBuffer(isBase64, data);
  3344. case 'blob':
  3345. var buffer = decodeDataUriArrayBuffer(isBase64, data);
  3346. return new Blob([buffer], {
  3347. type : mimeType
  3348. });
  3349. case 'document':
  3350. var parser = new DOMParser();
  3351. return parser.parseFromString(decodeDataUriText(isBase64, data), mimeType);
  3352. case 'json':
  3353. return JSON.parse(decodeDataUriText(isBase64, data));
  3354. default:
  3355. //>>includeStart('debug', pragmas.debug);
  3356. throw new Check.DeveloperError('Unhandled responseType: ' + responseType);
  3357. //>>includeEnd('debug');
  3358. }
  3359. }
  3360. /**
  3361. * Asynchronously loads the given resource. Returns a promise that will resolve to
  3362. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3363. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3364. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled. It's recommended that you use
  3365. * the more specific functions eg. fetchJson, fetchBlob, etc.
  3366. *
  3367. * @param {Object} [options] Object with the following properties:
  3368. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3369. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3370. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3371. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3372. *
  3373. *
  3374. * @example
  3375. * resource.fetch()
  3376. * .then(function(body) {
  3377. * // use the data
  3378. * }).otherwise(function(error) {
  3379. * // an error occurred
  3380. * });
  3381. *
  3382. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3383. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3384. */
  3385. Resource.prototype.fetch = function(options) {
  3386. options = defaultClone(options, {});
  3387. options.method = 'GET';
  3388. return this._makeRequest(options);
  3389. };
  3390. /**
  3391. * Creates a Resource from a URL and calls fetch() on it.
  3392. *
  3393. * @param {String|Object} options A url or an object with the following properties
  3394. * @param {String} options.url The url of the resource.
  3395. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3396. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3397. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3398. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3399. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3400. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3401. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3402. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3403. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3404. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3405. */
  3406. Resource.fetch = function (options) {
  3407. var resource = new Resource(options);
  3408. return resource.fetch({
  3409. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  3410. responseType: options.responseType,
  3411. overrideMimeType: options.overrideMimeType
  3412. });
  3413. };
  3414. /**
  3415. * Asynchronously deletes the given resource. Returns a promise that will resolve to
  3416. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3417. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3418. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3419. *
  3420. * @param {Object} [options] Object with the following properties:
  3421. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3422. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3423. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3424. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3425. *
  3426. *
  3427. * @example
  3428. * resource.delete()
  3429. * .then(function(body) {
  3430. * // use the data
  3431. * }).otherwise(function(error) {
  3432. * // an error occurred
  3433. * });
  3434. *
  3435. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3436. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3437. */
  3438. Resource.prototype.delete = function(options) {
  3439. options = defaultClone(options, {});
  3440. options.method = 'DELETE';
  3441. return this._makeRequest(options);
  3442. };
  3443. /**
  3444. * Creates a Resource from a URL and calls delete() on it.
  3445. *
  3446. * @param {String|Object} options A url or an object with the following properties
  3447. * @param {String} options.url The url of the resource.
  3448. * @param {Object} [options.data] Data that is posted with the resource.
  3449. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3450. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3451. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3452. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3453. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3454. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3455. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3456. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3457. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3458. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3459. */
  3460. Resource.delete = function (options) {
  3461. var resource = new Resource(options);
  3462. return resource.delete({
  3463. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  3464. responseType: options.responseType,
  3465. overrideMimeType: options.overrideMimeType,
  3466. data: options.data
  3467. });
  3468. };
  3469. /**
  3470. * Asynchronously gets headers the given resource. Returns a promise that will resolve to
  3471. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3472. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3473. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3474. *
  3475. * @param {Object} [options] Object with the following properties:
  3476. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3477. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3478. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3479. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3480. *
  3481. *
  3482. * @example
  3483. * resource.head()
  3484. * .then(function(headers) {
  3485. * // use the data
  3486. * }).otherwise(function(error) {
  3487. * // an error occurred
  3488. * });
  3489. *
  3490. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3491. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3492. */
  3493. Resource.prototype.head = function(options) {
  3494. options = defaultClone(options, {});
  3495. options.method = 'HEAD';
  3496. return this._makeRequest(options);
  3497. };
  3498. /**
  3499. * Creates a Resource from a URL and calls head() on it.
  3500. *
  3501. * @param {String|Object} options A url or an object with the following properties
  3502. * @param {String} options.url The url of the resource.
  3503. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3504. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3505. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3506. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3507. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3508. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3509. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3510. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3511. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3512. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3513. */
  3514. Resource.head = function (options) {
  3515. var resource = new Resource(options);
  3516. return resource.head({
  3517. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  3518. responseType: options.responseType,
  3519. overrideMimeType: options.overrideMimeType
  3520. });
  3521. };
  3522. /**
  3523. * Asynchronously gets options the given resource. Returns a promise that will resolve to
  3524. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3525. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3526. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3527. *
  3528. * @param {Object} [options] Object with the following properties:
  3529. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3530. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3531. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3532. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3533. *
  3534. *
  3535. * @example
  3536. * resource.options()
  3537. * .then(function(headers) {
  3538. * // use the data
  3539. * }).otherwise(function(error) {
  3540. * // an error occurred
  3541. * });
  3542. *
  3543. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3544. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3545. */
  3546. Resource.prototype.options = function(options) {
  3547. options = defaultClone(options, {});
  3548. options.method = 'OPTIONS';
  3549. return this._makeRequest(options);
  3550. };
  3551. /**
  3552. * Creates a Resource from a URL and calls options() on it.
  3553. *
  3554. * @param {String|Object} options A url or an object with the following properties
  3555. * @param {String} options.url The url of the resource.
  3556. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3557. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3558. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3559. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3560. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3561. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3562. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3563. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3564. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3565. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3566. */
  3567. Resource.options = function (options) {
  3568. var resource = new Resource(options);
  3569. return resource.options({
  3570. // Make copy of just the needed fields because headers can be passed to both the constructor and to fetch
  3571. responseType: options.responseType,
  3572. overrideMimeType: options.overrideMimeType
  3573. });
  3574. };
  3575. /**
  3576. * Asynchronously posts data to the given resource. Returns a promise that will resolve to
  3577. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3578. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3579. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3580. *
  3581. * @param {Object} data Data that is posted with the resource.
  3582. * @param {Object} [options] Object with the following properties:
  3583. * @param {Object} [options.data] Data that is posted with the resource.
  3584. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3585. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3586. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3587. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3588. *
  3589. *
  3590. * @example
  3591. * resource.post(data)
  3592. * .then(function(result) {
  3593. * // use the result
  3594. * }).otherwise(function(error) {
  3595. * // an error occurred
  3596. * });
  3597. *
  3598. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3599. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3600. */
  3601. Resource.prototype.post = function(data, options) {
  3602. Check.Check.defined('data', data);
  3603. options = defaultClone(options, {});
  3604. options.method = 'POST';
  3605. options.data = data;
  3606. return this._makeRequest(options);
  3607. };
  3608. /**
  3609. * Creates a Resource from a URL and calls post() on it.
  3610. *
  3611. * @param {Object} options A url or an object with the following properties
  3612. * @param {String} options.url The url of the resource.
  3613. * @param {Object} options.data Data that is posted with the resource.
  3614. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3615. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3616. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3617. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3618. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3619. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3620. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3621. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3622. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3623. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3624. */
  3625. Resource.post = function (options) {
  3626. var resource = new Resource(options);
  3627. return resource.post(options.data, {
  3628. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  3629. responseType: options.responseType,
  3630. overrideMimeType: options.overrideMimeType
  3631. });
  3632. };
  3633. /**
  3634. * Asynchronously puts data to the given resource. Returns a promise that will resolve to
  3635. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3636. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3637. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3638. *
  3639. * @param {Object} data Data that is posted with the resource.
  3640. * @param {Object} [options] Object with the following properties:
  3641. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3642. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3643. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3644. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3645. *
  3646. *
  3647. * @example
  3648. * resource.put(data)
  3649. * .then(function(result) {
  3650. * // use the result
  3651. * }).otherwise(function(error) {
  3652. * // an error occurred
  3653. * });
  3654. *
  3655. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3656. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3657. */
  3658. Resource.prototype.put = function(data, options) {
  3659. Check.Check.defined('data', data);
  3660. options = defaultClone(options, {});
  3661. options.method = 'PUT';
  3662. options.data = data;
  3663. return this._makeRequest(options);
  3664. };
  3665. /**
  3666. * Creates a Resource from a URL and calls put() on it.
  3667. *
  3668. * @param {Object} options A url or an object with the following properties
  3669. * @param {String} options.url The url of the resource.
  3670. * @param {Object} options.data Data that is posted with the resource.
  3671. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3672. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3673. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3674. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3675. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3676. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3677. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3678. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3679. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3680. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3681. */
  3682. Resource.put = function (options) {
  3683. var resource = new Resource(options);
  3684. return resource.put(options.data, {
  3685. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  3686. responseType: options.responseType,
  3687. overrideMimeType: options.overrideMimeType
  3688. });
  3689. };
  3690. /**
  3691. * Asynchronously patches data to the given resource. Returns a promise that will resolve to
  3692. * the result once loaded, or reject if the resource failed to load. The data is loaded
  3693. * using XMLHttpRequest, which means that in order to make requests to another origin,
  3694. * the server must have Cross-Origin Resource Sharing (CORS) headers enabled.
  3695. *
  3696. * @param {Object} data Data that is posted with the resource.
  3697. * @param {Object} [options] Object with the following properties:
  3698. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3699. * @param {Object} [options.headers] Additional HTTP headers to send with the request, if any.
  3700. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3701. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3702. *
  3703. *
  3704. * @example
  3705. * resource.patch(data)
  3706. * .then(function(result) {
  3707. * // use the result
  3708. * }).otherwise(function(error) {
  3709. * // an error occurred
  3710. * });
  3711. *
  3712. * @see {@link http://www.w3.org/TR/cors/|Cross-Origin Resource Sharing}
  3713. * @see {@link http://wiki.commonjs.org/wiki/Promises/A|CommonJS Promises/A}
  3714. */
  3715. Resource.prototype.patch = function(data, options) {
  3716. Check.Check.defined('data', data);
  3717. options = defaultClone(options, {});
  3718. options.method = 'PATCH';
  3719. options.data = data;
  3720. return this._makeRequest(options);
  3721. };
  3722. /**
  3723. * Creates a Resource from a URL and calls patch() on it.
  3724. *
  3725. * @param {Object} options A url or an object with the following properties
  3726. * @param {String} options.url The url of the resource.
  3727. * @param {Object} options.data Data that is posted with the resource.
  3728. * @param {Object} [options.queryParameters] An object containing query parameters that will be sent when retrieving the resource.
  3729. * @param {Object} [options.templateValues] Key/Value pairs that are used to replace template values (eg. {x}).
  3730. * @param {Object} [options.headers={}] Additional HTTP headers that will be sent.
  3731. * @param {DefaultProxy} [options.proxy] A proxy to be used when loading the resource.
  3732. * @param {Resource~RetryCallback} [options.retryCallback] The Function to call when a request for this resource fails. If it returns true, the request will be retried.
  3733. * @param {Number} [options.retryAttempts=0] The number of times the retryCallback should be called before giving up.
  3734. * @param {Request} [options.request] A Request object that will be used. Intended for internal use only.
  3735. * @param {String} [options.responseType] The type of response. This controls the type of item returned.
  3736. * @param {String} [options.overrideMimeType] Overrides the MIME type returned by the server.
  3737. * @returns {Promise.<Object>|undefined} a promise that will resolve to the requested data when loaded. Returns undefined if <code>request.throttle</code> is true and the request does not have high enough priority.
  3738. */
  3739. Resource.patch = function (options) {
  3740. var resource = new Resource(options);
  3741. return resource.patch(options.data, {
  3742. // Make copy of just the needed fields because headers can be passed to both the constructor and to post
  3743. responseType: options.responseType,
  3744. overrideMimeType: options.overrideMimeType
  3745. });
  3746. };
  3747. /**
  3748. * Contains implementations of functions that can be replaced for testing
  3749. *
  3750. * @private
  3751. */
  3752. Resource._Implementations = {};
  3753. function loadImageElement(url, crossOrigin, deferred) {
  3754. var image = new Image();
  3755. image.onload = function() {
  3756. deferred.resolve(image);
  3757. };
  3758. image.onerror = function(e) {
  3759. deferred.reject(e);
  3760. };
  3761. if (crossOrigin) {
  3762. if (TrustedServers.contains(url)) {
  3763. image.crossOrigin = 'use-credentials';
  3764. } else {
  3765. image.crossOrigin = '';
  3766. }
  3767. }
  3768. image.src = url;
  3769. }
  3770. Resource._Implementations.createImage = function(request, crossOrigin, deferred, flipY, preferImageBitmap) {
  3771. var url = request.url;
  3772. // Passing an Image to createImageBitmap will force it to run on the main thread
  3773. // since DOM elements don't exist on workers. We convert it to a blob so it's non-blocking.
  3774. // See:
  3775. // https://bugzilla.mozilla.org/show_bug.cgi?id=1044102#c38
  3776. // https://bugs.chromium.org/p/chromium/issues/detail?id=580202#c10
  3777. Resource.supportsImageBitmapOptions()
  3778. .then(function(supportsImageBitmap) {
  3779. // We can only use ImageBitmap if we can flip on decode.
  3780. // See: https://github.com/CesiumGS/cesium/pull/7579#issuecomment-466146898
  3781. if (!(supportsImageBitmap && preferImageBitmap)) {
  3782. loadImageElement(url, crossOrigin, deferred);
  3783. return;
  3784. }
  3785. var responseType = 'blob';
  3786. var method = 'GET';
  3787. var xhrDeferred = when.when.defer();
  3788. var xhr = Resource._Implementations.loadWithXhr(
  3789. url,
  3790. responseType,
  3791. method,
  3792. undefined,
  3793. undefined,
  3794. xhrDeferred,
  3795. undefined,
  3796. undefined,
  3797. undefined
  3798. );
  3799. if (when.defined(xhr) && when.defined(xhr.abort)) {
  3800. request.cancelFunction = function() {
  3801. xhr.abort();
  3802. };
  3803. }
  3804. return xhrDeferred.promise.then(function(blob) {
  3805. if (!when.defined(blob)) {
  3806. deferred.reject(new RuntimeError.RuntimeError('Successfully retrieved ' + url + ' but it contained no content.'));
  3807. return;
  3808. }
  3809. return Resource.createImageBitmapFromBlob(blob, {
  3810. flipY: flipY,
  3811. premultiplyAlpha: false
  3812. });
  3813. }).then(deferred.resolve);
  3814. })
  3815. .otherwise(deferred.reject);
  3816. };
  3817. /**
  3818. * Wrapper for createImageBitmap
  3819. *
  3820. * @private
  3821. */
  3822. Resource.createImageBitmapFromBlob = function(blob, options) {
  3823. Check.Check.defined('options', options);
  3824. Check.Check.typeOf.bool('options.flipY', options.flipY);
  3825. Check.Check.typeOf.bool('options.premultiplyAlpha', options.premultiplyAlpha);
  3826. return createImageBitmap(blob, {
  3827. imageOrientation: options.flipY ? 'flipY' : 'none',
  3828. premultiplyAlpha: options.premultiplyAlpha ? 'premultiply' : 'none'
  3829. });
  3830. };
  3831. function decodeResponse(loadWithHttpResponse, responseType) {
  3832. switch (responseType) {
  3833. case 'text':
  3834. return loadWithHttpResponse.toString('utf8');
  3835. case 'json':
  3836. return JSON.parse(loadWithHttpResponse.toString('utf8'));
  3837. default:
  3838. return new Uint8Array(loadWithHttpResponse).buffer;
  3839. }
  3840. }
  3841. function loadWithHttpRequest(url, responseType, method, data, headers, deferred, overrideMimeType) {
  3842. // Note: only the 'json' and 'text' responseTypes transforms the loaded buffer
  3843. var URL = require('url').parse(url); // eslint-disable-line
  3844. var http = URL.protocol === 'https:' ? require('https') : require('http'); // eslint-disable-line
  3845. var zlib = require('zlib'); // eslint-disable-line
  3846. var options = {
  3847. protocol : URL.protocol,
  3848. hostname : URL.hostname,
  3849. port : URL.port,
  3850. path : URL.path,
  3851. query : URL.query,
  3852. method : method,
  3853. headers : headers
  3854. };
  3855. http.request(options)
  3856. .on('response', function(res) {
  3857. if (res.statusCode < 200 || res.statusCode >= 300) {
  3858. deferred.reject(new RequestErrorEvent(res.statusCode, res, res.headers));
  3859. return;
  3860. }
  3861. var chunkArray = [];
  3862. res.on('data', function(chunk) {
  3863. chunkArray.push(chunk);
  3864. });
  3865. res.on('end', function() {
  3866. var result = Buffer.concat(chunkArray); // eslint-disable-line
  3867. if (res.headers['content-encoding'] === 'gzip') {
  3868. zlib.gunzip(result, function(error, resultUnzipped) {
  3869. if (error) {
  3870. deferred.reject(new RuntimeError.RuntimeError('Error decompressing response.'));
  3871. } else {
  3872. deferred.resolve(decodeResponse(resultUnzipped, responseType));
  3873. }
  3874. });
  3875. } else {
  3876. deferred.resolve(decodeResponse(result, responseType));
  3877. }
  3878. });
  3879. }).on('error', function(e) {
  3880. deferred.reject(new RequestErrorEvent());
  3881. }).end();
  3882. }
  3883. var noXMLHttpRequest = typeof XMLHttpRequest === 'undefined';
  3884. Resource._Implementations.loadWithXhr = function(url, responseType, method, data, headers, deferred, overrideMimeType) {
  3885. var dataUriRegexResult = dataUriRegex$1.exec(url);
  3886. if (dataUriRegexResult !== null) {
  3887. deferred.resolve(decodeDataUri(dataUriRegexResult, responseType));
  3888. return;
  3889. }
  3890. if (noXMLHttpRequest) {
  3891. loadWithHttpRequest(url, responseType, method, data, headers, deferred);
  3892. return;
  3893. }
  3894. var xhr = new XMLHttpRequest();
  3895. if (TrustedServers.contains(url)) {
  3896. xhr.withCredentials = true;
  3897. }
  3898. url = url.replace(/{/g, '%7B').replace(/}/g, '%7D');
  3899. xhr.open(method, url, true);
  3900. if (when.defined(overrideMimeType) && when.defined(xhr.overrideMimeType)) {
  3901. xhr.overrideMimeType(overrideMimeType);
  3902. }
  3903. if (when.defined(headers)) {
  3904. for (var key in headers) {
  3905. if (headers.hasOwnProperty(key)) {
  3906. xhr.setRequestHeader(key, headers[key]);
  3907. }
  3908. }
  3909. }
  3910. if (when.defined(responseType)) {
  3911. xhr.responseType = responseType;
  3912. }
  3913. // While non-standard, file protocol always returns a status of 0 on success
  3914. var localFile = false;
  3915. if (typeof url === 'string') {
  3916. localFile = (url.indexOf('file://') === 0) || (typeof window !== 'undefined' && window.location.origin === 'file://');
  3917. }
  3918. xhr.onload = function() {
  3919. if ((xhr.status < 200 || xhr.status >= 300) && !(localFile && xhr.status === 0)) {
  3920. deferred.reject(new RequestErrorEvent(xhr.status, xhr.response, xhr.getAllResponseHeaders()));
  3921. return;
  3922. }
  3923. var response = xhr.response;
  3924. var browserResponseType = xhr.responseType;
  3925. if (method === 'HEAD' || method === 'OPTIONS') {
  3926. var responseHeaderString = xhr.getAllResponseHeaders();
  3927. var splitHeaders = responseHeaderString.trim().split(/[\r\n]+/);
  3928. var responseHeaders = {};
  3929. splitHeaders.forEach(function (line) {
  3930. var parts = line.split(': ');
  3931. var header = parts.shift();
  3932. responseHeaders[header] = parts.join(': ');
  3933. });
  3934. deferred.resolve(responseHeaders);
  3935. return;
  3936. }
  3937. //All modern browsers will go into either the first or second if block or last else block.
  3938. //Other code paths support older browsers that either do not support the supplied responseType
  3939. //or do not support the xhr.response property.
  3940. if (xhr.status === 204) {
  3941. // accept no content
  3942. deferred.resolve();
  3943. } else if (when.defined(response) && (!when.defined(responseType) || (browserResponseType === responseType))) {
  3944. deferred.resolve(response);
  3945. } else if ((responseType === 'json') && typeof response === 'string') {
  3946. try {
  3947. deferred.resolve(JSON.parse(response));
  3948. } catch (e) {
  3949. deferred.reject(e);
  3950. }
  3951. } else if ((browserResponseType === '' || browserResponseType === 'document') && when.defined(xhr.responseXML) && xhr.responseXML.hasChildNodes()) {
  3952. deferred.resolve(xhr.responseXML);
  3953. } else if ((browserResponseType === '' || browserResponseType === 'text') && when.defined(xhr.responseText)) {
  3954. deferred.resolve(xhr.responseText);
  3955. } else {
  3956. deferred.reject(new RuntimeError.RuntimeError('Invalid XMLHttpRequest response type.'));
  3957. }
  3958. };
  3959. xhr.onerror = function(e) {
  3960. deferred.reject(new RequestErrorEvent());
  3961. };
  3962. xhr.send(data);
  3963. return xhr;
  3964. };
  3965. Resource._Implementations.loadAndExecuteScript = function(url, functionName, deferred) {
  3966. return loadAndExecuteScript(url).otherwise(deferred.reject);
  3967. };
  3968. /**
  3969. * The default implementations
  3970. *
  3971. * @private
  3972. */
  3973. Resource._DefaultImplementations = {};
  3974. Resource._DefaultImplementations.createImage = Resource._Implementations.createImage;
  3975. Resource._DefaultImplementations.loadWithXhr = Resource._Implementations.loadWithXhr;
  3976. Resource._DefaultImplementations.loadAndExecuteScript = Resource._Implementations.loadAndExecuteScript;
  3977. /**
  3978. * A resource instance initialized to the current browser location
  3979. *
  3980. * @type {Resource}
  3981. * @constant
  3982. */
  3983. Resource.DEFAULT = Object.freeze(new Resource({
  3984. url: (typeof document === 'undefined') ? '' : document.location.href.split('?')[0]
  3985. }));
  3986. /*global CESIUM_BASE_URL*/
  3987. var cesiumScriptRegex = /((?:.*\/)|^)Cesium\.js$/;
  3988. function getBaseUrlFromCesiumScript() {
  3989. var scripts = document.getElementsByTagName('script');
  3990. for ( var i = 0, len = scripts.length; i < len; ++i) {
  3991. var src = scripts[i].getAttribute('src');
  3992. var result = cesiumScriptRegex.exec(src);
  3993. if (result !== null) {
  3994. return result[1];
  3995. }
  3996. }
  3997. return undefined;
  3998. }
  3999. var a$1;
  4000. function tryMakeAbsolute(url) {
  4001. if (typeof document === 'undefined') {
  4002. //Node.js and Web Workers. In both cases, the URL will already be absolute.
  4003. return url;
  4004. }
  4005. if (!when.defined(a$1)) {
  4006. a$1 = document.createElement('a');
  4007. }
  4008. a$1.href = url;
  4009. // IE only absolutizes href on get, not set
  4010. a$1.href = a$1.href; // eslint-disable-line no-self-assign
  4011. return a$1.href;
  4012. }
  4013. var baseResource;
  4014. function getCesiumBaseUrl() {
  4015. if (when.defined(baseResource)) {
  4016. return baseResource;
  4017. }
  4018. var baseUrlString;
  4019. if (typeof CESIUM_BASE_URL !== 'undefined') {
  4020. baseUrlString = CESIUM_BASE_URL;
  4021. } else if (typeof define === 'object' && when.defined(define.amd) && !define.amd.toUrlUndefined && when.defined(require.toUrl)) {
  4022. baseUrlString = getAbsoluteUri('..', buildModuleUrl('Core/buildModuleUrl.js'));
  4023. } else {
  4024. baseUrlString = getBaseUrlFromCesiumScript();
  4025. }
  4026. //>>includeStart('debug', pragmas.debug);
  4027. if (!when.defined(baseUrlString)) {
  4028. throw new Check.DeveloperError('Unable to determine Cesium base URL automatically, try defining a global variable called CESIUM_BASE_URL.');
  4029. }
  4030. //>>includeEnd('debug');
  4031. baseResource = new Resource({
  4032. url: tryMakeAbsolute(baseUrlString)
  4033. });
  4034. baseResource.appendForwardSlash();
  4035. return baseResource;
  4036. }
  4037. function buildModuleUrlFromRequireToUrl(moduleID) {
  4038. //moduleID will be non-relative, so require it relative to this module, in Core.
  4039. return tryMakeAbsolute(require.toUrl('../' + moduleID));
  4040. }
  4041. function buildModuleUrlFromBaseUrl(moduleID) {
  4042. var resource = getCesiumBaseUrl().getDerivedResource({
  4043. url: moduleID
  4044. });
  4045. return resource.url;
  4046. }
  4047. var implementation;
  4048. /**
  4049. * Given a non-relative moduleID, returns an absolute URL to the file represented by that module ID,
  4050. * using, in order of preference, require.toUrl, the value of a global CESIUM_BASE_URL, or
  4051. * the base URL of the Cesium.js script.
  4052. *
  4053. * @private
  4054. */
  4055. function buildModuleUrl(moduleID) {
  4056. if (!when.defined(implementation)) {
  4057. //select implementation
  4058. if (typeof define === 'object' && when.defined(define.amd) && !define.amd.toUrlUndefined && when.defined(require.toUrl)) {
  4059. implementation = buildModuleUrlFromRequireToUrl;
  4060. } else {
  4061. implementation = buildModuleUrlFromBaseUrl;
  4062. }
  4063. }
  4064. var url = implementation(moduleID);
  4065. return url;
  4066. }
  4067. // exposed for testing
  4068. buildModuleUrl._cesiumScriptRegex = cesiumScriptRegex;
  4069. buildModuleUrl._buildModuleUrlFromBaseUrl = buildModuleUrlFromBaseUrl;
  4070. buildModuleUrl._clearBaseResource = function() {
  4071. baseResource = undefined;
  4072. };
  4073. /**
  4074. * Sets the base URL for resolving modules.
  4075. * @param {String} value The new base URL.
  4076. */
  4077. buildModuleUrl.setBaseUrl = function(value) {
  4078. baseResource = Resource.DEFAULT.getDerivedResource({
  4079. url: value
  4080. });
  4081. };
  4082. /**
  4083. * Gets the base URL for resolving modules.
  4084. */
  4085. buildModuleUrl.getCesiumBaseUrl = getCesiumBaseUrl;
  4086. exports.Resource = Resource;
  4087. exports.buildModuleUrl = buildModuleUrl;
  4088. exports.deprecationWarning = deprecationWarning;
  4089. exports.oneTimeWarning = oneTimeWarning;
  4090. });