styled-components-primitives.cjs.js 171 KB

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