styled-components.native.esm.js 171 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254
  1. import transformDeclPairs from 'css-to-react-native';
  2. import { isElement, isValidElementType } from 'react-is';
  3. import React, { useContext, useMemo, createElement, Component } from 'react';
  4. import 'shallowequal';
  5. import Stylis from '@emotion/stylis';
  6. import unitless from '@emotion/unitless';
  7. import supportsColor from 'supports-color';
  8. import hoist from 'hoist-non-react-statics';
  9. //
  10. /* eslint-disable no-bitwise */
  11. var AD_REPLACER_R = /(a)(d)/gi;
  12. /* This is the "capacity" of our alphabet i.e. 2x26 for all letters plus their capitalised
  13. * counterparts */
  14. var charsLength = 52;
  15. /* start at 75 for 'a' until 'z' (25) and then start at 65 for capitalised letters */
  16. var getAlphabeticChar = function getAlphabeticChar(code) {
  17. return String.fromCharCode(code + (code > 25 ? 39 : 97));
  18. };
  19. /* input a number, usually a hash and convert it to base-52 */
  20. function generateAlphabeticName(code) {
  21. var name = '';
  22. var x;
  23. /* get a char and divide by alphabet-length */
  24. for (x = Math.abs(code); x > charsLength; x = x / charsLength | 0) {
  25. name = getAlphabeticChar(x % charsLength) + name;
  26. }
  27. return (getAlphabeticChar(x % charsLength) + name).replace(AD_REPLACER_R, '$1-$2');
  28. }
  29. //
  30. /* eslint-disable */
  31. var SEED = 5381; // When we have separate strings it's useful to run a progressive
  32. // version of djb2 where we pretend that we're still looping over
  33. // the same string
  34. var phash = function phash(h, x) {
  35. var i = x.length;
  36. while (i) {
  37. h = h * 33 ^ x.charCodeAt(--i);
  38. }
  39. return h;
  40. }; // This is a djb2 hashing function
  41. var hash = function hash(x) {
  42. return phash(SEED, x);
  43. };
  44. //
  45. var generateComponentId = (function (str) {
  46. return generateAlphabeticName(hash(str) >>> 0);
  47. });
  48. //
  49. function getComponentName(target) {
  50. return (process.env.NODE_ENV !== 'production' ? typeof target === 'string' && target : false) || // $FlowFixMe
  51. target.displayName || // $FlowFixMe
  52. target.name || 'Component';
  53. }
  54. //
  55. function isFunction(test) {
  56. return typeof test === 'function';
  57. }
  58. //
  59. function isStatelessFunction(test) {
  60. return typeof test === 'function' && !(test.prototype && test.prototype.isReactComponent);
  61. }
  62. //
  63. var isPlainObject = (function (x) {
  64. return typeof x === 'object' && x.constructor === Object;
  65. });
  66. //
  67. function isStyledComponent(target) {
  68. return target && typeof target.styledComponentId === 'string';
  69. }
  70. function _defineProperties(target, props) {
  71. for (var i = 0; i < props.length; i++) {
  72. var descriptor = props[i];
  73. descriptor.enumerable = descriptor.enumerable || false;
  74. descriptor.configurable = true;
  75. if ("value" in descriptor) descriptor.writable = true;
  76. Object.defineProperty(target, descriptor.key, descriptor);
  77. }
  78. }
  79. function _createClass(Constructor, protoProps, staticProps) {
  80. if (protoProps) _defineProperties(Constructor.prototype, protoProps);
  81. if (staticProps) _defineProperties(Constructor, staticProps);
  82. return Constructor;
  83. }
  84. function _extends() {
  85. _extends = Object.assign || function (target) {
  86. for (var i = 1; i < arguments.length; i++) {
  87. var source = arguments[i];
  88. for (var key in source) {
  89. if (Object.prototype.hasOwnProperty.call(source, key)) {
  90. target[key] = source[key];
  91. }
  92. }
  93. }
  94. return target;
  95. };
  96. return _extends.apply(this, arguments);
  97. }
  98. function _inheritsLoose(subClass, superClass) {
  99. subClass.prototype = Object.create(superClass.prototype);
  100. subClass.prototype.constructor = subClass;
  101. subClass.__proto__ = superClass;
  102. }
  103. function _objectWithoutPropertiesLoose(source, excluded) {
  104. if (source == null) return {};
  105. var target = {};
  106. var sourceKeys = Object.keys(source);
  107. var key, i;
  108. for (i = 0; i < sourceKeys.length; i++) {
  109. key = sourceKeys[i];
  110. if (excluded.indexOf(key) >= 0) continue;
  111. target[key] = source[key];
  112. }
  113. return target;
  114. }
  115. //
  116. var SC_ATTR = typeof process !== 'undefined' && (process.env.REACT_APP_SC_ATTR || process.env.SC_ATTR) || 'data-styled';
  117. var SC_ATTR_ACTIVE = 'active';
  118. var SC_ATTR_VERSION = 'data-styled-version';
  119. var SC_VERSION = "5.0.1";
  120. var IS_BROWSER = typeof window !== 'undefined' && 'HTMLElement' in window;
  121. var DISABLE_SPEEDY = typeof SC_DISABLE_SPEEDY === 'boolean' && SC_DISABLE_SPEEDY || typeof process !== 'undefined' && (process.env.REACT_APP_SC_DISABLE_SPEEDY || process.env.SC_DISABLE_SPEEDY) || process.env.NODE_ENV !== 'production'; // Shared empty execution context when generating static styles
  122. //
  123. /* eslint-disable camelcase, no-undef */
  124. var getNonce = function getNonce() {
  125. return typeof __webpack_nonce__ !== 'undefined' ? __webpack_nonce__ : null;
  126. };
  127. var errorMap = {
  128. "1": "Cannot create styled-component for component: %s.\n\n",
  129. "2": "Can't collect styles once you've consumed a `ServerStyleSheet`'s styles! `ServerStyleSheet` is a one off instance for each server-side render cycle.\n\n- Are you trying to reuse it across renders?\n- Are you accidentally calling collectStyles twice?\n\n",
  130. "3": "Streaming SSR is only supported in a Node.js environment; Please do not try to call this method in the browser.\n\n",
  131. "4": "The `StyleSheetManager` expects a valid target or sheet prop!\n\n- Does this error occur on the client and is your target falsy?\n- Does this error occur on the server and is the sheet falsy?\n\n",
  132. "5": "The clone method cannot be used on the client!\n\n- Are you running in a client-like environment on the server?\n- Are you trying to run SSR on the client?\n\n",
  133. "6": "Trying to insert a new style tag, but the given Node is unmounted!\n\n- Are you using a custom target that isn't mounted?\n- Does your document not have a valid head element?\n- Have you accidentally removed a style tag manually?\n\n",
  134. "7": "ThemeProvider: Please return an object from your \"theme\" prop function, e.g.\n\n```js\ntheme={() => ({})}\n```\n\n",
  135. "8": "ThemeProvider: Please make your \"theme\" prop an object.\n\n",
  136. "9": "Missing document `<head>`\n\n",
  137. "10": "Cannot find a StyleSheet instance. Usually this happens if there are multiple copies of styled-components loaded at once. Check out this issue for how to troubleshoot and fix the common cases where this situation can happen: https://github.com/styled-components/styled-components/issues/1941#issuecomment-417862021\n\n",
  138. "11": "_This error was replaced with a dev-time warning, it will be deleted for v4 final._ [createGlobalStyle] received children which will not be rendered. Please use the component without passing children elements.\n\n",
  139. "12": "It seems you are interpolating a keyframe declaration (%s) into an untagged string. This was supported in styled-components v3, but is not longer supported in v4 as keyframes are now injected on-demand. Please wrap your string in the css\\`\\` helper which ensures the styles are injected correctly. See https://www.styled-components.com/docs/api#css\n\n",
  140. "13": "%s is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.\n\n",
  141. "14": "ThemeProvider: \"theme\" prop is required.\n\n",
  142. "15": "A stylis plugin has been supplied that is not named. We need a name for each plugin to be able to prevent styling collisions between different stylis configurations within the same app. Before you pass your plugin to `<StyleSheetManager stylisPlugins={[]}>`, please make sure each plugin is uniquely-named, e.g.\n\n```js\nObject.defineProperty(importedPlugin, 'name', { value: 'some-unique-name' });\n```\n\n",
  143. "16": "Reached the limit of how many styled components may be created at group %s.\nYou may only create up to 1,073,741,824 components. If you're creating components dynamically,\nas for instance in your render method then you may be running into this limitation.\n\n",
  144. "17": "CSSStyleSheet could not be found on HTMLStyleElement.\nHas styled-components' style tag been unmounted or altered by another script?\n"
  145. };
  146. //
  147. var ERRORS = process.env.NODE_ENV !== 'production' ? errorMap : {};
  148. /**
  149. * super basic version of sprintf
  150. */
  151. function format() {
  152. var a = arguments.length <= 0 ? undefined : arguments[0];
  153. var b = [];
  154. for (var c = 1, len = arguments.length; c < len; c += 1) {
  155. b.push(c < 0 || arguments.length <= c ? undefined : arguments[c]);
  156. }
  157. b.forEach(function (d) {
  158. a = a.replace(/%[a-z]/, d);
  159. });
  160. return a;
  161. }
  162. /**
  163. * Create an error file out of errors.md for development and a simple web link to the full errors
  164. * in production mode.
  165. */
  166. function throwStyledComponentsError(code) {
  167. for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  168. interpolations[_key - 1] = arguments[_key];
  169. }
  170. if (process.env.NODE_ENV === 'production') {
  171. throw new Error("An error occurred. See https://github.com/styled-components/styled-components/blob/master/packages/styled-components/src/utils/errors.md#" + code + " for more information." + (interpolations.length > 0 ? " Additional arguments: " + interpolations.join(', ') : ''));
  172. } else {
  173. throw new Error(format.apply(void 0, [ERRORS[code]].concat(interpolations)).trim());
  174. }
  175. }
  176. //
  177. var ELEMENT_TYPE = 1;
  178. /* Node.ELEMENT_TYPE */
  179. /** Find last style element if any inside target */
  180. var findLastStyleTag = function findLastStyleTag(target) {
  181. var childNodes = target.childNodes;
  182. for (var i = childNodes.length; i >= 0; i--) {
  183. var child = childNodes[i];
  184. if (child && child.nodeType === ELEMENT_TYPE && child.hasAttribute(SC_ATTR)) {
  185. return child;
  186. }
  187. }
  188. return undefined;
  189. };
  190. /** Create a style element inside `target` or <head> after the last */
  191. var makeStyleTag = function makeStyleTag(target) {
  192. var head = document.head;
  193. var parent = target || head;
  194. var style = document.createElement('style');
  195. var prevStyle = findLastStyleTag(parent);
  196. var nextSibling = prevStyle !== undefined ? prevStyle.nextSibling : null;
  197. style.setAttribute(SC_ATTR, SC_ATTR_ACTIVE);
  198. style.setAttribute(SC_ATTR_VERSION, SC_VERSION);
  199. var nonce = getNonce();
  200. if (nonce) style.setAttribute('nonce', nonce);
  201. parent.insertBefore(style, nextSibling);
  202. return style;
  203. };
  204. /** Get the CSSStyleSheet instance for a given style element */
  205. var getSheet = function getSheet(tag) {
  206. if (tag.sheet) {
  207. return tag.sheet;
  208. } // Avoid Firefox quirk where the style element might not have a sheet property
  209. var _document = document,
  210. styleSheets = _document.styleSheets;
  211. for (var i = 0, l = styleSheets.length; i < l; i++) {
  212. var sheet = styleSheets[i];
  213. if (sheet.ownerNode === tag) {
  214. return sheet;
  215. }
  216. }
  217. throwStyledComponentsError(17);
  218. return undefined;
  219. };
  220. //
  221. /** Create a CSSStyleSheet-like tag depending on the environment */
  222. var makeTag = function makeTag(_ref) {
  223. var isServer = _ref.isServer,
  224. useCSSOMInjection = _ref.useCSSOMInjection,
  225. target = _ref.target;
  226. if (isServer) {
  227. return new VirtualTag(target);
  228. } else if (useCSSOMInjection) {
  229. return new CSSOMTag(target);
  230. } else {
  231. return new TextTag(target);
  232. }
  233. };
  234. var CSSOMTag =
  235. /*#__PURE__*/
  236. function () {
  237. function CSSOMTag(target) {
  238. var element = this.element = makeStyleTag(target); // Avoid Edge bug where empty style elements don't create sheets
  239. element.appendChild(document.createTextNode(''));
  240. this.sheet = getSheet(element);
  241. this.length = 0;
  242. }
  243. var _proto = CSSOMTag.prototype;
  244. _proto.insertRule = function insertRule(index, rule) {
  245. try {
  246. this.sheet.insertRule(rule, index);
  247. this.length++;
  248. return true;
  249. } catch (_error) {
  250. return false;
  251. }
  252. };
  253. _proto.deleteRule = function deleteRule(index) {
  254. this.sheet.deleteRule(index);
  255. this.length--;
  256. };
  257. _proto.getRule = function getRule(index) {
  258. var rule = this.sheet.cssRules[index]; // Avoid IE11 quirk where cssText is inaccessible on some invalid rules
  259. if (rule !== undefined && typeof rule.cssText === 'string') {
  260. return rule.cssText;
  261. } else {
  262. return '';
  263. }
  264. };
  265. return CSSOMTag;
  266. }();
  267. /** A Tag that emulates the CSSStyleSheet API but uses text nodes */
  268. var TextTag =
  269. /*#__PURE__*/
  270. function () {
  271. function TextTag(target) {
  272. var element = this.element = makeStyleTag(target);
  273. this.nodes = element.childNodes;
  274. this.length = 0;
  275. }
  276. var _proto2 = TextTag.prototype;
  277. _proto2.insertRule = function insertRule(index, rule) {
  278. if (index <= this.length && index >= 0) {
  279. var node = document.createTextNode(rule);
  280. var refNode = this.nodes[index];
  281. this.element.insertBefore(node, refNode || null);
  282. this.length++;
  283. return true;
  284. } else {
  285. return false;
  286. }
  287. };
  288. _proto2.deleteRule = function deleteRule(index) {
  289. this.element.removeChild(this.nodes[index]);
  290. this.length--;
  291. };
  292. _proto2.getRule = function getRule(index) {
  293. if (index < this.length) {
  294. return this.nodes[index].textContent;
  295. } else {
  296. return '';
  297. }
  298. };
  299. return TextTag;
  300. }();
  301. /** A completely virtual (server-side) Tag that doesn't manipulate the DOM */
  302. var VirtualTag =
  303. /*#__PURE__*/
  304. function () {
  305. function VirtualTag(_target) {
  306. this.rules = [];
  307. this.length = 0;
  308. }
  309. var _proto3 = VirtualTag.prototype;
  310. _proto3.insertRule = function insertRule(index, rule) {
  311. if (index <= this.length) {
  312. this.rules.splice(index, 0, rule);
  313. this.length++;
  314. return true;
  315. } else {
  316. return false;
  317. }
  318. };
  319. _proto3.deleteRule = function deleteRule(index) {
  320. this.rules.splice(index, 1);
  321. this.length--;
  322. };
  323. _proto3.getRule = function getRule(index) {
  324. if (index < this.length) {
  325. return this.rules[index];
  326. } else {
  327. return '';
  328. }
  329. };
  330. return VirtualTag;
  331. }();
  332. //
  333. /** Create a GroupedTag with an underlying Tag implementation */
  334. var makeGroupedTag = function makeGroupedTag(tag) {
  335. return new DefaultGroupedTag(tag);
  336. };
  337. var BASE_SIZE = 1 << 9;
  338. var DefaultGroupedTag =
  339. /*#__PURE__*/
  340. function () {
  341. function DefaultGroupedTag(tag) {
  342. this.groupSizes = new Uint32Array(BASE_SIZE);
  343. this.length = BASE_SIZE;
  344. this.tag = tag;
  345. }
  346. var _proto = DefaultGroupedTag.prototype;
  347. _proto.indexOfGroup = function indexOfGroup(group) {
  348. var index = 0;
  349. for (var i = 0; i < group; i++) {
  350. index += this.groupSizes[i];
  351. }
  352. return index;
  353. };
  354. _proto.insertRules = function insertRules(group, rules) {
  355. if (group >= this.groupSizes.length) {
  356. var oldBuffer = this.groupSizes;
  357. var oldSize = oldBuffer.length;
  358. var newSize = oldSize;
  359. while (group >= newSize) {
  360. newSize <<= 1;
  361. if (newSize < 0) {
  362. throwStyledComponentsError(16, "" + group);
  363. }
  364. }
  365. this.groupSizes = new Uint32Array(newSize);
  366. this.groupSizes.set(oldBuffer);
  367. this.length = newSize;
  368. for (var i = oldSize; i < newSize; i++) {
  369. this.groupSizes[i] = 0;
  370. }
  371. }
  372. var ruleIndex = this.indexOfGroup(group + 1);
  373. for (var _i = 0, l = rules.length; _i < l; _i++) {
  374. if (this.tag.insertRule(ruleIndex, rules[_i])) {
  375. this.groupSizes[group]++;
  376. ruleIndex++;
  377. }
  378. }
  379. };
  380. _proto.clearGroup = function clearGroup(group) {
  381. if (group < this.length) {
  382. var length = this.groupSizes[group];
  383. var startIndex = this.indexOfGroup(group);
  384. var endIndex = startIndex + length;
  385. this.groupSizes[group] = 0;
  386. for (var i = startIndex; i < endIndex; i++) {
  387. this.tag.deleteRule(startIndex);
  388. }
  389. }
  390. };
  391. _proto.getGroup = function getGroup(group) {
  392. var css = '';
  393. if (group >= this.length || this.groupSizes[group] === 0) {
  394. return css;
  395. }
  396. var length = this.groupSizes[group];
  397. var startIndex = this.indexOfGroup(group);
  398. var endIndex = startIndex + length;
  399. for (var i = startIndex; i < endIndex; i++) {
  400. css += this.tag.getRule(i) + "\n";
  401. }
  402. return css;
  403. };
  404. return DefaultGroupedTag;
  405. }();
  406. //
  407. var MAX_SMI = 1 << 31 - 1;
  408. var groupIDRegister = new Map();
  409. var reverseRegister = new Map();
  410. var nextFreeGroup = 1;
  411. var getGroupForId = function getGroupForId(id) {
  412. if (groupIDRegister.has(id)) {
  413. return groupIDRegister.get(id);
  414. }
  415. var group = nextFreeGroup++;
  416. if (process.env.NODE_ENV !== 'production' && ((group | 0) < 0 || group > MAX_SMI)) {
  417. throwStyledComponentsError(16, "" + group);
  418. }
  419. groupIDRegister.set(id, group);
  420. reverseRegister.set(group, id);
  421. return group;
  422. };
  423. var getIdForGroup = function getIdForGroup(group) {
  424. return reverseRegister.get(group);
  425. };
  426. var setGroupForId = function setGroupForId(id, group) {
  427. if (group >= nextFreeGroup) {
  428. nextFreeGroup = group + 1;
  429. }
  430. groupIDRegister.set(id, group);
  431. reverseRegister.set(group, id);
  432. };
  433. //
  434. var SELECTOR = "style[" + SC_ATTR + "][" + SC_ATTR_VERSION + "=\"" + SC_VERSION + "\"]";
  435. var RULE_RE = /(?:\s*)?(.*?){((?:{[^}]*}|(?!{).*?)*)}/g;
  436. var MARKER_RE = new RegExp("^" + SC_ATTR + "\\.g(\\d+)\\[id=\"([\\w\\d-]+)\"\\]");
  437. var outputSheet = function outputSheet(sheet) {
  438. var tag = sheet.getTag();
  439. var length = tag.length;
  440. var css = '';
  441. for (var group = 0; group < length; group++) {
  442. var id = getIdForGroup(group);
  443. if (id === undefined) continue;
  444. var names = sheet.names.get(id);
  445. var rules = tag.getGroup(group);
  446. if (names === undefined || rules.length === 0) continue;
  447. var selector = SC_ATTR + ".g" + group + "[id=\"" + id + "\"]";
  448. var content = '';
  449. if (names !== undefined) {
  450. names.forEach(function (name) {
  451. if (name.length > 0) {
  452. content += name + ",";
  453. }
  454. });
  455. } // NOTE: It's easier to collect rules and have the marker
  456. // after the actual rules to simplify the rehydration
  457. css += "" + rules + selector + "{content:\"" + content + "\"}\n";
  458. }
  459. return css;
  460. };
  461. var rehydrateNamesFromContent = function rehydrateNamesFromContent(sheet, id, content) {
  462. var names = content.split(',');
  463. var name;
  464. for (var i = 0, l = names.length; i < l; i++) {
  465. // eslint-disable-next-line
  466. if (name = names[i]) {
  467. sheet.registerName(id, name);
  468. }
  469. }
  470. };
  471. var rehydrateSheetFromTag = function rehydrateSheetFromTag(sheet, style) {
  472. var rawHTML = style.innerHTML;
  473. var rules = [];
  474. var parts; // parts = [match, selector, content]
  475. // eslint-disable-next-line no-cond-assign
  476. while (parts = RULE_RE.exec(rawHTML)) {
  477. var marker = parts[1].match(MARKER_RE);
  478. if (marker) {
  479. var group = parseInt(marker[1], 10) | 0;
  480. var id = marker[2];
  481. if (group !== 0) {
  482. // Rehydrate componentId to group index mapping
  483. setGroupForId(id, group); // Rehydrate names and rules
  484. // looks like: data-styled.g11[id="idA"]{content:"nameA,"}
  485. rehydrateNamesFromContent(sheet, id, parts[2].split('"')[1]);
  486. sheet.getTag().insertRules(group, rules);
  487. }
  488. rules.length = 0;
  489. } else {
  490. rules.push(parts[0].trim());
  491. }
  492. }
  493. };
  494. var rehydrateSheet = function rehydrateSheet(sheet) {
  495. var nodes = document.querySelectorAll(SELECTOR);
  496. for (var i = 0, l = nodes.length; i < l; i++) {
  497. var node = nodes[i];
  498. if (node && node.getAttribute(SC_ATTR) !== SC_ATTR_ACTIVE) {
  499. rehydrateSheetFromTag(sheet, node);
  500. if (node.parentNode) {
  501. node.parentNode.removeChild(node);
  502. }
  503. }
  504. }
  505. };
  506. var SHOULD_REHYDRATE = IS_BROWSER;
  507. var defaultOptions = {
  508. isServer: !IS_BROWSER,
  509. useCSSOMInjection: !DISABLE_SPEEDY
  510. };
  511. /** Contains the main stylesheet logic for stringification and caching */
  512. var StyleSheet =
  513. /*#__PURE__*/
  514. function () {
  515. /** Register a group ID to give it an index */
  516. StyleSheet.registerId = function registerId(id) {
  517. return getGroupForId(id);
  518. };
  519. function StyleSheet(options, globalStyles, names) {
  520. if (options === void 0) {
  521. options = defaultOptions;
  522. }
  523. if (globalStyles === void 0) {
  524. globalStyles = {};
  525. }
  526. this.options = _extends({}, defaultOptions, {}, options);
  527. this.gs = globalStyles;
  528. this.names = new Map(names); // We rehydrate only once and use the sheet that is created first
  529. if (!this.options.isServer && IS_BROWSER && SHOULD_REHYDRATE) {
  530. SHOULD_REHYDRATE = false;
  531. rehydrateSheet(this);
  532. }
  533. }
  534. var _proto = StyleSheet.prototype;
  535. _proto.reconstructWithOptions = function reconstructWithOptions(options) {
  536. return new StyleSheet(_extends({}, this.options, {}, options), this.gs, this.names);
  537. };
  538. _proto.allocateGSInstance = function allocateGSInstance(id) {
  539. return this.gs[id] = (this.gs[id] || 0) + 1;
  540. }
  541. /** Lazily initialises a GroupedTag for when it's actually needed */
  542. ;
  543. _proto.getTag = function getTag() {
  544. return this.tag || (this.tag = makeGroupedTag(makeTag(this.options)));
  545. }
  546. /** Check whether a name is known for caching */
  547. ;
  548. _proto.hasNameForId = function hasNameForId(id, name) {
  549. return this.names.has(id) && this.names.get(id).has(name);
  550. }
  551. /** Mark a group's name as known for caching */
  552. ;
  553. _proto.registerName = function registerName(id, name) {
  554. getGroupForId(id);
  555. if (!this.names.has(id)) {
  556. var groupNames = new Set();
  557. groupNames.add(name);
  558. this.names.set(id, groupNames);
  559. } else {
  560. this.names.get(id).add(name);
  561. }
  562. }
  563. /** Insert new rules which also marks the name as known */
  564. ;
  565. _proto.insertRules = function insertRules(id, name, rules) {
  566. this.registerName(id, name);
  567. this.getTag().insertRules(getGroupForId(id), rules);
  568. }
  569. /** Clears all cached names for a given group ID */
  570. ;
  571. _proto.clearNames = function clearNames(id) {
  572. if (this.names.has(id)) {
  573. this.names.get(id).clear();
  574. }
  575. }
  576. /** Clears all rules for a given group ID */
  577. ;
  578. _proto.clearRules = function clearRules(id) {
  579. this.getTag().clearGroup(getGroupForId(id));
  580. this.clearNames(id);
  581. }
  582. /** Clears the entire tag which deletes all rules but not its names */
  583. ;
  584. _proto.clearTag = function clearTag() {
  585. // NOTE: This does not clear the names, since it's only used during SSR
  586. // so that we can continuously output only new rules
  587. this.tag = undefined;
  588. }
  589. /** Outputs the current sheet as a CSS string with markers for SSR */
  590. ;
  591. _proto.toString = function toString() {
  592. return outputSheet(this);
  593. };
  594. return StyleSheet;
  595. }();
  596. //
  597. var EMPTY_ARRAY = Object.freeze([]);
  598. var EMPTY_OBJECT = Object.freeze({});
  599. /**
  600. * MIT License
  601. *
  602. * Copyright (c) 2016 Sultan Tarimo
  603. *
  604. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  605. * this software and associated documentation files (the "Software"),
  606. * to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  607. * sell copies of the Software and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
  608. *
  609. * The above copyright notice and this permission notice shall be included in all
  610. * copies or substantial portions of the Software.
  611. *
  612. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  613. * OR IMPLIED INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  614. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  615. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
  616. * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
  617. * IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  618. */
  619. /* eslint-disable */
  620. function insertRulePlugin (insertRule) {
  621. var delimiter = '/*|*/';
  622. var needle = delimiter + "}";
  623. function toSheet(block) {
  624. if (block) {
  625. try {
  626. insertRule(block + "}");
  627. } catch (e) {}
  628. }
  629. }
  630. return function ruleSheet(context, content, selectors, parents, line, column, length, ns, depth, at) {
  631. switch (context) {
  632. // property
  633. case 1:
  634. // @import
  635. if (depth === 0 && content.charCodeAt(0) === 64) return insertRule(content + ";"), '';
  636. break;
  637. // selector
  638. case 2:
  639. if (ns === 0) return content + delimiter;
  640. break;
  641. // at-rule
  642. case 3:
  643. switch (ns) {
  644. // @font-face, @page
  645. case 102:
  646. case 112:
  647. return insertRule(selectors[0] + content), '';
  648. default:
  649. return content + (at === 0 ? delimiter : '');
  650. }
  651. case -2:
  652. content.split(needle).forEach(toSheet);
  653. }
  654. };
  655. }
  656. var COMMENT_REGEX = /^\s*\/\/.*$/gm;
  657. function createStylisInstance(_temp) {
  658. var _ref = _temp === void 0 ? EMPTY_OBJECT : _temp,
  659. _ref$options = _ref.options,
  660. options = _ref$options === void 0 ? EMPTY_OBJECT : _ref$options,
  661. _ref$plugins = _ref.plugins,
  662. plugins = _ref$plugins === void 0 ? EMPTY_ARRAY : _ref$plugins;
  663. var stylis = new Stylis(options); // Wrap `insertRulePlugin to build a list of rules,
  664. // and then make our own plugin to return the rules. This
  665. // makes it easier to hook into the existing SSR architecture
  666. var parsingRules = []; // eslint-disable-next-line consistent-return
  667. var returnRulesPlugin = function returnRulesPlugin(context) {
  668. if (context === -2) {
  669. var parsedRules = parsingRules;
  670. parsingRules = [];
  671. return parsedRules;
  672. }
  673. };
  674. var parseRulesPlugin = insertRulePlugin(function (rule) {
  675. parsingRules.push(rule);
  676. });
  677. var _componentId;
  678. var _selector;
  679. var _selectorRegexp;
  680. var selfReferenceReplacer = function selfReferenceReplacer(match, offset, string) {
  681. if ( // the first self-ref is always untouched
  682. offset > 0 && // there should be at least two self-refs to do a replacement (.b > .b)
  683. string.slice(0, offset).indexOf(_selector) !== -1 && // no consecutive self refs (.b.b); that is a precedence boost and treated differently
  684. string.slice(offset - _selector.length, offset) !== _selector) {
  685. return "." + _componentId;
  686. }
  687. return match;
  688. };
  689. /**
  690. * When writing a style like
  691. *
  692. * & + & {
  693. * color: red;
  694. * }
  695. *
  696. * The second ampersand should be a reference to the static component class. stylis
  697. * has no knowledge of static class so we have to intelligently replace the base selector.
  698. *
  699. * https://github.com/thysultan/stylis.js#plugins <- more info about the context phase values
  700. * "2" means this plugin is taking effect at the very end after all other processing is complete
  701. */
  702. var selfReferenceReplacementPlugin = function selfReferenceReplacementPlugin(context, _, selectors) {
  703. if (context === 2 && selectors.length && selectors[0].lastIndexOf(_selector) > 0) {
  704. // eslint-disable-next-line no-param-reassign
  705. selectors[0] = selectors[0].replace(_selectorRegexp, selfReferenceReplacer);
  706. }
  707. };
  708. stylis.use([].concat(plugins, [selfReferenceReplacementPlugin, parseRulesPlugin, returnRulesPlugin]));
  709. function stringifyRules(css, selector, prefix, componentId) {
  710. if (componentId === void 0) {
  711. componentId = '&';
  712. }
  713. var flatCSS = css.replace(COMMENT_REGEX, '');
  714. var cssStr = selector && prefix ? prefix + " " + selector + " { " + flatCSS + " }" : flatCSS; // stylis has no concept of state to be passed to plugins
  715. // but since JS is single=threaded, we can rely on that to ensure
  716. // these properties stay in sync with the current stylis run
  717. _componentId = componentId;
  718. _selector = selector;
  719. _selectorRegexp = new RegExp("\\" + _selector + "\\b", 'g');
  720. return stylis(prefix || !selector ? '' : selector, cssStr);
  721. }
  722. stringifyRules.hash = plugins.length ? plugins.reduce(function (acc, plugin) {
  723. if (!plugin.name) {
  724. throwStyledComponentsError(15);
  725. }
  726. return phash(acc, plugin.name);
  727. }, SEED).toString() : '';
  728. return stringifyRules;
  729. }
  730. //
  731. var StyleSheetContext = React.createContext();
  732. var StyleSheetConsumer = StyleSheetContext.Consumer;
  733. var StylisContext = React.createContext();
  734. var StylisConsumer = StylisContext.Consumer;
  735. var masterSheet = new StyleSheet();
  736. var masterStylis = createStylisInstance();
  737. //
  738. var Keyframes =
  739. /*#__PURE__*/
  740. function () {
  741. function Keyframes(name, stringifyArgs) {
  742. var _this = this;
  743. this.inject = function (styleSheet) {
  744. if (!styleSheet.hasNameForId(_this.id, _this.name)) {
  745. styleSheet.insertRules(_this.id, _this.name, masterStylis.apply(void 0, _this.stringifyArgs));
  746. }
  747. };
  748. this.toString = function () {
  749. return throwStyledComponentsError(12, String(_this.name));
  750. };
  751. this.name = name;
  752. this.id = "sc-keyframes-" + name;
  753. this.stringifyArgs = stringifyArgs;
  754. }
  755. var _proto = Keyframes.prototype;
  756. _proto.getName = function getName() {
  757. return this.name;
  758. };
  759. return Keyframes;
  760. }();
  761. //
  762. /**
  763. * inlined version of
  764. * https://github.com/facebook/fbjs/blob/master/packages/fbjs/src/core/hyphenateStyleName.js
  765. */
  766. var uppercasePattern = /([A-Z])/g;
  767. var msPattern = /^ms-/;
  768. /**
  769. * Hyphenates a camelcased CSS property name, for example:
  770. *
  771. * > hyphenateStyleName('backgroundColor')
  772. * < "background-color"
  773. * > hyphenateStyleName('MozTransition')
  774. * < "-moz-transition"
  775. * > hyphenateStyleName('msTransition')
  776. * < "-ms-transition"
  777. *
  778. * As Modernizr suggests (http://modernizr.com/docs/#prefixed), an `ms` prefix
  779. * is converted to `-ms-`.
  780. *
  781. * @param {string} string
  782. * @return {string}
  783. */
  784. function hyphenateStyleName(string) {
  785. return string.replace(uppercasePattern, '-$1').toLowerCase().replace(msPattern, '-ms-');
  786. }
  787. //
  788. function addUnitIfNeeded(name, value) {
  789. // https://github.com/amilajack/eslint-plugin-flowtype-errors/issues/133
  790. // $FlowFixMe
  791. if (value == null || typeof value === 'boolean' || value === '') {
  792. return '';
  793. }
  794. if (typeof value === 'number' && value !== 0 && !(name in unitless)) {
  795. return value + "px"; // Presumes implicit 'px' suffix for unitless numbers
  796. }
  797. return String(value).trim();
  798. }
  799. //
  800. /**
  801. * It's falsish not falsy because 0 is allowed.
  802. */
  803. var isFalsish = function isFalsish(chunk) {
  804. return chunk === undefined || chunk === null || chunk === false || chunk === '';
  805. };
  806. var objToCssArray = function objToCssArray(obj, prevKey) {
  807. var rules = [];
  808. var keys = Object.keys(obj);
  809. keys.forEach(function (key) {
  810. if (!isFalsish(obj[key])) {
  811. if (isPlainObject(obj[key])) {
  812. rules.push.apply(rules, objToCssArray(obj[key], key));
  813. return rules;
  814. } else if (isFunction(obj[key])) {
  815. rules.push(hyphenateStyleName(key) + ":", obj[key], ';');
  816. return rules;
  817. }
  818. rules.push(hyphenateStyleName(key) + ": " + addUnitIfNeeded(key, obj[key]) + ";");
  819. }
  820. return rules;
  821. });
  822. return prevKey ? [prevKey + " {"].concat(rules, ['}']) : rules;
  823. };
  824. function flatten(chunk, executionContext, styleSheet) {
  825. if (Array.isArray(chunk)) {
  826. var ruleSet = [];
  827. for (var i = 0, len = chunk.length, result; i < len; i += 1) {
  828. result = flatten(chunk[i], executionContext, styleSheet);
  829. if (result === '') continue;else if (Array.isArray(result)) ruleSet.push.apply(ruleSet, result);else ruleSet.push(result);
  830. }
  831. return ruleSet;
  832. }
  833. if (isFalsish(chunk)) {
  834. return '';
  835. }
  836. /* Handle other components */
  837. if (isStyledComponent(chunk)) {
  838. return "." + chunk.styledComponentId;
  839. }
  840. /* Either execute or defer the function */
  841. if (isFunction(chunk)) {
  842. if (isStatelessFunction(chunk) && executionContext) {
  843. var _result = chunk(executionContext);
  844. if (process.env.NODE_ENV !== 'production' && isElement(_result)) {
  845. // eslint-disable-next-line no-console
  846. console.warn(getComponentName(chunk) + " is not a styled component and cannot be referred to via component selector. See https://www.styled-components.com/docs/advanced#referring-to-other-components for more details.");
  847. }
  848. return flatten(_result, executionContext, styleSheet);
  849. } else return chunk;
  850. }
  851. if (chunk instanceof Keyframes) {
  852. if (styleSheet) {
  853. chunk.inject(styleSheet);
  854. return chunk.getName();
  855. } else return chunk;
  856. }
  857. /* Handle objects */
  858. return isPlainObject(chunk) ? objToCssArray(chunk) : chunk.toString();
  859. }
  860. //
  861. var printed = {};
  862. function warnOnce(message) {
  863. if (printed[message]) return;
  864. printed[message] = true;
  865. if (typeof console !== 'undefined' && console.warn) console.warn(message);
  866. }
  867. //
  868. var SINGLE_QUOTE = "'".charCodeAt(0);
  869. var DOUBLE_QUOTE = '"'.charCodeAt(0);
  870. var BACKSLASH = '\\'.charCodeAt(0);
  871. var SLASH = '/'.charCodeAt(0);
  872. var NEWLINE = '\n'.charCodeAt(0);
  873. var SPACE = ' '.charCodeAt(0);
  874. var FEED = '\f'.charCodeAt(0);
  875. var TAB = '\t'.charCodeAt(0);
  876. var CR = '\r'.charCodeAt(0);
  877. var OPEN_SQUARE = '['.charCodeAt(0);
  878. var CLOSE_SQUARE = ']'.charCodeAt(0);
  879. var OPEN_PARENTHESES = '('.charCodeAt(0);
  880. var CLOSE_PARENTHESES = ')'.charCodeAt(0);
  881. var OPEN_CURLY = '{'.charCodeAt(0);
  882. var CLOSE_CURLY = '}'.charCodeAt(0);
  883. var SEMICOLON = ';'.charCodeAt(0);
  884. var ASTERISK = '*'.charCodeAt(0);
  885. var COLON = ':'.charCodeAt(0);
  886. var AT = '@'.charCodeAt(0);
  887. var RE_AT_END = /[ \n\t\r\f\{\(\)'"\\;/\[\]#]/g;
  888. var RE_WORD_END = /[ \n\t\r\f\(\)\{\}:;@!'"\\\]\[#]|\/(?=\*)/g;
  889. var RE_BAD_BRACKET = /.[\\\/\("'\n]/;
  890. function tokenize(input, options) {
  891. if (options === void 0) {
  892. options = {};
  893. }
  894. var tokens = [];
  895. var css = input.css.valueOf();
  896. var ignore = options.ignoreErrors;
  897. var code, next, quote, lines, last, content, escape, nextLine, nextOffset, escaped, escapePos, prev, n;
  898. var length = css.length;
  899. var offset = -1;
  900. var line = 1;
  901. var pos = 0;
  902. function unclosed(what) {
  903. throw input.error("Unclosed " + what, line, pos - offset);
  904. }
  905. while (pos < length) {
  906. code = css.charCodeAt(pos);
  907. if (code === NEWLINE || code === FEED || code === CR && css.charCodeAt(pos + 1) !== NEWLINE) {
  908. offset = pos;
  909. line += 1;
  910. }
  911. switch (code) {
  912. case NEWLINE:
  913. case SPACE:
  914. case TAB:
  915. case CR:
  916. case FEED:
  917. next = pos;
  918. do {
  919. next += 1;
  920. code = css.charCodeAt(next);
  921. if (code === NEWLINE) {
  922. offset = next;
  923. line += 1;
  924. }
  925. } while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
  926. tokens.push(['space', css.slice(pos, next)]);
  927. pos = next - 1;
  928. break;
  929. case OPEN_SQUARE:
  930. tokens.push(['[', '[', line, pos - offset]);
  931. break;
  932. case CLOSE_SQUARE:
  933. tokens.push([']', ']', line, pos - offset]);
  934. break;
  935. case OPEN_CURLY:
  936. tokens.push(['{', '{', line, pos - offset]);
  937. break;
  938. case CLOSE_CURLY:
  939. tokens.push(['}', '}', line, pos - offset]);
  940. break;
  941. case COLON:
  942. tokens.push([':', ':', line, pos - offset]);
  943. break;
  944. case SEMICOLON:
  945. tokens.push([';', ';', line, pos - offset]);
  946. break;
  947. case OPEN_PARENTHESES:
  948. prev = tokens.length ? tokens[tokens.length - 1][1] : '';
  949. n = css.charCodeAt(pos + 1);
  950. if (prev === 'url' && n !== SINGLE_QUOTE && n !== DOUBLE_QUOTE && n !== SPACE && n !== NEWLINE && n !== TAB && n !== FEED && n !== CR) {
  951. next = pos;
  952. do {
  953. escaped = false;
  954. next = css.indexOf(')', next + 1);
  955. if (next === -1) {
  956. if (ignore) {
  957. next = pos;
  958. break;
  959. } else {
  960. unclosed('bracket');
  961. }
  962. }
  963. escapePos = next;
  964. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  965. escapePos -= 1;
  966. escaped = !escaped;
  967. }
  968. } while (escaped);
  969. tokens.push(['brackets', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
  970. pos = next;
  971. } else {
  972. next = css.indexOf(')', pos + 1);
  973. content = css.slice(pos, next + 1);
  974. if (next === -1 || RE_BAD_BRACKET.test(content)) {
  975. tokens.push(['(', '(', line, pos - offset]);
  976. } else {
  977. tokens.push(['brackets', content, line, pos - offset, line, next - offset]);
  978. pos = next;
  979. }
  980. }
  981. break;
  982. case CLOSE_PARENTHESES:
  983. tokens.push([')', ')', line, pos - offset]);
  984. break;
  985. case SINGLE_QUOTE:
  986. case DOUBLE_QUOTE:
  987. quote = code === SINGLE_QUOTE ? "'" : '"';
  988. next = pos;
  989. do {
  990. escaped = false;
  991. next = css.indexOf(quote, next + 1);
  992. if (next === -1) {
  993. if (ignore) {
  994. next = pos + 1;
  995. break;
  996. } else {
  997. unclosed('quote');
  998. }
  999. }
  1000. escapePos = next;
  1001. while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
  1002. escapePos -= 1;
  1003. escaped = !escaped;
  1004. }
  1005. } while (escaped);
  1006. content = css.slice(pos, next + 1);
  1007. lines = content.split('\n');
  1008. last = lines.length - 1;
  1009. if (last > 0) {
  1010. nextLine = line + last;
  1011. nextOffset = next - lines[last].length;
  1012. } else {
  1013. nextLine = line;
  1014. nextOffset = offset;
  1015. }
  1016. tokens.push(['string', css.slice(pos, next + 1), line, pos - offset, nextLine, next - nextOffset]);
  1017. offset = nextOffset;
  1018. line = nextLine;
  1019. pos = next;
  1020. break;
  1021. case AT:
  1022. RE_AT_END.lastIndex = pos + 1;
  1023. RE_AT_END.test(css);
  1024. if (RE_AT_END.lastIndex === 0) {
  1025. next = css.length - 1;
  1026. } else {
  1027. next = RE_AT_END.lastIndex - 2;
  1028. }
  1029. tokens.push(['at-word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
  1030. pos = next;
  1031. break;
  1032. case BACKSLASH:
  1033. next = pos;
  1034. escape = true;
  1035. while (css.charCodeAt(next + 1) === BACKSLASH) {
  1036. next += 1;
  1037. escape = !escape;
  1038. }
  1039. code = css.charCodeAt(next + 1);
  1040. if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
  1041. next += 1;
  1042. }
  1043. tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
  1044. pos = next;
  1045. break;
  1046. default:
  1047. if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
  1048. next = css.indexOf('*/', pos + 2) + 1;
  1049. if (next === 0) {
  1050. if (ignore) {
  1051. next = css.length;
  1052. } else {
  1053. unclosed('comment');
  1054. }
  1055. }
  1056. content = css.slice(pos, next + 1);
  1057. lines = content.split('\n');
  1058. last = lines.length - 1;
  1059. if (last > 0) {
  1060. nextLine = line + last;
  1061. nextOffset = next - lines[last].length;
  1062. } else {
  1063. nextLine = line;
  1064. nextOffset = offset;
  1065. }
  1066. tokens.push(['comment', content, line, pos - offset, nextLine, next - nextOffset]);
  1067. offset = nextOffset;
  1068. line = nextLine;
  1069. pos = next;
  1070. } else {
  1071. RE_WORD_END.lastIndex = pos + 1;
  1072. RE_WORD_END.test(css);
  1073. if (RE_WORD_END.lastIndex === 0) {
  1074. next = css.length - 1;
  1075. } else {
  1076. next = RE_WORD_END.lastIndex - 2;
  1077. }
  1078. tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
  1079. pos = next;
  1080. }
  1081. break;
  1082. }
  1083. pos++;
  1084. }
  1085. return tokens;
  1086. }
  1087. //
  1088. var HIGHLIGHT_THEME = {
  1089. brackets: [36, 39],
  1090. // cyan
  1091. string: [31, 39],
  1092. // red
  1093. 'at-word': [31, 39],
  1094. // red
  1095. comment: [90, 39],
  1096. // gray
  1097. '{': [32, 39],
  1098. // green
  1099. '}': [32, 39],
  1100. // green
  1101. ':': [1, 22],
  1102. // bold
  1103. ';': [1, 22],
  1104. // bold
  1105. '(': [1, 22],
  1106. // bold
  1107. ')': [1, 22] // bold
  1108. };
  1109. function code(color) {
  1110. return "\x1B[" + color + "m";
  1111. }
  1112. function terminalHighlight(css) {
  1113. var tokens = tokenize(new Input(css), {
  1114. ignoreErrors: true
  1115. });
  1116. var result = [];
  1117. tokens.forEach(function (token) {
  1118. var color = HIGHLIGHT_THEME[token[0]];
  1119. if (color) {
  1120. result.push(token[1].split(/\r?\n/).map(function (i) {
  1121. return code(color[0]) + i + code(color[1]);
  1122. }).join('\n'));
  1123. } else {
  1124. result.push(token[1]);
  1125. }
  1126. });
  1127. return result.join('');
  1128. }
  1129. /**
  1130. * The CSS parser throws this error for broken CSS.
  1131. *
  1132. * Custom parsers can throw this error for broken custom syntax using
  1133. * the {@link Node#error} method.
  1134. *
  1135. * PostCSS will use the input source map to detect the original error location.
  1136. * If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
  1137. * PostCSS will show the original position in the Sass file.
  1138. *
  1139. * If you need the position in the PostCSS input
  1140. * (e.g., to debug the previous compiler), use `error.input.file`.
  1141. *
  1142. * @example
  1143. * // Catching and checking syntax error
  1144. * try {
  1145. * postcss.parse('a{')
  1146. * } catch (error) {
  1147. * if ( error.name === 'CssSyntaxError' ) {
  1148. * error //=> CssSyntaxError
  1149. * }
  1150. * }
  1151. *
  1152. * @example
  1153. * // Raising error from plugin
  1154. * throw node.error('Unknown variable', { plugin: 'postcss-vars' });
  1155. */
  1156. var CssSyntaxError =
  1157. /*#__PURE__*/
  1158. function () {
  1159. /**
  1160. * @param {string} message - error message
  1161. * @param {number} [line] - source line of the error
  1162. * @param {number} [column] - source column of the error
  1163. * @param {string} [source] - source code of the broken file
  1164. * @param {string} [file] - absolute path to the broken file
  1165. * @param {string} [plugin] - PostCSS plugin name, if error came from plugin
  1166. */
  1167. function CssSyntaxError(message, line, column, source, file, plugin) {
  1168. /**
  1169. * @member {string} - Always equal to `'CssSyntaxError'`. You should
  1170. * always check error type
  1171. * by `error.name === 'CssSyntaxError'` instead of
  1172. * `error instanceof CssSyntaxError`, because
  1173. * npm could have several PostCSS versions.
  1174. *
  1175. * @example
  1176. * if ( error.name === 'CssSyntaxError' ) {
  1177. * error //=> CssSyntaxError
  1178. * }
  1179. */
  1180. this.name = 'CssSyntaxError';
  1181. /**
  1182. * @member {string} - Error message.
  1183. *
  1184. * @example
  1185. * error.message //=> 'Unclosed block'
  1186. */
  1187. this.reason = message;
  1188. if (file) {
  1189. /**
  1190. * @member {string} - Absolute path to the broken file.
  1191. *
  1192. * @example
  1193. * error.file //=> 'a.sass'
  1194. * error.input.file //=> 'a.css'
  1195. */
  1196. this.file = file;
  1197. }
  1198. if (source) {
  1199. /**
  1200. * @member {string} - Source code of the broken file.
  1201. *
  1202. * @example
  1203. * error.source //=> 'a { b {} }'
  1204. * error.input.column //=> 'a b { }'
  1205. */
  1206. this.source = source;
  1207. }
  1208. if (plugin) {
  1209. /**
  1210. * @member {string} - Plugin name, if error came from plugin.
  1211. *
  1212. * @example
  1213. * error.plugin //=> 'postcss-vars'
  1214. */
  1215. this.plugin = plugin;
  1216. }
  1217. if (typeof line !== 'undefined' && typeof column !== 'undefined') {
  1218. /**
  1219. * @member {number} - Source line of the error.
  1220. *
  1221. * @example
  1222. * error.line //=> 2
  1223. * error.input.line //=> 4
  1224. */
  1225. this.line = line;
  1226. /**
  1227. * @member {number} - Source column of the error.
  1228. *
  1229. * @example
  1230. * error.column //=> 1
  1231. * error.input.column //=> 4
  1232. */
  1233. this.column = column;
  1234. }
  1235. this.setMessage();
  1236. if (Error.captureStackTrace) {
  1237. Error.captureStackTrace(this, CssSyntaxError);
  1238. }
  1239. }
  1240. var _proto = CssSyntaxError.prototype;
  1241. _proto.setMessage = function setMessage() {
  1242. /**
  1243. * @member {string} - Full error text in the GNU error format
  1244. * with plugin, file, line and column.
  1245. *
  1246. * @example
  1247. * error.message //=> 'a.css:1:1: Unclosed block'
  1248. */
  1249. this.message = this.plugin ? this.plugin + ": " : '';
  1250. this.message += this.file ? this.file : '<css input>';
  1251. if (typeof this.line !== 'undefined') {
  1252. this.message += ":" + this.line + ":" + this.column;
  1253. }
  1254. this.message += ": " + this.reason;
  1255. }
  1256. /**
  1257. * Returns a few lines of CSS source that caused the error.
  1258. *
  1259. * If the CSS has an input source map without `sourceContent`,
  1260. * this method will return an empty string.
  1261. *
  1262. * @param {boolean} [color] whether arrow will be colored red by terminal
  1263. * color codes. By default, PostCSS will detect
  1264. * color support by `process.stdout.isTTY`
  1265. * and `process.env.NODE_DISABLE_COLORS`.
  1266. *
  1267. * @example
  1268. * error.showSourceCode() //=> " 4 | }
  1269. * // 5 | a {
  1270. * // > 6 | bad
  1271. * // | ^
  1272. * // 7 | }
  1273. * // 8 | b {"
  1274. *
  1275. * @return {string} few lines of CSS source that caused the error
  1276. */
  1277. ;
  1278. _proto.showSourceCode = function showSourceCode(color) {
  1279. var _this = this;
  1280. if (!this.source) return '';
  1281. var css = this.source;
  1282. if (typeof color === 'undefined') color = supportsColor;
  1283. if (color) css = terminalHighlight(css);
  1284. var lines = css.split(/\r?\n/);
  1285. var start = Math.max(this.line - 3, 0);
  1286. var end = Math.min(this.line + 2, lines.length);
  1287. var maxWidth = String(end).length;
  1288. return lines.slice(start, end).map(function (line, index) {
  1289. var number = start + 1 + index;
  1290. var padded = (" " + number).slice(-maxWidth);
  1291. var gutter = " " + padded + " | ";
  1292. if (number === _this.line) {
  1293. var spacing = gutter.replace(/\d/g, ' ') + line.slice(0, _this.column - 1).replace(/[^\t]/g, ' ');
  1294. return ">" + gutter + line + "\n " + spacing + "^";
  1295. } else {
  1296. return " " + gutter + line;
  1297. }
  1298. }).join('\n');
  1299. }
  1300. /**
  1301. * Returns error position, message and source code of the broken part.
  1302. *
  1303. * @example
  1304. * error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
  1305. * // > 1 | a {
  1306. * // | ^"
  1307. *
  1308. * @return {string} error position, message and source code
  1309. */
  1310. ;
  1311. _proto.toString = function toString() {
  1312. var code = this.showSourceCode();
  1313. if (code) {
  1314. code = "\n\n" + code + "\n";
  1315. }
  1316. return this.name + ": " + this.message + code;
  1317. };
  1318. _createClass(CssSyntaxError, [{
  1319. key: "generated",
  1320. get: function get() {
  1321. warnOnce('CssSyntaxError#generated is deprecated. Use input instead.');
  1322. return this.input;
  1323. }
  1324. /**
  1325. * @memberof CssSyntaxError#
  1326. * @member {Input} input - Input object with PostCSS internal information
  1327. * about input file. If input has source map
  1328. * from previous tool, PostCSS will use origin
  1329. * (for example, Sass) source. You can use this
  1330. * object to get PostCSS input source.
  1331. *
  1332. * @example
  1333. * error.input.file //=> 'a.css'
  1334. * error.file //=> 'a.sass'
  1335. */
  1336. }]);
  1337. return CssSyntaxError;
  1338. }();
  1339. //
  1340. /* eslint-disable valid-jsdoc */
  1341. var defaultRaw = {
  1342. colon: ': ',
  1343. indent: ' ',
  1344. beforeDecl: '\n',
  1345. beforeRule: '\n',
  1346. beforeOpen: ' ',
  1347. beforeClose: '\n',
  1348. beforeComment: '\n',
  1349. after: '\n',
  1350. emptyBody: '',
  1351. commentLeft: ' ',
  1352. commentRight: ' '
  1353. };
  1354. function capitalize(str) {
  1355. return str[0].toUpperCase() + str.slice(1);
  1356. }
  1357. var Stringifier =
  1358. /*#__PURE__*/
  1359. function () {
  1360. function Stringifier(builder) {
  1361. this.builder = builder;
  1362. }
  1363. var _proto = Stringifier.prototype;
  1364. _proto.stringify = function stringify(node, semicolon) {
  1365. this[node.type](node, semicolon);
  1366. };
  1367. _proto.root = function root(node) {
  1368. this.body(node);
  1369. if (node.raws.after) this.builder(node.raws.after);
  1370. };
  1371. _proto.comment = function comment(node) {
  1372. var left = this.raw(node, 'left', 'commentLeft');
  1373. var right = this.raw(node, 'right', 'commentRight');
  1374. this.builder("/*" + left + node.text + right + "*/", node);
  1375. };
  1376. _proto.decl = function decl(node, semicolon) {
  1377. var between = this.raw(node, 'between', 'colon');
  1378. var string = node.prop + between + this.rawValue(node, 'value');
  1379. if (node.important) {
  1380. string += node.raws.important || ' !important';
  1381. }
  1382. if (semicolon) string += ';';
  1383. this.builder(string, node);
  1384. };
  1385. _proto.rule = function rule(node) {
  1386. this.block(node, this.rawValue(node, 'selector'));
  1387. };
  1388. _proto.atrule = function atrule(node, semicolon) {
  1389. var name = "@" + node.name;
  1390. var params = node.params ? this.rawValue(node, 'params') : '';
  1391. if (typeof node.raws.afterName !== 'undefined') {
  1392. name += node.raws.afterName;
  1393. } else if (params) {
  1394. name += ' ';
  1395. }
  1396. if (node.nodes) {
  1397. this.block(node, name + params);
  1398. } else {
  1399. var end = (node.raws.between || '') + (semicolon ? ';' : '');
  1400. this.builder(name + params + end, node);
  1401. }
  1402. };
  1403. _proto.body = function body(node) {
  1404. var last = node.nodes.length - 1;
  1405. while (last > 0) {
  1406. if (node.nodes[last].type !== 'comment') break;
  1407. last -= 1;
  1408. }
  1409. var semicolon = this.raw(node, 'semicolon');
  1410. for (var i = 0; i < node.nodes.length; i++) {
  1411. var child = node.nodes[i];
  1412. var before = this.raw(child, 'before');
  1413. if (before) this.builder(before);
  1414. this.stringify(child, last !== i || semicolon);
  1415. }
  1416. };
  1417. _proto.block = function block(node, start) {
  1418. var between = this.raw(node, 'between', 'beforeOpen');
  1419. this.builder(start + between + "{", node, 'start');
  1420. var after;
  1421. if (node.nodes && node.nodes.length) {
  1422. this.body(node);
  1423. after = this.raw(node, 'after');
  1424. } else {
  1425. after = this.raw(node, 'after', 'emptyBody');
  1426. }
  1427. if (after) this.builder(after);
  1428. this.builder('}', node, 'end');
  1429. };
  1430. _proto.raw = function raw(node, own, detect) {
  1431. var value;
  1432. if (!detect) detect = own; // Already had
  1433. if (own) {
  1434. value = node.raws[own];
  1435. if (typeof value !== 'undefined') return value;
  1436. }
  1437. var parent = node.parent; // Hack for first rule in CSS
  1438. if (detect === 'before') {
  1439. if (!parent || parent.type === 'root' && parent.first === node) {
  1440. return '';
  1441. }
  1442. } // Floating child without parent
  1443. if (!parent) return defaultRaw[detect]; // Detect style by other nodes
  1444. var root = node.root();
  1445. if (!root.rawCache) root.rawCache = {};
  1446. if (typeof root.rawCache[detect] !== 'undefined') {
  1447. return root.rawCache[detect];
  1448. }
  1449. if (detect === 'before' || detect === 'after') {
  1450. return this.beforeAfter(node, detect);
  1451. } else {
  1452. var method = "raw" + capitalize(detect);
  1453. if (this[method]) {
  1454. value = this[method](root, node);
  1455. } else {
  1456. root.walk(function (i) {
  1457. value = i.raws[own];
  1458. if (typeof value !== 'undefined') return false;
  1459. });
  1460. }
  1461. }
  1462. if (typeof value === 'undefined') value = defaultRaw[detect];
  1463. root.rawCache[detect] = value;
  1464. return value;
  1465. };
  1466. _proto.rawSemicolon = function rawSemicolon(root) {
  1467. var value;
  1468. root.walk(function (i) {
  1469. if (i.nodes && i.nodes.length && i.last.type === 'decl') {
  1470. value = i.raws.semicolon;
  1471. if (typeof value !== 'undefined') return false;
  1472. }
  1473. });
  1474. return value;
  1475. };
  1476. _proto.rawEmptyBody = function rawEmptyBody(root) {
  1477. var value;
  1478. root.walk(function (i) {
  1479. if (i.nodes && i.nodes.length === 0) {
  1480. value = i.raws.after;
  1481. if (typeof value !== 'undefined') return false;
  1482. }
  1483. });
  1484. return value;
  1485. };
  1486. _proto.rawIndent = function rawIndent(root) {
  1487. if (root.raws.indent) return root.raws.indent;
  1488. var value;
  1489. root.walk(function (i) {
  1490. var p = i.parent;
  1491. if (p && p !== root && p.parent && p.parent === root) {
  1492. if (typeof i.raws.before !== 'undefined') {
  1493. var parts = i.raws.before.split('\n');
  1494. value = parts[parts.length - 1];
  1495. value = value.replace(/[^\s]/g, '');
  1496. return false;
  1497. }
  1498. }
  1499. });
  1500. return value;
  1501. };
  1502. _proto.rawBeforeComment = function rawBeforeComment(root, node) {
  1503. var value;
  1504. root.walkComments(function (i) {
  1505. if (typeof i.raws.before !== 'undefined') {
  1506. value = i.raws.before;
  1507. if (value.indexOf('\n') !== -1) {
  1508. value = value.replace(/[^\n]+$/, '');
  1509. }
  1510. return false;
  1511. }
  1512. });
  1513. if (typeof value === 'undefined') {
  1514. value = this.raw(node, null, 'beforeDecl');
  1515. }
  1516. return value;
  1517. };
  1518. _proto.rawBeforeDecl = function rawBeforeDecl(root, node) {
  1519. var value;
  1520. root.walkDecls(function (i) {
  1521. if (typeof i.raws.before !== 'undefined') {
  1522. value = i.raws.before;
  1523. if (value.indexOf('\n') !== -1) {
  1524. value = value.replace(/[^\n]+$/, '');
  1525. }
  1526. return false;
  1527. }
  1528. });
  1529. if (typeof value === 'undefined') {
  1530. value = this.raw(node, null, 'beforeRule');
  1531. }
  1532. return value;
  1533. };
  1534. _proto.rawBeforeRule = function rawBeforeRule(root) {
  1535. var value;
  1536. root.walk(function (i) {
  1537. if (i.nodes && (i.parent !== root || root.first !== i)) {
  1538. if (typeof i.raws.before !== 'undefined') {
  1539. value = i.raws.before;
  1540. if (value.indexOf('\n') !== -1) {
  1541. value = value.replace(/[^\n]+$/, '');
  1542. }
  1543. return false;
  1544. }
  1545. }
  1546. });
  1547. return value;
  1548. };
  1549. _proto.rawBeforeClose = function rawBeforeClose(root) {
  1550. var value;
  1551. root.walk(function (i) {
  1552. if (i.nodes && i.nodes.length > 0) {
  1553. if (typeof i.raws.after !== 'undefined') {
  1554. value = i.raws.after;
  1555. if (value.indexOf('\n') !== -1) {
  1556. value = value.replace(/[^\n]+$/, '');
  1557. }
  1558. return false;
  1559. }
  1560. }
  1561. });
  1562. return value;
  1563. };
  1564. _proto.rawBeforeOpen = function rawBeforeOpen(root) {
  1565. var value;
  1566. root.walk(function (i) {
  1567. if (i.type !== 'decl') {
  1568. value = i.raws.between;
  1569. if (typeof value !== 'undefined') return false;
  1570. }
  1571. });
  1572. return value;
  1573. };
  1574. _proto.rawColon = function rawColon(root) {
  1575. var value;
  1576. root.walkDecls(function (i) {
  1577. if (typeof i.raws.between !== 'undefined') {
  1578. value = i.raws.between.replace(/[^\s:]/g, '');
  1579. return false;
  1580. }
  1581. });
  1582. return value;
  1583. };
  1584. _proto.beforeAfter = function beforeAfter(node, detect) {
  1585. var value;
  1586. if (node.type === 'decl') {
  1587. value = this.raw(node, null, 'beforeDecl');
  1588. } else if (node.type === 'comment') {
  1589. value = this.raw(node, null, 'beforeComment');
  1590. } else if (detect === 'before') {
  1591. value = this.raw(node, null, 'beforeRule');
  1592. } else {
  1593. value = this.raw(node, null, 'beforeClose');
  1594. }
  1595. var buf = node.parent;
  1596. var depth = 0;
  1597. while (buf && buf.type !== 'root') {
  1598. depth += 1;
  1599. buf = buf.parent;
  1600. }
  1601. if (value.indexOf('\n') !== -1) {
  1602. var indent = this.raw(node, null, 'indent');
  1603. if (indent.length) {
  1604. for (var step = 0; step < depth; step++) {
  1605. value += indent;
  1606. }
  1607. }
  1608. }
  1609. return value;
  1610. };
  1611. _proto.rawValue = function rawValue(node, prop) {
  1612. var value = node[prop];
  1613. var raw = node.raws[prop];
  1614. if (raw && raw.value === value) {
  1615. return raw.raw;
  1616. } else {
  1617. return value;
  1618. }
  1619. };
  1620. return Stringifier;
  1621. }();
  1622. //
  1623. function stringify(node, builder) {
  1624. var str = new Stringifier(builder);
  1625. str.stringify(node);
  1626. }
  1627. /**
  1628. * @typedef {object} position
  1629. * @property {number} line - source line in file
  1630. * @property {number} column - source column in file
  1631. */
  1632. /**
  1633. * @typedef {object} source
  1634. * @property {Input} input - {@link Input} with input file
  1635. * @property {position} start - The starting position of the node’s source
  1636. * @property {position} end - The ending position of the node’s source
  1637. */
  1638. var cloneNode = function cloneNode(obj, parent) {
  1639. var cloned = new obj.constructor();
  1640. for (var i in obj) {
  1641. if (!obj.hasOwnProperty(i)) continue;
  1642. var value = obj[i];
  1643. var type = typeof value;
  1644. if (i === 'parent' && type === 'object') {
  1645. if (parent) cloned[i] = parent;
  1646. } else if (i === 'source') {
  1647. cloned[i] = value;
  1648. } else if (value instanceof Array) {
  1649. cloned[i] = value.map(function (j) {
  1650. return cloneNode(j, cloned);
  1651. });
  1652. } else if (i !== 'before' && i !== 'after' && i !== 'between' && i !== 'semicolon') {
  1653. if (type === 'object' && value !== null) value = cloneNode(value);
  1654. cloned[i] = value;
  1655. }
  1656. }
  1657. return cloned;
  1658. };
  1659. /**
  1660. * All node classes inherit the following common methods.
  1661. *
  1662. * @abstract
  1663. */
  1664. var Node =
  1665. /*#__PURE__*/
  1666. function () {
  1667. /**
  1668. * @param {object} [defaults] - value for node properties
  1669. */
  1670. function Node(defaults) {
  1671. if (defaults === void 0) {
  1672. defaults = {};
  1673. }
  1674. this.raws = {};
  1675. for (var name in defaults) {
  1676. this[name] = defaults[name];
  1677. }
  1678. }
  1679. /**
  1680. * Returns a CssSyntaxError instance containing the original position
  1681. * of the node in the source, showing line and column numbers and also
  1682. * a small excerpt to facilitate debugging.
  1683. *
  1684. * If present, an input source map will be used to get the original position
  1685. * of the source, even from a previous compilation step
  1686. * (e.g., from Sass compilation).
  1687. *
  1688. * This method produces very useful error messages.
  1689. *
  1690. * @param {string} message - error description
  1691. * @param {object} [opts] - options
  1692. * @param {string} opts.plugin - plugin name that created this error.
  1693. * PostCSS will set it automatically.
  1694. * @param {string} opts.word - a word inside a node’s string that should
  1695. * be highlighted as the source of the error
  1696. * @param {number} opts.index - an index inside a node’s string that should
  1697. * be highlighted as the source of the error
  1698. *
  1699. * @return {CssSyntaxError} error object to throw it
  1700. *
  1701. * @example
  1702. * if ( !variables[name] ) {
  1703. * throw decl.error('Unknown variable ' + name, { word: name });
  1704. * // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
  1705. * // color: $black
  1706. * // a
  1707. * // ^
  1708. * // background: white
  1709. * }
  1710. */
  1711. var _proto = Node.prototype;
  1712. _proto.error = function error(message, opts) {
  1713. if (opts === void 0) {
  1714. opts = {};
  1715. }
  1716. if (this.source) {
  1717. var pos = this.positionBy(opts);
  1718. return this.source.input.error(message, pos.line, pos.column, opts);
  1719. } else {
  1720. return new CssSyntaxError(message);
  1721. }
  1722. }
  1723. /**
  1724. * This method is provided as a convenience wrapper for {@link Result#warn}.
  1725. *
  1726. * @param {Result} result - the {@link Result} instance
  1727. * that will receive the warning
  1728. * @param {string} text - warning message
  1729. * @param {object} [opts] - options
  1730. * @param {string} opts.plugin - plugin name that created this warning.
  1731. * PostCSS will set it automatically.
  1732. * @param {string} opts.word - a word inside a node’s string that should
  1733. * be highlighted as the source of the warning
  1734. * @param {number} opts.index - an index inside a node’s string that should
  1735. * be highlighted as the source of the warning
  1736. *
  1737. * @return {Warning} created warning object
  1738. *
  1739. * @example
  1740. * const plugin = postcss.plugin('postcss-deprecated', () => {
  1741. * return (root, result) => {
  1742. * root.walkDecls('bad', decl => {
  1743. * decl.warn(result, 'Deprecated property bad');
  1744. * });
  1745. * };
  1746. * });
  1747. */
  1748. ;
  1749. _proto.warn = function warn(result, text, opts) {
  1750. var data = {
  1751. node: this
  1752. };
  1753. for (var i in opts) {
  1754. data[i] = opts[i];
  1755. }
  1756. return result.warn(text, data);
  1757. }
  1758. /**
  1759. * Removes the node from its parent and cleans the parent properties
  1760. * from the node and its children.
  1761. *
  1762. * @example
  1763. * if ( decl.prop.match(/^-webkit-/) ) {
  1764. * decl.remove();
  1765. * }
  1766. *
  1767. * @return {Node} node to make calls chain
  1768. */
  1769. ;
  1770. _proto.remove = function remove() {
  1771. if (this.parent) {
  1772. this.parent.removeChild(this);
  1773. }
  1774. this.parent = undefined;
  1775. return this;
  1776. }
  1777. /**
  1778. * Returns a CSS string representing the node.
  1779. *
  1780. * @param {stringifier|syntax} [stringifier] - a syntax to use
  1781. * in string generation
  1782. *
  1783. * @return {string} CSS string of this node
  1784. *
  1785. * @example
  1786. * postcss.rule({ selector: 'a' }).toString() //=> "a {}"
  1787. */
  1788. ;
  1789. _proto.toString = function toString(stringifier) {
  1790. if (stringifier === void 0) {
  1791. stringifier = stringify;
  1792. }
  1793. if (stringifier.stringify) stringifier = stringifier.stringify;
  1794. var result = '';
  1795. stringifier(this, function (i) {
  1796. result += i;
  1797. });
  1798. return result;
  1799. }
  1800. /**
  1801. * Returns a clone of the node.
  1802. *
  1803. * The resulting cloned node and its (cloned) children will have
  1804. * a clean parent and code style properties.
  1805. *
  1806. * @param {object} [overrides] - new properties to override in the clone.
  1807. *
  1808. * @example
  1809. * const cloned = decl.clone({ prop: '-moz-' + decl.prop });
  1810. * cloned.raws.before //=> undefined
  1811. * cloned.parent //=> undefined
  1812. * cloned.toString() //=> -moz-transform: scale(0)
  1813. *
  1814. * @return {Node} clone of the node
  1815. */
  1816. ;
  1817. _proto.clone = function clone(overrides) {
  1818. if (overrides === void 0) {
  1819. overrides = {};
  1820. }
  1821. var cloned = cloneNode(this);
  1822. for (var name in overrides) {
  1823. cloned[name] = overrides[name];
  1824. }
  1825. return cloned;
  1826. }
  1827. /**
  1828. * Shortcut to clone the node and insert the resulting cloned node
  1829. * before the current node.
  1830. *
  1831. * @param {object} [overrides] - new properties to override in the clone.
  1832. *
  1833. * @example
  1834. * decl.cloneBefore({ prop: '-moz-' + decl.prop });
  1835. *
  1836. * @return {Node} - new node
  1837. */
  1838. ;
  1839. _proto.cloneBefore = function cloneBefore(overrides) {
  1840. if (overrides === void 0) {
  1841. overrides = {};
  1842. }
  1843. var cloned = this.clone(overrides);
  1844. this.parent.insertBefore(this, cloned);
  1845. return cloned;
  1846. }
  1847. /**
  1848. * Shortcut to clone the node and insert the resulting cloned node
  1849. * after the current node.
  1850. *
  1851. * @param {object} [overrides] - new properties to override in the clone.
  1852. *
  1853. * @return {Node} - new node
  1854. */
  1855. ;
  1856. _proto.cloneAfter = function cloneAfter(overrides) {
  1857. if (overrides === void 0) {
  1858. overrides = {};
  1859. }
  1860. var cloned = this.clone(overrides);
  1861. this.parent.insertAfter(this, cloned);
  1862. return cloned;
  1863. }
  1864. /**
  1865. * Inserts node(s) before the current node and removes the current node.
  1866. *
  1867. * @param {...Node} nodes - node(s) to replace current one
  1868. *
  1869. * @example
  1870. * if ( atrule.name == 'mixin' ) {
  1871. * atrule.replaceWith(mixinRules[atrule.params]);
  1872. * }
  1873. *
  1874. * @return {Node} current node to methods chain
  1875. */
  1876. ;
  1877. _proto.replaceWith = function replaceWith() {
  1878. var _this = this;
  1879. if (this.parent) {
  1880. for (var _len = arguments.length, nodes = new Array(_len), _key = 0; _key < _len; _key++) {
  1881. nodes[_key] = arguments[_key];
  1882. }
  1883. nodes.forEach(function (node) {
  1884. _this.parent.insertBefore(_this, node);
  1885. });
  1886. this.remove();
  1887. }
  1888. return this;
  1889. }
  1890. /**
  1891. * Removes the node from its current parent and inserts it
  1892. * at the end of `newParent`.
  1893. *
  1894. * This will clean the `before` and `after` code {@link Node#raws} data
  1895. * from the node and replace them with the indentation style of `newParent`.
  1896. * It will also clean the `between` property
  1897. * if `newParent` is in another {@link Root}.
  1898. *
  1899. * @param {Container} newParent - container node where the current node
  1900. * will be moved
  1901. *
  1902. * @example
  1903. * atrule.moveTo(atrule.root());
  1904. *
  1905. * @return {Node} current node to methods chain
  1906. */
  1907. ;
  1908. _proto.moveTo = function moveTo(newParent) {
  1909. this.cleanRaws(this.root() === newParent.root());
  1910. this.remove();
  1911. newParent.append(this);
  1912. return this;
  1913. }
  1914. /**
  1915. * Removes the node from its current parent and inserts it into
  1916. * a new parent before `otherNode`.
  1917. *
  1918. * This will also clean the node’s code style properties just as it would
  1919. * in {@link Node#moveTo}.
  1920. *
  1921. * @param {Node} otherNode - node that will be before current node
  1922. *
  1923. * @return {Node} current node to methods chain
  1924. */
  1925. ;
  1926. _proto.moveBefore = function moveBefore(otherNode) {
  1927. this.cleanRaws(this.root() === otherNode.root());
  1928. this.remove();
  1929. otherNode.parent.insertBefore(otherNode, this);
  1930. return this;
  1931. }
  1932. /**
  1933. * Removes the node from its current parent and inserts it into
  1934. * a new parent after `otherNode`.
  1935. *
  1936. * This will also clean the node’s code style properties just as it would
  1937. * in {@link Node#moveTo}.
  1938. *
  1939. * @param {Node} otherNode - node that will be after current node
  1940. *
  1941. * @return {Node} current node to methods chain
  1942. */
  1943. ;
  1944. _proto.moveAfter = function moveAfter(otherNode) {
  1945. this.cleanRaws(this.root() === otherNode.root());
  1946. this.remove();
  1947. otherNode.parent.insertAfter(otherNode, this);
  1948. return this;
  1949. }
  1950. /**
  1951. * Returns the next child of the node’s parent.
  1952. * Returns `undefined` if the current node is the last child.
  1953. *
  1954. * @return {Node|undefined} next node
  1955. *
  1956. * @example
  1957. * if ( comment.text === 'delete next' ) {
  1958. * const next = comment.next();
  1959. * if ( next ) {
  1960. * next.remove();
  1961. * }
  1962. * }
  1963. */
  1964. ;
  1965. _proto.next = function next() {
  1966. var index = this.parent.index(this);
  1967. return this.parent.nodes[index + 1];
  1968. }
  1969. /**
  1970. * Returns the previous child of the node’s parent.
  1971. * Returns `undefined` if the current node is the first child.
  1972. *
  1973. * @return {Node|undefined} previous node
  1974. *
  1975. * @example
  1976. * const annotation = decl.prev();
  1977. * if ( annotation.type == 'comment' ) {
  1978. * readAnnotation(annotation.text);
  1979. * }
  1980. */
  1981. ;
  1982. _proto.prev = function prev() {
  1983. var index = this.parent.index(this);
  1984. return this.parent.nodes[index - 1];
  1985. };
  1986. _proto.toJSON = function toJSON() {
  1987. var fixed = {};
  1988. for (var name in this) {
  1989. if (!this.hasOwnProperty(name)) continue;
  1990. if (name === 'parent') continue;
  1991. var value = this[name];
  1992. if (value instanceof Array) {
  1993. fixed[name] = value.map(function (i) {
  1994. if (typeof i === 'object' && i.toJSON) {
  1995. return i.toJSON();
  1996. } else {
  1997. return i;
  1998. }
  1999. });
  2000. } else if (typeof value === 'object' && value.toJSON) {
  2001. fixed[name] = value.toJSON();
  2002. } else {
  2003. fixed[name] = value;
  2004. }
  2005. }
  2006. return fixed;
  2007. }
  2008. /**
  2009. * Returns a {@link Node#raws} value. If the node is missing
  2010. * the code style property (because the node was manually built or cloned),
  2011. * PostCSS will try to autodetect the code style property by looking
  2012. * at other nodes in the tree.
  2013. *
  2014. * @param {string} prop - name of code style property
  2015. * @param {string} [defaultType] - name of default value, it can be missed
  2016. * if the value is the same as prop
  2017. *
  2018. * @example
  2019. * const root = postcss.parse('a { background: white }');
  2020. * root.nodes[0].append({ prop: 'color', value: 'black' });
  2021. * root.nodes[0].nodes[1].raws.before //=> undefined
  2022. * root.nodes[0].nodes[1].raw('before') //=> ' '
  2023. *
  2024. * @return {string} code style value
  2025. */
  2026. ;
  2027. _proto.raw = function raw(prop, defaultType) {
  2028. var str = new Stringifier();
  2029. return str.raw(this, prop, defaultType);
  2030. }
  2031. /**
  2032. * Finds the Root instance of the node’s tree.
  2033. *
  2034. * @example
  2035. * root.nodes[0].nodes[0].root() === root
  2036. *
  2037. * @return {Root} root parent
  2038. */
  2039. ;
  2040. _proto.root = function root() {
  2041. var result = this;
  2042. while (result.parent) {
  2043. result = result.parent;
  2044. }
  2045. return result;
  2046. };
  2047. _proto.cleanRaws = function cleanRaws(keepBetween) {
  2048. delete this.raws.before;
  2049. delete this.raws.after;
  2050. if (!keepBetween) delete this.raws.between;
  2051. };
  2052. _proto.positionInside = function positionInside(index) {
  2053. var string = this.toString();
  2054. var column = this.source.start.column;
  2055. var line = this.source.start.line;
  2056. for (var i = 0; i < index; i++) {
  2057. if (string[i] === '\n') {
  2058. column = 1;
  2059. line += 1;
  2060. } else {
  2061. column += 1;
  2062. }
  2063. }
  2064. return {
  2065. line: line,
  2066. column: column
  2067. };
  2068. };
  2069. _proto.positionBy = function positionBy(opts) {
  2070. var pos = this.source.start;
  2071. if (opts.index) {
  2072. pos = this.positionInside(opts.index);
  2073. } else if (opts.word) {
  2074. var index = this.toString().indexOf(opts.word);
  2075. if (index !== -1) pos = this.positionInside(index);
  2076. }
  2077. return pos;
  2078. };
  2079. _proto.removeSelf = function removeSelf() {
  2080. warnOnce('Node#removeSelf is deprecated. Use Node#remove.');
  2081. return this.remove();
  2082. };
  2083. _proto.replace = function replace(nodes) {
  2084. warnOnce('Node#replace is deprecated. Use Node#replaceWith');
  2085. return this.replaceWith(nodes);
  2086. };
  2087. _proto.style = function style(own, detect) {
  2088. warnOnce('Node#style() is deprecated. Use Node#raw()');
  2089. return this.raw(own, detect);
  2090. };
  2091. _proto.cleanStyles = function cleanStyles(keepBetween) {
  2092. warnOnce('Node#cleanStyles() is deprecated. Use Node#cleanRaws()');
  2093. return this.cleanRaws(keepBetween);
  2094. };
  2095. _createClass(Node, [{
  2096. key: "before",
  2097. get: function get() {
  2098. warnOnce('Node#before is deprecated. Use Node#raws.before');
  2099. return this.raws.before;
  2100. },
  2101. set: function set(val) {
  2102. warnOnce('Node#before is deprecated. Use Node#raws.before');
  2103. this.raws.before = val;
  2104. }
  2105. }, {
  2106. key: "between",
  2107. get: function get() {
  2108. warnOnce('Node#between is deprecated. Use Node#raws.between');
  2109. return this.raws.between;
  2110. },
  2111. set: function set(val) {
  2112. warnOnce('Node#between is deprecated. Use Node#raws.between');
  2113. this.raws.between = val;
  2114. }
  2115. /**
  2116. * @memberof Node#
  2117. * @member {string} type - String representing the node’s type.
  2118. * Possible values are `root`, `atrule`, `rule`,
  2119. * `decl`, or `comment`.
  2120. *
  2121. * @example
  2122. * postcss.decl({ prop: 'color', value: 'black' }).type //=> 'decl'
  2123. */
  2124. /**
  2125. * @memberof Node#
  2126. * @member {Container} parent - the node’s parent node.
  2127. *
  2128. * @example
  2129. * root.nodes[0].parent == root;
  2130. */
  2131. /**
  2132. * @memberof Node#
  2133. * @member {source} source - the input source of the node
  2134. *
  2135. * The property is used in source map generation.
  2136. *
  2137. * If you create a node manually (e.g., with `postcss.decl()`),
  2138. * that node will not have a `source` property and will be absent
  2139. * from the source map. For this reason, the plugin developer should
  2140. * consider cloning nodes to create new ones (in which case the new node’s
  2141. * source will reference the original, cloned node) or setting
  2142. * the `source` property manually.
  2143. *
  2144. * ```js
  2145. * // Bad
  2146. * const prefixed = postcss.decl({
  2147. * prop: '-moz-' + decl.prop,
  2148. * value: decl.value
  2149. * });
  2150. *
  2151. * // Good
  2152. * const prefixed = decl.clone({ prop: '-moz-' + decl.prop });
  2153. * ```
  2154. *
  2155. * ```js
  2156. * if ( atrule.name == 'add-link' ) {
  2157. * const rule = postcss.rule({ selector: 'a', source: atrule.source });
  2158. * atrule.parent.insertBefore(atrule, rule);
  2159. * }
  2160. * ```
  2161. *
  2162. * @example
  2163. * decl.source.input.from //=> '/home/ai/a.sass'
  2164. * decl.source.start //=> { line: 10, column: 2 }
  2165. * decl.source.end //=> { line: 10, column: 12 }
  2166. */
  2167. /**
  2168. * @memberof Node#
  2169. * @member {object} raws - Information to generate byte-to-byte equal
  2170. * node string as it was in the origin input.
  2171. *
  2172. * Every parser saves its own properties,
  2173. * but the default CSS parser uses:
  2174. *
  2175. * * `before`: the space symbols before the node. It also stores `*`
  2176. * and `_` symbols before the declaration (IE hack).
  2177. * * `after`: the space symbols after the last child of the node
  2178. * to the end of the node.
  2179. * * `between`: the symbols between the property and value
  2180. * for declarations, selector and `{` for rules, or last parameter
  2181. * and `{` for at-rules.
  2182. * * `semicolon`: contains true if the last child has
  2183. * an (optional) semicolon.
  2184. * * `afterName`: the space between the at-rule name and its parameters.
  2185. * * `left`: the space symbols between `/*` and the comment’s text.
  2186. * * `right`: the space symbols between the comment’s text
  2187. * and <code>*&#47;</code>.
  2188. * * `important`: the content of the important statement,
  2189. * if it is not just `!important`.
  2190. *
  2191. * PostCSS cleans selectors, declaration values and at-rule parameters
  2192. * from comments and extra spaces, but it stores origin content in raws
  2193. * properties. As such, if you don’t change a declaration’s value,
  2194. * PostCSS will use the raw value with comments.
  2195. *
  2196. * @example
  2197. * const root = postcss.parse('a {\n color:black\n}')
  2198. * root.first.first.raws //=> { before: '\n ', between: ':' }
  2199. */
  2200. }]);
  2201. return Node;
  2202. }();
  2203. /**
  2204. * Represents a CSS declaration.
  2205. *
  2206. * @extends Node
  2207. *
  2208. * @example
  2209. * const root = postcss.parse('a { color: black }');
  2210. * const decl = root.first.first;
  2211. * decl.type //=> 'decl'
  2212. * decl.toString() //=> ' color: black'
  2213. */
  2214. var Declaration =
  2215. /*#__PURE__*/
  2216. function (_Node) {
  2217. _inheritsLoose(Declaration, _Node);
  2218. function Declaration(defaults) {
  2219. var _this;
  2220. _this = _Node.call(this, defaults) || this;
  2221. _this.type = 'decl';
  2222. return _this;
  2223. }
  2224. _createClass(Declaration, [{
  2225. key: "_value",
  2226. get: function get() {
  2227. warnOnce('Node#_value was deprecated. Use Node#raws.value');
  2228. return this.raws.value;
  2229. },
  2230. set: function set(val) {
  2231. warnOnce('Node#_value was deprecated. Use Node#raws.value');
  2232. this.raws.value = val;
  2233. }
  2234. }, {
  2235. key: "_important",
  2236. get: function get() {
  2237. warnOnce('Node#_important was deprecated. Use Node#raws.important');
  2238. return this.raws.important;
  2239. },
  2240. set: function set(val) {
  2241. warnOnce('Node#_important was deprecated. Use Node#raws.important');
  2242. this.raws.important = val;
  2243. }
  2244. /**
  2245. * @memberof Declaration#
  2246. * @member {string} prop - the declaration’s property name
  2247. *
  2248. * @example
  2249. * const root = postcss.parse('a { color: black }');
  2250. * const decl = root.first.first;
  2251. * decl.prop //=> 'color'
  2252. */
  2253. /**
  2254. * @memberof Declaration#
  2255. * @member {string} value - the declaration’s value
  2256. *
  2257. * @example
  2258. * const root = postcss.parse('a { color: black }');
  2259. * const decl = root.first.first;
  2260. * decl.value //=> 'black'
  2261. */
  2262. /**
  2263. * @memberof Declaration#
  2264. * @member {boolean} important - `true` if the declaration
  2265. * has an !important annotation.
  2266. *
  2267. * @example
  2268. * const root = postcss.parse('a { color: black !important; color: red }');
  2269. * root.first.first.important //=> true
  2270. * root.first.last.important //=> undefined
  2271. */
  2272. /**
  2273. * @memberof Declaration#
  2274. * @member {object} raws - Information to generate byte-to-byte equal
  2275. * node string as it was in the origin input.
  2276. *
  2277. * Every parser saves its own properties,
  2278. * but the default CSS parser uses:
  2279. *
  2280. * * `before`: the space symbols before the node. It also stores `*`
  2281. * and `_` symbols before the declaration (IE hack).
  2282. * * `between`: the symbols between the property and value
  2283. * for declarations, selector and `{` for rules, or last parameter
  2284. * and `{` for at-rules.
  2285. * * `important`: the content of the important statement,
  2286. * if it is not just `!important`.
  2287. *
  2288. * PostCSS cleans declaration from comments and extra spaces,
  2289. * but it stores origin content in raws properties.
  2290. * As such, if you don’t change a declaration’s value,
  2291. * PostCSS will use the raw value with comments.
  2292. *
  2293. * @example
  2294. * const root = postcss.parse('a {\n color:black\n}')
  2295. * root.first.first.raws //=> { before: '\n ', between: ':' }
  2296. */
  2297. }]);
  2298. return Declaration;
  2299. }(Node);
  2300. /**
  2301. * Represents a comment between declarations or statements (rule and at-rules).
  2302. *
  2303. * Comments inside selectors, at-rule parameters, or declaration values
  2304. * will be stored in the `raws` properties explained above.
  2305. *
  2306. * @extends Node
  2307. */
  2308. var Comment =
  2309. /*#__PURE__*/
  2310. function (_Node) {
  2311. _inheritsLoose(Comment, _Node);
  2312. function Comment(defaults) {
  2313. var _this;
  2314. _this = _Node.call(this, defaults) || this;
  2315. _this.type = 'comment';
  2316. return _this;
  2317. }
  2318. _createClass(Comment, [{
  2319. key: "left",
  2320. get: function get() {
  2321. warnOnce('Comment#left was deprecated. Use Comment#raws.left');
  2322. return this.raws.left;
  2323. },
  2324. set: function set(val) {
  2325. warnOnce('Comment#left was deprecated. Use Comment#raws.left');
  2326. this.raws.left = val;
  2327. }
  2328. }, {
  2329. key: "right",
  2330. get: function get() {
  2331. warnOnce('Comment#right was deprecated. Use Comment#raws.right');
  2332. return this.raws.right;
  2333. },
  2334. set: function set(val) {
  2335. warnOnce('Comment#right was deprecated. Use Comment#raws.right');
  2336. this.raws.right = val;
  2337. }
  2338. /**
  2339. * @memberof Comment#
  2340. * @member {string} text - the comment’s text
  2341. */
  2342. /**
  2343. * @memberof Comment#
  2344. * @member {object} raws - Information to generate byte-to-byte equal
  2345. * node string as it was in the origin input.
  2346. *
  2347. * Every parser saves its own properties,
  2348. * but the default CSS parser uses:
  2349. *
  2350. * * `before`: the space symbols before the node.
  2351. * * `left`: the space symbols between `/*` and the comment’s text.
  2352. * * `right`: the space symbols between the comment’s text.
  2353. */
  2354. }]);
  2355. return Comment;
  2356. }(Node);
  2357. //
  2358. var Parser =
  2359. /*#__PURE__*/
  2360. function () {
  2361. function Parser(input) {
  2362. this.input = input;
  2363. this.pos = 0;
  2364. this.root = new Root();
  2365. this.current = this.root;
  2366. this.spaces = '';
  2367. this.semicolon = false;
  2368. this.root.source = {
  2369. input: input,
  2370. start: {
  2371. line: 1,
  2372. column: 1
  2373. }
  2374. };
  2375. }
  2376. var _proto = Parser.prototype;
  2377. _proto.tokenize = function tokenize$1() {
  2378. this.tokens = tokenize(this.input);
  2379. };
  2380. _proto.loop = function loop() {
  2381. var token;
  2382. while (this.pos < this.tokens.length) {
  2383. token = this.tokens[this.pos];
  2384. switch (token[0]) {
  2385. case 'space':
  2386. case ';':
  2387. this.spaces += token[1];
  2388. break;
  2389. case '}':
  2390. this.end(token);
  2391. break;
  2392. case 'comment':
  2393. this.comment(token);
  2394. break;
  2395. case 'at-word':
  2396. this.atrule(token);
  2397. break;
  2398. case '{':
  2399. this.emptyRule(token);
  2400. break;
  2401. default:
  2402. this.other();
  2403. break;
  2404. }
  2405. this.pos += 1;
  2406. }
  2407. this.endFile();
  2408. };
  2409. _proto.comment = function comment(token) {
  2410. var node = new Comment();
  2411. this.init(node, token[2], token[3]);
  2412. node.source.end = {
  2413. line: token[4],
  2414. column: token[5]
  2415. };
  2416. var text = token[1].slice(2, -2);
  2417. if (/^\s*$/.test(text)) {
  2418. node.text = '';
  2419. node.raws.left = text;
  2420. node.raws.right = '';
  2421. } else {
  2422. var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
  2423. node.text = match[2];
  2424. node.raws.left = match[1];
  2425. node.raws.right = match[3];
  2426. }
  2427. };
  2428. _proto.emptyRule = function emptyRule(token) {
  2429. var node = new Rule();
  2430. this.init(node, token[2], token[3]);
  2431. node.selector = '';
  2432. node.raws.between = '';
  2433. this.current = node;
  2434. };
  2435. _proto.other = function other() {
  2436. var token;
  2437. var end = false;
  2438. var type = null;
  2439. var colon = false;
  2440. var bracket = null;
  2441. var brackets = [];
  2442. var start = this.pos;
  2443. while (this.pos < this.tokens.length) {
  2444. token = this.tokens[this.pos];
  2445. type = token[0];
  2446. if (type === '(' || type === '[') {
  2447. if (!bracket) bracket = token;
  2448. brackets.push(type === '(' ? ')' : ']');
  2449. } else if (brackets.length === 0) {
  2450. if (type === ';') {
  2451. if (colon) {
  2452. this.decl(this.tokens.slice(start, this.pos + 1));
  2453. return;
  2454. } else {
  2455. break;
  2456. }
  2457. } else if (type === '{') {
  2458. this.rule(this.tokens.slice(start, this.pos + 1));
  2459. return;
  2460. } else if (type === '}') {
  2461. this.pos -= 1;
  2462. end = true;
  2463. break;
  2464. } else if (type === ':') {
  2465. colon = true;
  2466. }
  2467. } else if (type === brackets[brackets.length - 1]) {
  2468. brackets.pop();
  2469. if (brackets.length === 0) bracket = null;
  2470. }
  2471. this.pos += 1;
  2472. }
  2473. if (this.pos === this.tokens.length) {
  2474. this.pos -= 1;
  2475. end = true;
  2476. }
  2477. if (brackets.length > 0) this.unclosedBracket(bracket);
  2478. if (end && colon) {
  2479. while (this.pos > start) {
  2480. token = this.tokens[this.pos][0];
  2481. if (token !== 'space' && token !== 'comment') break;
  2482. this.pos -= 1;
  2483. }
  2484. this.decl(this.tokens.slice(start, this.pos + 1));
  2485. return;
  2486. }
  2487. this.unknownWord(start);
  2488. };
  2489. _proto.rule = function rule(tokens) {
  2490. tokens.pop();
  2491. var node = new Rule();
  2492. this.init(node, tokens[0][2], tokens[0][3]);
  2493. node.raws.between = this.spacesFromEnd(tokens);
  2494. this.raw(node, 'selector', tokens);
  2495. this.current = node;
  2496. };
  2497. _proto.decl = function decl(tokens) {
  2498. var node = new Declaration();
  2499. this.init(node);
  2500. var last = tokens[tokens.length - 1];
  2501. if (last[0] === ';') {
  2502. this.semicolon = true;
  2503. tokens.pop();
  2504. }
  2505. if (last[4]) {
  2506. node.source.end = {
  2507. line: last[4],
  2508. column: last[5]
  2509. };
  2510. } else {
  2511. node.source.end = {
  2512. line: last[2],
  2513. column: last[3]
  2514. };
  2515. }
  2516. while (tokens[0][0] !== 'word') {
  2517. node.raws.before += tokens.shift()[1];
  2518. }
  2519. node.source.start = {
  2520. line: tokens[0][2],
  2521. column: tokens[0][3]
  2522. };
  2523. node.prop = '';
  2524. while (tokens.length) {
  2525. var type = tokens[0][0];
  2526. if (type === ':' || type === 'space' || type === 'comment') {
  2527. break;
  2528. }
  2529. node.prop += tokens.shift()[1];
  2530. }
  2531. node.raws.between = '';
  2532. var token;
  2533. while (tokens.length) {
  2534. token = tokens.shift();
  2535. if (token[0] === ':') {
  2536. node.raws.between += token[1];
  2537. break;
  2538. } else {
  2539. node.raws.between += token[1];
  2540. }
  2541. }
  2542. if (node.prop[0] === '_' || node.prop[0] === '*') {
  2543. node.raws.before += node.prop[0];
  2544. node.prop = node.prop.slice(1);
  2545. }
  2546. node.raws.between += this.spacesFromStart(tokens);
  2547. this.precheckMissedSemicolon(tokens);
  2548. for (var i = tokens.length - 1; i > 0; i--) {
  2549. token = tokens[i];
  2550. if (token[1] === '!important') {
  2551. node.important = true;
  2552. var string = this.stringFrom(tokens, i);
  2553. string = this.spacesFromEnd(tokens) + string;
  2554. if (string !== ' !important') node.raws.important = string;
  2555. break;
  2556. } else if (token[1] === 'important') {
  2557. var cache = tokens.slice(0);
  2558. var str = '';
  2559. for (var j = i; j > 0; j--) {
  2560. var _type = cache[j][0];
  2561. if (str.trim().indexOf('!') === 0 && _type !== 'space') {
  2562. break;
  2563. }
  2564. str = cache.pop()[1] + str;
  2565. }
  2566. if (str.trim().indexOf('!') === 0) {
  2567. node.important = true;
  2568. node.raws.important = str;
  2569. tokens = cache;
  2570. }
  2571. }
  2572. if (token[0] !== 'space' && token[0] !== 'comment') {
  2573. break;
  2574. }
  2575. }
  2576. this.raw(node, 'value', tokens);
  2577. if (node.value.indexOf(':') !== -1) this.checkMissedSemicolon(tokens);
  2578. };
  2579. _proto.atrule = function atrule(token) {
  2580. var node = new AtRule();
  2581. node.name = token[1].slice(1);
  2582. if (node.name === '') {
  2583. this.unnamedAtrule(node, token);
  2584. }
  2585. this.init(node, token[2], token[3]);
  2586. var last = false;
  2587. var open = false;
  2588. var params = [];
  2589. this.pos += 1;
  2590. while (this.pos < this.tokens.length) {
  2591. token = this.tokens[this.pos];
  2592. if (token[0] === ';') {
  2593. node.source.end = {
  2594. line: token[2],
  2595. column: token[3]
  2596. };
  2597. this.semicolon = true;
  2598. break;
  2599. } else if (token[0] === '{') {
  2600. open = true;
  2601. break;
  2602. } else if (token[0] === '}') {
  2603. this.end(token);
  2604. break;
  2605. } else {
  2606. params.push(token);
  2607. }
  2608. this.pos += 1;
  2609. }
  2610. if (this.pos === this.tokens.length) {
  2611. last = true;
  2612. }
  2613. node.raws.between = this.spacesFromEnd(params);
  2614. if (params.length) {
  2615. node.raws.afterName = this.spacesFromStart(params);
  2616. this.raw(node, 'params', params);
  2617. if (last) {
  2618. token = params[params.length - 1];
  2619. node.source.end = {
  2620. line: token[4],
  2621. column: token[5]
  2622. };
  2623. this.spaces = node.raws.between;
  2624. node.raws.between = '';
  2625. }
  2626. } else {
  2627. node.raws.afterName = '';
  2628. node.params = '';
  2629. }
  2630. if (open) {
  2631. node.nodes = [];
  2632. this.current = node;
  2633. }
  2634. };
  2635. _proto.end = function end(token) {
  2636. if (this.current.nodes && this.current.nodes.length) {
  2637. this.current.raws.semicolon = this.semicolon;
  2638. }
  2639. this.semicolon = false;
  2640. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  2641. this.spaces = '';
  2642. if (this.current.parent) {
  2643. this.current.source.end = {
  2644. line: token[2],
  2645. column: token[3]
  2646. };
  2647. this.current = this.current.parent;
  2648. } else {
  2649. this.unexpectedClose(token);
  2650. }
  2651. };
  2652. _proto.endFile = function endFile() {
  2653. if (this.current.parent) this.unclosedBlock();
  2654. if (this.current.nodes && this.current.nodes.length) {
  2655. this.current.raws.semicolon = this.semicolon;
  2656. }
  2657. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  2658. } // Helpers
  2659. ;
  2660. _proto.init = function init(node, line, column) {
  2661. this.current.push(node);
  2662. node.source = {
  2663. start: {
  2664. line: line,
  2665. column: column
  2666. },
  2667. input: this.input
  2668. };
  2669. node.raws.before = this.spaces;
  2670. this.spaces = '';
  2671. if (node.type !== 'comment') this.semicolon = false;
  2672. };
  2673. _proto.raw = function raw(node, prop, tokens) {
  2674. var token, type;
  2675. var length = tokens.length;
  2676. var value = '';
  2677. var clean = true;
  2678. for (var i = 0; i < length; i += 1) {
  2679. token = tokens[i];
  2680. type = token[0];
  2681. if (type === 'comment' || type === 'space' && i === length - 1) {
  2682. clean = false;
  2683. } else {
  2684. value += token[1];
  2685. }
  2686. }
  2687. if (!clean) {
  2688. var raw = tokens.reduce(function (all, i) {
  2689. return all + i[1];
  2690. }, '');
  2691. node.raws[prop] = {
  2692. value: value,
  2693. raw: raw
  2694. };
  2695. }
  2696. node[prop] = value;
  2697. };
  2698. _proto.spacesFromEnd = function spacesFromEnd(tokens) {
  2699. var lastTokenType;
  2700. var spaces = '';
  2701. while (tokens.length) {
  2702. lastTokenType = tokens[tokens.length - 1][0];
  2703. if (lastTokenType !== 'space' && lastTokenType !== 'comment') break;
  2704. spaces = tokens.pop()[1] + spaces;
  2705. }
  2706. return spaces;
  2707. };
  2708. _proto.spacesFromStart = function spacesFromStart(tokens) {
  2709. var next;
  2710. var spaces = '';
  2711. while (tokens.length) {
  2712. next = tokens[0][0];
  2713. if (next !== 'space' && next !== 'comment') break;
  2714. spaces += tokens.shift()[1];
  2715. }
  2716. return spaces;
  2717. };
  2718. _proto.stringFrom = function stringFrom(tokens, from) {
  2719. var result = '';
  2720. for (var i = from; i < tokens.length; i++) {
  2721. result += tokens[i][1];
  2722. }
  2723. tokens.splice(from, tokens.length - from);
  2724. return result;
  2725. };
  2726. _proto.colon = function colon(tokens) {
  2727. var brackets = 0;
  2728. var token, type, prev;
  2729. for (var i = 0; i < tokens.length; i++) {
  2730. token = tokens[i];
  2731. type = token[0];
  2732. if (type === '(') {
  2733. brackets += 1;
  2734. } else if (type === ')') {
  2735. brackets -= 1;
  2736. } else if (brackets === 0 && type === ':') {
  2737. if (!prev) {
  2738. this.doubleColon(token);
  2739. } else if (prev[0] === 'word' && prev[1] === 'progid') {
  2740. continue;
  2741. } else {
  2742. return i;
  2743. }
  2744. }
  2745. prev = token;
  2746. }
  2747. return false;
  2748. } // Errors
  2749. ;
  2750. _proto.unclosedBracket = function unclosedBracket(bracket) {
  2751. throw this.input.error('Unclosed bracket', bracket[2], bracket[3]);
  2752. };
  2753. _proto.unknownWord = function unknownWord(start) {
  2754. var token = this.tokens[start];
  2755. throw this.input.error('Unknown word', token[2], token[3]);
  2756. };
  2757. _proto.unexpectedClose = function unexpectedClose(token) {
  2758. throw this.input.error('Unexpected }', token[2], token[3]);
  2759. };
  2760. _proto.unclosedBlock = function unclosedBlock() {
  2761. var pos = this.current.source.start;
  2762. throw this.input.error('Unclosed block', pos.line, pos.column);
  2763. };
  2764. _proto.doubleColon = function doubleColon(token) {
  2765. throw this.input.error('Double colon', token[2], token[3]);
  2766. };
  2767. _proto.unnamedAtrule = function unnamedAtrule(node, token) {
  2768. throw this.input.error('At-rule without name', token[2], token[3]);
  2769. };
  2770. _proto.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
  2771. };
  2772. _proto.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
  2773. var colon = this.colon(tokens);
  2774. if (colon === false) return;
  2775. var founded = 0;
  2776. var token;
  2777. for (var j = colon - 1; j >= 0; j--) {
  2778. token = tokens[j];
  2779. if (token[0] !== 'space') {
  2780. founded += 1;
  2781. if (founded === 2) break;
  2782. }
  2783. }
  2784. throw this.input.error('Missed semicolon', token[2], token[3]);
  2785. };
  2786. return Parser;
  2787. }();
  2788. //
  2789. function parse(css, opts) {
  2790. if (opts && opts.safe) {
  2791. throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")');
  2792. }
  2793. var input = new Input(css, opts);
  2794. var parser = new Parser(input);
  2795. try {
  2796. parser.tokenize();
  2797. parser.loop();
  2798. } catch (e) {
  2799. if (e.name === 'CssSyntaxError' && opts && opts.from) {
  2800. if (/\.scss$/i.test(opts.from)) {
  2801. e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser';
  2802. } else if (/\.less$/i.test(opts.from)) {
  2803. e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser';
  2804. }
  2805. }
  2806. throw e;
  2807. }
  2808. return parser.root;
  2809. }
  2810. function cleanSource(nodes) {
  2811. return nodes.map(function (i) {
  2812. if (i.nodes) i.nodes = cleanSource(i.nodes);
  2813. delete i.source;
  2814. return i;
  2815. });
  2816. }
  2817. /**
  2818. * @callback childCondition
  2819. * @param {Node} node - container child
  2820. * @param {number} index - child index
  2821. * @param {Node[]} nodes - all container children
  2822. * @return {boolean}
  2823. */
  2824. /**
  2825. * @callback childIterator
  2826. * @param {Node} node - container child
  2827. * @param {number} index - child index
  2828. * @return {false|undefined} returning `false` will break iteration
  2829. */
  2830. /**
  2831. * The {@link Root}, {@link AtRule}, and {@link Rule} container nodes
  2832. * inherit some common methods to help work with their children.
  2833. *
  2834. * Note that all containers can store any content. If you write a rule inside
  2835. * a rule, PostCSS will parse it.
  2836. *
  2837. * @extends Node
  2838. * @abstract
  2839. */
  2840. var Container =
  2841. /*#__PURE__*/
  2842. function (_Node) {
  2843. _inheritsLoose(Container, _Node);
  2844. function Container() {
  2845. return _Node.apply(this, arguments) || this;
  2846. }
  2847. var _proto = Container.prototype;
  2848. _proto.push = function push(child) {
  2849. child.parent = this;
  2850. this.nodes.push(child);
  2851. return this;
  2852. }
  2853. /**
  2854. * Iterates through the container’s immediate children,
  2855. * calling `callback` for each child.
  2856. *
  2857. * Returning `false` in the callback will break iteration.
  2858. *
  2859. * This method only iterates through the container’s immediate children.
  2860. * If you need to recursively iterate through all the container’s descendant
  2861. * nodes, use {@link Container#walk}.
  2862. *
  2863. * Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe
  2864. * if you are mutating the array of child nodes during iteration.
  2865. * PostCSS will adjust the current index to match the mutations.
  2866. *
  2867. * @param {childIterator} callback - iterator receives each node and index
  2868. *
  2869. * @return {false|undefined} returns `false` if iteration was broke
  2870. *
  2871. * @example
  2872. * const root = postcss.parse('a { color: black; z-index: 1 }');
  2873. * const rule = root.first;
  2874. *
  2875. * for ( let decl of rule.nodes ) {
  2876. * decl.cloneBefore({ prop: '-webkit-' + decl.prop });
  2877. * // Cycle will be infinite, because cloneBefore moves the current node
  2878. * // to the next index
  2879. * }
  2880. *
  2881. * rule.each(decl => {
  2882. * decl.cloneBefore({ prop: '-webkit-' + decl.prop });
  2883. * // Will be executed only for color and z-index
  2884. * });
  2885. */
  2886. ;
  2887. _proto.each = function each(callback) {
  2888. if (!this.lastEach) this.lastEach = 0;
  2889. if (!this.indexes) this.indexes = {};
  2890. this.lastEach += 1;
  2891. var id = this.lastEach;
  2892. this.indexes[id] = 0;
  2893. if (!this.nodes) return undefined;
  2894. var index, result;
  2895. while (this.indexes[id] < this.nodes.length) {
  2896. index = this.indexes[id];
  2897. result = callback(this.nodes[index], index);
  2898. if (result === false) break;
  2899. this.indexes[id] += 1;
  2900. }
  2901. delete this.indexes[id];
  2902. return result;
  2903. }
  2904. /**
  2905. * Traverses the container’s descendant nodes, calling callback
  2906. * for each node.
  2907. *
  2908. * Like container.each(), this method is safe to use
  2909. * if you are mutating arrays during iteration.
  2910. *
  2911. * If you only need to iterate through the container’s immediate children,
  2912. * use {@link Container#each}.
  2913. *
  2914. * @param {childIterator} callback - iterator receives each node and index
  2915. *
  2916. * @return {false|undefined} returns `false` if iteration was broke
  2917. *
  2918. * @example
  2919. * root.walk(node => {
  2920. * // Traverses all descendant nodes.
  2921. * });
  2922. */
  2923. ;
  2924. _proto.walk = function walk(callback) {
  2925. return this.each(function (child, i) {
  2926. var result = callback(child, i);
  2927. if (result !== false && child.walk) {
  2928. result = child.walk(callback);
  2929. }
  2930. return result;
  2931. });
  2932. }
  2933. /**
  2934. * Traverses the container’s descendant nodes, calling callback
  2935. * for each declaration node.
  2936. *
  2937. * If you pass a filter, iteration will only happen over declarations
  2938. * with matching properties.
  2939. *
  2940. * Like {@link Container#each}, this method is safe
  2941. * to use if you are mutating arrays during iteration.
  2942. *
  2943. * @param {string|RegExp} [prop] - string or regular expression
  2944. * to filter declarations by property name
  2945. * @param {childIterator} callback - iterator receives each node and index
  2946. *
  2947. * @return {false|undefined} returns `false` if iteration was broke
  2948. *
  2949. * @example
  2950. * root.walkDecls(decl => {
  2951. * checkPropertySupport(decl.prop);
  2952. * });
  2953. *
  2954. * root.walkDecls('border-radius', decl => {
  2955. * decl.remove();
  2956. * });
  2957. *
  2958. * root.walkDecls(/^background/, decl => {
  2959. * decl.value = takeFirstColorFromGradient(decl.value);
  2960. * });
  2961. */
  2962. ;
  2963. _proto.walkDecls = function walkDecls(prop, callback) {
  2964. if (!callback) {
  2965. callback = prop;
  2966. return this.walk(function (child, i) {
  2967. if (child.type === 'decl') {
  2968. return callback(child, i);
  2969. }
  2970. });
  2971. } else if (prop instanceof RegExp) {
  2972. return this.walk(function (child, i) {
  2973. if (child.type === 'decl' && prop.test(child.prop)) {
  2974. return callback(child, i);
  2975. }
  2976. });
  2977. } else {
  2978. return this.walk(function (child, i) {
  2979. if (child.type === 'decl' && child.prop === prop) {
  2980. return callback(child, i);
  2981. }
  2982. });
  2983. }
  2984. }
  2985. /**
  2986. * Traverses the container’s descendant nodes, calling callback
  2987. * for each rule node.
  2988. *
  2989. * If you pass a filter, iteration will only happen over rules
  2990. * with matching selectors.
  2991. *
  2992. * Like {@link Container#each}, this method is safe
  2993. * to use if you are mutating arrays during iteration.
  2994. *
  2995. * @param {string|RegExp} [selector] - string or regular expression
  2996. * to filter rules by selector
  2997. * @param {childIterator} callback - iterator receives each node and index
  2998. *
  2999. * @return {false|undefined} returns `false` if iteration was broke
  3000. *
  3001. * @example
  3002. * const selectors = [];
  3003. * root.walkRules(rule => {
  3004. * selectors.push(rule.selector);
  3005. * });
  3006. * console.log(`Your CSS uses ${selectors.length} selectors`);
  3007. */
  3008. ;
  3009. _proto.walkRules = function walkRules(selector, callback) {
  3010. if (!callback) {
  3011. callback = selector;
  3012. return this.walk(function (child, i) {
  3013. if (child.type === 'rule') {
  3014. return callback(child, i);
  3015. }
  3016. });
  3017. } else if (selector instanceof RegExp) {
  3018. return this.walk(function (child, i) {
  3019. if (child.type === 'rule' && selector.test(child.selector)) {
  3020. return callback(child, i);
  3021. }
  3022. });
  3023. } else {
  3024. return this.walk(function (child, i) {
  3025. if (child.type === 'rule' && child.selector === selector) {
  3026. return callback(child, i);
  3027. }
  3028. });
  3029. }
  3030. }
  3031. /**
  3032. * Traverses the container’s descendant nodes, calling callback
  3033. * for each at-rule node.
  3034. *
  3035. * If you pass a filter, iteration will only happen over at-rules
  3036. * that have matching names.
  3037. *
  3038. * Like {@link Container#each}, this method is safe
  3039. * to use if you are mutating arrays during iteration.
  3040. *
  3041. * @param {string|RegExp} [name] - string or regular expression
  3042. * to filter at-rules by name
  3043. * @param {childIterator} callback - iterator receives each node and index
  3044. *
  3045. * @return {false|undefined} returns `false` if iteration was broke
  3046. *
  3047. * @example
  3048. * root.walkAtRules(rule => {
  3049. * if ( isOld(rule.name) ) rule.remove();
  3050. * });
  3051. *
  3052. * let first = false;
  3053. * root.walkAtRules('charset', rule => {
  3054. * if ( !first ) {
  3055. * first = true;
  3056. * } else {
  3057. * rule.remove();
  3058. * }
  3059. * });
  3060. */
  3061. ;
  3062. _proto.walkAtRules = function walkAtRules(name, callback) {
  3063. if (!callback) {
  3064. callback = name;
  3065. return this.walk(function (child, i) {
  3066. if (child.type === 'atrule') {
  3067. return callback(child, i);
  3068. }
  3069. });
  3070. } else if (name instanceof RegExp) {
  3071. return this.walk(function (child, i) {
  3072. if (child.type === 'atrule' && name.test(child.name)) {
  3073. return callback(child, i);
  3074. }
  3075. });
  3076. } else {
  3077. return this.walk(function (child, i) {
  3078. if (child.type === 'atrule' && child.name === name) {
  3079. return callback(child, i);
  3080. }
  3081. });
  3082. }
  3083. }
  3084. /**
  3085. * Traverses the container’s descendant nodes, calling callback
  3086. * for each comment node.
  3087. *
  3088. * Like {@link Container#each}, this method is safe
  3089. * to use if you are mutating arrays during iteration.
  3090. *
  3091. * @param {childIterator} callback - iterator receives each node and index
  3092. *
  3093. * @return {false|undefined} returns `false` if iteration was broke
  3094. *
  3095. * @example
  3096. * root.walkComments(comment => {
  3097. * comment.remove();
  3098. * });
  3099. */
  3100. ;
  3101. _proto.walkComments = function walkComments(callback) {
  3102. return this.walk(function (child, i) {
  3103. if (child.type === 'comment') {
  3104. return callback(child, i);
  3105. }
  3106. });
  3107. }
  3108. /**
  3109. * Inserts new nodes to the start of the container.
  3110. *
  3111. * @param {...(Node|object|string|Node[])} children - new nodes
  3112. *
  3113. * @return {Node} this node for methods chain
  3114. *
  3115. * @example
  3116. * const decl1 = postcss.decl({ prop: 'color', value: 'black' });
  3117. * const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
  3118. * rule.append(decl1, decl2);
  3119. *
  3120. * root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
  3121. * root.append({ selector: 'a' }); // rule
  3122. * rule.append({ prop: 'color', value: 'black' }); // declaration
  3123. * rule.append({ text: 'Comment' }) // comment
  3124. *
  3125. * root.append('a {}');
  3126. * root.first.append('color: black; z-index: 1');
  3127. */
  3128. ;
  3129. _proto.append = function append() {
  3130. var _this = this;
  3131. for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) {
  3132. children[_key] = arguments[_key];
  3133. }
  3134. children.forEach(function (child) {
  3135. var nodes = _this.normalize(child, _this.last);
  3136. nodes.forEach(function (node) {
  3137. return _this.nodes.push(node);
  3138. });
  3139. });
  3140. return this;
  3141. }
  3142. /**
  3143. * Inserts new nodes to the end of the container.
  3144. *
  3145. * @param {...(Node|object|string|Node[])} children - new nodes
  3146. *
  3147. * @return {Node} this node for methods chain
  3148. *
  3149. * @example
  3150. * const decl1 = postcss.decl({ prop: 'color', value: 'black' });
  3151. * const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
  3152. * rule.prepend(decl1, decl2);
  3153. *
  3154. * root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
  3155. * root.append({ selector: 'a' }); // rule
  3156. * rule.append({ prop: 'color', value: 'black' }); // declaration
  3157. * rule.append({ text: 'Comment' }) // comment
  3158. *
  3159. * root.append('a {}');
  3160. * root.first.append('color: black; z-index: 1');
  3161. */
  3162. ;
  3163. _proto.prepend = function prepend() {
  3164. var _this2 = this;
  3165. for (var _len2 = arguments.length, children = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  3166. children[_key2] = arguments[_key2];
  3167. }
  3168. children = children.reverse();
  3169. children.forEach(function (child) {
  3170. var nodes = _this2.normalize(child, _this2.first, 'prepend').reverse();
  3171. nodes.forEach(function (node) {
  3172. return _this2.nodes.unshift(node);
  3173. });
  3174. for (var id in _this2.indexes) {
  3175. _this2.indexes[id] = _this2.indexes[id] + nodes.length;
  3176. }
  3177. });
  3178. return this;
  3179. };
  3180. _proto.cleanRaws = function cleanRaws(keepBetween) {
  3181. _Node.prototype.cleanRaws.call(this, keepBetween);
  3182. if (this.nodes) {
  3183. this.nodes.forEach(function (node) {
  3184. return node.cleanRaws(keepBetween);
  3185. });
  3186. }
  3187. }
  3188. /**
  3189. * Insert new node before old node within the container.
  3190. *
  3191. * @param {Node|number} exist - child or child’s index.
  3192. * @param {Node|object|string|Node[]} add - new node
  3193. *
  3194. * @return {Node} this node for methods chain
  3195. *
  3196. * @example
  3197. * rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }));
  3198. */
  3199. ;
  3200. _proto.insertBefore = function insertBefore(exist, add) {
  3201. var _this3 = this;
  3202. exist = this.index(exist);
  3203. var type = exist === 0 ? 'prepend' : false;
  3204. var nodes = this.normalize(add, this.nodes[exist], type).reverse();
  3205. nodes.forEach(function (node) {
  3206. return _this3.nodes.splice(exist, 0, node);
  3207. });
  3208. var index;
  3209. for (var id in this.indexes) {
  3210. index = this.indexes[id];
  3211. if (exist <= index) {
  3212. this.indexes[id] = index + nodes.length;
  3213. }
  3214. }
  3215. return this;
  3216. }
  3217. /**
  3218. * Insert new node after old node within the container.
  3219. *
  3220. * @param {Node|number} exist - child or child’s index
  3221. * @param {Node|object|string|Node[]} add - new node
  3222. *
  3223. * @return {Node} this node for methods chain
  3224. */
  3225. ;
  3226. _proto.insertAfter = function insertAfter(exist, add) {
  3227. var _this4 = this;
  3228. exist = this.index(exist);
  3229. var nodes = this.normalize(add, this.nodes[exist]).reverse();
  3230. nodes.forEach(function (node) {
  3231. return _this4.nodes.splice(exist + 1, 0, node);
  3232. });
  3233. var index;
  3234. for (var id in this.indexes) {
  3235. index = this.indexes[id];
  3236. if (exist < index) {
  3237. this.indexes[id] = index + nodes.length;
  3238. }
  3239. }
  3240. return this;
  3241. };
  3242. _proto.remove = function remove(child) {
  3243. if (typeof child !== 'undefined') {
  3244. warnOnce('Container#remove is deprecated. ' + 'Use Container#removeChild');
  3245. this.removeChild(child);
  3246. } else {
  3247. _Node.prototype.remove.call(this);
  3248. }
  3249. return this;
  3250. }
  3251. /**
  3252. * Removes node from the container and cleans the parent properties
  3253. * from the node and its children.
  3254. *
  3255. * @param {Node|number} child - child or child’s index
  3256. *
  3257. * @return {Node} this node for methods chain
  3258. *
  3259. * @example
  3260. * rule.nodes.length //=> 5
  3261. * rule.removeChild(decl);
  3262. * rule.nodes.length //=> 4
  3263. * decl.parent //=> undefined
  3264. */
  3265. ;
  3266. _proto.removeChild = function removeChild(child) {
  3267. child = this.index(child);
  3268. this.nodes[child].parent = undefined;
  3269. this.nodes.splice(child, 1);
  3270. var index;
  3271. for (var id in this.indexes) {
  3272. index = this.indexes[id];
  3273. if (index >= child) {
  3274. this.indexes[id] = index - 1;
  3275. }
  3276. }
  3277. return this;
  3278. }
  3279. /**
  3280. * Removes all children from the container
  3281. * and cleans their parent properties.
  3282. *
  3283. * @return {Node} this node for methods chain
  3284. *
  3285. * @example
  3286. * rule.removeAll();
  3287. * rule.nodes.length //=> 0
  3288. */
  3289. ;
  3290. _proto.removeAll = function removeAll() {
  3291. this.nodes.forEach(function (node) {
  3292. return node.parent = undefined;
  3293. });
  3294. this.nodes = [];
  3295. return this;
  3296. }
  3297. /**
  3298. * Passes all declaration values within the container that match pattern
  3299. * through callback, replacing those values with the returned result
  3300. * of callback.
  3301. *
  3302. * This method is useful if you are using a custom unit or function
  3303. * and need to iterate through all values.
  3304. *
  3305. * @param {string|RegExp} pattern - replace pattern
  3306. * @param {object} opts - options to speed up the search
  3307. * @param {string|string[]} opts.props - an array of property names
  3308. * @param {string} opts.fast - string that’s used
  3309. * to narrow down values and speed up
  3310. the regexp search
  3311. * @param {function|string} callback - string to replace pattern
  3312. * or callback that returns a new
  3313. * value.
  3314. * The callback will receive
  3315. * the same arguments as those
  3316. * passed to a function parameter
  3317. * of `String#replace`.
  3318. *
  3319. * @return {Node} this node for methods chain
  3320. *
  3321. * @example
  3322. * root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
  3323. * return 15 * parseInt(string) + 'px';
  3324. * });
  3325. */
  3326. ;
  3327. _proto.replaceValues = function replaceValues(pattern, opts, callback) {
  3328. if (!callback) {
  3329. callback = opts;
  3330. opts = {};
  3331. }
  3332. this.walkDecls(function (decl) {
  3333. if (opts.props && opts.props.indexOf(decl.prop) === -1) return;
  3334. if (opts.fast && decl.value.indexOf(opts.fast) === -1) return;
  3335. decl.value = decl.value.replace(pattern, callback);
  3336. });
  3337. return this;
  3338. }
  3339. /**
  3340. * Returns `true` if callback returns `true`
  3341. * for all of the container’s children.
  3342. *
  3343. * @param {childCondition} condition - iterator returns true or false.
  3344. *
  3345. * @return {boolean} is every child pass condition
  3346. *
  3347. * @example
  3348. * const noPrefixes = rule.every(i => i.prop[0] !== '-');
  3349. */
  3350. ;
  3351. _proto.every = function every(condition) {
  3352. return this.nodes.every(condition);
  3353. }
  3354. /**
  3355. * Returns `true` if callback returns `true` for (at least) one
  3356. * of the container’s children.
  3357. *
  3358. * @param {childCondition} condition - iterator returns true or false.
  3359. *
  3360. * @return {boolean} is some child pass condition
  3361. *
  3362. * @example
  3363. * const hasPrefix = rule.some(i => i.prop[0] === '-');
  3364. */
  3365. ;
  3366. _proto.some = function some(condition) {
  3367. return this.nodes.some(condition);
  3368. }
  3369. /**
  3370. * Returns a `child`’s index within the {@link Container#nodes} array.
  3371. *
  3372. * @param {Node} child - child of the current container.
  3373. *
  3374. * @return {number} child index
  3375. *
  3376. * @example
  3377. * rule.index( rule.nodes[2] ) //=> 2
  3378. */
  3379. ;
  3380. _proto.index = function index(child) {
  3381. if (typeof child === 'number') {
  3382. return child;
  3383. } else {
  3384. return this.nodes.indexOf(child);
  3385. }
  3386. }
  3387. /**
  3388. * The container’s first child.
  3389. *
  3390. * @type {Node}
  3391. *
  3392. * @example
  3393. * rule.first == rules.nodes[0];
  3394. */
  3395. ;
  3396. _proto.normalize = function normalize(nodes, sample) {
  3397. var _this5 = this;
  3398. if (typeof nodes === 'string') {
  3399. nodes = cleanSource(parse(nodes).nodes);
  3400. } else if (!Array.isArray(nodes)) {
  3401. if (nodes.type === 'root') {
  3402. nodes = nodes.nodes;
  3403. } else if (nodes.type) {
  3404. nodes = [nodes];
  3405. } else if (nodes.prop) {
  3406. if (typeof nodes.value === 'undefined') {
  3407. throw new Error('Value field is missed in node creation');
  3408. } else if (typeof nodes.value !== 'string') {
  3409. nodes.value = String(nodes.value);
  3410. }
  3411. nodes = [new Declaration(nodes)];
  3412. } else if (nodes.selector) {
  3413. nodes = [new Rule(nodes)];
  3414. } else if (nodes.name) {
  3415. nodes = [new AtRule(nodes)];
  3416. } else if (nodes.text) {
  3417. nodes = [new Comment(nodes)];
  3418. } else {
  3419. throw new Error('Unknown node type in node creation');
  3420. }
  3421. }
  3422. var processed = nodes.map(function (i) {
  3423. if (typeof i.raws === 'undefined') i = _this5.rebuild(i);
  3424. if (i.parent) i = i.clone();
  3425. if (typeof i.raws.before === 'undefined') {
  3426. if (sample && typeof sample.raws.before !== 'undefined') {
  3427. i.raws.before = sample.raws.before.replace(/[^\s]/g, '');
  3428. }
  3429. }
  3430. i.parent = _this5;
  3431. return i;
  3432. });
  3433. return processed;
  3434. };
  3435. _proto.rebuild = function rebuild(node, parent) {
  3436. var _this6 = this;
  3437. var fix;
  3438. if (node.type === 'root') {
  3439. fix = new Root();
  3440. } else if (node.type === 'atrule') {
  3441. fix = new AtRule();
  3442. } else if (node.type === 'rule') {
  3443. fix = new Rule();
  3444. } else if (node.type === 'decl') {
  3445. fix = new Declaration();
  3446. } else if (node.type === 'comment') {
  3447. fix = new Comment();
  3448. }
  3449. for (var i in node) {
  3450. if (i === 'nodes') {
  3451. fix.nodes = node.nodes.map(function (j) {
  3452. return _this6.rebuild(j, fix);
  3453. });
  3454. } else if (i === 'parent' && parent) {
  3455. fix.parent = parent;
  3456. } else if (node.hasOwnProperty(i)) {
  3457. fix[i] = node[i];
  3458. }
  3459. }
  3460. return fix;
  3461. };
  3462. _proto.eachInside = function eachInside(callback) {
  3463. warnOnce('Container#eachInside is deprecated. ' + 'Use Container#walk instead.');
  3464. return this.walk(callback);
  3465. };
  3466. _proto.eachDecl = function eachDecl(prop, callback) {
  3467. warnOnce('Container#eachDecl is deprecated. ' + 'Use Container#walkDecls instead.');
  3468. return this.walkDecls(prop, callback);
  3469. };
  3470. _proto.eachRule = function eachRule(selector, callback) {
  3471. warnOnce('Container#eachRule is deprecated. ' + 'Use Container#walkRules instead.');
  3472. return this.walkRules(selector, callback);
  3473. };
  3474. _proto.eachAtRule = function eachAtRule(name, callback) {
  3475. warnOnce('Container#eachAtRule is deprecated. ' + 'Use Container#walkAtRules instead.');
  3476. return this.walkAtRules(name, callback);
  3477. };
  3478. _proto.eachComment = function eachComment(callback) {
  3479. warnOnce('Container#eachComment is deprecated. ' + 'Use Container#walkComments instead.');
  3480. return this.walkComments(callback);
  3481. };
  3482. _createClass(Container, [{
  3483. key: "first",
  3484. get: function get() {
  3485. if (!this.nodes) return undefined;
  3486. return this.nodes[0];
  3487. }
  3488. /**
  3489. * The container’s last child.
  3490. *
  3491. * @type {Node}
  3492. *
  3493. * @example
  3494. * rule.last == rule.nodes[rule.nodes.length - 1];
  3495. */
  3496. }, {
  3497. key: "last",
  3498. get: function get() {
  3499. if (!this.nodes) return undefined;
  3500. return this.nodes[this.nodes.length - 1];
  3501. }
  3502. }, {
  3503. key: "semicolon",
  3504. get: function get() {
  3505. warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon');
  3506. return this.raws.semicolon;
  3507. },
  3508. set: function set(val) {
  3509. warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon');
  3510. this.raws.semicolon = val;
  3511. }
  3512. }, {
  3513. key: "after",
  3514. get: function get() {
  3515. warnOnce('Node#after is deprecated. Use Node#raws.after');
  3516. return this.raws.after;
  3517. },
  3518. set: function set(val) {
  3519. warnOnce('Node#after is deprecated. Use Node#raws.after');
  3520. this.raws.after = val;
  3521. }
  3522. /**
  3523. * @memberof Container#
  3524. * @member {Node[]} nodes - an array containing the container’s children
  3525. *
  3526. * @example
  3527. * const root = postcss.parse('a { color: black }');
  3528. * root.nodes.length //=> 1
  3529. * root.nodes[0].selector //=> 'a'
  3530. * root.nodes[0].nodes[0].prop //=> 'color'
  3531. */
  3532. }]);
  3533. return Container;
  3534. }(Node);
  3535. /**
  3536. * Represents an at-rule.
  3537. *
  3538. * If it’s followed in the CSS by a {} block, this node will have
  3539. * a nodes property representing its children.
  3540. *
  3541. * @extends Container
  3542. *
  3543. * @example
  3544. * const root = postcss.parse('@charset "UTF-8"; @media print {}');
  3545. *
  3546. * const charset = root.first;
  3547. * charset.type //=> 'atrule'
  3548. * charset.nodes //=> undefined
  3549. *
  3550. * const media = root.last;
  3551. * media.nodes //=> []
  3552. */
  3553. var AtRule =
  3554. /*#__PURE__*/
  3555. function (_Container) {
  3556. _inheritsLoose(AtRule, _Container);
  3557. function AtRule(defaults) {
  3558. var _this;
  3559. _this = _Container.call(this, defaults) || this;
  3560. _this.type = 'atrule';
  3561. return _this;
  3562. }
  3563. var _proto = AtRule.prototype;
  3564. _proto.append = function append() {
  3565. var _Container$prototype$;
  3566. if (!this.nodes) this.nodes = [];
  3567. for (var _len = arguments.length, children = new Array(_len), _key = 0; _key < _len; _key++) {
  3568. children[_key] = arguments[_key];
  3569. }
  3570. return (_Container$prototype$ = _Container.prototype.append).call.apply(_Container$prototype$, [this].concat(children));
  3571. };
  3572. _proto.prepend = function prepend() {
  3573. var _Container$prototype$2;
  3574. if (!this.nodes) this.nodes = [];
  3575. for (var _len2 = arguments.length, children = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
  3576. children[_key2] = arguments[_key2];
  3577. }
  3578. return (_Container$prototype$2 = _Container.prototype.prepend).call.apply(_Container$prototype$2, [this].concat(children));
  3579. };
  3580. _createClass(AtRule, [{
  3581. key: "afterName",
  3582. get: function get() {
  3583. warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName');
  3584. return this.raws.afterName;
  3585. },
  3586. set: function set(val) {
  3587. warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName');
  3588. this.raws.afterName = val;
  3589. }
  3590. }, {
  3591. key: "_params",
  3592. get: function get() {
  3593. warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params');
  3594. return this.raws.params;
  3595. },
  3596. set: function set(val) {
  3597. warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params');
  3598. this.raws.params = val;
  3599. }
  3600. /**
  3601. * @memberof AtRule#
  3602. * @member {string} name - the at-rule’s name immediately follows the `@`
  3603. *
  3604. * @example
  3605. * const root = postcss.parse('@media print {}');
  3606. * media.name //=> 'media'
  3607. * const media = root.first;
  3608. */
  3609. /**
  3610. * @memberof AtRule#
  3611. * @member {string} params - the at-rule’s parameters, the values
  3612. * that follow the at-rule’s name but precede
  3613. * any {} block
  3614. *
  3615. * @example
  3616. * const root = postcss.parse('@media print, screen {}');
  3617. * const media = root.first;
  3618. * media.params //=> 'print, screen'
  3619. */
  3620. /**
  3621. * @memberof AtRule#
  3622. * @member {object} raws - Information to generate byte-to-byte equal
  3623. * node string as it was in the origin input.
  3624. *
  3625. * Every parser saves its own properties,
  3626. * but the default CSS parser uses:
  3627. *
  3628. * * `before`: the space symbols before the node. It also stores `*`
  3629. * and `_` symbols before the declaration (IE hack).
  3630. * * `after`: the space symbols after the last child of the node
  3631. * to the end of the node.
  3632. * * `between`: the symbols between the property and value
  3633. * for declarations, selector and `{` for rules, or last parameter
  3634. * and `{` for at-rules.
  3635. * * `semicolon`: contains true if the last child has
  3636. * an (optional) semicolon.
  3637. * * `afterName`: the space between the at-rule name and its parameters.
  3638. *
  3639. * PostCSS cleans at-rule parameters from comments and extra spaces,
  3640. * but it stores origin content in raws properties.
  3641. * As such, if you don’t change a declaration’s value,
  3642. * PostCSS will use the raw value with comments.
  3643. *
  3644. * @example
  3645. * const root = postcss.parse(' @media\nprint {\n}')
  3646. * root.first.first.raws //=> { before: ' ',
  3647. * // between: ' ',
  3648. * // afterName: '\n',
  3649. * // after: '\n' }
  3650. */
  3651. }]);
  3652. return AtRule;
  3653. }(Container);
  3654. //
  3655. /**
  3656. * Contains helpers for safely splitting lists of CSS values,
  3657. * preserving parentheses and quotes.
  3658. *
  3659. * @example
  3660. * const list = postcss.list;
  3661. *
  3662. * @namespace list
  3663. */
  3664. var list = {
  3665. split: function split(string, separators, last) {
  3666. var array = [];
  3667. var current = '';
  3668. var split = false;
  3669. var func = 0;
  3670. var quote = false;
  3671. var escape = false;
  3672. for (var i = 0; i < string.length; i++) {
  3673. var letter = string[i];
  3674. if (quote) {
  3675. if (escape) {
  3676. escape = false;
  3677. } else if (letter === '\\') {
  3678. escape = true;
  3679. } else if (letter === quote) {
  3680. quote = false;
  3681. }
  3682. } else if (letter === '"' || letter === "'") {
  3683. quote = letter;
  3684. } else if (letter === '(') {
  3685. func += 1;
  3686. } else if (letter === ')') {
  3687. if (func > 0) func -= 1;
  3688. } else if (func === 0) {
  3689. if (separators.indexOf(letter) !== -1) split = true;
  3690. }
  3691. if (split) {
  3692. if (current !== '') array.push(current.trim());
  3693. current = '';
  3694. split = false;
  3695. } else {
  3696. current += letter;
  3697. }
  3698. }
  3699. if (last || current !== '') array.push(current.trim());
  3700. return array;
  3701. },
  3702. /**
  3703. * Safely splits space-separated values (such as those for `background`,
  3704. * `border-radius`, and other shorthand properties).
  3705. *
  3706. * @param {string} string - space-separated values
  3707. *
  3708. * @return {string[]} splitted values
  3709. *
  3710. * @example
  3711. * postcss.list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
  3712. */
  3713. space: function space(string) {
  3714. var spaces = [' ', '\n', '\t'];
  3715. return list.split(string, spaces);
  3716. },
  3717. /**
  3718. * Safely splits comma-separated values (such as those for `transition-*`
  3719. * and `background` properties).
  3720. *
  3721. * @param {string} string - comma-separated values
  3722. *
  3723. * @return {string[]} splitted values
  3724. *
  3725. * @example
  3726. * postcss.list.comma('black, linear-gradient(white, black)')
  3727. * //=> ['black', 'linear-gradient(white, black)']
  3728. */
  3729. comma: function comma(string) {
  3730. var comma = ',';
  3731. return list.split(string, [comma], true);
  3732. }
  3733. };
  3734. /**
  3735. * Represents a CSS rule: a selector followed by a declaration block.
  3736. *
  3737. * @extends Container
  3738. *
  3739. * @example
  3740. * const root = postcss.parse('a{}');
  3741. * const rule = root.first;
  3742. * rule.type //=> 'rule'
  3743. * rule.toString() //=> 'a{}'
  3744. */
  3745. var Rule =
  3746. /*#__PURE__*/
  3747. function (_Container) {
  3748. _inheritsLoose(Rule, _Container);
  3749. function Rule(defaults) {
  3750. var _this;
  3751. _this = _Container.call(this, defaults) || this;
  3752. _this.type = 'rule';
  3753. if (!_this.nodes) _this.nodes = [];
  3754. return _this;
  3755. }
  3756. /**
  3757. * An array containing the rule’s individual selectors.
  3758. * Groups of selectors are split at commas.
  3759. *
  3760. * @type {string[]}
  3761. *
  3762. * @example
  3763. * const root = postcss.parse('a, b { }');
  3764. * const rule = root.first;
  3765. *
  3766. * rule.selector //=> 'a, b'
  3767. * rule.selectors //=> ['a', 'b']
  3768. *
  3769. * rule.selectors = ['a', 'strong'];
  3770. * rule.selector //=> 'a, strong'
  3771. */
  3772. _createClass(Rule, [{
  3773. key: "selectors",
  3774. get: function get() {
  3775. return list.comma(this.selector);
  3776. },
  3777. set: function set(values) {
  3778. var match = this.selector ? this.selector.match(/,\s*/) : null;
  3779. var sep = match ? match[0] : "," + this.raw('between', 'beforeOpen');
  3780. this.selector = values.join(sep);
  3781. }
  3782. }, {
  3783. key: "_selector",
  3784. get: function get() {
  3785. warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector');
  3786. return this.raws.selector;
  3787. },
  3788. set: function set(val) {
  3789. warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector');
  3790. this.raws.selector = val;
  3791. }
  3792. /**
  3793. * @memberof Rule#
  3794. * @member {string} selector - the rule’s full selector represented
  3795. * as a string
  3796. *
  3797. * @example
  3798. * const root = postcss.parse('a, b { }');
  3799. * const rule = root.first;
  3800. * rule.selector //=> 'a, b'
  3801. */
  3802. /**
  3803. * @memberof Rule#
  3804. * @member {object} raws - Information to generate byte-to-byte equal
  3805. * node string as it was in the origin input.
  3806. *
  3807. * Every parser saves its own properties,
  3808. * but the default CSS parser uses:
  3809. *
  3810. * * `before`: the space symbols before the node. It also stores `*`
  3811. * and `_` symbols before the declaration (IE hack).
  3812. * * `after`: the space symbols after the last child of the node
  3813. * to the end of the node.
  3814. * * `between`: the symbols between the property and value
  3815. * for declarations, selector and `{` for rules, or last parameter
  3816. * and `{` for at-rules.
  3817. * * `semicolon`: contains true if the last child has
  3818. * an (optional) semicolon.
  3819. *
  3820. * PostCSS cleans selectors from comments and extra spaces,
  3821. * but it stores origin content in raws properties.
  3822. * As such, if you don’t change a declaration’s value,
  3823. * PostCSS will use the raw value with comments.
  3824. *
  3825. * @example
  3826. * const root = postcss.parse('a {\n color:black\n}')
  3827. * root.first.first.raws //=> { before: '', between: ' ', after: '\n' }
  3828. */
  3829. }]);
  3830. return Rule;
  3831. }(Container);
  3832. //
  3833. /**
  3834. * Represents a plugin’s warning. It can be created using {@link Node#warn}.
  3835. *
  3836. * @example
  3837. * if ( decl.important ) {
  3838. * decl.warn(result, 'Avoid !important', { word: '!important' });
  3839. * }
  3840. */
  3841. var Warning =
  3842. /*#__PURE__*/
  3843. function () {
  3844. /**
  3845. * @param {string} text - warning message
  3846. * @param {Object} [opts] - warning options
  3847. * @param {Node} opts.node - CSS node that caused the warning
  3848. * @param {string} opts.word - word in CSS source that caused the warning
  3849. * @param {number} opts.index - index in CSS node string that caused
  3850. * the warning
  3851. * @param {string} opts.plugin - name of the plugin that created
  3852. * this warning. {@link Result#warn} fills
  3853. * this property automatically.
  3854. */
  3855. function Warning(text, opts) {
  3856. if (opts === void 0) {
  3857. opts = {};
  3858. }
  3859. /**
  3860. * @member {string} - Type to filter warnings from
  3861. * {@link Result#messages}. Always equal
  3862. * to `"warning"`.
  3863. *
  3864. * @example
  3865. * const nonWarning = result.messages.filter(i => i.type !== 'warning')
  3866. */
  3867. this.type = 'warning';
  3868. /**
  3869. * @member {string} - The warning message.
  3870. *
  3871. * @example
  3872. * warning.text //=> 'Try to avoid !important'
  3873. */
  3874. this.text = text;
  3875. if (opts.node && opts.node.source) {
  3876. var pos = opts.node.positionBy(opts);
  3877. /**
  3878. * @member {number} - Line in the input file
  3879. * with this warning’s source
  3880. *
  3881. * @example
  3882. * warning.line //=> 5
  3883. */
  3884. this.line = pos.line;
  3885. /**
  3886. * @member {number} - Column in the input file
  3887. * with this warning’s source.
  3888. *
  3889. * @example
  3890. * warning.column //=> 6
  3891. */
  3892. this.column = pos.column;
  3893. }
  3894. for (var opt in opts) {
  3895. this[opt] = opts[opt];
  3896. }
  3897. }
  3898. /**
  3899. * Returns a warning position and message.
  3900. *
  3901. * @example
  3902. * warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
  3903. *
  3904. * @return {string} warning position and message
  3905. */
  3906. var _proto = Warning.prototype;
  3907. _proto.toString = function toString() {
  3908. if (this.node) {
  3909. return this.node.error(this.text, {
  3910. plugin: this.plugin,
  3911. index: this.index,
  3912. word: this.word
  3913. }).message;
  3914. } else if (this.plugin) {
  3915. return this.plugin + ": " + this.text;
  3916. } else {
  3917. return this.text;
  3918. }
  3919. }
  3920. /**
  3921. * @memberof Warning#
  3922. * @member {string} plugin - The name of the plugin that created
  3923. * it will fill this property automatically.
  3924. * this warning. When you call {@link Node#warn}
  3925. *
  3926. * @example
  3927. * warning.plugin //=> 'postcss-important'
  3928. */
  3929. /**
  3930. * @memberof Warning#
  3931. * @member {Node} node - Contains the CSS node that caused the warning.
  3932. *
  3933. * @example
  3934. * warning.node.toString() //=> 'color: white !important'
  3935. */
  3936. ;
  3937. return Warning;
  3938. }();
  3939. /**
  3940. * @typedef {object} Message
  3941. * @property {string} type - message type
  3942. * @property {string} plugin - source PostCSS plugin name
  3943. */
  3944. /**
  3945. * Provides the result of the PostCSS transformations.
  3946. *
  3947. * A Result instance is returned by {@link LazyResult#then}
  3948. * or {@link Root#toResult} methods.
  3949. *
  3950. * @example
  3951. * postcss([cssnext]).process(css).then(function (result) {
  3952. * console.log(result.css);
  3953. * });
  3954. *
  3955. * @example
  3956. * var result2 = postcss.parse(css).toResult();
  3957. */
  3958. var Result =
  3959. /*#__PURE__*/
  3960. function () {
  3961. /**
  3962. * @param {Processor} processor - processor used for this transformation.
  3963. * @param {Root} root - Root node after all transformations.
  3964. * @param {processOptions} opts - options from the {@link Processor#process}
  3965. * or {@link Root#toResult}
  3966. */
  3967. function Result(processor, root, opts) {
  3968. /**
  3969. * @member {Processor} - The Processor instance used
  3970. * for this transformation.
  3971. *
  3972. * @example
  3973. * for ( let plugin of result.processor.plugins) {
  3974. * if ( plugin.postcssPlugin === 'postcss-bad' ) {
  3975. * throw 'postcss-good is incompatible with postcss-bad';
  3976. * }
  3977. * });
  3978. */
  3979. this.processor = processor;
  3980. /**
  3981. * @member {Message[]} - Contains messages from plugins
  3982. * (e.g., warnings or custom messages).
  3983. * Each message should have type
  3984. * and plugin properties.
  3985. *
  3986. * @example
  3987. * postcss.plugin('postcss-min-browser', () => {
  3988. * return (root, result) => {
  3989. * var browsers = detectMinBrowsersByCanIUse(root);
  3990. * result.messages.push({
  3991. * type: 'min-browser',
  3992. * plugin: 'postcss-min-browser',
  3993. * browsers: browsers
  3994. * });
  3995. * };
  3996. * });
  3997. */
  3998. this.messages = [];
  3999. /**
  4000. * @member {Root} - Root node after all transformations.
  4001. *
  4002. * @example
  4003. * root.toResult().root == root;
  4004. */
  4005. this.root = root;
  4006. /**
  4007. * @member {processOptions} - Options from the {@link Processor#process}
  4008. * or {@link Root#toResult} call
  4009. * that produced this Result instance.
  4010. *
  4011. * @example
  4012. * root.toResult(opts).opts == opts;
  4013. */
  4014. this.opts = opts;
  4015. /**
  4016. * @member {string} - A CSS string representing of {@link Result#root}.
  4017. *
  4018. * @example
  4019. * postcss.parse('a{}').toResult().css //=> "a{}"
  4020. */
  4021. this.css = undefined;
  4022. /**
  4023. * @member {SourceMapGenerator} - An instance of `SourceMapGenerator`
  4024. * class from the `source-map` library,
  4025. * representing changes
  4026. * to the {@link Result#root} instance.
  4027. *
  4028. * @example
  4029. * result.map.toJSON() //=> { version: 3, file: 'a.css', … }
  4030. *
  4031. * @example
  4032. * if ( result.map ) {
  4033. * fs.writeFileSync(result.opts.to + '.map', result.map.toString());
  4034. * }
  4035. */
  4036. this.map = undefined;
  4037. }
  4038. /**
  4039. * Returns for @{link Result#css} content.
  4040. *
  4041. * @example
  4042. * result + '' === result.css
  4043. *
  4044. * @return {string} string representing of {@link Result#root}
  4045. */
  4046. var _proto = Result.prototype;
  4047. _proto.toString = function toString() {
  4048. return this.css;
  4049. }
  4050. /**
  4051. * Creates an instance of {@link Warning} and adds it
  4052. * to {@link Result#messages}.
  4053. *
  4054. * @param {string} text - warning message
  4055. * @param {Object} [opts] - warning options
  4056. * @param {Node} opts.node - CSS node that caused the warning
  4057. * @param {string} opts.word - word in CSS source that caused the warning
  4058. * @param {number} opts.index - index in CSS node string that caused
  4059. * the warning
  4060. * @param {string} opts.plugin - name of the plugin that created
  4061. * this warning. {@link Result#warn} fills
  4062. * this property automatically.
  4063. *
  4064. * @return {Warning} created warning
  4065. */
  4066. ;
  4067. _proto.warn = function warn(text, opts) {
  4068. if (opts === void 0) {
  4069. opts = {};
  4070. }
  4071. if (!opts.plugin) {
  4072. if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
  4073. opts.plugin = this.lastPlugin.postcssPlugin;
  4074. }
  4075. }
  4076. var warning = new Warning(text, opts);
  4077. this.messages.push(warning);
  4078. return warning;
  4079. }
  4080. /**
  4081. * Returns warnings from plugins. Filters {@link Warning} instances
  4082. * from {@link Result#messages}.
  4083. *
  4084. * @example
  4085. * result.warnings().forEach(warn => {
  4086. * console.warn(warn.toString());
  4087. * });
  4088. *
  4089. * @return {Warning[]} warnings from plugins
  4090. */
  4091. ;
  4092. _proto.warnings = function warnings() {
  4093. return this.messages.filter(function (i) {
  4094. return i.type === 'warning';
  4095. });
  4096. }
  4097. /**
  4098. * An alias for the {@link Result#css} property.
  4099. * Use it with syntaxes that generate non-CSS output.
  4100. * @type {string}
  4101. *
  4102. * @example
  4103. * result.css === result.content;
  4104. */
  4105. ;
  4106. _createClass(Result, [{
  4107. key: "content",
  4108. get: function get() {
  4109. return this.css;
  4110. }
  4111. }]);
  4112. return Result;
  4113. }();
  4114. function isPromise(obj) {
  4115. return typeof obj === 'object' && typeof obj.then === 'function';
  4116. }
  4117. /**
  4118. * @callback onFulfilled
  4119. * @param {Result} result
  4120. */
  4121. /**
  4122. * @callback onRejected
  4123. * @param {Error} error
  4124. */
  4125. /**
  4126. * A Promise proxy for the result of PostCSS transformations.
  4127. *
  4128. * A `LazyResult` instance is returned by {@link Processor#process}.
  4129. *
  4130. * @example
  4131. * const lazy = postcss([cssnext]).process(css);
  4132. */
  4133. var LazyResult =
  4134. /*#__PURE__*/
  4135. function () {
  4136. function LazyResult(processor, css, opts) {
  4137. this.stringified = false;
  4138. this.processed = false;
  4139. var root;
  4140. if (typeof css === 'object' && css.type === 'root') {
  4141. root = css;
  4142. } else if (css instanceof LazyResult || css instanceof Result) {
  4143. root = css.root;
  4144. if (css.map) {
  4145. if (typeof opts.map === 'undefined') opts.map = {};
  4146. if (!opts.map.inline) opts.map.inline = false;
  4147. opts.map.prev = css.map;
  4148. }
  4149. } else {
  4150. var parser = parse;
  4151. if (opts.syntax) parser = opts.syntax.parse;
  4152. if (opts.parser) parser = opts.parser;
  4153. if (parser.parse) parser = parser.parse;
  4154. try {
  4155. root = parser(css, opts);
  4156. } catch (error) {
  4157. this.error = error;
  4158. }
  4159. }
  4160. this.result = new Result(processor, root, opts);
  4161. }
  4162. /**
  4163. * Returns a {@link Processor} instance, which will be used
  4164. * for CSS transformations.
  4165. * @type {Processor}
  4166. */
  4167. var _proto = LazyResult.prototype;
  4168. /**
  4169. * Processes input CSS through synchronous plugins
  4170. * and calls {@link Result#warnings()}.
  4171. *
  4172. * @return {Warning[]} warnings from plugins
  4173. */
  4174. _proto.warnings = function warnings() {
  4175. return this.sync().warnings();
  4176. }
  4177. /**
  4178. * Alias for the {@link LazyResult#css} property.
  4179. *
  4180. * @example
  4181. * lazy + '' === lazy.css;
  4182. *
  4183. * @return {string} output CSS
  4184. */
  4185. ;
  4186. _proto.toString = function toString() {
  4187. return this.css;
  4188. }
  4189. /**
  4190. * Processes input CSS through synchronous and asynchronous plugins
  4191. * and calls `onFulfilled` with a Result instance. If a plugin throws
  4192. * an error, the `onRejected` callback will be executed.
  4193. *
  4194. * It implements standard Promise API.
  4195. *
  4196. * @param {onFulfilled} onFulfilled - callback will be executed
  4197. * when all plugins will finish work
  4198. * @param {onRejected} onRejected - callback will be execited on any error
  4199. *
  4200. * @return {Promise} Promise API to make queue
  4201. *
  4202. * @example
  4203. * postcss([cssnext]).process(css).then(result => {
  4204. * console.log(result.css);
  4205. * });
  4206. */
  4207. ;
  4208. _proto.then = function then(onFulfilled, onRejected) {
  4209. return this.async().then(onFulfilled, onRejected);
  4210. }
  4211. /**
  4212. * Processes input CSS through synchronous and asynchronous plugins
  4213. * and calls onRejected for each error thrown in any plugin.
  4214. *
  4215. * It implements standard Promise API.
  4216. *
  4217. * @param {onRejected} onRejected - callback will be execited on any error
  4218. *
  4219. * @return {Promise} Promise API to make queue
  4220. *
  4221. * @example
  4222. * postcss([cssnext]).process(css).then(result => {
  4223. * console.log(result.css);
  4224. * }).catch(error => {
  4225. * console.error(error);
  4226. * });
  4227. */
  4228. ;
  4229. _proto["catch"] = function _catch(onRejected) {
  4230. return this.async()["catch"](onRejected);
  4231. };
  4232. _proto.handleError = function handleError(error, plugin) {
  4233. try {
  4234. this.error = error;
  4235. if (error.name === 'CssSyntaxError' && !error.plugin) {
  4236. error.plugin = plugin.postcssPlugin;
  4237. error.setMessage();
  4238. } else if (plugin.postcssVersion) {
  4239. var pluginName = plugin.postcssPlugin;
  4240. var pluginVer = plugin.postcssVersion;
  4241. var runtimeVer = this.result.processor.version;
  4242. var a = pluginVer.split('.');
  4243. var b = runtimeVer.split('.');
  4244. if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
  4245. warnOnce("" + ('Your current PostCSS version ' + 'is ') + runtimeVer + ", but " + pluginName + " " + ("uses " + pluginVer + ". Perhaps this is ") + "the source of the error below.");
  4246. }
  4247. }
  4248. } catch (err) {
  4249. if (console && console.error) console.error(err);
  4250. }
  4251. };
  4252. _proto.asyncTick = function asyncTick(resolve, reject) {
  4253. var _this = this;
  4254. if (this.plugin >= this.processor.plugins.length) {
  4255. this.processed = true;
  4256. return resolve();
  4257. }
  4258. try {
  4259. var plugin = this.processor.plugins[this.plugin];
  4260. var promise = this.run(plugin);
  4261. this.plugin += 1;
  4262. if (isPromise(promise)) {
  4263. promise.then(function () {
  4264. _this.asyncTick(resolve, reject);
  4265. })["catch"](function (error) {
  4266. _this.handleError(error, plugin);
  4267. _this.processed = true;
  4268. reject(error);
  4269. });
  4270. } else {
  4271. this.asyncTick(resolve, reject);
  4272. }
  4273. } catch (error) {
  4274. this.processed = true;
  4275. reject(error);
  4276. }
  4277. };
  4278. _proto.async = function async() {
  4279. var _this2 = this;
  4280. if (this.processed) {
  4281. return new Promise(function (resolve, reject) {
  4282. if (_this2.error) {
  4283. reject(_this2.error);
  4284. } else {
  4285. resolve(_this2.stringify());
  4286. }
  4287. });
  4288. }
  4289. if (this.processing) {
  4290. return this.processing;
  4291. }
  4292. this.processing = new Promise(function (resolve, reject) {
  4293. if (_this2.error) return reject(_this2.error);
  4294. _this2.plugin = 0;
  4295. _this2.asyncTick(resolve, reject);
  4296. }).then(function () {
  4297. _this2.processed = true;
  4298. return _this2.stringify();
  4299. });
  4300. return this.processing;
  4301. };
  4302. _proto.sync = function sync() {
  4303. var _this3 = this;
  4304. if (this.processed) return this.result;
  4305. this.processed = true;
  4306. if (this.processing) {
  4307. throw new Error('Use process(css).then(cb) to work with async plugins');
  4308. }
  4309. if (this.error) throw this.error;
  4310. this.result.processor.plugins.forEach(function (plugin) {
  4311. var promise = _this3.run(plugin);
  4312. if (isPromise(promise)) {
  4313. throw new Error('Use process(css).then(cb) to work with async plugins');
  4314. }
  4315. });
  4316. return this.result;
  4317. };
  4318. _proto.run = function run(plugin) {
  4319. this.result.lastPlugin = plugin;
  4320. try {
  4321. return plugin(this.result.root, this.result);
  4322. } catch (error) {
  4323. this.handleError(error, plugin);
  4324. throw error;
  4325. }
  4326. };
  4327. _proto.stringify = function stringify$1() {
  4328. if (this.stringified) return this.result;
  4329. this.stringified = true;
  4330. this.sync();
  4331. var opts = this.result.opts;
  4332. var str = stringify;
  4333. if (opts.syntax) str = opts.syntax.stringify;
  4334. if (opts.stringifier) str = opts.stringifier;
  4335. if (str.stringify) str = str.stringify;
  4336. var result = '';
  4337. str(this.root, function (i) {
  4338. result += i;
  4339. });
  4340. this.result.css = result;
  4341. return this.result;
  4342. };
  4343. _createClass(LazyResult, [{
  4344. key: "processor",
  4345. get: function get() {
  4346. return this.result.processor;
  4347. }
  4348. /**
  4349. * Options from the {@link Processor#process} call.
  4350. * @type {processOptions}
  4351. */
  4352. }, {
  4353. key: "opts",
  4354. get: function get() {
  4355. return this.result.opts;
  4356. }
  4357. /**
  4358. * Processes input CSS through synchronous plugins, converts `Root`
  4359. * to a CSS string and returns {@link Result#css}.
  4360. *
  4361. * This property will only work with synchronous plugins.
  4362. * If the processor contains any asynchronous plugins
  4363. * it will throw an error. This is why this method is only
  4364. * for debug purpose, you should always use {@link LazyResult#then}.
  4365. *
  4366. * @type {string}
  4367. * @see Result#css
  4368. */
  4369. }, {
  4370. key: "css",
  4371. get: function get() {
  4372. return this.stringify().css;
  4373. }
  4374. /**
  4375. * An alias for the `css` property. Use it with syntaxes
  4376. * that generate non-CSS output.
  4377. *
  4378. * This property will only work with synchronous plugins.
  4379. * If the processor contains any asynchronous plugins
  4380. * it will throw an error. This is why this method is only
  4381. * for debug purpose, you should always use {@link LazyResult#then}.
  4382. *
  4383. * @type {string}
  4384. * @see Result#content
  4385. */
  4386. }, {
  4387. key: "content",
  4388. get: function get() {
  4389. return this.stringify().content;
  4390. }
  4391. /**
  4392. * Processes input CSS through synchronous plugins
  4393. * and returns {@link Result#map}.
  4394. *
  4395. * This property will only work with synchronous plugins.
  4396. * If the processor contains any asynchronous plugins
  4397. * it will throw an error. This is why this method is only
  4398. * for debug purpose, you should always use {@link LazyResult#then}.
  4399. *
  4400. * @type {SourceMapGenerator}
  4401. * @see Result#map
  4402. */
  4403. }, {
  4404. key: "map",
  4405. get: function get() {
  4406. return this.stringify().map;
  4407. }
  4408. /**
  4409. * Processes input CSS through synchronous plugins
  4410. * and returns {@link Result#root}.
  4411. *
  4412. * This property will only work with synchronous plugins. If the processor
  4413. * contains any asynchronous plugins it will throw an error.
  4414. *
  4415. * This is why this method is only for debug purpose,
  4416. * you should always use {@link LazyResult#then}.
  4417. *
  4418. * @type {Root}
  4419. * @see Result#root
  4420. */
  4421. }, {
  4422. key: "root",
  4423. get: function get() {
  4424. return this.sync().root;
  4425. }
  4426. /**
  4427. * Processes input CSS through synchronous plugins
  4428. * and returns {@link Result#messages}.
  4429. *
  4430. * This property will only work with synchronous plugins. If the processor
  4431. * contains any asynchronous plugins it will throw an error.
  4432. *
  4433. * This is why this method is only for debug purpose,
  4434. * you should always use {@link LazyResult#then}.
  4435. *
  4436. * @type {Message[]}
  4437. * @see Result#messages
  4438. */
  4439. }, {
  4440. key: "messages",
  4441. get: function get() {
  4442. return this.sync().messages;
  4443. }
  4444. }]);
  4445. return LazyResult;
  4446. }();
  4447. //
  4448. /**
  4449. * @callback builder
  4450. * @param {string} part - part of generated CSS connected to this node
  4451. * @param {Node} node - AST node
  4452. * @param {"start"|"end"} [type] - node’s part type
  4453. */
  4454. /**
  4455. * @callback parser
  4456. *
  4457. * @param {string|toString} css - string with input CSS or any object
  4458. * with toString() method, like a Buffer
  4459. * @param {processOptions} [opts] - options with only `from` and `map` keys
  4460. *
  4461. * @return {Root} PostCSS AST
  4462. */
  4463. /**
  4464. * @callback stringifier
  4465. *
  4466. * @param {Node} node - start node for stringifing. Usually {@link Root}.
  4467. * @param {builder} builder - function to concatenate CSS from node’s parts
  4468. * or generate string and source map
  4469. *
  4470. * @return {void}
  4471. */
  4472. /**
  4473. * @typedef {object} syntax
  4474. * @property {parser} parse - function to generate AST by string
  4475. * @property {stringifier} stringify - function to generate string by AST
  4476. */
  4477. /**
  4478. * @typedef {object} toString
  4479. * @property {function} toString
  4480. */
  4481. /**
  4482. * @callback pluginFunction
  4483. * @param {Root} root - parsed input CSS
  4484. * @param {Result} result - result to set warnings or check other plugins
  4485. */
  4486. /**
  4487. * @typedef {object} Plugin
  4488. * @property {function} postcss - PostCSS plugin function
  4489. */
  4490. /**
  4491. * @typedef {object} processOptions
  4492. * @property {string} from - the path of the CSS source file.
  4493. * You should always set `from`,
  4494. * because it is used in source map
  4495. * generation and syntax error messages.
  4496. * @property {string} to - the path where you’ll put the output
  4497. * CSS file. You should always set `to`
  4498. * to generate correct source maps.
  4499. * @property {parser} parser - function to generate AST by string
  4500. * @property {stringifier} stringifier - class to generate string by AST
  4501. * @property {syntax} syntax - object with `parse` and `stringify`
  4502. * @property {object} map - source map options
  4503. * @property {boolean} map.inline - does source map should
  4504. * be embedded in the output
  4505. * CSS as a base64-encoded
  4506. * comment
  4507. * @property {string|object|false|function} map.prev - source map content
  4508. * from a previous
  4509. * processing step
  4510. * (for example, Sass).
  4511. * PostCSS will try to find
  4512. * previous map
  4513. * automatically, so you
  4514. * could disable it by
  4515. * `false` value.
  4516. * @property {boolean} map.sourcesContent - does PostCSS should set
  4517. * the origin content to map
  4518. * @property {string|false} map.annotation - does PostCSS should set
  4519. * annotation comment to map
  4520. * @property {string} map.from - override `from` in map’s
  4521. * `sources`
  4522. */
  4523. /**
  4524. * Contains plugins to process CSS. Create one `Processor` instance,
  4525. * initialize its plugins, and then use that instance on numerous CSS files.
  4526. *
  4527. * @example
  4528. * const processor = postcss([autoprefixer, precss]);
  4529. * processor.process(css1).then(result => console.log(result.css));
  4530. * processor.process(css2).then(result => console.log(result.css));
  4531. */
  4532. var Processor =
  4533. /*#__PURE__*/
  4534. function () {
  4535. /**
  4536. * @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS
  4537. * plugins. See {@link Processor#use} for plugin format.
  4538. */
  4539. function Processor(plugins) {
  4540. if (plugins === void 0) {
  4541. plugins = [];
  4542. }
  4543. /**
  4544. * @member {string} - Current PostCSS version.
  4545. *
  4546. * @example
  4547. * if ( result.processor.version.split('.')[0] !== '5' ) {
  4548. * throw new Error('This plugin works only with PostCSS 5');
  4549. * }
  4550. */
  4551. this.version = '5.2.0';
  4552. /**
  4553. * @member {pluginFunction[]} - Plugins added to this processor.
  4554. *
  4555. * @example
  4556. * const processor = postcss([autoprefixer, precss]);
  4557. * processor.plugins.length //=> 2
  4558. */
  4559. this.plugins = this.normalize(plugins);
  4560. }
  4561. /**
  4562. * Adds a plugin to be used as a CSS processor.
  4563. *
  4564. * PostCSS plugin can be in 4 formats:
  4565. * * A plugin created by {@link postcss.plugin} method.
  4566. * * A function. PostCSS will pass the function a @{link Root}
  4567. * as the first argument and current {@link Result} instance
  4568. * as the second.
  4569. * * An object with a `postcss` method. PostCSS will use that method
  4570. * as described in #2.
  4571. * * Another {@link Processor} instance. PostCSS will copy plugins
  4572. * from that instance into this one.
  4573. *
  4574. * Plugins can also be added by passing them as arguments when creating
  4575. * a `postcss` instance (see [`postcss(plugins)`]).
  4576. *
  4577. * Asynchronous plugins should return a `Promise` instance.
  4578. *
  4579. * @param {Plugin|pluginFunction|Processor} plugin - PostCSS plugin
  4580. * or {@link Processor}
  4581. * with plugins
  4582. *
  4583. * @example
  4584. * const processor = postcss()
  4585. * .use(autoprefixer)
  4586. * .use(precss);
  4587. *
  4588. * @return {Processes} current processor to make methods chain
  4589. */
  4590. var _proto = Processor.prototype;
  4591. _proto.use = function use(plugin) {
  4592. this.plugins = this.plugins.concat(this.normalize([plugin]));
  4593. return this;
  4594. }
  4595. /**
  4596. * Parses source CSS and returns a {@link LazyResult} Promise proxy.
  4597. * Because some plugins can be asynchronous it doesn’t make
  4598. * any transformations. Transformations will be applied
  4599. * in the {@link LazyResult} methods.
  4600. *
  4601. * @param {string|toString|Result} css - String with input CSS or
  4602. * any object with a `toString()`
  4603. * method, like a Buffer.
  4604. * Optionally, send a {@link Result}
  4605. * instance and the processor will
  4606. * take the {@link Root} from it.
  4607. * @param {processOptions} [opts] - options
  4608. *
  4609. * @return {LazyResult} Promise proxy
  4610. *
  4611. * @example
  4612. * processor.process(css, { from: 'a.css', to: 'a.out.css' })
  4613. * .then(result => {
  4614. * console.log(result.css);
  4615. * });
  4616. */
  4617. ;
  4618. _proto.process = function process(css, opts) {
  4619. if (opts === void 0) {
  4620. opts = {};
  4621. }
  4622. return new LazyResult(this, css, opts);
  4623. };
  4624. _proto.normalize = function normalize(plugins) {
  4625. var normalized = [];
  4626. plugins.forEach(function (i) {
  4627. if (i.postcss) i = i.postcss;
  4628. if (typeof i === 'object' && Array.isArray(i.plugins)) {
  4629. normalized = normalized.concat(i.plugins);
  4630. } else if (typeof i === 'function') {
  4631. normalized.push(i);
  4632. } else {
  4633. throw new Error(i + " is not a PostCSS plugin");
  4634. }
  4635. });
  4636. return normalized;
  4637. };
  4638. return Processor;
  4639. }();
  4640. /**
  4641. * Represents a CSS file and contains all its parsed nodes.
  4642. *
  4643. * @extends Container
  4644. *
  4645. * @example
  4646. * const root = postcss.parse('a{color:black} b{z-index:2}');
  4647. * root.type //=> 'root'
  4648. * root.nodes.length //=> 2
  4649. */
  4650. var Root =
  4651. /*#__PURE__*/
  4652. function (_Container) {
  4653. _inheritsLoose(Root, _Container);
  4654. function Root(defaults) {
  4655. var _this;
  4656. _this = _Container.call(this, defaults) || this;
  4657. _this.type = 'root';
  4658. if (!_this.nodes) _this.nodes = [];
  4659. return _this;
  4660. }
  4661. var _proto = Root.prototype;
  4662. _proto.removeChild = function removeChild(child) {
  4663. child = this.index(child);
  4664. if (child === 0 && this.nodes.length > 1) {
  4665. this.nodes[1].raws.before = this.nodes[child].raws.before;
  4666. }
  4667. return _Container.prototype.removeChild.call(this, child);
  4668. };
  4669. _proto.normalize = function normalize(child, sample, type) {
  4670. var nodes = _Container.prototype.normalize.call(this, child);
  4671. if (sample) {
  4672. if (type === 'prepend') {
  4673. if (this.nodes.length > 1) {
  4674. sample.raws.before = this.nodes[1].raws.before;
  4675. } else {
  4676. delete sample.raws.before;
  4677. }
  4678. } else if (this.first !== sample) {
  4679. nodes.forEach(function (node) {
  4680. node.raws.before = sample.raws.before;
  4681. });
  4682. }
  4683. }
  4684. return nodes;
  4685. }
  4686. /**
  4687. * Returns a {@link Result} instance representing the root’s CSS.
  4688. *
  4689. * @param {processOptions} [opts] - options with only `to` and `map` keys
  4690. *
  4691. * @return {Result} result with current root’s CSS
  4692. *
  4693. * @example
  4694. * const root1 = postcss.parse(css1, { from: 'a.css' });
  4695. * const root2 = postcss.parse(css2, { from: 'b.css' });
  4696. * root1.append(root2);
  4697. * const result = root1.toResult({ to: 'all.css', map: true });
  4698. */
  4699. ;
  4700. _proto.toResult = function toResult(opts) {
  4701. if (opts === void 0) {
  4702. opts = {};
  4703. }
  4704. var lazy = new LazyResult(new Processor(), this, opts);
  4705. return lazy.stringify();
  4706. };
  4707. _proto.remove = function remove(child) {
  4708. warnOnce('Root#remove is deprecated. Use Root#removeChild');
  4709. this.removeChild(child);
  4710. };
  4711. _proto.prevMap = function prevMap() {
  4712. warnOnce('Root#prevMap is deprecated. Use Root#source.input.map');
  4713. return this.source.input.map;
  4714. }
  4715. /**
  4716. * @memberof Root#
  4717. * @member {object} raws - Information to generate byte-to-byte equal
  4718. * node string as it was in the origin input.
  4719. *
  4720. * Every parser saves its own properties,
  4721. * but the default CSS parser uses:
  4722. *
  4723. * * `after`: the space symbols after the last child to the end of file.
  4724. * * `semicolon`: is the last child has an (optional) semicolon.
  4725. *
  4726. * @example
  4727. * postcss.parse('a {}\n').raws //=> { after: '\n' }
  4728. * postcss.parse('a {}').raws //=> { after: '' }
  4729. */
  4730. ;
  4731. return Root;
  4732. }(Container);
  4733. var sequence = 0;
  4734. /**
  4735. * @typedef {object} filePosition
  4736. * @property {string} file - path to file
  4737. * @property {number} line - source line in file
  4738. * @property {number} column - source column in file
  4739. */
  4740. /**
  4741. * Represents the source CSS.
  4742. *
  4743. * @example
  4744. * const root = postcss.parse(css, { from: file });
  4745. * const input = root.source.input;
  4746. */
  4747. var Input =
  4748. /*#__PURE__*/
  4749. function () {
  4750. /**
  4751. * @param {string} css - input CSS source
  4752. * @param {object} [opts] - {@link Processor#process} options
  4753. */
  4754. function Input(css, opts) {
  4755. if (opts === void 0) {
  4756. opts = {};
  4757. }
  4758. /**
  4759. * @member {string} - input CSS source
  4760. *
  4761. * @example
  4762. * const input = postcss.parse('a{}', { from: file }).input;
  4763. * input.css //=> "a{}";
  4764. */
  4765. this.css = css.toString();
  4766. if (this.css[0] === "\uFEFF" || this.css[0] === "\uFFFE") {
  4767. this.css = this.css.slice(1);
  4768. }
  4769. if (opts.from) {
  4770. if (/^\w+:\/\//.test(opts.from)) {
  4771. /**
  4772. * @member {string} - The absolute path to the CSS source file
  4773. * defined with the `from` option.
  4774. *
  4775. * @example
  4776. * const root = postcss.parse(css, { from: 'a.css' });
  4777. * root.source.input.file //=> '/home/ai/a.css'
  4778. */
  4779. this.file = opts.from;
  4780. } else {
  4781. this.file = path.resolve(opts.from);
  4782. }
  4783. }
  4784. /*
  4785. let map = new PreviousMap(this.css, opts);
  4786. if ( map.text ) {
  4787. /!**
  4788. * @member {PreviousMap} - The input source map passed from
  4789. * a compilation step before PostCSS
  4790. * (for example, from Sass compiler).
  4791. *
  4792. * @example
  4793. * root.source.input.map.consumer().sources //=> ['a.sass']
  4794. *!/
  4795. this.map = map;
  4796. let file = map.consumer().file;
  4797. if ( !this.file && file ) this.file = this.mapResolve(file);
  4798. }
  4799. */
  4800. if (!this.file) {
  4801. sequence += 1;
  4802. /**
  4803. * @member {string} - The unique ID of the CSS source. It will be
  4804. * created if `from` option is not provided
  4805. * (because PostCSS does not know the file path).
  4806. *
  4807. * @example
  4808. * const root = postcss.parse(css);
  4809. * root.source.input.file //=> undefined
  4810. * root.source.input.id //=> "<input css 1>"
  4811. */
  4812. this.id = "<input css " + sequence + ">";
  4813. }
  4814. if (this.map) this.map.file = this.from;
  4815. }
  4816. var _proto = Input.prototype;
  4817. _proto.error = function error(message, line, column, opts) {
  4818. if (opts === void 0) {
  4819. opts = {};
  4820. }
  4821. var result;
  4822. var origin = this.origin(line, column);
  4823. if (origin) {
  4824. result = new CssSyntaxError(message, origin.line, origin.column, origin.source, origin.file, opts.plugin);
  4825. } else {
  4826. result = new CssSyntaxError(message, line, column, this.css, this.file, opts.plugin);
  4827. }
  4828. result.input = {
  4829. line: line,
  4830. column: column,
  4831. source: this.css
  4832. };
  4833. if (this.file) result.input.file = this.file;
  4834. return result;
  4835. }
  4836. /**
  4837. * Reads the input source map and returns a symbol position
  4838. * in the input source (e.g., in a Sass file that was compiled
  4839. * to CSS before being passed to PostCSS).
  4840. *
  4841. * @param {number} line - line in input CSS
  4842. * @param {number} column - column in input CSS
  4843. *
  4844. * @return {filePosition} position in input source
  4845. *
  4846. * @example
  4847. * root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
  4848. */
  4849. ;
  4850. _proto.origin = function origin(line, column) {
  4851. if (!this.map) return false;
  4852. var consumer = this.map.consumer();
  4853. var from = consumer.originalPositionFor({
  4854. line: line,
  4855. column: column
  4856. });
  4857. if (!from.source) return false;
  4858. var result = {
  4859. file: this.mapResolve(from.source),
  4860. line: from.line,
  4861. column: from.column
  4862. };
  4863. var source = consumer.sourceContentFor(from.source);
  4864. if (source) result.source = source;
  4865. return result;
  4866. };
  4867. _proto.mapResolve = function mapResolve(file) {
  4868. if (/^\w+:\/\//.test(file)) {
  4869. return file;
  4870. } else {
  4871. return path.resolve(this.map.consumer().sourceRoot || '.', file);
  4872. }
  4873. }
  4874. /**
  4875. * The CSS source identifier. Contains {@link Input#file} if the user
  4876. * set the `from` option, or {@link Input#id} if they did not.
  4877. * @type {string}
  4878. *
  4879. * @example
  4880. * const root = postcss.parse(css, { from: 'a.css' });
  4881. * root.source.input.from //=> "/home/ai/a.css"
  4882. *
  4883. * const root = postcss.parse(css);
  4884. * root.source.input.from //=> "<input css 1>"
  4885. */
  4886. ;
  4887. _createClass(Input, [{
  4888. key: "from",
  4889. get: function get() {
  4890. return this.file || this.id;
  4891. }
  4892. }]);
  4893. return Input;
  4894. }();
  4895. var SafeParser =
  4896. /*#__PURE__*/
  4897. function (_Parser) {
  4898. _inheritsLoose(SafeParser, _Parser);
  4899. function SafeParser() {
  4900. return _Parser.apply(this, arguments) || this;
  4901. }
  4902. var _proto = SafeParser.prototype;
  4903. _proto.tokenize = function tokenize$1() {
  4904. this.tokens = tokenize(this.input, {
  4905. ignoreErrors: true
  4906. });
  4907. };
  4908. _proto.comment = function comment(token) {
  4909. var node = new Comment();
  4910. this.init(node, token[2], token[3]);
  4911. node.source.end = {
  4912. line: token[4],
  4913. column: token[5]
  4914. };
  4915. var text = token[1].slice(2);
  4916. if (text.slice(-2) === '*/') text = text.slice(0, -2);
  4917. if (/^\s*$/.test(text)) {
  4918. node.text = '';
  4919. node.raws.left = text;
  4920. node.raws.right = '';
  4921. } else {
  4922. var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
  4923. node.text = match[2];
  4924. node.raws.left = match[1];
  4925. node.raws.right = match[3];
  4926. }
  4927. };
  4928. _proto.unclosedBracket = function unclosedBracket() {};
  4929. _proto.unknownWord = function unknownWord(start) {
  4930. var buffer = this.tokens.slice(start, this.pos + 1);
  4931. this.spaces += buffer.map(function (i) {
  4932. return i[1];
  4933. }).join('');
  4934. };
  4935. _proto.unexpectedClose = function unexpectedClose() {
  4936. this.current.raws.after += '}';
  4937. };
  4938. _proto.doubleColon = function doubleColon() {};
  4939. _proto.unnamedAtrule = function unnamedAtrule(node) {
  4940. node.name = '';
  4941. };
  4942. _proto.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
  4943. var colon = this.colon(tokens);
  4944. if (colon === false) return;
  4945. var split;
  4946. for (split = colon - 1; split >= 0; split--) {
  4947. if (tokens[split][0] === 'word') break;
  4948. }
  4949. for (split -= 1; split >= 0; split--) {
  4950. if (tokens[split][0] !== 'space') {
  4951. split += 1;
  4952. break;
  4953. }
  4954. }
  4955. var other = tokens.splice(split, tokens.length - split);
  4956. this.decl(other);
  4957. };
  4958. _proto.checkMissedSemicolon = function checkMissedSemicolon() {};
  4959. _proto.endFile = function endFile() {
  4960. if (this.current.nodes && this.current.nodes.length) {
  4961. this.current.raws.semicolon = this.semicolon;
  4962. }
  4963. this.current.raws.after = (this.current.raws.after || '') + this.spaces;
  4964. while (this.current.parent) {
  4965. this.current = this.current.parent;
  4966. this.current.raws.after = '';
  4967. }
  4968. };
  4969. return SafeParser;
  4970. }(Parser);
  4971. //
  4972. function safeParse(css, opts) {
  4973. var input = new Input(css, opts);
  4974. var parser = new SafeParser(input);
  4975. parser.tokenize();
  4976. parser.loop();
  4977. return parser.root;
  4978. }
  4979. //
  4980. var generated = {};
  4981. /*
  4982. InlineStyle takes arbitrary CSS and generates a flat object
  4983. */
  4984. var _InlineStyle = (function (styleSheet) {
  4985. var InlineStyle =
  4986. /*#__PURE__*/
  4987. function () {
  4988. function InlineStyle(rules) {
  4989. this.rules = rules;
  4990. }
  4991. var _proto = InlineStyle.prototype;
  4992. _proto.generateStyleObject = function generateStyleObject(executionContext) {
  4993. var flatCSS = flatten(this.rules, executionContext).join('');
  4994. var hash = generateComponentId(flatCSS);
  4995. if (!generated[hash]) {
  4996. var root = safeParse(flatCSS);
  4997. var declPairs = [];
  4998. root.each(function (node) {
  4999. if (node.type === 'decl') {
  5000. declPairs.push([node.prop, node.value]);
  5001. } else if (process.env.NODE_ENV !== 'production' && node.type !== 'comment') {
  5002. /* eslint-disable no-console */
  5003. console.warn("Node of type " + node.type + " not supported as an inline style");
  5004. }
  5005. }); // RN currently does not support differing values for the corner radii of Image
  5006. // components (but does for View). It is almost impossible to tell whether we'll have
  5007. // support, so we'll just disable multiple values here.
  5008. // https://github.com/styled-components/css-to-react-native/issues/11
  5009. var styleObject = transformDeclPairs(declPairs, ['borderRadius', 'borderWidth', 'borderColor', 'borderStyle']);
  5010. var styles = styleSheet.create({
  5011. generated: styleObject
  5012. });
  5013. generated[hash] = styles.generated;
  5014. }
  5015. return generated[hash];
  5016. };
  5017. return InlineStyle;
  5018. }();
  5019. return InlineStyle;
  5020. });
  5021. /* eslint-disable */
  5022. /**
  5023. mixin-deep; https://github.com/jonschlinkert/mixin-deep
  5024. Inlined such that it will be consistently transpiled to an IE-compatible syntax.
  5025. The MIT License (MIT)
  5026. Copyright (c) 2014-present, Jon Schlinkert.
  5027. Permission is hereby granted, free of charge, to any person obtaining a copy
  5028. of this software and associated documentation files (the "Software"), to deal
  5029. in the Software without restriction, including without limitation the rights
  5030. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  5031. copies of the Software, and to permit persons to whom the Software is
  5032. furnished to do so, subject to the following conditions:
  5033. The above copyright notice and this permission notice shall be included in
  5034. all copies or substantial portions of the Software.
  5035. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  5036. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  5037. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  5038. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  5039. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  5040. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  5041. THE SOFTWARE.
  5042. */
  5043. var isObject = function isObject(val) {
  5044. return typeof val === 'function' || typeof val === 'object' && val !== null && !Array.isArray(val);
  5045. };
  5046. var isValidKey = function isValidKey(key) {
  5047. return key !== '__proto__' && key !== 'constructor' && key !== 'prototype';
  5048. };
  5049. function mixin(target, val, key) {
  5050. var obj = target[key];
  5051. if (isObject(val) && isObject(obj)) {
  5052. mixinDeep(obj, val);
  5053. } else {
  5054. target[key] = val;
  5055. }
  5056. }
  5057. function mixinDeep(target) {
  5058. for (var _len = arguments.length, rest = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  5059. rest[_key - 1] = arguments[_key];
  5060. }
  5061. for (var _i = 0, _rest = rest; _i < _rest.length; _i++) {
  5062. var obj = _rest[_i];
  5063. if (isObject(obj)) {
  5064. for (var key in obj) {
  5065. if (isValidKey(key)) {
  5066. mixin(target, obj[key], key);
  5067. }
  5068. }
  5069. }
  5070. }
  5071. return target;
  5072. }
  5073. //
  5074. var determineTheme = (function (props, providedTheme, defaultProps) {
  5075. if (defaultProps === void 0) {
  5076. defaultProps = EMPTY_OBJECT;
  5077. }
  5078. return props.theme !== defaultProps.theme && props.theme || providedTheme || defaultProps.theme;
  5079. });
  5080. //
  5081. function isTag(target) {
  5082. return typeof target === 'string' && (process.env.NODE_ENV !== 'production' ? target.charAt(0) === target.charAt(0).toLowerCase() : true);
  5083. }
  5084. //
  5085. function generateDisplayName(target) {
  5086. // $FlowFixMe
  5087. return isTag(target) ? "styled." + target : "Styled(" + getComponentName(target) + ")";
  5088. }
  5089. var ThemeContext = React.createContext();
  5090. var ThemeConsumer = ThemeContext.Consumer;
  5091. function mergeTheme(theme, outerTheme) {
  5092. if (!theme) {
  5093. return throwStyledComponentsError(14);
  5094. }
  5095. if (isFunction(theme)) {
  5096. var mergedTheme = theme(outerTheme);
  5097. if (process.env.NODE_ENV !== 'production' && (mergedTheme === null || Array.isArray(mergedTheme) || typeof mergedTheme !== 'object')) {
  5098. return throwStyledComponentsError(7);
  5099. }
  5100. return mergedTheme;
  5101. }
  5102. if (Array.isArray(theme) || typeof theme !== 'object') {
  5103. return throwStyledComponentsError(8);
  5104. }
  5105. return outerTheme ? _extends({}, outerTheme, {}, theme) : theme;
  5106. }
  5107. /**
  5108. * Provide a theme to an entire react component tree via context
  5109. */
  5110. function ThemeProvider(props) {
  5111. var outerTheme = useContext(ThemeContext);
  5112. var themeContext = useMemo(function () {
  5113. return mergeTheme(props.theme, outerTheme);
  5114. }, [props.theme, outerTheme]);
  5115. if (!props.children) {
  5116. return null;
  5117. }
  5118. return React.createElement(ThemeContext.Provider, {
  5119. value: themeContext
  5120. }, props.children);
  5121. }
  5122. // if the user makes use of ThemeProvider or StyleSheetManager things will break.
  5123. var StyledNativeComponent =
  5124. /*#__PURE__*/
  5125. function (_Component) {
  5126. _inheritsLoose(StyledNativeComponent, _Component);
  5127. function StyledNativeComponent() {
  5128. var _this;
  5129. for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
  5130. args[_key] = arguments[_key];
  5131. }
  5132. _this = _Component.call.apply(_Component, [this].concat(args)) || this;
  5133. _this.attrs = {};
  5134. return _this;
  5135. }
  5136. var _proto = StyledNativeComponent.prototype;
  5137. _proto.render = function render() {
  5138. var _this2 = this;
  5139. return React.createElement(ThemeConsumer, null, function (theme) {
  5140. var _this2$props = _this2.props,
  5141. renderAs = _this2$props.as,
  5142. forwardedComponent = _this2$props.forwardedComponent,
  5143. forwardedAs = _this2$props.forwardedAs,
  5144. forwardedRef = _this2$props.forwardedRef,
  5145. _this2$props$style = _this2$props.style,
  5146. style = _this2$props$style === void 0 ? [] : _this2$props$style,
  5147. props = _objectWithoutPropertiesLoose(_this2$props, ["as", "forwardedComponent", "forwardedAs", "forwardedRef", "style"]);
  5148. var defaultProps = forwardedComponent.defaultProps,
  5149. target = forwardedComponent.target;
  5150. var generatedStyles = _this2.generateAndInjectStyles(determineTheme(_this2.props, theme, defaultProps) || EMPTY_OBJECT, _this2.props);
  5151. var propsForElement = _extends({}, props, {}, _this2.attrs, {
  5152. style: [generatedStyles].concat(style)
  5153. });
  5154. if (forwardedRef) propsForElement.ref = forwardedRef;
  5155. if (forwardedAs) propsForElement.as = forwardedAs;
  5156. return createElement(renderAs || target, propsForElement);
  5157. });
  5158. };
  5159. _proto.buildExecutionContext = function buildExecutionContext(theme, props, attrs) {
  5160. var _this3 = this;
  5161. var context = _extends({}, props, {
  5162. theme: theme
  5163. });
  5164. if (!attrs.length) return context;
  5165. this.attrs = {};
  5166. attrs.forEach(function (attrDef) {
  5167. var resolvedAttrDef = attrDef;
  5168. var attr;
  5169. var key;
  5170. if (isFunction(resolvedAttrDef)) {
  5171. resolvedAttrDef = resolvedAttrDef(context);
  5172. }
  5173. /* eslint-disable guard-for-in */
  5174. for (key in resolvedAttrDef) {
  5175. attr = resolvedAttrDef[key];
  5176. _this3.attrs[key] = attr;
  5177. context[key] = attr;
  5178. }
  5179. /* eslint-enable */
  5180. });
  5181. return context;
  5182. };
  5183. _proto.generateAndInjectStyles = function generateAndInjectStyles(theme, props) {
  5184. var inlineStyle = props.forwardedComponent.inlineStyle;
  5185. var executionContext = this.buildExecutionContext(theme, props, props.forwardedComponent.attrs);
  5186. return inlineStyle.generateStyleObject(executionContext);
  5187. };
  5188. _proto.setNativeProps = function setNativeProps(nativeProps) {
  5189. if (this.root !== undefined) {
  5190. // $FlowFixMe
  5191. this.root.setNativeProps(nativeProps);
  5192. } else if (process.env.NODE_ENV !== 'production') {
  5193. // eslint-disable-next-line no-console
  5194. console.warn('setNativeProps was called on a Styled Component wrapping a stateless functional component.');
  5195. }
  5196. };
  5197. return StyledNativeComponent;
  5198. }(Component);
  5199. var _StyledNativeComponent = (function (InlineStyle) {
  5200. var createStyledNativeComponent = function createStyledNativeComponent(target, options, rules) {
  5201. var _options$attrs = options.attrs,
  5202. attrs = _options$attrs === void 0 ? EMPTY_ARRAY : _options$attrs,
  5203. _options$displayName = options.displayName,
  5204. displayName = _options$displayName === void 0 ? generateDisplayName(target) : _options$displayName,
  5205. _options$ParentCompon = options.ParentComponent,
  5206. ParentComponent = _options$ParentCompon === void 0 ? StyledNativeComponent : _options$ParentCompon;
  5207. var isClass = !isTag(target);
  5208. var isTargetStyledComp = isStyledComponent(target); // $FlowFixMe
  5209. var WrappedStyledNativeComponent = React.forwardRef(function (props, ref) {
  5210. return React.createElement(ParentComponent, _extends({}, props, {
  5211. forwardedComponent: WrappedStyledNativeComponent,
  5212. forwardedRef: ref
  5213. }));
  5214. });
  5215. var finalAttrs = // $FlowFixMe
  5216. isTargetStyledComp && target.attrs ? Array.prototype.concat(target.attrs, attrs).filter(Boolean) : attrs;
  5217. /**
  5218. * forwardRef creates a new interim component, which we'll take advantage of
  5219. * instead of extending ParentComponent to create _another_ interim class
  5220. */
  5221. // $FlowFixMe
  5222. WrappedStyledNativeComponent.attrs = finalAttrs;
  5223. WrappedStyledNativeComponent.displayName = displayName; // $FlowFixMe
  5224. WrappedStyledNativeComponent.inlineStyle = new InlineStyle( // $FlowFixMe
  5225. isTargetStyledComp ? target.inlineStyle.rules.concat(rules) : rules); // $FlowFixMe
  5226. WrappedStyledNativeComponent.styledComponentId = 'StyledNativeComponent'; // $FlowFixMe
  5227. WrappedStyledNativeComponent.target = isTargetStyledComp ? // $FlowFixMe
  5228. target.target : target; // $FlowFixMe
  5229. WrappedStyledNativeComponent.withComponent = function withComponent(tag) {
  5230. var _ = options.displayName,
  5231. __ = options.componentId,
  5232. optionsToCopy = _objectWithoutPropertiesLoose(options, ["displayName", "componentId"]);
  5233. var newOptions = _extends({}, optionsToCopy, {
  5234. attrs: finalAttrs,
  5235. ParentComponent: ParentComponent
  5236. });
  5237. return createStyledNativeComponent(tag, newOptions, rules);
  5238. }; // $FlowFixMe
  5239. Object.defineProperty(WrappedStyledNativeComponent, 'defaultProps', {
  5240. get: function get() {
  5241. return this._foldedDefaultProps;
  5242. },
  5243. set: function set(obj) {
  5244. // $FlowFixMe
  5245. this._foldedDefaultProps = isTargetStyledComp ? mixinDeep({}, target.defaultProps, obj) : obj;
  5246. }
  5247. });
  5248. if (isClass) {
  5249. hoist(WrappedStyledNativeComponent, target, {
  5250. // all SC-specific things should not be hoisted
  5251. attrs: true,
  5252. displayName: true,
  5253. inlineStyle: true,
  5254. styledComponentId: true,
  5255. target: true,
  5256. withComponent: true
  5257. });
  5258. }
  5259. return WrappedStyledNativeComponent;
  5260. };
  5261. return createStyledNativeComponent;
  5262. });
  5263. //
  5264. var interleave = (function (strings, interpolations) {
  5265. var result = [strings[0]];
  5266. for (var i = 0, len = interpolations.length; i < len; i += 1) {
  5267. result.push(interpolations[i], strings[i + 1]);
  5268. }
  5269. return result;
  5270. });
  5271. //
  5272. function css(styles) {
  5273. for (var _len = arguments.length, interpolations = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  5274. interpolations[_key - 1] = arguments[_key];
  5275. }
  5276. if (isFunction(styles) || isPlainObject(styles)) {
  5277. // $FlowFixMe
  5278. return flatten(interleave(EMPTY_ARRAY, [styles].concat(interpolations)));
  5279. }
  5280. if (interpolations.length === 0 && styles.length === 1 && typeof styles[0] === "string") {
  5281. // $FlowFixMe
  5282. return styles;
  5283. } // $FlowFixMe
  5284. return flatten(interleave(styles, interpolations));
  5285. }
  5286. function constructWithOptions(componentConstructor, tag, options) {
  5287. if (options === void 0) {
  5288. options = EMPTY_OBJECT;
  5289. }
  5290. if (!isValidElementType(tag)) {
  5291. return throwStyledComponentsError(1, String(tag));
  5292. }
  5293. /* This is callable directly as a template function */
  5294. // $FlowFixMe: Not typed to avoid destructuring arguments
  5295. var templateFunction = function templateFunction() {
  5296. return componentConstructor(tag, options, css.apply(void 0, arguments));
  5297. };
  5298. /* If config methods are called, wrap up a new template function and merge options */
  5299. templateFunction.withConfig = function (config) {
  5300. return constructWithOptions(componentConstructor, tag, _extends({}, options, {}, config));
  5301. };
  5302. /* Modify/inject new props at runtime */
  5303. templateFunction.attrs = function (attrs) {
  5304. return constructWithOptions(componentConstructor, tag, _extends({}, options, {
  5305. attrs: Array.prototype.concat(options.attrs, attrs).filter(Boolean)
  5306. }));
  5307. };
  5308. return templateFunction;
  5309. }
  5310. // export default <Config: { theme?: any }, Instance>(
  5311. // Component: AbstractComponent<Config, Instance>
  5312. // ): AbstractComponent<$Diff<Config, { theme?: any }> & { theme?: any }, Instance>
  5313. //
  5314. // but the old build system tooling doesn't support the syntax
  5315. var withTheme = (function (Component) {
  5316. // $FlowFixMe This should be React.forwardRef<Config, Instance>
  5317. var WithTheme = React.forwardRef(function (props, ref) {
  5318. var theme = useContext(ThemeContext); // $FlowFixMe defaultProps isn't declared so it can be inferrable
  5319. var defaultProps = Component.defaultProps;
  5320. var themeProp = determineTheme(props, theme, defaultProps);
  5321. if (process.env.NODE_ENV !== 'production' && themeProp === undefined) {
  5322. // eslint-disable-next-line no-console
  5323. console.warn("[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps in component class \"" + getComponentName(Component) + "\"");
  5324. }
  5325. return React.createElement(Component, _extends({}, props, {
  5326. theme: themeProp,
  5327. ref: ref
  5328. }));
  5329. });
  5330. hoist(WithTheme, Component);
  5331. WithTheme.displayName = "WithTheme(" + getComponentName(Component) + ")";
  5332. return WithTheme;
  5333. });
  5334. //
  5335. var useTheme = function useTheme() {
  5336. return useContext(ThemeContext);
  5337. };
  5338. //
  5339. var reactNative = require('react-native');
  5340. var InlineStyle = _InlineStyle(reactNative.StyleSheet);
  5341. var StyledNativeComponent$1 = _StyledNativeComponent(InlineStyle);
  5342. var styled = function styled(tag) {
  5343. return constructWithOptions(StyledNativeComponent$1, tag);
  5344. };
  5345. /* React native lazy-requires each of these modules for some reason, so let's
  5346. * assume it's for a good reason and not eagerly load them all */
  5347. var aliases = "ActivityIndicator ActivityIndicatorIOS ART Button DatePickerIOS DrawerLayoutAndroid\n Image ImageBackground ImageEditor ImageStore KeyboardAvoidingView ListView MapView Modal NavigatorIOS\n Picker PickerIOS ProgressBarAndroid ProgressViewIOS ScrollView SegmentedControlIOS Slider\n SliderIOS SnapshotViewIOS Switch RecyclerViewBackedScrollView RefreshControl SafeAreaView StatusBar\n SwipeableListView SwitchAndroid SwitchIOS TabBarIOS Text TextInput ToastAndroid ToolbarAndroid\n Touchable TouchableHighlight TouchableNativeFeedback TouchableOpacity TouchableWithoutFeedback\n View ViewPagerAndroid WebView FlatList SectionList VirtualizedList";
  5348. /* Define a getter for each alias which simply gets the reactNative component
  5349. * and passes it to styled */
  5350. aliases.split(/\s+/m).forEach(function (alias) {
  5351. return Object.defineProperty(styled, alias, {
  5352. enumerable: true,
  5353. configurable: false,
  5354. get: function get() {
  5355. return styled(reactNative[alias]);
  5356. }
  5357. });
  5358. });
  5359. export default styled;
  5360. export { ThemeConsumer, ThemeContext, ThemeProvider, css, isStyledComponent, useTheme, withTheme };
  5361. //# sourceMappingURL=styled-components.native.esm.js.map