index.cjs 203 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688
  1. "use strict";
  2. var __create = Object.create;
  3. var __defProp = Object.defineProperty;
  4. var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
  5. var __getOwnPropNames = Object.getOwnPropertyNames;
  6. var __getProtoOf = Object.getPrototypeOf;
  7. var __hasOwnProp = Object.prototype.hasOwnProperty;
  8. var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
  9. var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
  10. var __glob = (map) => (path) => {
  11. var fn = map[path];
  12. if (fn) return fn();
  13. throw new Error("Module not found in bundle: " + path);
  14. };
  15. var __esm = (fn, res) => function __init() {
  16. return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
  17. };
  18. var __export = (target, all) => {
  19. for (var name in all)
  20. __defProp(target, name, { get: all[name], enumerable: true });
  21. };
  22. var __copyProps = (to, from, except, desc) => {
  23. if (from && typeof from === "object" || typeof from === "function") {
  24. for (let key of __getOwnPropNames(from))
  25. if (!__hasOwnProp.call(to, key) && key !== except)
  26. __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  27. }
  28. return to;
  29. };
  30. var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  31. // If the importer is in node compatibility mode or this is not an ESM
  32. // file that has been converted to a CommonJS file using a Babel-
  33. // compatible transform (i.e. "__esModule" has not been set), then set
  34. // "default" to the CommonJS "module.exports" for node compatibility.
  35. isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  36. mod
  37. ));
  38. var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
  39. var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
  40. // src/utils/is-promise.js
  41. function isPromise(value) {
  42. if (!value) return false;
  43. if (typeof value !== "object") return false;
  44. return typeof value.then === "function";
  45. }
  46. var init_is_promise = __esm({
  47. "src/utils/is-promise.js"() {
  48. "use strict";
  49. __name(isPromise, "isPromise");
  50. }
  51. });
  52. // src/utils/capitalize.js
  53. function capitalize(string) {
  54. if (!string || typeof string !== "string") return string;
  55. return string.charAt(0).toUpperCase() + string.slice(1);
  56. }
  57. var init_capitalize = __esm({
  58. "src/utils/capitalize.js"() {
  59. "use strict";
  60. __name(capitalize, "capitalize");
  61. }
  62. });
  63. // src/utils/clone-deep.js
  64. function cloneDeep(value) {
  65. if (!value) return value;
  66. const types = [Number, String, Boolean];
  67. let result;
  68. types.forEach((type) => {
  69. if (value instanceof type) result = type(value);
  70. });
  71. if (result === void 0) {
  72. if (Array.isArray(value)) {
  73. result = [];
  74. value.forEach((child, index) => {
  75. result[index] = cloneDeep(child);
  76. });
  77. } else if (typeof value === "object") {
  78. if ("nodeType" in value && value.nodeType && "cloneNode" in value && typeof value.cloneNode === "function") {
  79. result = value.cloneNode(true);
  80. } else if (!("prototype" in value) || !value.prototype) {
  81. if (value instanceof Date) {
  82. result = new Date(value);
  83. } else if (value.constructor && value.constructor.name === "Object") {
  84. result = {};
  85. for (const key in value) {
  86. result[key] = cloneDeep(value[key]);
  87. }
  88. } else {
  89. result = value;
  90. }
  91. } else {
  92. result = value;
  93. }
  94. } else {
  95. result = value;
  96. }
  97. }
  98. return result;
  99. }
  100. var init_clone_deep = __esm({
  101. "src/utils/clone-deep.js"() {
  102. "use strict";
  103. __name(cloneDeep, "cloneDeep");
  104. }
  105. });
  106. // src/utils/singularize.js
  107. function singularize(noun) {
  108. if (!noun || typeof noun !== "string") return noun;
  109. const endings = {
  110. ves: "fe",
  111. ies: "y",
  112. i: "us",
  113. zes: "ze",
  114. ses: "s",
  115. es: "e",
  116. s: ""
  117. };
  118. return noun.replace(
  119. new RegExp(`(${Object.keys(endings).join("|")})$`),
  120. (r) => endings[r]
  121. );
  122. }
  123. var init_singularize = __esm({
  124. "src/utils/singularize.js"() {
  125. "use strict";
  126. __name(singularize, "singularize");
  127. }
  128. });
  129. // src/utils/is-deep-equal.js
  130. function isDeepEqual(firstValue, secondValue) {
  131. const cached = /* @__PURE__ */ new WeakMap();
  132. const compare = /* @__PURE__ */ __name((a, b) => {
  133. if (a === null || b === null) return a === b;
  134. if (typeof a !== "object" || typeof b !== "object") return a === b;
  135. const dataTypeA = Array.isArray(a) ? "array" : "object";
  136. const dataTypeB = Array.isArray(b) ? "array" : "object";
  137. if (dataTypeA !== dataTypeB) return false;
  138. const keysA = Object.keys(a);
  139. const keysB = Object.keys(b);
  140. if (keysA.length !== keysB.length) return false;
  141. const symbolsA = Object.getOwnPropertySymbols(a);
  142. const symbolsB = Object.getOwnPropertySymbols(b);
  143. if (symbolsA.length !== symbolsB.length) return false;
  144. let setForA = cached.get(a);
  145. if (setForA == null) {
  146. setForA = /* @__PURE__ */ new Set();
  147. cached.set(a, setForA);
  148. } else if (setForA.has(b)) {
  149. return true;
  150. }
  151. setForA.add(b);
  152. let setForB = cached.get(b);
  153. if (setForB == null) {
  154. setForB = /* @__PURE__ */ new Set();
  155. cached.set(b, setForB);
  156. } else if (setForB.has(a)) {
  157. return true;
  158. }
  159. setForB.add(a);
  160. const propertyNamesA = [...keysA, ...symbolsA];
  161. for (const propertyNameA of propertyNamesA) {
  162. if (!Object.prototype.hasOwnProperty.call(b, propertyNameA)) return false;
  163. const propertyValueA = a[propertyNameA];
  164. const propertyValueB = b[propertyNameA];
  165. if (!compare(propertyValueA, propertyValueB)) return false;
  166. }
  167. return true;
  168. }, "compare");
  169. return compare(firstValue, secondValue);
  170. }
  171. var init_is_deep_equal = __esm({
  172. "src/utils/is-deep-equal.js"() {
  173. "use strict";
  174. __name(isDeepEqual, "isDeepEqual");
  175. }
  176. });
  177. // src/errors/not-implemented-error.js
  178. var import_js_format, _NotImplementedError, NotImplementedError;
  179. var init_not_implemented_error = __esm({
  180. "src/errors/not-implemented-error.js"() {
  181. "use strict";
  182. import_js_format = require("@e22m4u/js-format");
  183. _NotImplementedError = class _NotImplementedError extends import_js_format.Errorf {
  184. };
  185. __name(_NotImplementedError, "NotImplementedError");
  186. NotImplementedError = _NotImplementedError;
  187. }
  188. });
  189. // src/errors/invalid-argument-error.js
  190. var import_js_format2, _InvalidArgumentError, InvalidArgumentError;
  191. var init_invalid_argument_error = __esm({
  192. "src/errors/invalid-argument-error.js"() {
  193. "use strict";
  194. import_js_format2 = require("@e22m4u/js-format");
  195. _InvalidArgumentError = class _InvalidArgumentError extends import_js_format2.Errorf {
  196. };
  197. __name(_InvalidArgumentError, "InvalidArgumentError");
  198. InvalidArgumentError = _InvalidArgumentError;
  199. }
  200. });
  201. // src/errors/invalid-operator-value-error.js
  202. var import_js_format3, _InvalidOperatorValueError, InvalidOperatorValueError;
  203. var init_invalid_operator_value_error = __esm({
  204. "src/errors/invalid-operator-value-error.js"() {
  205. "use strict";
  206. import_js_format3 = require("@e22m4u/js-format");
  207. _InvalidOperatorValueError = class _InvalidOperatorValueError extends Error {
  208. /**
  209. * Constructor.
  210. *
  211. * @param {string} operator
  212. * @param {string} expected
  213. * @param {*} value
  214. */
  215. constructor(operator, expected, value) {
  216. super(
  217. (0, import_js_format3.format)(
  218. "Condition of {%s: ...} should have %s, but %v was given.",
  219. operator,
  220. expected,
  221. value
  222. )
  223. );
  224. }
  225. };
  226. __name(_InvalidOperatorValueError, "InvalidOperatorValueError");
  227. InvalidOperatorValueError = _InvalidOperatorValueError;
  228. }
  229. });
  230. // src/errors/index.js
  231. var init_errors = __esm({
  232. "src/errors/index.js"() {
  233. "use strict";
  234. init_not_implemented_error();
  235. init_invalid_argument_error();
  236. init_invalid_operator_value_error();
  237. }
  238. });
  239. // src/utils/like-to-regexp.js
  240. function likeToRegexp(pattern, isCaseInsensitive = false) {
  241. if (typeof pattern !== "string") {
  242. throw new InvalidArgumentError(
  243. "The first argument of `likeToRegexp` should be a String, but %v was given.",
  244. pattern
  245. );
  246. }
  247. const regexSpecials = "-[]{}()*+?.\\^$|";
  248. let regexString = "";
  249. let isEscaping = false;
  250. for (const char of pattern) {
  251. if (isEscaping) {
  252. regexString += regexSpecials.includes(char) ? `\\${char}` : char;
  253. isEscaping = false;
  254. } else if (char === "\\") {
  255. isEscaping = true;
  256. } else if (char === "%") {
  257. regexString += ".*";
  258. } else if (char === "_") {
  259. regexString += ".";
  260. } else if (regexSpecials.includes(char)) {
  261. regexString += `\\${char}`;
  262. } else {
  263. regexString += char;
  264. }
  265. }
  266. if (isEscaping) {
  267. regexString += "\\\\";
  268. }
  269. const flags = isCaseInsensitive ? "i" : "";
  270. return new RegExp(`^${regexString}$`, flags);
  271. }
  272. var init_like_to_regexp = __esm({
  273. "src/utils/like-to-regexp.js"() {
  274. "use strict";
  275. init_errors();
  276. __name(likeToRegexp, "likeToRegexp");
  277. }
  278. });
  279. // src/utils/is-plain-object.js
  280. function isPlainObject(value) {
  281. return Boolean(
  282. typeof value === "object" && value && !Array.isArray(value) && (!value.constructor || value.constructor && value.constructor.name === "Object")
  283. );
  284. }
  285. var init_is_plain_object = __esm({
  286. "src/utils/is-plain-object.js"() {
  287. "use strict";
  288. __name(isPlainObject, "isPlainObject");
  289. }
  290. });
  291. // src/utils/string-to-regexp.js
  292. function stringToRegexp(pattern, flags = void 0) {
  293. if (pattern instanceof RegExp) {
  294. return new RegExp(pattern, flags);
  295. }
  296. return new RegExp(pattern, flags);
  297. }
  298. var init_string_to_regexp = __esm({
  299. "src/utils/string-to-regexp.js"() {
  300. "use strict";
  301. __name(stringToRegexp, "stringToRegexp");
  302. }
  303. });
  304. // src/utils/get-value-by-path.js
  305. function getValueByPath(obj, path, orElse = void 0) {
  306. if (!obj || typeof obj !== "object") return orElse;
  307. if (!path || typeof path !== "string") return orElse;
  308. const keys = path.split(".");
  309. let value = obj;
  310. for (const key of keys) {
  311. if (typeof value === "object" && value !== null && key in value) {
  312. value = value[key];
  313. } else {
  314. value = orElse;
  315. break;
  316. }
  317. }
  318. return value;
  319. }
  320. var init_get_value_by_path = __esm({
  321. "src/utils/get-value-by-path.js"() {
  322. "use strict";
  323. __name(getValueByPath, "getValueByPath");
  324. }
  325. });
  326. // src/utils/select-object-keys.js
  327. function selectObjectKeys(obj, keys) {
  328. if (!obj || typeof obj !== "object" || Array.isArray(obj))
  329. throw new InvalidArgumentError(
  330. "The first argument of selectObjectKeys should be an Object, but %v was given.",
  331. obj
  332. );
  333. if (!Array.isArray(keys))
  334. throw new InvalidArgumentError(
  335. "The second argument of selectObjectKeys should be an Array of String, but %v was given.",
  336. keys
  337. );
  338. keys.forEach((key) => {
  339. if (typeof key !== "string")
  340. throw new InvalidArgumentError(
  341. "The second argument of selectObjectKeys should be an Array of String, but %v was given.",
  342. key
  343. );
  344. });
  345. const result = {};
  346. const allKeys = Object.keys(obj);
  347. allKeys.forEach((key) => {
  348. if (keys.includes(key)) result[key] = obj[key];
  349. });
  350. return result;
  351. }
  352. var init_select_object_keys = __esm({
  353. "src/utils/select-object-keys.js"() {
  354. "use strict";
  355. init_errors();
  356. __name(selectObjectKeys, "selectObjectKeys");
  357. }
  358. });
  359. // src/utils/exclude-object-keys.js
  360. function excludeObjectKeys(obj, keys) {
  361. if (typeof obj !== "object" || !obj || Array.isArray(obj))
  362. throw new InvalidArgumentError(
  363. "Cannot exclude keys from a non-Object value, %v was given.",
  364. obj
  365. );
  366. const result = { ...obj };
  367. keys = Array.isArray(keys) ? keys : [keys];
  368. keys.forEach((key) => delete result[key]);
  369. return result;
  370. }
  371. var init_exclude_object_keys = __esm({
  372. "src/utils/exclude-object-keys.js"() {
  373. "use strict";
  374. init_errors();
  375. __name(excludeObjectKeys, "excludeObjectKeys");
  376. }
  377. });
  378. // src/utils/model-name-to-model-key.js
  379. function modelNameToModelKey(modelName) {
  380. if (!modelName || typeof modelName !== "string" || /\s/.test(modelName))
  381. throw new InvalidArgumentError(
  382. "The model name should be a non-empty String without spaces, but %v was given.",
  383. modelName
  384. );
  385. return modelName.toLowerCase().replace(/[-_]/g, "");
  386. }
  387. var init_model_name_to_model_key = __esm({
  388. "src/utils/model-name-to-model-key.js"() {
  389. "use strict";
  390. init_errors();
  391. __name(modelNameToModelKey, "modelNameToModelKey");
  392. }
  393. });
  394. // src/utils/index.js
  395. var init_utils = __esm({
  396. "src/utils/index.js"() {
  397. "use strict";
  398. init_is_promise();
  399. init_capitalize();
  400. init_clone_deep();
  401. init_singularize();
  402. init_is_deep_equal();
  403. init_like_to_regexp();
  404. init_is_plain_object();
  405. init_string_to_regexp();
  406. init_get_value_by_path();
  407. init_select_object_keys();
  408. init_exclude_object_keys();
  409. init_model_name_to_model_key();
  410. }
  411. });
  412. // src/filter/slice-clause-tool.js
  413. var import_js_service, _SliceClauseTool, SliceClauseTool;
  414. var init_slice_clause_tool = __esm({
  415. "src/filter/slice-clause-tool.js"() {
  416. "use strict";
  417. import_js_service = require("@e22m4u/js-service");
  418. init_errors();
  419. _SliceClauseTool = class _SliceClauseTool extends import_js_service.Service {
  420. /**
  421. * Slice.
  422. *
  423. * @param {object[]} entities
  424. * @param {number|undefined} skip
  425. * @param {number|undefined} limit
  426. * @returns {object[]}
  427. */
  428. slice(entities, skip = void 0, limit = void 0) {
  429. if (!Array.isArray(entities))
  430. throw new InvalidArgumentError(
  431. "The first argument of SliceClauseTool.slice should be an Array, but %v was given.",
  432. entities
  433. );
  434. if (skip != null && typeof skip !== "number")
  435. throw new InvalidArgumentError(
  436. 'The provided option "skip" should be a Number, but %v was given.',
  437. skip
  438. );
  439. if (limit != null && typeof limit !== "number")
  440. throw new InvalidArgumentError(
  441. 'The provided option "limit" should be a Number, but %v was given.',
  442. limit
  443. );
  444. skip = skip || 0;
  445. limit = limit || entities.length;
  446. return entities.slice(skip, skip + limit);
  447. }
  448. /**
  449. * Validate skip clause.
  450. *
  451. * @param {number|undefined} skip
  452. */
  453. static validateSkipClause(skip) {
  454. if (skip == null) return;
  455. if (typeof skip !== "number")
  456. throw new InvalidArgumentError(
  457. 'The provided option "skip" should be a Number, but %v was given.',
  458. skip
  459. );
  460. }
  461. /**
  462. * Validate limit clause.
  463. *
  464. * @param {number|undefined} limit
  465. */
  466. static validateLimitClause(limit) {
  467. if (limit == null) return;
  468. if (typeof limit !== "number")
  469. throw new InvalidArgumentError(
  470. 'The provided option "limit" should be a Number, but %v was given.',
  471. limit
  472. );
  473. }
  474. };
  475. __name(_SliceClauseTool, "SliceClauseTool");
  476. SliceClauseTool = _SliceClauseTool;
  477. }
  478. });
  479. // src/filter/order-clause-tool.js
  480. function compareFn(a, b) {
  481. let undefinedA, undefinedB;
  482. for (let i = 0, l = this.length; i < l; i++) {
  483. const aVal = getValueByPath(a, this[i].key);
  484. const bVal = getValueByPath(b, this[i].key);
  485. undefinedB = bVal === void 0 && aVal !== void 0;
  486. undefinedA = aVal === void 0 && bVal !== void 0;
  487. if (undefinedB || aVal > bVal) {
  488. return this[i].reverse;
  489. } else if (undefinedA || aVal < bVal) {
  490. return -1 * this[i].reverse;
  491. }
  492. }
  493. return 0;
  494. }
  495. var import_js_service2, _OrderClauseTool, OrderClauseTool;
  496. var init_order_clause_tool = __esm({
  497. "src/filter/order-clause-tool.js"() {
  498. "use strict";
  499. import_js_service2 = require("@e22m4u/js-service");
  500. init_utils();
  501. init_errors();
  502. _OrderClauseTool = class _OrderClauseTool extends import_js_service2.Service {
  503. /**
  504. * Sort.
  505. *
  506. * @param {object[]} entities
  507. * @param {string|string[]|undefined} clause
  508. */
  509. sort(entities, clause) {
  510. if (clause == null) return;
  511. if (Array.isArray(clause) === false) clause = [clause];
  512. if (!clause.length) return;
  513. const mapping = [];
  514. clause.forEach((key, index) => {
  515. if (!key || typeof key !== "string")
  516. throw new InvalidArgumentError(
  517. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v was given.',
  518. key
  519. );
  520. let reverse = 1;
  521. const matches = key.match(/\s+(A|DE)SC$/i);
  522. if (matches) {
  523. key = key.replace(/\s+(A|DE)SC/i, "");
  524. if (matches[1].toLowerCase() === "de") reverse = -1;
  525. }
  526. mapping[index] = { key, reverse };
  527. });
  528. entities.sort(compareFn.bind(mapping));
  529. }
  530. /**
  531. * Validate order clause.
  532. *
  533. * @param {string|string[]|undefined} clause
  534. */
  535. static validateOrderClause(clause) {
  536. if (clause == null) return;
  537. if (Array.isArray(clause) === false) clause = [clause];
  538. if (!clause.length) return;
  539. clause.forEach((field) => {
  540. if (!field || typeof field !== "string")
  541. throw new InvalidArgumentError(
  542. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v was given.',
  543. field
  544. );
  545. });
  546. }
  547. /**
  548. * Normalize order clause.
  549. *
  550. * @param {string|string[]|undefined} clause
  551. * @returns {string[]|undefined}
  552. */
  553. static normalizeOrderClause(clause) {
  554. if (clause == null) return;
  555. if (Array.isArray(clause) === false) clause = [clause];
  556. if (!clause.length) return;
  557. clause.forEach((field) => {
  558. if (!field || typeof field !== "string")
  559. throw new InvalidArgumentError(
  560. 'The provided option "order" should be a non-empty String or an Array of non-empty String, but %v was given.',
  561. field
  562. );
  563. });
  564. return clause;
  565. }
  566. };
  567. __name(_OrderClauseTool, "OrderClauseTool");
  568. OrderClauseTool = _OrderClauseTool;
  569. __name(compareFn, "compareFn");
  570. }
  571. });
  572. // src/filter/operator-clause-tool.js
  573. var import_js_service3, _OperatorClauseTool, OperatorClauseTool;
  574. var init_operator_clause_tool = __esm({
  575. "src/filter/operator-clause-tool.js"() {
  576. "use strict";
  577. import_js_service3 = require("@e22m4u/js-service");
  578. init_utils();
  579. init_errors();
  580. _OperatorClauseTool = class _OperatorClauseTool extends import_js_service3.Service {
  581. /**
  582. * Compare.
  583. *
  584. * @param {*} val1 The 1st value
  585. * @param {*} val2 The 2nd value
  586. * @param {*} noTypeConversion
  587. * @returns {number} 0: =, positive: >, negative <
  588. */
  589. compare(val1, val2, noTypeConversion = false) {
  590. if (val1 === val2) {
  591. return 0;
  592. }
  593. if (val1 == null || val2 == null) {
  594. return val1 == val2 ? 0 : NaN;
  595. }
  596. const type1 = typeof val1;
  597. const type2 = typeof val2;
  598. if (type1 === "object" || type2 === "object") {
  599. return isDeepEqual(val1, val2) ? 0 : NaN;
  600. }
  601. if ((type1 === "number" || type1 === "string" || type1 === "boolean") && (type2 === "number" || type2 === "string" || type2 === "boolean")) {
  602. if (noTypeConversion && type1 !== type2) {
  603. return NaN;
  604. }
  605. const num1 = Number(val1);
  606. const num2 = Number(val2);
  607. if (!isNaN(num1) && !isNaN(num2)) {
  608. return num1 - num2;
  609. }
  610. }
  611. if (type1 === "string" && type2 === "string") {
  612. if (val1 > val2) return 1;
  613. if (val1 < val2) return -1;
  614. return 0;
  615. }
  616. return NaN;
  617. }
  618. /**
  619. * Test all operators.
  620. *
  621. * @param {object} clause
  622. * @param {*} value
  623. * @returns {boolean|undefined}
  624. */
  625. testAll(clause, value) {
  626. if (!clause || typeof clause !== "object" || Array.isArray(clause))
  627. throw new InvalidArgumentError(
  628. "The first argument of OperatorUtils.testAll should be an Object, but %v was given.",
  629. clause
  630. );
  631. const operatorMap = {
  632. eq: this.testEqNeq,
  633. neq: this.testEqNeq,
  634. gt: this.testGtLt,
  635. gte: this.testGtLt,
  636. lt: this.testGtLt,
  637. lte: this.testGtLt,
  638. inq: this.testInq,
  639. nin: this.testNin,
  640. between: this.testBetween,
  641. exists: this.testExists,
  642. like: this.testLike,
  643. nlike: this.testNlike,
  644. ilike: this.testIlike,
  645. nilike: this.testNilike,
  646. regexp: this.testRegexp
  647. };
  648. const clauseKeys = Object.keys(clause);
  649. const knownOperators = clauseKeys.filter((key) => operatorMap[key]);
  650. if (knownOperators.length === 0) {
  651. return void 0;
  652. }
  653. return knownOperators.every((op) => {
  654. const singleOpClause = { [op]: clause[op] };
  655. if (op === "regexp" && "flags" in clause) {
  656. singleOpClause.flags = clause.flags;
  657. }
  658. const testFn = operatorMap[op];
  659. const result = testFn.call(this, singleOpClause, value);
  660. return result;
  661. });
  662. }
  663. /**
  664. * Test eq/neq operator.
  665. *
  666. * @example
  667. * ```ts
  668. * {
  669. * eq: 'foo',
  670. * }
  671. * ```
  672. *
  673. * @example
  674. * ```ts
  675. * {
  676. * neq: 'foo',
  677. * }
  678. * ```
  679. *
  680. * @param {object} clause
  681. * @param {*} value
  682. * @returns {boolean|undefined}
  683. */
  684. testEqNeq(clause, value) {
  685. if (!clause || typeof clause !== "object")
  686. throw new InvalidArgumentError(
  687. "The first argument of OperatorUtils.testEqNeq should be an Object, but %v was given.",
  688. clause
  689. );
  690. if ("eq" in clause) return this.compare(clause.eq, value, true) === 0;
  691. if ("neq" in clause) return this.compare(clause.neq, value, true) !== 0;
  692. }
  693. /**
  694. * Test lt/gt/lte/gte operator.
  695. *
  696. * @example
  697. * ```ts
  698. * {
  699. * lt: 10,
  700. * }
  701. * ```
  702. *
  703. * @example
  704. * ```ts
  705. * {
  706. * lte: 10,
  707. * }
  708. * ```
  709. *
  710. * @example
  711. * ```ts
  712. * {
  713. * gt: 10,
  714. * }
  715. * ```
  716. *
  717. * @example
  718. * ```ts
  719. * {
  720. * gte: 10,
  721. * }
  722. * ```
  723. *
  724. * @param {object} clause
  725. * @param {*} value
  726. * @returns {boolean|undefined}
  727. */
  728. testGtLt(clause, value) {
  729. if (!clause || typeof clause !== "object")
  730. throw new InvalidArgumentError(
  731. "The first argument of OperatorUtils.testGtLt should be an Object, but %v was given.",
  732. clause
  733. );
  734. if ("gt" in clause) return this.compare(value, clause.gt) > 0;
  735. if ("gte" in clause) return this.compare(value, clause.gte) >= 0;
  736. if ("lt" in clause) return this.compare(value, clause.lt) < 0;
  737. if ("lte" in clause) return this.compare(value, clause.lte) <= 0;
  738. }
  739. /**
  740. * Test inc operator.
  741. *
  742. * @example
  743. * ```ts
  744. * {
  745. * inc: ['foo', 'bar'],
  746. * }
  747. * ```
  748. *
  749. * @param {object} clause
  750. * @param {*} value
  751. * @returns {boolean|undefined}
  752. */
  753. testInq(clause, value) {
  754. if (!clause || typeof clause !== "object")
  755. throw new InvalidArgumentError(
  756. "The first argument of OperatorUtils.testInq should be an Object, but %v was given.",
  757. clause
  758. );
  759. if ("inq" in clause && clause.inq !== void 0) {
  760. if (!clause.inq || !Array.isArray(clause.inq)) {
  761. throw new InvalidOperatorValueError(
  762. "inq",
  763. "an Array of possible values",
  764. clause.inq
  765. );
  766. }
  767. for (let i = 0; i < clause.inq.length; i++) {
  768. if (this.compare(clause.inq[i], value, true) === 0) {
  769. return true;
  770. }
  771. }
  772. return false;
  773. }
  774. }
  775. /**
  776. * Test nin operator.
  777. *
  778. * @example
  779. * ```ts
  780. * {
  781. * nin: ['foo', 'bar'],
  782. * }
  783. * ```
  784. *
  785. * @param {object} clause
  786. * @param {*} value
  787. * @returns {boolean|undefined}
  788. */
  789. testNin(clause, value) {
  790. if (!clause || typeof clause !== "object")
  791. throw new InvalidArgumentError(
  792. "The first argument of OperatorUtils.testNin should be an Object, but %v was given.",
  793. clause
  794. );
  795. if ("nin" in clause && clause.nin !== void 0) {
  796. if (!clause.nin || !Array.isArray(clause.nin)) {
  797. throw new InvalidOperatorValueError(
  798. "nin",
  799. "an Array of possible values",
  800. clause.nin
  801. );
  802. }
  803. return clause.nin.every((element) => {
  804. return this.compare(element, value, true) !== 0;
  805. });
  806. }
  807. }
  808. /**
  809. * Test between operator.
  810. *
  811. * @example
  812. * ```ts
  813. * {
  814. * between: [10, 20],
  815. * }
  816. * ```
  817. *
  818. * @param {object} clause
  819. * @param {*} value
  820. * @returns {boolean|undefined}
  821. */
  822. testBetween(clause, value) {
  823. if (!clause || typeof clause !== "object")
  824. throw new InvalidArgumentError(
  825. "The first argument of OperatorUtils.testBetween should be an Object, but %v was given.",
  826. clause
  827. );
  828. if ("between" in clause && clause.between !== void 0) {
  829. if (!Array.isArray(clause.between) || clause.between.length !== 2) {
  830. throw new InvalidOperatorValueError(
  831. "between",
  832. "an Array of 2 elements",
  833. clause.between
  834. );
  835. }
  836. return this.testGtLt({ gte: clause.between[0] }, value) && this.testGtLt({ lte: clause.between[1] }, value);
  837. }
  838. }
  839. /**
  840. * Test exists operator.
  841. *
  842. * @example
  843. * ```ts
  844. * {
  845. * exists: true,
  846. * }
  847. * ```
  848. *
  849. * @param {object} clause
  850. * @param {*} value
  851. * @returns {boolean|undefined}
  852. */
  853. testExists(clause, value) {
  854. if (!clause || typeof clause !== "object")
  855. throw new InvalidArgumentError(
  856. "The first argument of OperatorUtils.testExists should be an Object, but %v was given.",
  857. clause
  858. );
  859. if ("exists" in clause && clause.exists !== void 0) {
  860. if (typeof clause.exists !== "boolean") {
  861. throw new InvalidOperatorValueError(
  862. "exists",
  863. "a Boolean",
  864. clause.exists
  865. );
  866. }
  867. return clause.exists ? value !== void 0 : value === void 0;
  868. }
  869. }
  870. /**
  871. * Test like operator.
  872. *
  873. * @example
  874. * ```ts
  875. * {
  876. * like: 'foo',
  877. * }
  878. * ```
  879. *
  880. * @param {object} clause
  881. * @param {*} value
  882. * @returns {boolean|undefined}
  883. */
  884. testLike(clause, value) {
  885. if (!clause || typeof clause !== "object" || Array.isArray(clause))
  886. throw new InvalidArgumentError(
  887. "The first argument of OperatorUtils.testLike should be an Object, but %v was given.",
  888. clause
  889. );
  890. if ("like" in clause && clause.like !== void 0) {
  891. if (typeof clause.like !== "string")
  892. throw new InvalidOperatorValueError("like", "a String", clause.like);
  893. return likeToRegexp(clause.like).test(value);
  894. }
  895. }
  896. /**
  897. * Test nlike operator.
  898. *
  899. * @example
  900. * ```ts
  901. * {
  902. * nlike: 'foo',
  903. * }
  904. * ```
  905. *
  906. * @param {object} clause
  907. * @param {*} value
  908. * @returns {boolean|undefined}
  909. */
  910. testNlike(clause, value) {
  911. if (!clause || typeof clause !== "object" || Array.isArray(clause))
  912. throw new InvalidArgumentError(
  913. "The first argument of OperatorUtils.testNlike should be an Object, but %v was given.",
  914. clause
  915. );
  916. if ("nlike" in clause && clause.nlike !== void 0) {
  917. if (typeof clause.nlike !== "string") {
  918. throw new InvalidOperatorValueError("nlike", "a String", clause.nlike);
  919. }
  920. return !likeToRegexp(clause.nlike).test(value);
  921. }
  922. }
  923. /**
  924. * Test ilike operator.
  925. *
  926. * @example
  927. * ```ts
  928. * {
  929. * ilike: 'foo',
  930. * }
  931. * ```
  932. *
  933. * @param {object} clause
  934. * @param {*} value
  935. * @returns {boolean|undefined}
  936. */
  937. testIlike(clause, value) {
  938. if (!clause || typeof clause !== "object" || Array.isArray(clause))
  939. throw new InvalidArgumentError(
  940. "The first argument of OperatorUtils.testIlike should be an Object, but %v was given.",
  941. clause
  942. );
  943. if ("ilike" in clause && clause.ilike !== void 0) {
  944. if (typeof clause.ilike !== "string") {
  945. throw new InvalidOperatorValueError("ilike", "a String", clause.ilike);
  946. }
  947. return likeToRegexp(clause.ilike, true).test(value);
  948. }
  949. }
  950. /**
  951. * Test nilike operator.
  952. *
  953. * @example
  954. * ```ts
  955. * {
  956. * nilike: 'foo',
  957. * }
  958. * ```
  959. *
  960. * @param {object} clause
  961. * @param {*} value
  962. * @returns {boolean|undefined}
  963. */
  964. testNilike(clause, value) {
  965. if (!clause || typeof clause !== "object" || Array.isArray(clause))
  966. throw new InvalidArgumentError(
  967. "The first argument of OperatorUtils.testNilike should be an Object, but %v was given.",
  968. clause
  969. );
  970. if ("nilike" in clause && clause.nilike !== void 0) {
  971. if (typeof clause.nilike !== "string") {
  972. throw new InvalidOperatorValueError(
  973. "nilike",
  974. "a String",
  975. clause.nilike
  976. );
  977. }
  978. return !likeToRegexp(clause.nilike, true).test(value);
  979. }
  980. }
  981. /**
  982. * Test regexp.
  983. *
  984. * @example
  985. * ```ts
  986. * {
  987. * regexp: 'foo.*',
  988. * }
  989. * ```
  990. *
  991. * @example
  992. * ```ts
  993. * {
  994. * regexp: 'foo.*',
  995. * flags: 'i',
  996. * }
  997. * ```
  998. *
  999. * @param {object} clause
  1000. * @param {*} value
  1001. * @returns {boolean|undefined}
  1002. */
  1003. testRegexp(clause, value) {
  1004. if (!clause || typeof clause !== "object")
  1005. throw new InvalidArgumentError(
  1006. "The first argument of OperatorUtils.testRegexp should be an Object, but %v was given.",
  1007. clause
  1008. );
  1009. if ("regexp" in clause && clause.regexp !== void 0) {
  1010. if (typeof clause.regexp !== "string" && !(clause.regexp instanceof RegExp)) {
  1011. throw new InvalidOperatorValueError(
  1012. "regexp",
  1013. "a String",
  1014. clause.regexp
  1015. );
  1016. }
  1017. const flags = clause.flags || void 0;
  1018. if (flags && typeof flags !== "string")
  1019. throw new InvalidArgumentError(
  1020. "RegExp flags should be a String, but %v was given.",
  1021. clause.flags
  1022. );
  1023. if (!value || typeof value !== "string") return false;
  1024. const regExp = stringToRegexp(clause.regexp, flags);
  1025. return !!value.match(regExp);
  1026. }
  1027. }
  1028. };
  1029. __name(_OperatorClauseTool, "OperatorClauseTool");
  1030. OperatorClauseTool = _OperatorClauseTool;
  1031. }
  1032. });
  1033. // src/filter/where-clause-tool.js
  1034. var import_js_service4, _WhereClauseTool, WhereClauseTool;
  1035. var init_where_clause_tool = __esm({
  1036. "src/filter/where-clause-tool.js"() {
  1037. "use strict";
  1038. import_js_service4 = require("@e22m4u/js-service");
  1039. init_errors();
  1040. init_operator_clause_tool();
  1041. init_utils();
  1042. _WhereClauseTool = class _WhereClauseTool extends import_js_service4.Service {
  1043. /**
  1044. * Filter by where clause.
  1045. *
  1046. * @example
  1047. * ```
  1048. * const entities = [
  1049. * {foo: 1, bar: 'a'},
  1050. * {foo: 2, bar: 'b'},
  1051. * {foo: 3, bar: 'b'},
  1052. * {foo: 4, bar: 'b'},
  1053. * ];
  1054. *
  1055. * const result = filterByWhereClause(entities, {
  1056. * foo: {gt: 2},
  1057. * bar: 'b',
  1058. * });
  1059. *
  1060. * console.log(result);
  1061. * // [
  1062. * // {foo: 3, bar: 'b'},
  1063. * // {foo: 4, bar: 'b'},
  1064. * // ];
  1065. *
  1066. * ```
  1067. *
  1068. * @param {object[]} entities
  1069. * @param {WhereClause|undefined} where
  1070. * @returns {object[]}
  1071. */
  1072. filter(entities, where = void 0) {
  1073. if (!Array.isArray(entities))
  1074. throw new InvalidArgumentError(
  1075. "The first argument of WhereClauseTool.filter should be an Array of Object, but %v was given.",
  1076. entities
  1077. );
  1078. if (where == null) return entities;
  1079. return entities.filter(this._createFilter(where));
  1080. }
  1081. /**
  1082. * Create where filter.
  1083. *
  1084. * @param {WhereClause} whereClause
  1085. * @returns {Function}
  1086. */
  1087. _createFilter(whereClause) {
  1088. if (typeof whereClause !== "object" || Array.isArray(whereClause))
  1089. throw new InvalidArgumentError(
  1090. 'The provided option "where" should be an Object, but %v was given.',
  1091. whereClause
  1092. );
  1093. const keys = Object.keys(whereClause);
  1094. return (data) => {
  1095. if (typeof data !== "object")
  1096. throw new InvalidArgumentError(
  1097. "The first argument of WhereClauseTool.filter should be an Array of Object, but %v was given.",
  1098. data
  1099. );
  1100. return keys.every((key) => {
  1101. if (key === "and" && key in whereClause) {
  1102. const andClause = whereClause[key];
  1103. if (Array.isArray(andClause))
  1104. return andClause.every((clause) => this._createFilter(clause)(data));
  1105. } else if (key === "or" && key in whereClause) {
  1106. const orClause = whereClause[key];
  1107. if (Array.isArray(orClause))
  1108. return orClause.some((clause) => this._createFilter(clause)(data));
  1109. }
  1110. const value = getValueByPath(data, key);
  1111. const matcher = whereClause[key];
  1112. if (this._test(matcher, value)) return true;
  1113. });
  1114. };
  1115. }
  1116. /**
  1117. * Value testing.
  1118. *
  1119. * @param {*} example
  1120. * @param {*} value
  1121. * @returns {boolean}
  1122. */
  1123. _test(example, value) {
  1124. if (example === value) {
  1125. return true;
  1126. }
  1127. if (example === null) {
  1128. return value === null;
  1129. }
  1130. if (example === void 0) {
  1131. return value === void 0;
  1132. }
  1133. if (example instanceof RegExp) {
  1134. if (typeof value === "string") {
  1135. return example.test(value);
  1136. }
  1137. if (Array.isArray(value)) {
  1138. return value.some((el) => typeof el === "string" && example.test(el));
  1139. }
  1140. return false;
  1141. }
  1142. if (isPlainObject(example)) {
  1143. const operatorsTest = this.getService(OperatorClauseTool).testAll(
  1144. example,
  1145. value
  1146. );
  1147. if (operatorsTest !== void 0) {
  1148. if ("neq" in example && Array.isArray(value)) {
  1149. return !value.some((el) => isDeepEqual(el, example.neq));
  1150. }
  1151. return operatorsTest;
  1152. }
  1153. }
  1154. if (Array.isArray(value)) {
  1155. const isElementMatched = value.some((el) => isDeepEqual(el, example));
  1156. if (isElementMatched) return true;
  1157. }
  1158. return isDeepEqual(example, value);
  1159. }
  1160. /**
  1161. * Validate where clause.
  1162. *
  1163. * @param {WhereClause|undefined} clause
  1164. */
  1165. static validateWhereClause(clause) {
  1166. if (clause == null || typeof clause === "function") return;
  1167. if (typeof clause !== "object" || Array.isArray(clause))
  1168. throw new InvalidArgumentError(
  1169. 'The provided option "where" should be an Object, but %v was given.',
  1170. clause
  1171. );
  1172. }
  1173. };
  1174. __name(_WhereClauseTool, "WhereClauseTool");
  1175. WhereClauseTool = _WhereClauseTool;
  1176. }
  1177. });
  1178. // src/definition/model/relations/relation-type.js
  1179. var RelationType;
  1180. var init_relation_type = __esm({
  1181. "src/definition/model/relations/relation-type.js"() {
  1182. "use strict";
  1183. RelationType = {
  1184. BELONGS_TO: "belongsTo",
  1185. HAS_ONE: "hasOne",
  1186. HAS_MANY: "hasMany",
  1187. REFERENCES_MANY: "referencesMany"
  1188. };
  1189. }
  1190. });
  1191. // src/definition/model/relations/relation-definition.js
  1192. var init_relation_definition = __esm({
  1193. "src/definition/model/relations/relation-definition.js"() {
  1194. "use strict";
  1195. }
  1196. });
  1197. // src/definition/model/relations/relations-definition-validator.js
  1198. var import_js_service5, _RelationsDefinitionValidator, RelationsDefinitionValidator;
  1199. var init_relations_definition_validator = __esm({
  1200. "src/definition/model/relations/relations-definition-validator.js"() {
  1201. "use strict";
  1202. import_js_service5 = require("@e22m4u/js-service");
  1203. init_relation_type();
  1204. init_errors();
  1205. _RelationsDefinitionValidator = class _RelationsDefinitionValidator extends import_js_service5.Service {
  1206. /**
  1207. * Validate.
  1208. *
  1209. * @param {string} modelName
  1210. * @param {object} relDefs
  1211. */
  1212. validate(modelName, relDefs) {
  1213. if (!modelName || typeof modelName !== "string")
  1214. throw new InvalidArgumentError(
  1215. "The first argument of RelationsDefinitionValidator.validate should be a non-empty String, but %v was given.",
  1216. modelName
  1217. );
  1218. if (!relDefs || typeof relDefs !== "object" || Array.isArray(relDefs))
  1219. throw new InvalidArgumentError(
  1220. 'The provided option "relations" of the model %v should be an Object, but %v was given.',
  1221. modelName,
  1222. relDefs
  1223. );
  1224. const relNames = Object.keys(relDefs);
  1225. relNames.forEach((relName) => {
  1226. const relDef = relDefs[relName];
  1227. this._validateRelation(modelName, relName, relDef);
  1228. });
  1229. }
  1230. /**
  1231. * Validate relation.
  1232. *
  1233. * @param {string} modelName
  1234. * @param {string} relName
  1235. * @param {object} relDef
  1236. */
  1237. _validateRelation(modelName, relName, relDef) {
  1238. if (!modelName || typeof modelName !== "string")
  1239. throw new InvalidArgumentError(
  1240. "The first argument of RelationsDefinitionValidator._validateRelation should be a non-empty String, but %v was given.",
  1241. modelName
  1242. );
  1243. if (!relName || typeof relName !== "string")
  1244. throw new InvalidArgumentError(
  1245. "The relation name of the model %v should be a non-empty String, but %v was given.",
  1246. modelName,
  1247. relName
  1248. );
  1249. if (!relDef || typeof relDef !== "object" || Array.isArray(relDef))
  1250. throw new InvalidArgumentError(
  1251. "The relation %v of the model %v should be an Object, but %v was given.",
  1252. relName,
  1253. modelName,
  1254. relDef
  1255. );
  1256. if (!relDef.type || !Object.values(RelationType).includes(relDef.type))
  1257. throw new InvalidArgumentError(
  1258. 'The relation %v of the model %v requires the option "type" to have one of relation types: %l, but %v was given.',
  1259. relName,
  1260. modelName,
  1261. Object.values(RelationType),
  1262. relDef.type
  1263. );
  1264. this._validateBelongsTo(modelName, relName, relDef);
  1265. this._validateHasOne(modelName, relName, relDef);
  1266. this._validateHasMany(modelName, relName, relDef);
  1267. this._validateReferencesMany(modelName, relName, relDef);
  1268. }
  1269. /**
  1270. * Validate "belongsTo".
  1271. *
  1272. * @example The regular "belongsTo" relation.
  1273. * ```
  1274. * {
  1275. * type: RelationType.BELONGS_TO,
  1276. * model: 'model',
  1277. * foreignKey: 'modelId', // optional
  1278. * }
  1279. * ```
  1280. *
  1281. * @example The polymorphic "belongsTo" relation.
  1282. * ```
  1283. * {
  1284. * type: RelationType.BELONGS_TO,
  1285. * polymorphic: true,
  1286. * foreignKey: 'referenceId', // optional
  1287. * discriminator: 'referenceType', // optional
  1288. * }
  1289. * ```
  1290. *
  1291. * @param {string} modelName
  1292. * @param {string} relName
  1293. * @param {object} relDef
  1294. * @private
  1295. */
  1296. _validateBelongsTo(modelName, relName, relDef) {
  1297. if (relDef.type !== RelationType.BELONGS_TO) return;
  1298. if (relDef.polymorphic) {
  1299. if (typeof relDef.polymorphic !== "boolean")
  1300. throw new InvalidArgumentError(
  1301. 'The relation %v of the model %v has the type "belongsTo", so it expects the option "polymorphic" to be a Boolean, but %v was given.',
  1302. relName,
  1303. modelName,
  1304. relDef.polymorphic
  1305. );
  1306. if (relDef.foreignKey && typeof relDef.foreignKey !== "string")
  1307. throw new InvalidArgumentError(
  1308. 'The relation %v of the model %v is a polymorphic "belongsTo" relation, so it expects the provided option "foreignKey" to be a String, but %v was given.',
  1309. relName,
  1310. modelName,
  1311. relDef.foreignKey
  1312. );
  1313. if (relDef.discriminator && typeof relDef.discriminator !== "string")
  1314. throw new InvalidArgumentError(
  1315. 'The relation %v of the model %v is a polymorphic "belongsTo" relation, so it expects the provided option "discriminator" to be a String, but %v was given.',
  1316. relName,
  1317. modelName,
  1318. relDef.discriminator
  1319. );
  1320. } else {
  1321. if (!relDef.model || typeof relDef.model !== "string")
  1322. throw new InvalidArgumentError(
  1323. 'The relation %v of the model %v has the type "belongsTo", so it requires the option "model" to be a non-empty String, but %v was given.',
  1324. relName,
  1325. modelName,
  1326. relDef.model
  1327. );
  1328. if (relDef.foreignKey && typeof relDef.foreignKey !== "string")
  1329. throw new InvalidArgumentError(
  1330. 'The relation %v of the model %v has the type "belongsTo", so it expects the provided option "foreignKey" to be a String, but %v was given.',
  1331. relName,
  1332. modelName,
  1333. relDef.foreignKey
  1334. );
  1335. if (relDef.discriminator)
  1336. throw new InvalidArgumentError(
  1337. 'The relation %v of the model %v is a non-polymorphic "belongsTo" relation, so it should not have the option "discriminator" to be provided.',
  1338. relName,
  1339. modelName
  1340. );
  1341. }
  1342. }
  1343. /**
  1344. * Validate "hasOne".
  1345. *
  1346. * @example The regular "hasOne" relation.
  1347. * ```
  1348. * {
  1349. * type: RelationType.HAS_ONE,
  1350. * model: 'model',
  1351. * foreignKey: 'modelId',
  1352. * }
  1353. * ```
  1354. *
  1355. * @example The polymorphic "hasOne" relation with a target relation name.
  1356. * ```
  1357. * {
  1358. * type: RelationType.HAS_ONE,
  1359. * model: 'model',
  1360. * polymorphic: 'reference',
  1361. * }
  1362. * ```
  1363. *
  1364. * @example The polymorphic "hasOne" relation with target relation keys.
  1365. * ```
  1366. * {
  1367. * type: RelationType.HAS_ONE,
  1368. * model: 'model',
  1369. * polymorphic: true,
  1370. * foreignKey: 'referenceId',
  1371. * discriminator: 'referenceType',
  1372. * }
  1373. * ```
  1374. *
  1375. * @param {string} modelName
  1376. * @param {string} relName
  1377. * @param {object} relDef
  1378. * @private
  1379. */
  1380. _validateHasOne(modelName, relName, relDef) {
  1381. if (relDef.type !== RelationType.HAS_ONE) return;
  1382. if (!relDef.model || typeof relDef.model !== "string")
  1383. throw new InvalidArgumentError(
  1384. 'The relation %v of the model %v has the type "hasOne", so it requires the option "model" to be a non-empty String, but %v was given.',
  1385. relName,
  1386. modelName,
  1387. relDef.model
  1388. );
  1389. if (relDef.polymorphic) {
  1390. if (typeof relDef.polymorphic === "string") {
  1391. if (relDef.foreignKey)
  1392. throw new InvalidArgumentError(
  1393. 'The relation %v of the model %v has the option "polymorphic" with a String value, so it should not have the option "foreignKey" to be provided.',
  1394. relName,
  1395. modelName
  1396. );
  1397. if (relDef.discriminator)
  1398. throw new InvalidArgumentError(
  1399. 'The relation %v of the model %v has the option "polymorphic" with a String value, so it should not have the option "discriminator" to be provided.',
  1400. relName,
  1401. modelName
  1402. );
  1403. } else if (typeof relDef.polymorphic === "boolean") {
  1404. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  1405. throw new InvalidArgumentError(
  1406. 'The relation %v of the model %v has the option "polymorphic" with "true" value, so it requires the option "foreignKey" to be a non-empty String, but %v was given.',
  1407. relName,
  1408. modelName,
  1409. relDef.foreignKey
  1410. );
  1411. if (!relDef.discriminator || typeof relDef.discriminator !== "string")
  1412. throw new InvalidArgumentError(
  1413. 'The relation %v of the model %v has the option "polymorphic" with "true" value, so it requires the option "discriminator" to be a non-empty String, but %v was given.',
  1414. relName,
  1415. modelName,
  1416. relDef.discriminator
  1417. );
  1418. } else {
  1419. throw new InvalidArgumentError(
  1420. 'The relation %v of the model %v has the type "hasOne", so it expects the provided option "polymorphic" to be a String or a Boolean, but %v was given.',
  1421. relName,
  1422. modelName,
  1423. relDef.polymorphic
  1424. );
  1425. }
  1426. } else {
  1427. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  1428. throw new InvalidArgumentError(
  1429. 'The relation %v of the model %v has the type "hasOne", so it requires the option "foreignKey" to be a non-empty String, but %v was given.',
  1430. relName,
  1431. modelName,
  1432. relDef.foreignKey
  1433. );
  1434. if (relDef.discriminator)
  1435. throw new InvalidArgumentError(
  1436. 'The relation %v of the model %v is a non-polymorphic "hasOne" relation, so it should not have the option "discriminator" to be provided.',
  1437. relName,
  1438. modelName
  1439. );
  1440. }
  1441. }
  1442. /**
  1443. * Validate "hasMany".
  1444. *
  1445. * @example The regular "hasMany" relation.
  1446. * ```
  1447. * {
  1448. * type: RelationType.HAS_MANY,
  1449. * model: 'model',
  1450. * foreignKey: 'modelId',
  1451. * }
  1452. * ```
  1453. *
  1454. * @example The polymorphic "hasMany" relation with a target relation name.
  1455. * ```
  1456. * {
  1457. * type: RelationType.HAS_MANY,
  1458. * model: 'model',
  1459. * polymorphic: 'reference',
  1460. * }
  1461. * ```
  1462. *
  1463. * @example The polymorphic "hasMany" relation with target relation keys.
  1464. * ```
  1465. * {
  1466. * type: RelationType.HAS_MANY,
  1467. * model: 'model',
  1468. * polymorphic: true,
  1469. * foreignKey: 'referenceId',
  1470. * discriminator: 'referenceType',
  1471. * }
  1472. * ```
  1473. *
  1474. * @param {string} modelName
  1475. * @param {string} relName
  1476. * @param {object} relDef
  1477. * @private
  1478. */
  1479. _validateHasMany(modelName, relName, relDef) {
  1480. if (relDef.type !== RelationType.HAS_MANY) return;
  1481. if (!relDef.model || typeof relDef.model !== "string")
  1482. throw new InvalidArgumentError(
  1483. 'The relation %v of the model %v has the type "hasMany", so it requires the option "model" to be a non-empty String, but %v was given.',
  1484. relName,
  1485. modelName,
  1486. relDef.model
  1487. );
  1488. if (relDef.polymorphic) {
  1489. if (typeof relDef.polymorphic === "string") {
  1490. if (relDef.foreignKey)
  1491. throw new InvalidArgumentError(
  1492. 'The relation %v of the model %v has the option "polymorphic" with a String value, so it should not have the option "foreignKey" to be provided.',
  1493. relName,
  1494. modelName
  1495. );
  1496. if (relDef.discriminator)
  1497. throw new InvalidArgumentError(
  1498. 'The relation %v of the model %v has the option "polymorphic" with a String value, so it should not have the option "discriminator" to be provided.',
  1499. relName,
  1500. modelName
  1501. );
  1502. } else if (typeof relDef.polymorphic === "boolean") {
  1503. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  1504. throw new InvalidArgumentError(
  1505. 'The relation %v of the model %v has the option "polymorphic" with "true" value, so it requires the option "foreignKey" to be a non-empty String, but %v was given.',
  1506. relName,
  1507. modelName,
  1508. relDef.foreignKey
  1509. );
  1510. if (!relDef.discriminator || typeof relDef.discriminator !== "string")
  1511. throw new InvalidArgumentError(
  1512. 'The relation %v of the model %v has the option "polymorphic" with "true" value, so it requires the option "discriminator" to be a non-empty String, but %v was given.',
  1513. relName,
  1514. modelName,
  1515. relDef.discriminator
  1516. );
  1517. } else {
  1518. throw new InvalidArgumentError(
  1519. 'The relation %v of the model %v has the type "hasMany", so it expects the provided option "polymorphic" to be a String or a Boolean, but %v was given.',
  1520. relName,
  1521. modelName,
  1522. relDef.polymorphic
  1523. );
  1524. }
  1525. } else {
  1526. if (!relDef.foreignKey || typeof relDef.foreignKey !== "string")
  1527. throw new InvalidArgumentError(
  1528. 'The relation %v of the model %v has the type "hasMany", so it requires the option "foreignKey" to be a non-empty String, but %v was given.',
  1529. relName,
  1530. modelName,
  1531. relDef.foreignKey
  1532. );
  1533. if (relDef.discriminator)
  1534. throw new InvalidArgumentError(
  1535. 'The relation %v of the model %v is a non-polymorphic "hasMany" relation, so it should not have the option "discriminator" to be provided.',
  1536. relName,
  1537. modelName
  1538. );
  1539. }
  1540. }
  1541. /**
  1542. * Validate "referencesMany".
  1543. *
  1544. * @example
  1545. * ```
  1546. * {
  1547. * type: RelationType.REFERENCES_MANY,
  1548. * model: 'model',
  1549. * foreignKey: 'modelIds', // optional
  1550. * }
  1551. * ```
  1552. *
  1553. * @param {string} modelName
  1554. * @param {string} relName
  1555. * @param {object} relDef
  1556. * @private
  1557. */
  1558. _validateReferencesMany(modelName, relName, relDef) {
  1559. if (relDef.type !== RelationType.REFERENCES_MANY) return;
  1560. if (!relDef.model || typeof relDef.model !== "string")
  1561. throw new InvalidArgumentError(
  1562. 'The relation %v of the model %v has the type "referencesMany", so it requires the option "model" to be a non-empty String, but %v was given.',
  1563. relName,
  1564. modelName,
  1565. relDef.model
  1566. );
  1567. if (relDef.foreignKey && typeof relDef.foreignKey !== "string")
  1568. throw new InvalidArgumentError(
  1569. 'The relation %v of the model %v has the type "referencesMany", so it expects the provided option "foreignKey" to be a String, but %v was given.',
  1570. relName,
  1571. modelName,
  1572. relDef.foreignKey
  1573. );
  1574. if (relDef.discriminator)
  1575. throw new InvalidArgumentError(
  1576. 'The relation %v of the model %v has the type "referencesMany", so it should not have the option "discriminator" to be provided.',
  1577. relName,
  1578. modelName
  1579. );
  1580. }
  1581. };
  1582. __name(_RelationsDefinitionValidator, "RelationsDefinitionValidator");
  1583. RelationsDefinitionValidator = _RelationsDefinitionValidator;
  1584. }
  1585. });
  1586. // src/definition/model/relations/index.js
  1587. var init_relations = __esm({
  1588. "src/definition/model/relations/index.js"() {
  1589. "use strict";
  1590. init_relation_type();
  1591. init_relation_definition();
  1592. init_relations_definition_validator();
  1593. }
  1594. });
  1595. // src/definition/model/properties/data-type.js
  1596. var DataType;
  1597. var init_data_type = __esm({
  1598. "src/definition/model/properties/data-type.js"() {
  1599. "use strict";
  1600. DataType = {
  1601. ANY: "any",
  1602. STRING: "string",
  1603. NUMBER: "number",
  1604. BOOLEAN: "boolean",
  1605. ARRAY: "array",
  1606. OBJECT: "object"
  1607. };
  1608. }
  1609. });
  1610. // src/definition/model/properties/property-definition.js
  1611. var init_property_definition = __esm({
  1612. "src/definition/model/properties/property-definition.js"() {
  1613. "use strict";
  1614. }
  1615. });
  1616. // src/definition/model/properties/property-uniqueness.js
  1617. var PropertyUniqueness;
  1618. var init_property_uniqueness = __esm({
  1619. "src/definition/model/properties/property-uniqueness.js"() {
  1620. "use strict";
  1621. PropertyUniqueness = {
  1622. STRICT: "strict",
  1623. SPARSE: "sparse",
  1624. NON_UNIQUE: "nonUnique"
  1625. };
  1626. }
  1627. });
  1628. // src/definition/definition-registry.js
  1629. var import_js_service6, _DefinitionRegistry, DefinitionRegistry;
  1630. var init_definition_registry = __esm({
  1631. "src/definition/definition-registry.js"() {
  1632. "use strict";
  1633. import_js_service6 = require("@e22m4u/js-service");
  1634. init_utils();
  1635. init_errors();
  1636. init_model();
  1637. init_definition();
  1638. _DefinitionRegistry = class _DefinitionRegistry extends import_js_service6.Service {
  1639. /**
  1640. * Datasources.
  1641. *
  1642. * @type {object}
  1643. */
  1644. _datasources = {};
  1645. /**
  1646. * Models.
  1647. *
  1648. * @type {object}
  1649. */
  1650. _models = {};
  1651. /**
  1652. * Add datasource.
  1653. *
  1654. * @param {object} datasourceDef
  1655. */
  1656. addDatasource(datasourceDef) {
  1657. this.getService(DatasourceDefinitionValidator).validate(datasourceDef);
  1658. const name = datasourceDef.name;
  1659. if (name in this._datasources)
  1660. throw new InvalidArgumentError(
  1661. "The datasource %v is already defined.",
  1662. name
  1663. );
  1664. this._datasources[name] = datasourceDef;
  1665. }
  1666. /**
  1667. * Has datasource.
  1668. *
  1669. * @param {string} name
  1670. * @returns {boolean}
  1671. */
  1672. hasDatasource(name) {
  1673. return Boolean(this._datasources[name]);
  1674. }
  1675. /**
  1676. * Get datasource.
  1677. *
  1678. * @param {string} name
  1679. * @returns {object}
  1680. */
  1681. getDatasource(name) {
  1682. const datasourceDef = this._datasources[name];
  1683. if (!datasourceDef)
  1684. throw new InvalidArgumentError("The datasource %v is not defined.", name);
  1685. return datasourceDef;
  1686. }
  1687. /**
  1688. * Add model.
  1689. *
  1690. * @param {object} modelDef
  1691. */
  1692. addModel(modelDef) {
  1693. this.getService(ModelDefinitionValidator).validate(modelDef);
  1694. const modelKey = modelNameToModelKey(modelDef.name);
  1695. if (modelKey in this._models)
  1696. throw new InvalidArgumentError(
  1697. "The model %v is already defined.",
  1698. modelDef.name
  1699. );
  1700. this._models[modelKey] = modelDef;
  1701. }
  1702. /**
  1703. * Has model.
  1704. *
  1705. * @param {string} name
  1706. * @returns {boolean}
  1707. */
  1708. hasModel(name) {
  1709. const modelKey = modelNameToModelKey(name);
  1710. return Boolean(this._models[modelKey]);
  1711. }
  1712. /**
  1713. * Get model.
  1714. *
  1715. * @param {string} name
  1716. * @returns {object}
  1717. */
  1718. getModel(name) {
  1719. const modelKey = modelNameToModelKey(name);
  1720. const modelDef = this._models[modelKey];
  1721. if (!modelDef)
  1722. throw new InvalidArgumentError("The model %v is not defined.", name);
  1723. return modelDef;
  1724. }
  1725. };
  1726. __name(_DefinitionRegistry, "DefinitionRegistry");
  1727. DefinitionRegistry = _DefinitionRegistry;
  1728. }
  1729. });
  1730. // src/definition/model/model-definition-utils.js
  1731. var import_js_service7, DEFAULT_PRIMARY_KEY_PROPERTY_NAME, _ModelDefinitionUtils, ModelDefinitionUtils;
  1732. var init_model_definition_utils = __esm({
  1733. "src/definition/model/model-definition-utils.js"() {
  1734. "use strict";
  1735. import_js_service7 = require("@e22m4u/js-service");
  1736. init_properties();
  1737. init_errors();
  1738. init_definition_registry();
  1739. init_utils();
  1740. DEFAULT_PRIMARY_KEY_PROPERTY_NAME = "id";
  1741. _ModelDefinitionUtils = class _ModelDefinitionUtils extends import_js_service7.Service {
  1742. /**
  1743. * Get primary key as property name.
  1744. *
  1745. * @param {string} modelName
  1746. * @returns {string}
  1747. */
  1748. getPrimaryKeyAsPropertyName(modelName) {
  1749. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1750. const propNames = Object.keys(propDefs).filter((propName) => {
  1751. const propDef = propDefs[propName];
  1752. return propDef && typeof propDef === "object" && propDef.primaryKey;
  1753. });
  1754. if (propNames.length < 1) {
  1755. const isDefaultPrimaryKeyAlreadyInUse = Object.keys(propDefs).includes(
  1756. DEFAULT_PRIMARY_KEY_PROPERTY_NAME
  1757. );
  1758. if (isDefaultPrimaryKeyAlreadyInUse)
  1759. throw new InvalidArgumentError(
  1760. 'The property name %v of the model %v is defined as a regular property. In this case, a primary key should be defined explicitly. Do use the option "primaryKey" to specify the primary key.',
  1761. DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  1762. modelName
  1763. );
  1764. return DEFAULT_PRIMARY_KEY_PROPERTY_NAME;
  1765. }
  1766. return propNames[0];
  1767. }
  1768. /**
  1769. * Get primary key as column name.
  1770. *
  1771. * @param {string} modelName
  1772. * @returns {string}
  1773. */
  1774. getPrimaryKeyAsColumnName(modelName) {
  1775. const pkPropName = this.getPrimaryKeyAsPropertyName(modelName);
  1776. let pkColName;
  1777. try {
  1778. pkColName = this.getColumnNameByPropertyName(modelName, pkPropName);
  1779. } catch (error) {
  1780. if (!(error instanceof InvalidArgumentError)) throw error;
  1781. }
  1782. if (pkColName === void 0) return pkPropName;
  1783. return pkColName;
  1784. }
  1785. /**
  1786. * Get table name by model name.
  1787. *
  1788. * @param {string} modelName
  1789. * @returns {string}
  1790. */
  1791. getTableNameByModelName(modelName) {
  1792. var _a;
  1793. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  1794. return (_a = modelDef.tableName) != null ? _a : modelName;
  1795. }
  1796. /**
  1797. * Get column name by property name.
  1798. *
  1799. * @param {string} modelName
  1800. * @param {string} propertyName
  1801. * @returns {string}
  1802. */
  1803. getColumnNameByPropertyName(modelName, propertyName) {
  1804. var _a;
  1805. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1806. const propDef = propDefs[propertyName];
  1807. if (!propDef)
  1808. throw new InvalidArgumentError(
  1809. "The model %v does not have the property %v.",
  1810. modelName,
  1811. propertyName
  1812. );
  1813. if (propDef && typeof propDef === "object")
  1814. return (_a = propDef.columnName) != null ? _a : propertyName;
  1815. return propertyName;
  1816. }
  1817. /**
  1818. * Get default property value.
  1819. *
  1820. * @param {string} modelName
  1821. * @param {string} propertyName
  1822. * @returns {*}
  1823. */
  1824. getDefaultPropertyValue(modelName, propertyName) {
  1825. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1826. const propDef = propDefs[propertyName];
  1827. if (!propDef)
  1828. throw new InvalidArgumentError(
  1829. "The model %v does not have the property %v.",
  1830. modelName,
  1831. propertyName
  1832. );
  1833. if (propDef && typeof propDef === "object")
  1834. return propDef.default instanceof Function ? propDef.default() : propDef.default;
  1835. }
  1836. /**
  1837. * Set default values to empty properties.
  1838. *
  1839. * @param {string} modelName
  1840. * @param {object} modelData
  1841. * @param {boolean|undefined} onlyProvidedProperties
  1842. * @returns {object}
  1843. */
  1844. setDefaultValuesToEmptyProperties(modelName, modelData, onlyProvidedProperties = false) {
  1845. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1846. const propNames = onlyProvidedProperties ? Object.keys(modelData) : Object.keys(propDefs);
  1847. const extendedData = cloneDeep(modelData);
  1848. propNames.forEach((propName) => {
  1849. const propDef = propDefs[propName];
  1850. const propValue = extendedData[propName];
  1851. if (propValue != null) {
  1852. return;
  1853. }
  1854. if (propDef && typeof propDef === "object" && propDef.default !== void 0) {
  1855. extendedData[propName] = this.getDefaultPropertyValue(
  1856. modelName,
  1857. propName
  1858. );
  1859. }
  1860. });
  1861. return extendedData;
  1862. }
  1863. /**
  1864. * Convert property names to column names.
  1865. *
  1866. * @param {string} modelName
  1867. * @param {object} modelData
  1868. * @returns {object}
  1869. */
  1870. convertPropertyNamesToColumnNames(modelName, modelData) {
  1871. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1872. const propNames = Object.keys(propDefs);
  1873. const convertedData = cloneDeep(modelData);
  1874. propNames.forEach((propName) => {
  1875. if (!(propName in convertedData)) return;
  1876. const colName = this.getColumnNameByPropertyName(modelName, propName);
  1877. let propValue = convertedData[propName];
  1878. const propDef = propDefs[propName];
  1879. if (propValue !== null && typeof propValue === "object" && !Array.isArray(propValue) && propDef !== null && typeof propDef === "object" && propDef.type === DataType.OBJECT && propDef.model) {
  1880. propValue = this.convertPropertyNamesToColumnNames(
  1881. propDef.model,
  1882. propValue
  1883. );
  1884. }
  1885. if (Array.isArray(propValue) && propDef !== null && typeof propDef === "object" && propDef.type === DataType.ARRAY && propDef.itemModel) {
  1886. propValue = propValue.map((el) => {
  1887. return el !== null && typeof el === "object" && !Array.isArray(el) ? this.convertPropertyNamesToColumnNames(propDef.itemModel, el) : el;
  1888. });
  1889. }
  1890. delete convertedData[propName];
  1891. convertedData[colName] = propValue;
  1892. });
  1893. return convertedData;
  1894. }
  1895. /**
  1896. * Convert column names to property names.
  1897. *
  1898. * @param {string} modelName
  1899. * @param {object} tableData
  1900. * @returns {object}
  1901. */
  1902. convertColumnNamesToPropertyNames(modelName, tableData) {
  1903. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1904. const propNames = Object.keys(propDefs);
  1905. const convertedData = cloneDeep(tableData);
  1906. propNames.forEach((propName) => {
  1907. const colName = this.getColumnNameByPropertyName(modelName, propName);
  1908. if (!(colName in convertedData)) return;
  1909. let colValue = convertedData[colName];
  1910. const propDef = propDefs[propName];
  1911. if (colValue !== null && typeof colValue === "object" && !Array.isArray(colValue) && propDef !== null && typeof propDef === "object" && propDef.type === DataType.OBJECT && propDef.model) {
  1912. colValue = this.convertColumnNamesToPropertyNames(
  1913. propDef.model,
  1914. colValue
  1915. );
  1916. }
  1917. if (Array.isArray(colValue) && propDef !== null && typeof propDef === "object" && propDef.type === DataType.ARRAY && propDef.itemModel) {
  1918. colValue = colValue.map((el) => {
  1919. return el !== null && typeof el === "object" && !Array.isArray(el) ? this.convertColumnNamesToPropertyNames(propDef.itemModel, el) : el;
  1920. });
  1921. }
  1922. delete convertedData[colName];
  1923. convertedData[propName] = colValue;
  1924. });
  1925. return convertedData;
  1926. }
  1927. /**
  1928. * Get data type by property name.
  1929. *
  1930. * @param {string} modelName
  1931. * @param {string} propertyName
  1932. * @returns {string}
  1933. */
  1934. getDataTypeByPropertyName(modelName, propertyName) {
  1935. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  1936. const propDef = propDefs[propertyName];
  1937. if (!propDef) {
  1938. const pkPropName = this.getPrimaryKeyAsPropertyName(modelName);
  1939. if (pkPropName === propertyName) return DataType.ANY;
  1940. throw new InvalidArgumentError(
  1941. "The model %v does not have the property %v.",
  1942. modelName,
  1943. propertyName
  1944. );
  1945. }
  1946. if (typeof propDef === "string") return propDef;
  1947. return propDef.type;
  1948. }
  1949. /**
  1950. * Get data type from property definition.
  1951. *
  1952. * @param {object} propDef
  1953. * @returns {string}
  1954. */
  1955. getDataTypeFromPropertyDefinition(propDef) {
  1956. if ((!propDef || typeof propDef !== "object") && !Object.values(DataType).includes(propDef)) {
  1957. throw new InvalidArgumentError(
  1958. 'The argument "propDef" of the ModelDefinitionUtils.getDataTypeFromPropertyDefinition should be an Object or the DataType enum, but %v was given.',
  1959. propDef
  1960. );
  1961. }
  1962. if (typeof propDef === "string") return propDef;
  1963. const dataType = propDef.type;
  1964. if (!Object.values(DataType).includes(dataType))
  1965. throw new InvalidArgumentError(
  1966. 'The given Object to the ModelDefinitionUtils.getDataTypeFromPropertyDefinition should have the "type" property with one of values: %l, but %v was given.',
  1967. Object.values(DataType),
  1968. propDef.type
  1969. );
  1970. return dataType;
  1971. }
  1972. /**
  1973. * Get own properties definition of primary keys.
  1974. *
  1975. * @param {string} modelName
  1976. * @returns {object}
  1977. */
  1978. getOwnPropertiesDefinitionOfPrimaryKeys(modelName) {
  1979. var _a;
  1980. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  1981. const propDefs = (_a = modelDef.properties) != null ? _a : {};
  1982. const pkPropNames = Object.keys(propDefs).filter((propName) => {
  1983. const propDef = propDefs[propName];
  1984. return typeof propDef === "object" && propDef.primaryKey;
  1985. });
  1986. return pkPropNames.reduce((a, k) => ({ ...a, [k]: propDefs[k] }), {});
  1987. }
  1988. /**
  1989. * Get own properties definition without primary keys.
  1990. *
  1991. * @param {string} modelName
  1992. * @returns {object}
  1993. */
  1994. getOwnPropertiesDefinitionWithoutPrimaryKeys(modelName) {
  1995. var _a;
  1996. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  1997. const propDefs = (_a = modelDef.properties) != null ? _a : {};
  1998. return Object.keys(propDefs).reduce((result, propName) => {
  1999. const propDef = propDefs[propName];
  2000. if (typeof propDef === "object" && propDef.primaryKey) return result;
  2001. return { ...result, [propName]: propDef };
  2002. }, {});
  2003. }
  2004. /**
  2005. * Get properties definition in base model hierarchy.
  2006. *
  2007. * @param {string} modelName
  2008. * @returns {object}
  2009. */
  2010. getPropertiesDefinitionInBaseModelHierarchy(modelName) {
  2011. let pkPropDefs = {};
  2012. let regularPropDefs = {};
  2013. const recursion = /* @__PURE__ */ __name((currModelName, prevModelName = void 0) => {
  2014. if (currModelName === prevModelName)
  2015. throw new InvalidArgumentError(
  2016. "The model %v has a circular inheritance.",
  2017. currModelName
  2018. );
  2019. if (Object.keys(pkPropDefs).length === 0)
  2020. pkPropDefs = this.getOwnPropertiesDefinitionOfPrimaryKeys(currModelName);
  2021. regularPropDefs = {
  2022. ...this.getOwnPropertiesDefinitionWithoutPrimaryKeys(currModelName),
  2023. ...regularPropDefs
  2024. };
  2025. const modelDef = this.getService(DefinitionRegistry).getModel(currModelName);
  2026. if (modelDef.base) recursion(modelDef.base, currModelName);
  2027. }, "recursion");
  2028. recursion(modelName);
  2029. return { ...pkPropDefs, ...regularPropDefs };
  2030. }
  2031. /**
  2032. * Get own relations definition.
  2033. *
  2034. * @param {string} modelName
  2035. * @returns {object}
  2036. */
  2037. getOwnRelationsDefinition(modelName) {
  2038. var _a;
  2039. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  2040. return (_a = modelDef.relations) != null ? _a : {};
  2041. }
  2042. /**
  2043. * Get relations definition in base model hierarchy.
  2044. *
  2045. * @param {string} modelName
  2046. * @returns {object}
  2047. */
  2048. getRelationsDefinitionInBaseModelHierarchy(modelName) {
  2049. let result = {};
  2050. const recursion = /* @__PURE__ */ __name((currModelName, prevModelName = void 0) => {
  2051. var _a;
  2052. if (currModelName === prevModelName)
  2053. throw new InvalidArgumentError(
  2054. "The model %v has a circular inheritance.",
  2055. currModelName
  2056. );
  2057. const modelDef = this.getService(DefinitionRegistry).getModel(currModelName);
  2058. const ownRelDefs = (_a = modelDef.relations) != null ? _a : {};
  2059. result = { ...ownRelDefs, ...result };
  2060. if (modelDef.base) recursion(modelDef.base, currModelName);
  2061. }, "recursion");
  2062. recursion(modelName);
  2063. return result;
  2064. }
  2065. /**
  2066. * Get relation definition by name.
  2067. *
  2068. * @param {string} modelName
  2069. * @param {string} relationName
  2070. * @returns {object}
  2071. */
  2072. getRelationDefinitionByName(modelName, relationName) {
  2073. const relDefs = this.getRelationsDefinitionInBaseModelHierarchy(modelName);
  2074. const relNames = Object.keys(relDefs);
  2075. let foundDef;
  2076. for (const relName of relNames) {
  2077. if (relName === relationName) {
  2078. foundDef = relDefs[relName];
  2079. break;
  2080. }
  2081. }
  2082. if (!foundDef)
  2083. throw new InvalidArgumentError(
  2084. "The model %v does not have relation name %v.",
  2085. modelName,
  2086. relationName
  2087. );
  2088. return foundDef;
  2089. }
  2090. /**
  2091. * Exclude object keys by relation names.
  2092. *
  2093. * @param {string} modelName
  2094. * @param {object} modelData
  2095. * @returns {object}
  2096. */
  2097. excludeObjectKeysByRelationNames(modelName, modelData) {
  2098. if (!modelData || typeof modelData !== "object" || Array.isArray(modelData))
  2099. throw new InvalidArgumentError(
  2100. "The second argument of ModelDefinitionUtils.excludeObjectKeysByRelationNames should be an Object, but %v was given.",
  2101. modelData
  2102. );
  2103. const relDefs = this.getRelationsDefinitionInBaseModelHierarchy(modelName);
  2104. const relNames = Object.keys(relDefs);
  2105. return excludeObjectKeys(modelData, relNames);
  2106. }
  2107. /**
  2108. * Get model name of property value if defined.
  2109. *
  2110. * @param {string} modelName
  2111. * @param {string} propertyName
  2112. * @returns {string|undefined}
  2113. */
  2114. getModelNameOfPropertyValueIfDefined(modelName, propertyName) {
  2115. if (!modelName || typeof modelName !== "string")
  2116. throw new InvalidArgumentError(
  2117. 'Parameter "modelName" of ModelDefinitionUtils.getModelNameOfPropertyValueIfDefined requires a non-empty String, but %v was given.',
  2118. modelName
  2119. );
  2120. if (!propertyName || typeof propertyName !== "string")
  2121. throw new InvalidArgumentError(
  2122. 'Parameter "propertyName" of ModelDefinitionUtils.getModelNameOfPropertyValueIfDefined requires a non-empty String, but %v was given.',
  2123. propertyName
  2124. );
  2125. const propDefs = this.getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2126. const propDef = propDefs[propertyName];
  2127. if (!propDef) return void 0;
  2128. if (propDef && typeof propDef === "object") {
  2129. if (propDef.type === DataType.OBJECT) return propDef.model || void 0;
  2130. if (propDef.type === DataType.ARRAY)
  2131. return propDef.itemModel || void 0;
  2132. }
  2133. return void 0;
  2134. }
  2135. };
  2136. __name(_ModelDefinitionUtils, "ModelDefinitionUtils");
  2137. ModelDefinitionUtils = _ModelDefinitionUtils;
  2138. }
  2139. });
  2140. // src/definition/model/properties/required-property-validator.js
  2141. var import_js_service8, _RequiredPropertyValidator, RequiredPropertyValidator;
  2142. var init_required_property_validator = __esm({
  2143. "src/definition/model/properties/required-property-validator.js"() {
  2144. "use strict";
  2145. init_data_type();
  2146. import_js_service8 = require("@e22m4u/js-service");
  2147. init_errors();
  2148. init_model_definition_utils();
  2149. _RequiredPropertyValidator = class _RequiredPropertyValidator extends import_js_service8.Service {
  2150. /**
  2151. * Validate.
  2152. *
  2153. * @param {string} modelName
  2154. * @param {object} modelData
  2155. * @param {boolean} [isPartial]
  2156. */
  2157. validate(modelName, modelData, isPartial = false) {
  2158. if (!modelName || typeof modelName !== "string") {
  2159. throw new InvalidArgumentError(
  2160. 'Parameter "modelName" must be a non-empty String, but %v was given.',
  2161. modelName
  2162. );
  2163. }
  2164. if (!modelData || typeof modelData !== "object" || Array.isArray(modelData)) {
  2165. throw new InvalidArgumentError(
  2166. "Data of the model %v should be an Object, but %v was given.",
  2167. modelName,
  2168. modelData
  2169. );
  2170. }
  2171. if (typeof isPartial !== "boolean") {
  2172. throw new InvalidArgumentError(
  2173. 'Parameter "isPartial" must be a Boolean, but %v was given.',
  2174. isPartial
  2175. );
  2176. }
  2177. const propDefs = this.getService(
  2178. ModelDefinitionUtils
  2179. ).getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2180. const propNames = Object.keys(isPartial ? modelData : propDefs);
  2181. for (const propName of propNames) {
  2182. const propDef = propDefs[propName];
  2183. if (!propDef || typeof propDef !== "object") {
  2184. continue;
  2185. }
  2186. const propValue = modelData[propName];
  2187. if (propDef.required && propValue == null) {
  2188. throw new InvalidArgumentError(
  2189. "Property %v of the model %v is required, but %v was given.",
  2190. propName,
  2191. modelName,
  2192. propValue
  2193. );
  2194. }
  2195. if (propDef.type === DataType.OBJECT && propDef.model && propValue !== null && typeof propValue === "object" && !Array.isArray(propValue)) {
  2196. this.validate(propDef.model, propValue);
  2197. } else if (propDef.type === DataType.ARRAY && propDef.itemType === DataType.OBJECT && propDef.itemModel && Array.isArray(propValue)) {
  2198. propValue.forEach((itemData) => {
  2199. if (itemData !== null && typeof itemData === "object" && !Array.isArray(itemData)) {
  2200. this.validate(propDef.itemModel, itemData);
  2201. }
  2202. });
  2203. }
  2204. }
  2205. }
  2206. };
  2207. __name(_RequiredPropertyValidator, "RequiredPropertyValidator");
  2208. RequiredPropertyValidator = _RequiredPropertyValidator;
  2209. }
  2210. });
  2211. // src/definition/model/properties/property-uniqueness-validator.js
  2212. var import_js_service9, _PropertyUniquenessValidator, PropertyUniquenessValidator;
  2213. var init_property_uniqueness_validator = __esm({
  2214. "src/definition/model/properties/property-uniqueness-validator.js"() {
  2215. "use strict";
  2216. import_js_service9 = require("@e22m4u/js-service");
  2217. init_utils();
  2218. init_property_uniqueness();
  2219. init_errors();
  2220. init_model_definition_utils();
  2221. _PropertyUniquenessValidator = class _PropertyUniquenessValidator extends import_js_service9.Service {
  2222. /**
  2223. * Validate.
  2224. *
  2225. * @param {Function} countMethod
  2226. * @param {string} methodName
  2227. * @param {string} modelName
  2228. * @param {object} modelData
  2229. * @param {*} modelId
  2230. * @returns {Promise<undefined>}
  2231. */
  2232. async validate(countMethod, methodName, modelName, modelData, modelId = void 0) {
  2233. if (typeof countMethod !== "function")
  2234. throw new InvalidArgumentError(
  2235. 'The parameter "countMethod" of the PropertyUniquenessValidator must be a Function, but %v was given.',
  2236. countMethod
  2237. );
  2238. if (!methodName || typeof methodName !== "string")
  2239. throw new InvalidArgumentError(
  2240. 'The parameter "methodName" of the PropertyUniquenessValidator must be a non-empty String, but %v was given.',
  2241. methodName
  2242. );
  2243. if (!modelName || typeof modelName !== "string")
  2244. throw new InvalidArgumentError(
  2245. 'The parameter "modelName" of the PropertyUniquenessValidator must be a non-empty String, but %v was given.',
  2246. modelName
  2247. );
  2248. if (!isPlainObject(modelData))
  2249. throw new InvalidArgumentError(
  2250. "The data of the model %v should be an Object, but %v was given.",
  2251. modelName,
  2252. modelData
  2253. );
  2254. const propDefs = this.getService(
  2255. ModelDefinitionUtils
  2256. ).getPropertiesDefinitionInBaseModelHierarchy(modelName);
  2257. const isPartial = methodName === "patch" || methodName === "patchById";
  2258. const propNames = Object.keys(isPartial ? modelData : propDefs);
  2259. const idProp = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  2260. modelName
  2261. );
  2262. const createError = /* @__PURE__ */ __name((propName, propValue) => new InvalidArgumentError(
  2263. "An existing document of the model %v already has the property %v with the value %v and should be unique.",
  2264. modelName,
  2265. propName,
  2266. propValue
  2267. ), "createError");
  2268. let willBeReplaced = void 0;
  2269. for (const propName of propNames) {
  2270. const propDef = propDefs[propName];
  2271. if (!propDef || typeof propDef === "string" || !propDef.unique || propDef.unique === PropertyUniqueness.NON_UNIQUE) {
  2272. continue;
  2273. }
  2274. const propValue = modelData[propName];
  2275. if (propDef.unique === PropertyUniqueness.SPARSE && !propValue) {
  2276. continue;
  2277. }
  2278. if (methodName === "create") {
  2279. const count = await countMethod({ [propName]: propValue });
  2280. if (count > 0) throw createError(propName, propValue);
  2281. } else if (methodName === "replaceById") {
  2282. const count = await countMethod({
  2283. [idProp]: { neq: modelId },
  2284. [propName]: propValue
  2285. });
  2286. if (count > 0) throw createError(propName, propValue);
  2287. } else if (methodName === "replaceOrCreate") {
  2288. const idFromData = modelData[idProp];
  2289. if (willBeReplaced == null && idFromData != null) {
  2290. const count = await countMethod({ [idProp]: idFromData });
  2291. willBeReplaced = count > 0;
  2292. }
  2293. if (willBeReplaced) {
  2294. const count = await countMethod({
  2295. [idProp]: { neq: idFromData },
  2296. [propName]: propValue
  2297. });
  2298. if (count > 0) throw createError(propName, propValue);
  2299. } else {
  2300. const count = await countMethod({ [propName]: propValue });
  2301. if (count > 0) throw createError(propName, propValue);
  2302. }
  2303. } else if (methodName === "patch") {
  2304. const count = await countMethod({ [propName]: propValue });
  2305. if (count > 0) throw createError(propName, propValue);
  2306. } else if (methodName === "patchById") {
  2307. const count = await countMethod({
  2308. [idProp]: { neq: modelId },
  2309. [propName]: propValue
  2310. });
  2311. if (count > 0) throw createError(propName, propValue);
  2312. } else {
  2313. throw new InvalidArgumentError(
  2314. "The PropertyUniquenessValidator does not support the adapter method %v.",
  2315. methodName
  2316. );
  2317. }
  2318. }
  2319. }
  2320. };
  2321. __name(_PropertyUniquenessValidator, "PropertyUniquenessValidator");
  2322. PropertyUniquenessValidator = _PropertyUniquenessValidator;
  2323. }
  2324. });
  2325. // src/definition/model/properties/primary-keys-definition-validator.js
  2326. var import_js_service10, _PrimaryKeysDefinitionValidator, PrimaryKeysDefinitionValidator;
  2327. var init_primary_keys_definition_validator = __esm({
  2328. "src/definition/model/properties/primary-keys-definition-validator.js"() {
  2329. "use strict";
  2330. import_js_service10 = require("@e22m4u/js-service");
  2331. init_errors();
  2332. init_model_definition_utils();
  2333. _PrimaryKeysDefinitionValidator = class _PrimaryKeysDefinitionValidator extends import_js_service10.Service {
  2334. /**
  2335. * Validate.
  2336. *
  2337. * @param {string} modelName
  2338. * @param {object} propDefs
  2339. */
  2340. validate(modelName, propDefs) {
  2341. const propNames = Object.keys(propDefs).filter((propName) => {
  2342. const propDef = propDefs[propName];
  2343. return propDef && typeof propDef === "object" && propDef.primaryKey;
  2344. });
  2345. if (propNames.length < 1) {
  2346. const isDefaultPrimaryKeyAlreadyInUse = Object.keys(propDefs).includes(DEFAULT_PRIMARY_KEY_PROPERTY_NAME);
  2347. if (isDefaultPrimaryKeyAlreadyInUse)
  2348. throw new InvalidArgumentError(
  2349. 'The property name %v of the model %v is defined as a regular property. In this case, a primary key should be defined explicitly. Do use the option "primaryKey" to specify the primary key.',
  2350. DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  2351. modelName
  2352. );
  2353. return;
  2354. }
  2355. if (propNames.length > 1)
  2356. throw new InvalidArgumentError(
  2357. "The model definition %v should not have multiple primary keys, but %v keys given.",
  2358. modelName,
  2359. propNames.length
  2360. );
  2361. const pkPropName = propNames[0];
  2362. const pkPropDef = propDefs[pkPropName];
  2363. if (pkPropDef && typeof pkPropDef === "object" && pkPropDef.default !== void 0) {
  2364. throw new InvalidArgumentError(
  2365. "Do not specify a default value for the primary key %v of the model %v.",
  2366. pkPropName,
  2367. modelName
  2368. );
  2369. }
  2370. }
  2371. };
  2372. __name(_PrimaryKeysDefinitionValidator, "PrimaryKeysDefinitionValidator");
  2373. PrimaryKeysDefinitionValidator = _PrimaryKeysDefinitionValidator;
  2374. }
  2375. });
  2376. // src/definition/model/properties/properties-definition-validator.js
  2377. var import_js_service11, _PropertiesDefinitionValidator, PropertiesDefinitionValidator;
  2378. var init_properties_definition_validator = __esm({
  2379. "src/definition/model/properties/properties-definition-validator.js"() {
  2380. "use strict";
  2381. import_js_service11 = require("@e22m4u/js-service");
  2382. init_data_type();
  2383. init_utils();
  2384. init_property_uniqueness();
  2385. init_errors();
  2386. init_primary_keys_definition_validator();
  2387. _PropertiesDefinitionValidator = class _PropertiesDefinitionValidator extends import_js_service11.Service {
  2388. /**
  2389. * Validate.
  2390. *
  2391. * @param {string} modelName
  2392. * @param {object} propDefs
  2393. */
  2394. validate(modelName, propDefs) {
  2395. if (!modelName || typeof modelName !== "string")
  2396. throw new InvalidArgumentError(
  2397. "The first argument of PropertiesDefinitionValidator.validate should be a non-empty String, but %v was given.",
  2398. modelName
  2399. );
  2400. if (!propDefs || typeof propDefs !== "object" || Array.isArray(propDefs)) {
  2401. throw new InvalidArgumentError(
  2402. 'The provided option "properties" of the model %v should be an Object, but %v was given.',
  2403. modelName,
  2404. propDefs
  2405. );
  2406. }
  2407. const propNames = Object.keys(propDefs);
  2408. propNames.forEach((propName) => {
  2409. const propDef = propDefs[propName];
  2410. this._validateProperty(modelName, propName, propDef);
  2411. });
  2412. this.getService(PrimaryKeysDefinitionValidator).validate(
  2413. modelName,
  2414. propDefs
  2415. );
  2416. }
  2417. /**
  2418. * Validate property.
  2419. *
  2420. * @param {string} modelName
  2421. * @param {string} propName
  2422. * @param {object} propDef
  2423. */
  2424. _validateProperty(modelName, propName, propDef) {
  2425. if (!modelName || typeof modelName !== "string")
  2426. throw new InvalidArgumentError(
  2427. "The first argument of PropertiesDefinitionValidator._validateProperty should be a non-empty String, but %v was given.",
  2428. modelName
  2429. );
  2430. if (!propName || typeof propName !== "string")
  2431. throw new InvalidArgumentError(
  2432. "The property name of the model %v should be a non-empty String, but %v was given.",
  2433. modelName,
  2434. propName
  2435. );
  2436. if (!propDef)
  2437. throw new InvalidArgumentError(
  2438. "The property %v of the model %v should have a property definition, but %v was given.",
  2439. propName,
  2440. modelName,
  2441. propDef
  2442. );
  2443. if (typeof propDef === "string") {
  2444. if (!Object.values(DataType).includes(propDef))
  2445. throw new InvalidArgumentError(
  2446. "In case of a short property definition, the property %v of the model %v should have one of data types: %l, but %v was given.",
  2447. propName,
  2448. modelName,
  2449. Object.values(DataType),
  2450. propDef
  2451. );
  2452. return;
  2453. }
  2454. if (!propDef || typeof propDef !== "object" || Array.isArray(propDef)) {
  2455. throw new InvalidArgumentError(
  2456. "In case of a full property definition, the property %v of the model %v should be an Object, but %v was given.",
  2457. propName,
  2458. modelName,
  2459. propDef
  2460. );
  2461. }
  2462. if (!propDef.type || !Object.values(DataType).includes(propDef.type))
  2463. throw new InvalidArgumentError(
  2464. 'The property %v of the model %v requires the option "type" to have one of data types: %l, but %v was given.',
  2465. propName,
  2466. modelName,
  2467. Object.values(DataType),
  2468. propDef.type
  2469. );
  2470. if (propDef.itemType && !Object.values(DataType).includes(propDef.itemType)) {
  2471. throw new InvalidArgumentError(
  2472. 'The provided option "itemType" of the property %v in the model %v should have one of data types: %l, but %v was given.',
  2473. propName,
  2474. modelName,
  2475. Object.values(DataType),
  2476. propDef.itemType
  2477. );
  2478. }
  2479. if (propDef.itemModel && typeof propDef.itemModel !== "string") {
  2480. throw new InvalidArgumentError(
  2481. 'The provided option "itemModel" of the property %v in the model %v should be a String, but %v was given.',
  2482. propName,
  2483. modelName,
  2484. propDef.itemModel
  2485. );
  2486. }
  2487. if (propDef.model && typeof propDef.model !== "string")
  2488. throw new InvalidArgumentError(
  2489. 'The provided option "model" of the property %v in the model %v should be a String, but %v was given.',
  2490. propName,
  2491. modelName,
  2492. propDef.model
  2493. );
  2494. if (propDef.primaryKey && typeof propDef.primaryKey !== "boolean")
  2495. throw new InvalidArgumentError(
  2496. 'The provided option "primaryKey" of the property %v in the model %v should be a Boolean, but %v was given.',
  2497. propName,
  2498. modelName,
  2499. propDef.primaryKey
  2500. );
  2501. if (propDef.columnName && typeof propDef.columnName !== "string")
  2502. throw new InvalidArgumentError(
  2503. 'The provided option "columnName" of the property %v in the model %v should be a String, but %v was given.',
  2504. propName,
  2505. modelName,
  2506. propDef.columnName
  2507. );
  2508. if (propDef.columnType && typeof propDef.columnType !== "string")
  2509. throw new InvalidArgumentError(
  2510. 'The provided option "columnType" of the property %v in the model %v should be a String, but %v was given.',
  2511. propName,
  2512. modelName,
  2513. propDef.columnType
  2514. );
  2515. if (propDef.required && typeof propDef.required !== "boolean")
  2516. throw new InvalidArgumentError(
  2517. 'The provided option "required" of the property %v in the model %v should be a Boolean, but %v was given.',
  2518. propName,
  2519. modelName,
  2520. propDef.required
  2521. );
  2522. if (propDef.required && propDef.default !== void 0)
  2523. throw new InvalidArgumentError(
  2524. 'The property %v of the model %v is a required property, so it should not have the option "default" to be provided.',
  2525. propName,
  2526. modelName
  2527. );
  2528. if (propDef.primaryKey && propDef.required)
  2529. throw new InvalidArgumentError(
  2530. 'The property %v of the model %v is a primary key, so it should not have the option "required" to be provided.',
  2531. propName,
  2532. modelName
  2533. );
  2534. if (propDef.primaryKey && propDef.default !== void 0)
  2535. throw new InvalidArgumentError(
  2536. 'The property %v of the model %v is a primary key, so it should not have the option "default" to be provided.',
  2537. propName,
  2538. modelName
  2539. );
  2540. if (propDef.itemType && propDef.type !== DataType.ARRAY)
  2541. throw new InvalidArgumentError(
  2542. 'The property %v of the model %v has a non-array type, so it should not have the option "itemType" to be provided.',
  2543. propName,
  2544. modelName,
  2545. propDef.type
  2546. );
  2547. if (propDef.itemModel && propDef.type !== DataType.ARRAY)
  2548. throw new InvalidArgumentError(
  2549. 'The option "itemModel" is not supported for %s property type, so the property %v of the model %v should not have the option "itemModel" to be provided.',
  2550. capitalize(propDef.type),
  2551. propName,
  2552. modelName
  2553. );
  2554. if (propDef.itemModel && propDef.itemType !== DataType.OBJECT) {
  2555. if (propDef.itemType) {
  2556. throw new InvalidArgumentError(
  2557. 'The provided option "itemModel" requires the option "itemType" to be explicitly set to Object, but the property %v of the model %v has specified item type as %s.',
  2558. propName,
  2559. modelName,
  2560. capitalize(propDef.itemType)
  2561. );
  2562. } else {
  2563. throw new InvalidArgumentError(
  2564. 'The provided option "itemModel" requires the option "itemType" to be explicitly set to Object, but the property %v of the model %v does not have specified item type.',
  2565. propName,
  2566. modelName
  2567. );
  2568. }
  2569. }
  2570. if (propDef.model && propDef.type !== DataType.OBJECT)
  2571. throw new InvalidArgumentError(
  2572. 'The option "model" is not supported for %s property type, so the property %v of the model %v should not have the option "model" to be provided.',
  2573. capitalize(propDef.type),
  2574. propName,
  2575. modelName
  2576. );
  2577. if (propDef.unique) {
  2578. if (typeof propDef.unique !== "boolean" && !Object.values(PropertyUniqueness).includes(propDef.unique)) {
  2579. throw new InvalidArgumentError(
  2580. 'The provided option "unique" of the property %v in the model %v should be a Boolean or one of values: %l, but %v was given.',
  2581. propName,
  2582. modelName,
  2583. Object.values(PropertyUniqueness),
  2584. propDef.unique
  2585. );
  2586. }
  2587. }
  2588. if (propDef.unique && propDef.primaryKey)
  2589. throw new InvalidArgumentError(
  2590. 'The property %v of the model %v is a primary key, so it should not have the option "unique" to be provided.',
  2591. propName,
  2592. modelName
  2593. );
  2594. }
  2595. };
  2596. __name(_PropertiesDefinitionValidator, "PropertiesDefinitionValidator");
  2597. PropertiesDefinitionValidator = _PropertiesDefinitionValidator;
  2598. }
  2599. });
  2600. // src/definition/model/properties/index.js
  2601. var init_properties = __esm({
  2602. "src/definition/model/properties/index.js"() {
  2603. "use strict";
  2604. init_data_type();
  2605. init_property_definition();
  2606. init_property_uniqueness();
  2607. init_required_property_validator();
  2608. init_property_uniqueness_validator();
  2609. init_properties_definition_validator();
  2610. init_primary_keys_definition_validator();
  2611. }
  2612. });
  2613. // src/definition/model/model-definition.js
  2614. var init_model_definition = __esm({
  2615. "src/definition/model/model-definition.js"() {
  2616. "use strict";
  2617. }
  2618. });
  2619. // src/definition/model/model-data-sanitizer.js
  2620. var import_js_service12, _ModelDataSanitizer, ModelDataSanitizer;
  2621. var init_model_data_sanitizer = __esm({
  2622. "src/definition/model/model-data-sanitizer.js"() {
  2623. "use strict";
  2624. import_js_service12 = require("@e22m4u/js-service");
  2625. init_errors();
  2626. init_model_definition_utils();
  2627. _ModelDataSanitizer = class _ModelDataSanitizer extends import_js_service12.Service {
  2628. /**
  2629. * Validate.
  2630. *
  2631. * @param {string} modelName
  2632. * @param {object} modelData
  2633. * @returns {object}
  2634. */
  2635. sanitize(modelName, modelData) {
  2636. if (!modelName || typeof modelName !== "string")
  2637. throw new InvalidArgumentError(
  2638. "The first argument of ModelDataSanitizer.sanitize should be a string, but %v was given.",
  2639. modelName
  2640. );
  2641. if (!modelData || typeof modelData !== "object")
  2642. throw new InvalidArgumentError(
  2643. "The second argument of ModelDataSanitizer.sanitize should be an Object, but %v was given.",
  2644. modelData
  2645. );
  2646. return this.getService(
  2647. ModelDefinitionUtils
  2648. ).excludeObjectKeysByRelationNames(modelName, modelData);
  2649. }
  2650. };
  2651. __name(_ModelDataSanitizer, "ModelDataSanitizer");
  2652. ModelDataSanitizer = _ModelDataSanitizer;
  2653. }
  2654. });
  2655. // src/definition/model/model-definition-validator.js
  2656. var import_js_service13, _ModelDefinitionValidator, ModelDefinitionValidator;
  2657. var init_model_definition_validator = __esm({
  2658. "src/definition/model/model-definition-validator.js"() {
  2659. "use strict";
  2660. import_js_service13 = require("@e22m4u/js-service");
  2661. init_errors();
  2662. init_relations();
  2663. init_properties();
  2664. _ModelDefinitionValidator = class _ModelDefinitionValidator extends import_js_service13.Service {
  2665. /**
  2666. * Validate.
  2667. *
  2668. * @param {object} modelDef
  2669. */
  2670. validate(modelDef) {
  2671. if (!modelDef || typeof modelDef !== "object" || Array.isArray(modelDef))
  2672. throw new InvalidArgumentError(
  2673. "The model definition should be an Object, but %v was given.",
  2674. modelDef
  2675. );
  2676. if (!modelDef.name || typeof modelDef.name !== "string")
  2677. throw new InvalidArgumentError(
  2678. 'The model definition requires the option "name" as a non-empty String, but %v was given.',
  2679. modelDef.name
  2680. );
  2681. if (modelDef.datasource && typeof modelDef.datasource !== "string")
  2682. throw new InvalidArgumentError(
  2683. 'The provided option "datasource" of the model %v should be a String, but %v was given.',
  2684. modelDef.name,
  2685. modelDef.datasource
  2686. );
  2687. if (modelDef.base && typeof modelDef.base !== "string")
  2688. throw new InvalidArgumentError(
  2689. 'The provided option "base" of the model %v should be a String, but %v was given.',
  2690. modelDef.name,
  2691. modelDef.base
  2692. );
  2693. if (modelDef.tableName && typeof modelDef.tableName !== "string")
  2694. throw new InvalidArgumentError(
  2695. 'The provided option "tableName" of the model %v should be a String, but %v was given.',
  2696. modelDef.name,
  2697. modelDef.tableName
  2698. );
  2699. if (modelDef.properties) {
  2700. if (typeof modelDef.properties !== "object" || Array.isArray(modelDef.properties)) {
  2701. throw new InvalidArgumentError(
  2702. 'The provided option "properties" of the model %v should be an Object, but %v was given.',
  2703. modelDef.name,
  2704. modelDef.properties
  2705. );
  2706. }
  2707. this.getService(PropertiesDefinitionValidator).validate(
  2708. modelDef.name,
  2709. modelDef.properties
  2710. );
  2711. }
  2712. if (modelDef.relations) {
  2713. if (typeof modelDef.relations !== "object" || Array.isArray(modelDef.relations)) {
  2714. throw new InvalidArgumentError(
  2715. 'The provided option "relations" of the model %v should be an Object, but %v was given.',
  2716. modelDef.name,
  2717. modelDef.relations
  2718. );
  2719. }
  2720. this.getService(RelationsDefinitionValidator).validate(
  2721. modelDef.name,
  2722. modelDef.relations
  2723. );
  2724. }
  2725. }
  2726. };
  2727. __name(_ModelDefinitionValidator, "ModelDefinitionValidator");
  2728. ModelDefinitionValidator = _ModelDefinitionValidator;
  2729. }
  2730. });
  2731. // src/definition/model/index.js
  2732. var init_model = __esm({
  2733. "src/definition/model/index.js"() {
  2734. "use strict";
  2735. init_relations();
  2736. init_properties();
  2737. init_model_definition();
  2738. init_model_data_sanitizer();
  2739. init_model_definition_utils();
  2740. init_model_definition_validator();
  2741. }
  2742. });
  2743. // src/definition/datasource/datasource-definition-validator.js
  2744. var import_js_service14, _DatasourceDefinitionValidator, DatasourceDefinitionValidator;
  2745. var init_datasource_definition_validator = __esm({
  2746. "src/definition/datasource/datasource-definition-validator.js"() {
  2747. "use strict";
  2748. import_js_service14 = require("@e22m4u/js-service");
  2749. init_errors();
  2750. _DatasourceDefinitionValidator = class _DatasourceDefinitionValidator extends import_js_service14.Service {
  2751. /**
  2752. * Validate.
  2753. *
  2754. * @param {object} datasourceDef
  2755. */
  2756. validate(datasourceDef) {
  2757. if (!datasourceDef || typeof datasourceDef !== "object")
  2758. throw new InvalidArgumentError(
  2759. "The datasource definition should be an Object, but %v was given.",
  2760. datasourceDef
  2761. );
  2762. if (!datasourceDef.name || typeof datasourceDef.name !== "string")
  2763. throw new InvalidArgumentError(
  2764. 'The datasource definition requires the option "name" as a non-empty String, but %v was given.',
  2765. datasourceDef.name
  2766. );
  2767. if (!datasourceDef.adapter || typeof datasourceDef.adapter !== "string")
  2768. throw new InvalidArgumentError(
  2769. 'The datasource %v requires the option "adapter" as a non-empty String, but %v was given.',
  2770. datasourceDef.name,
  2771. datasourceDef.adapter
  2772. );
  2773. }
  2774. };
  2775. __name(_DatasourceDefinitionValidator, "DatasourceDefinitionValidator");
  2776. DatasourceDefinitionValidator = _DatasourceDefinitionValidator;
  2777. }
  2778. });
  2779. // src/definition/datasource/index.js
  2780. var init_datasource = __esm({
  2781. "src/definition/datasource/index.js"() {
  2782. "use strict";
  2783. init_datasource_definition_validator();
  2784. }
  2785. });
  2786. // src/definition/index.js
  2787. var init_definition = __esm({
  2788. "src/definition/index.js"() {
  2789. "use strict";
  2790. init_model();
  2791. init_datasource();
  2792. init_definition_registry();
  2793. }
  2794. });
  2795. // src/filter/fields-clause-tool.js
  2796. var import_js_service15, _FieldsClauseTool, FieldsClauseTool;
  2797. var init_fields_clause_tool = __esm({
  2798. "src/filter/fields-clause-tool.js"() {
  2799. "use strict";
  2800. import_js_service15 = require("@e22m4u/js-service");
  2801. init_utils();
  2802. init_errors();
  2803. init_definition();
  2804. _FieldsClauseTool = class _FieldsClauseTool extends import_js_service15.Service {
  2805. /**
  2806. * Filter.
  2807. *
  2808. * @param {object|object[]} input
  2809. * @param {string} modelName
  2810. * @param {string|string[]|undefined} clause
  2811. * @returns {object|object[]}
  2812. */
  2813. filter(input, modelName, clause) {
  2814. const isArray = Array.isArray(input);
  2815. let entities = isArray ? input : [input];
  2816. entities.forEach((entity) => {
  2817. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  2818. throw new InvalidArgumentError(
  2819. "The first argument of FieldsClauseTool.filter should be an Object or an Array of Object, but %v was given.",
  2820. entity
  2821. );
  2822. });
  2823. if (!modelName || typeof modelName !== "string")
  2824. throw new InvalidArgumentError(
  2825. "The second argument of FieldsClauseTool.filter should be a non-empty String, but %v was given.",
  2826. modelName
  2827. );
  2828. if (clause == null) return input;
  2829. const fields = Array.isArray(clause) ? clause.slice() : [clause];
  2830. if (!fields.length) return input;
  2831. fields.forEach((field) => {
  2832. if (!field || typeof field !== "string")
  2833. throw new InvalidArgumentError(
  2834. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v was given.',
  2835. field
  2836. );
  2837. });
  2838. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  2839. modelName
  2840. );
  2841. if (fields.indexOf(pkPropName) === -1) fields.push(pkPropName);
  2842. entities = entities.map((entity) => selectObjectKeys(entity, fields));
  2843. return isArray ? entities : entities[0];
  2844. }
  2845. /**
  2846. * Validate fields clause.
  2847. *
  2848. * @param {string|string[]|undefined} clause
  2849. */
  2850. static validateFieldsClause(clause) {
  2851. if (clause == null) return;
  2852. const fields = Array.isArray(clause) ? clause : [clause];
  2853. if (!fields.length) return;
  2854. fields.forEach((field) => {
  2855. if (!field || typeof field !== "string")
  2856. throw new InvalidArgumentError(
  2857. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v was given.',
  2858. field
  2859. );
  2860. });
  2861. }
  2862. /**
  2863. * Normalize fields clause.
  2864. *
  2865. * @param {string|string[]|undefined} clause
  2866. * @returns {string[]|undefined}
  2867. */
  2868. static normalizeFieldsClause(clause) {
  2869. if (clause == null) return;
  2870. const fields = Array.isArray(clause) ? clause : [clause];
  2871. if (!fields.length) return;
  2872. fields.forEach((field) => {
  2873. if (!field || typeof field !== "string")
  2874. throw new InvalidArgumentError(
  2875. 'The provided option "fields" should be a non-empty String or an Array of non-empty String, but %v was given.',
  2876. field
  2877. );
  2878. });
  2879. return fields;
  2880. }
  2881. };
  2882. __name(_FieldsClauseTool, "FieldsClauseTool");
  2883. FieldsClauseTool = _FieldsClauseTool;
  2884. }
  2885. });
  2886. // src/adapter/decorator/inclusion-decorator.js
  2887. var import_js_service16, _InclusionDecorator, InclusionDecorator;
  2888. var init_inclusion_decorator = __esm({
  2889. "src/adapter/decorator/inclusion-decorator.js"() {
  2890. "use strict";
  2891. init_adapter();
  2892. import_js_service16 = require("@e22m4u/js-service");
  2893. init_filter();
  2894. init_errors();
  2895. _InclusionDecorator = class _InclusionDecorator extends import_js_service16.Service {
  2896. /**
  2897. * Decorate.
  2898. *
  2899. * @param {Adapter} adapter
  2900. */
  2901. decorate(adapter) {
  2902. if (!adapter || !(adapter instanceof Adapter))
  2903. throw new InvalidArgumentError(
  2904. "The first argument of InclusionDecorator.decorate should be an Adapter instance, but %v was given.",
  2905. adapter
  2906. );
  2907. const tool = adapter.getService(IncludeClauseTool);
  2908. const includeTo = /* @__PURE__ */ __name((...args) => tool.includeTo(...args), "includeTo");
  2909. const create = adapter.create;
  2910. adapter.create = async function(modelName, modelData, filter) {
  2911. const retvalData = await create.call(this, modelName, modelData, filter);
  2912. if (filter && typeof filter === "object" && filter.include)
  2913. await includeTo([retvalData], modelName, filter.include);
  2914. return retvalData;
  2915. };
  2916. const replaceById = adapter.replaceById;
  2917. adapter.replaceById = async function(modelName, id, modelData, filter) {
  2918. const retvalData = await replaceById.call(
  2919. this,
  2920. modelName,
  2921. id,
  2922. modelData,
  2923. filter
  2924. );
  2925. if (filter && typeof filter === "object" && filter.include)
  2926. await includeTo([retvalData], modelName, filter.include);
  2927. return retvalData;
  2928. };
  2929. const replaceOrCreate = adapter.replaceOrCreate;
  2930. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  2931. const retvalData = await replaceOrCreate.call(
  2932. this,
  2933. modelName,
  2934. modelData,
  2935. filter
  2936. );
  2937. if (filter && typeof filter === "object" && filter.include)
  2938. await includeTo([retvalData], modelName, filter.include);
  2939. return retvalData;
  2940. };
  2941. const patchById = adapter.patchById;
  2942. adapter.patchById = async function(modelName, id, modelData, filter) {
  2943. const retvalData = await patchById.call(
  2944. this,
  2945. modelName,
  2946. id,
  2947. modelData,
  2948. filter
  2949. );
  2950. if (filter && typeof filter === "object" && filter.include)
  2951. await includeTo([retvalData], modelName, filter.include);
  2952. return retvalData;
  2953. };
  2954. const find = adapter.find;
  2955. adapter.find = async function(modelName, filter) {
  2956. const modelItems = await find.call(this, modelName, filter);
  2957. if (filter && typeof filter === "object" && filter.include)
  2958. await includeTo(modelItems, modelName, filter.include);
  2959. return modelItems;
  2960. };
  2961. const findById = adapter.findById;
  2962. adapter.findById = async function(modelName, id, filter) {
  2963. const retvalData = await findById.call(this, modelName, id, filter);
  2964. if (filter && typeof filter === "object" && filter.include)
  2965. await includeTo([retvalData], modelName, filter.include);
  2966. return retvalData;
  2967. };
  2968. }
  2969. };
  2970. __name(_InclusionDecorator, "InclusionDecorator");
  2971. InclusionDecorator = _InclusionDecorator;
  2972. }
  2973. });
  2974. // src/adapter/decorator/default-values-decorator.js
  2975. var import_js_service17, _DefaultValuesDecorator, DefaultValuesDecorator;
  2976. var init_default_values_decorator = __esm({
  2977. "src/adapter/decorator/default-values-decorator.js"() {
  2978. "use strict";
  2979. init_adapter();
  2980. import_js_service17 = require("@e22m4u/js-service");
  2981. init_errors();
  2982. init_definition();
  2983. _DefaultValuesDecorator = class _DefaultValuesDecorator extends import_js_service17.Service {
  2984. /**
  2985. * Decorate.
  2986. *
  2987. * @param {Adapter} adapter
  2988. */
  2989. decorate(adapter) {
  2990. if (!adapter || !(adapter instanceof Adapter))
  2991. throw new InvalidArgumentError(
  2992. "The first argument of DefaultValuesDecorator.decorate should be an Adapter instance, but %v was given.",
  2993. adapter
  2994. );
  2995. const utils = adapter.getService(ModelDefinitionUtils);
  2996. const setDefaults = /* @__PURE__ */ __name((...args) => utils.setDefaultValuesToEmptyProperties(...args), "setDefaults");
  2997. const create = adapter.create;
  2998. adapter.create = function(modelName, modelData, filter) {
  2999. modelData = setDefaults(modelName, modelData);
  3000. return create.call(this, modelName, modelData, filter);
  3001. };
  3002. const replaceById = adapter.replaceById;
  3003. adapter.replaceById = function(modelName, id, modelData, filter) {
  3004. modelData = setDefaults(modelName, modelData);
  3005. return replaceById.call(this, modelName, id, modelData, filter);
  3006. };
  3007. const replaceOrCreate = adapter.replaceOrCreate;
  3008. adapter.replaceOrCreate = function(modelName, modelData, filter) {
  3009. modelData = setDefaults(modelName, modelData);
  3010. return replaceOrCreate.call(this, modelName, modelData, filter);
  3011. };
  3012. const patch = adapter.patch;
  3013. adapter.patch = function(modelName, modelData, where) {
  3014. modelData = setDefaults(modelName, modelData, true);
  3015. return patch.call(this, modelName, modelData, where);
  3016. };
  3017. const patchById = adapter.patchById;
  3018. adapter.patchById = function(modelName, id, modelData, filter) {
  3019. modelData = setDefaults(modelName, modelData, true);
  3020. return patchById.call(this, modelName, id, modelData, filter);
  3021. };
  3022. const find = adapter.find;
  3023. adapter.find = async function(modelName, filter) {
  3024. const modelItems = await find.call(this, modelName, filter);
  3025. return modelItems.map((modelItem) => setDefaults(modelName, modelItem));
  3026. };
  3027. const findById = adapter.findById;
  3028. adapter.findById = async function(modelName, id, filter) {
  3029. const retvalData = await findById.call(this, modelName, id, filter);
  3030. return setDefaults(modelName, retvalData);
  3031. };
  3032. }
  3033. };
  3034. __name(_DefaultValuesDecorator, "DefaultValuesDecorator");
  3035. DefaultValuesDecorator = _DefaultValuesDecorator;
  3036. }
  3037. });
  3038. // src/adapter/decorator/data-sanitizing-decorator.js
  3039. var import_js_service18, _DataSanitizingDecorator, DataSanitizingDecorator;
  3040. var init_data_sanitizing_decorator = __esm({
  3041. "src/adapter/decorator/data-sanitizing-decorator.js"() {
  3042. "use strict";
  3043. init_adapter();
  3044. import_js_service18 = require("@e22m4u/js-service");
  3045. init_errors();
  3046. init_definition();
  3047. _DataSanitizingDecorator = class _DataSanitizingDecorator extends import_js_service18.Service {
  3048. /**
  3049. * Decorate.
  3050. *
  3051. * @param {Adapter} adapter
  3052. */
  3053. decorate(adapter) {
  3054. if (!adapter || !(adapter instanceof Adapter))
  3055. throw new InvalidArgumentError(
  3056. "The first argument of DataSanitizingDecorator.decorate should be an Adapter instance, but %v was given.",
  3057. adapter
  3058. );
  3059. const sanitizer = adapter.getService(ModelDataSanitizer);
  3060. const sanitize = /* @__PURE__ */ __name((...args) => sanitizer.sanitize(...args), "sanitize");
  3061. const create = adapter.create;
  3062. adapter.create = async function(modelName, modelData, filter) {
  3063. modelData = sanitize(modelName, modelData);
  3064. return create.call(this, modelName, modelData, filter);
  3065. };
  3066. const replaceById = adapter.replaceById;
  3067. adapter.replaceById = async function(modelName, id, modelData, filter) {
  3068. modelData = sanitize(modelName, modelData);
  3069. return replaceById.call(this, modelName, id, modelData, filter);
  3070. };
  3071. const replaceOrCreate = adapter.replaceOrCreate;
  3072. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  3073. modelData = sanitize(modelName, modelData);
  3074. return replaceOrCreate.call(this, modelName, modelData, filter);
  3075. };
  3076. const patch = adapter.patch;
  3077. adapter.patch = async function(modelName, modelData, where) {
  3078. modelData = sanitize(modelName, modelData);
  3079. return patch.call(this, modelName, modelData, where);
  3080. };
  3081. const patchById = adapter.patchById;
  3082. adapter.patchById = async function(modelName, id, modelData, filter) {
  3083. modelData = sanitize(modelName, modelData);
  3084. return patchById.call(this, modelName, id, modelData, filter);
  3085. };
  3086. }
  3087. };
  3088. __name(_DataSanitizingDecorator, "DataSanitizingDecorator");
  3089. DataSanitizingDecorator = _DataSanitizingDecorator;
  3090. }
  3091. });
  3092. // src/adapter/decorator/fields-filtering-decorator.js
  3093. var import_js_service19, _FieldsFilteringDecorator, FieldsFilteringDecorator;
  3094. var init_fields_filtering_decorator = __esm({
  3095. "src/adapter/decorator/fields-filtering-decorator.js"() {
  3096. "use strict";
  3097. init_adapter();
  3098. import_js_service19 = require("@e22m4u/js-service");
  3099. init_filter();
  3100. init_errors();
  3101. _FieldsFilteringDecorator = class _FieldsFilteringDecorator extends import_js_service19.Service {
  3102. /**
  3103. * Decorate.
  3104. *
  3105. * @param {Adapter} adapter
  3106. */
  3107. decorate(adapter) {
  3108. if (!adapter || !(adapter instanceof Adapter))
  3109. throw new InvalidArgumentError(
  3110. "The first argument of FieldsFilteringDecorator.decorate should be an Adapter instance, but %v was given.",
  3111. adapter
  3112. );
  3113. const tool = adapter.getService(FieldsClauseTool);
  3114. const selectFields = /* @__PURE__ */ __name((...args) => tool.filter(...args), "selectFields");
  3115. const create = adapter.create;
  3116. adapter.create = async function(modelName, modelData, filter) {
  3117. let result = await create.call(this, modelName, modelData, filter);
  3118. if (filter && typeof filter === "object" && filter.fields)
  3119. result = selectFields(result, modelName, filter.fields);
  3120. return result;
  3121. };
  3122. const replaceById = adapter.replaceById;
  3123. adapter.replaceById = async function(modelName, id, modelData, filter) {
  3124. let result = await replaceById.call(
  3125. this,
  3126. modelName,
  3127. id,
  3128. modelData,
  3129. filter
  3130. );
  3131. if (filter && typeof filter === "object" && filter.fields)
  3132. result = selectFields(result, modelName, filter.fields);
  3133. return result;
  3134. };
  3135. const replaceOrCreate = adapter.replaceOrCreate;
  3136. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  3137. let result = await replaceOrCreate.call(
  3138. this,
  3139. modelName,
  3140. modelData,
  3141. filter
  3142. );
  3143. if (filter && typeof filter === "object" && filter.fields)
  3144. result = selectFields(result, modelName, filter.fields);
  3145. return result;
  3146. };
  3147. const patchById = adapter.patchById;
  3148. adapter.patchById = async function(modelName, id, modelData, filter) {
  3149. let result = await patchById.call(this, modelName, id, modelData, filter);
  3150. if (filter && typeof filter === "object" && filter.fields)
  3151. result = selectFields(result, modelName, filter.fields);
  3152. return result;
  3153. };
  3154. const find = adapter.find;
  3155. adapter.find = async function(modelName, filter) {
  3156. let result = await find.call(this, modelName, filter);
  3157. if (filter && typeof filter === "object" && filter.fields)
  3158. result = selectFields(result, modelName, filter.fields);
  3159. return result;
  3160. };
  3161. const findById = adapter.findById;
  3162. adapter.findById = async function(modelName, id, filter) {
  3163. let result = await findById.call(this, modelName, id, filter);
  3164. if (filter && typeof filter === "object" && filter.fields)
  3165. result = selectFields(result, modelName, filter.fields);
  3166. return result;
  3167. };
  3168. }
  3169. };
  3170. __name(_FieldsFilteringDecorator, "FieldsFilteringDecorator");
  3171. FieldsFilteringDecorator = _FieldsFilteringDecorator;
  3172. }
  3173. });
  3174. // src/adapter/decorator/required-property-decorator.js
  3175. var import_js_service20, _RequiredPropertyDecorator, RequiredPropertyDecorator;
  3176. var init_required_property_decorator = __esm({
  3177. "src/adapter/decorator/required-property-decorator.js"() {
  3178. "use strict";
  3179. init_adapter();
  3180. import_js_service20 = require("@e22m4u/js-service");
  3181. init_errors();
  3182. init_definition();
  3183. _RequiredPropertyDecorator = class _RequiredPropertyDecorator extends import_js_service20.Service {
  3184. /**
  3185. * Decorate.
  3186. *
  3187. * @param {Adapter} adapter
  3188. */
  3189. decorate(adapter) {
  3190. if (!adapter || !(adapter instanceof Adapter))
  3191. throw new InvalidArgumentError(
  3192. "The first argument of RequiredPropertyDecorator.decorate should be an Adapter instance, but %v was given.",
  3193. adapter
  3194. );
  3195. const validator = this.getService(RequiredPropertyValidator);
  3196. const create = adapter.create;
  3197. adapter.create = async function(modelName, modelData, filter) {
  3198. validator.validate(modelName, modelData);
  3199. return create.call(this, modelName, modelData, filter);
  3200. };
  3201. const replaceById = adapter.replaceById;
  3202. adapter.replaceById = async function(modelName, id, modelData, filter) {
  3203. validator.validate(modelName, modelData);
  3204. return replaceById.call(this, modelName, id, modelData, filter);
  3205. };
  3206. const replaceOrCreate = adapter.replaceOrCreate;
  3207. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  3208. validator.validate(modelName, modelData);
  3209. return replaceOrCreate.call(this, modelName, modelData, filter);
  3210. };
  3211. const patch = adapter.patch;
  3212. adapter.patch = async function(modelName, modelData, where) {
  3213. validator.validate(modelName, modelData, true);
  3214. return patch.call(this, modelName, modelData, where);
  3215. };
  3216. const patchById = adapter.patchById;
  3217. adapter.patchById = async function(modelName, id, modelData, filter) {
  3218. validator.validate(modelName, modelData, true);
  3219. return patchById.call(this, modelName, id, modelData, filter);
  3220. };
  3221. }
  3222. };
  3223. __name(_RequiredPropertyDecorator, "RequiredPropertyDecorator");
  3224. RequiredPropertyDecorator = _RequiredPropertyDecorator;
  3225. }
  3226. });
  3227. // src/adapter/decorator/property-uniqueness-decorator.js
  3228. var import_js_service21, _PropertyUniquenessDecorator, PropertyUniquenessDecorator;
  3229. var init_property_uniqueness_decorator = __esm({
  3230. "src/adapter/decorator/property-uniqueness-decorator.js"() {
  3231. "use strict";
  3232. init_adapter();
  3233. import_js_service21 = require("@e22m4u/js-service");
  3234. init_errors();
  3235. init_definition();
  3236. _PropertyUniquenessDecorator = class _PropertyUniquenessDecorator extends import_js_service21.Service {
  3237. /**
  3238. * Decorate.
  3239. *
  3240. * @param {Adapter} adapter
  3241. */
  3242. decorate(adapter) {
  3243. if (!adapter || !(adapter instanceof Adapter))
  3244. throw new InvalidArgumentError(
  3245. "The first argument of PropertyUniquenessDecorator.decorate should be an Adapter instance, but %v was given.",
  3246. adapter
  3247. );
  3248. const validator = this.getService(PropertyUniquenessValidator);
  3249. const create = adapter.create;
  3250. adapter.create = async function(modelName, modelData, filter) {
  3251. const countMethod = adapter.count.bind(adapter, modelName);
  3252. await validator.validate(countMethod, "create", modelName, modelData);
  3253. return create.call(this, modelName, modelData, filter);
  3254. };
  3255. const replaceById = adapter.replaceById;
  3256. adapter.replaceById = async function(modelName, id, modelData, filter) {
  3257. const countMethod = adapter.count.bind(adapter, modelName);
  3258. await validator.validate(
  3259. countMethod,
  3260. "replaceById",
  3261. modelName,
  3262. modelData,
  3263. id
  3264. );
  3265. return replaceById.call(this, modelName, id, modelData, filter);
  3266. };
  3267. const replaceOrCreate = adapter.replaceOrCreate;
  3268. adapter.replaceOrCreate = async function(modelName, modelData, filter) {
  3269. const countMethod = adapter.count.bind(adapter, modelName);
  3270. await validator.validate(
  3271. countMethod,
  3272. "replaceOrCreate",
  3273. modelName,
  3274. modelData
  3275. );
  3276. return replaceOrCreate.call(this, modelName, modelData, filter);
  3277. };
  3278. const patch = adapter.patch;
  3279. adapter.patch = async function(modelName, modelData, where) {
  3280. const countMethod = adapter.count.bind(adapter, modelName);
  3281. await validator.validate(countMethod, "patch", modelName, modelData);
  3282. return patch.call(this, modelName, modelData, where);
  3283. };
  3284. const patchById = adapter.patchById;
  3285. adapter.patchById = async function(modelName, id, modelData, filter) {
  3286. const countMethod = adapter.count.bind(adapter, modelName);
  3287. await validator.validate(
  3288. countMethod,
  3289. "patchById",
  3290. modelName,
  3291. modelData,
  3292. id
  3293. );
  3294. return patchById.call(this, modelName, id, modelData, filter);
  3295. };
  3296. }
  3297. };
  3298. __name(_PropertyUniquenessDecorator, "PropertyUniquenessDecorator");
  3299. PropertyUniquenessDecorator = _PropertyUniquenessDecorator;
  3300. }
  3301. });
  3302. // src/adapter/decorator/index.js
  3303. var init_decorator = __esm({
  3304. "src/adapter/decorator/index.js"() {
  3305. "use strict";
  3306. init_inclusion_decorator();
  3307. init_default_values_decorator();
  3308. init_data_sanitizing_decorator();
  3309. init_fields_filtering_decorator();
  3310. init_required_property_decorator();
  3311. init_property_uniqueness_decorator();
  3312. }
  3313. });
  3314. // src/adapter/adapter.js
  3315. var import_js_service22, ADAPTER_CLASS_NAME, _Adapter, Adapter;
  3316. var init_adapter = __esm({
  3317. "src/adapter/adapter.js"() {
  3318. "use strict";
  3319. import_js_service22 = require("@e22m4u/js-service");
  3320. init_errors();
  3321. init_decorator();
  3322. ADAPTER_CLASS_NAME = "Adapter";
  3323. _Adapter = class _Adapter extends import_js_service22.Service {
  3324. /**
  3325. * Settings.
  3326. *
  3327. * @type {object|undefined}
  3328. */
  3329. _settings;
  3330. /**
  3331. * Settings.
  3332. *
  3333. * @returns {object|undefined}
  3334. */
  3335. get settings() {
  3336. return this._settings;
  3337. }
  3338. /**
  3339. * Constructor.
  3340. *
  3341. * @param {object|undefined} container
  3342. * @param {object|undefined} settings
  3343. */
  3344. constructor(container = void 0, settings = void 0) {
  3345. super(container);
  3346. this._settings = settings;
  3347. if (this.constructor !== _Adapter) {
  3348. this.getService(DataSanitizingDecorator).decorate(this);
  3349. this.getService(DefaultValuesDecorator).decorate(this);
  3350. this.getService(RequiredPropertyDecorator).decorate(this);
  3351. this.getService(PropertyUniquenessDecorator).decorate(this);
  3352. this.getService(FieldsFilteringDecorator).decorate(this);
  3353. this.getService(InclusionDecorator).decorate(this);
  3354. }
  3355. }
  3356. /**
  3357. * Create.
  3358. *
  3359. * @param {string} modelName
  3360. * @param {object} modelData
  3361. * @param {object|undefined} filter
  3362. * @returns {Promise<object>}
  3363. */
  3364. create(modelName, modelData, filter = void 0) {
  3365. throw new NotImplementedError(
  3366. "%s.create is not implemented.",
  3367. this.constructor.name
  3368. );
  3369. }
  3370. /**
  3371. * Replace by id.
  3372. *
  3373. * @param {string} modelName
  3374. * @param {number|string} id
  3375. * @param {object} modelData
  3376. * @param {object|undefined} filter
  3377. * @returns {Promise<object>}
  3378. */
  3379. replaceById(modelName, id, modelData, filter = void 0) {
  3380. throw new NotImplementedError(
  3381. "%s.replaceById is not implemented.",
  3382. this.constructor.name
  3383. );
  3384. }
  3385. /**
  3386. * Replace or create.
  3387. *
  3388. * @param {string} modelName
  3389. * @param {object} modelData
  3390. * @param {object|undefined} filter
  3391. * @returns {Promise<object>}
  3392. */
  3393. replaceOrCreate(modelName, modelData, filter = void 0) {
  3394. throw new NotImplementedError(
  3395. "%s.replaceOrCreate is not implemented.",
  3396. this.constructor.name
  3397. );
  3398. }
  3399. /**
  3400. * Patch.
  3401. *
  3402. * @param {string} modelName
  3403. * @param {object} modelData
  3404. * @param {object|undefined} where
  3405. * @returns {Promise<number>}
  3406. */
  3407. patch(modelName, modelData, where = void 0) {
  3408. throw new NotImplementedError(
  3409. "%s.patch is not implemented.",
  3410. this.constructor.name
  3411. );
  3412. }
  3413. /**
  3414. * Patch by id.
  3415. *
  3416. * @param {string} modelName
  3417. * @param {number|string} id
  3418. * @param {object} modelData
  3419. * @param {object|undefined} filter
  3420. * @returns {Promise<object>}
  3421. */
  3422. patchById(modelName, id, modelData, filter = void 0) {
  3423. throw new NotImplementedError(
  3424. "%s.patchById is not implemented.",
  3425. this.constructor.name
  3426. );
  3427. }
  3428. /**
  3429. * Find.
  3430. *
  3431. * @param {string} modelName
  3432. * @param {object|undefined} filter
  3433. * @returns {Promise<object[]>}
  3434. */
  3435. find(modelName, filter = void 0) {
  3436. throw new NotImplementedError(
  3437. "%s.find is not implemented.",
  3438. this.constructor.name
  3439. );
  3440. }
  3441. /**
  3442. * Find by id.
  3443. *
  3444. * @param {string} modelName
  3445. * @param {number|string} id
  3446. * @param {object|undefined} filter
  3447. * @returns {Promise<object>}
  3448. */
  3449. findById(modelName, id, filter = void 0) {
  3450. throw new NotImplementedError(
  3451. "%s.findById is not implemented.",
  3452. this.constructor.name
  3453. );
  3454. }
  3455. /**
  3456. * Delete.
  3457. *
  3458. * @param {string} modelName
  3459. * @param {object|undefined} where
  3460. * @returns {Promise<number>}
  3461. */
  3462. delete(modelName, where = void 0) {
  3463. throw new NotImplementedError(
  3464. "%s.delete is not implemented.",
  3465. this.constructor.name
  3466. );
  3467. }
  3468. /**
  3469. * Delete by id.
  3470. *
  3471. * @param {string} modelName
  3472. * @param {number|string} id
  3473. * @returns {Promise<boolean>}
  3474. */
  3475. deleteById(modelName, id) {
  3476. throw new NotImplementedError(
  3477. "%s.deleteById is not implemented.",
  3478. this.constructor.name
  3479. );
  3480. }
  3481. /**
  3482. * Exists.
  3483. *
  3484. * @param {string} modelName
  3485. * @param {number|string} id
  3486. * @returns {Promise<boolean>}
  3487. */
  3488. exists(modelName, id) {
  3489. throw new NotImplementedError(
  3490. "%s.exists is not implemented.",
  3491. this.constructor.name
  3492. );
  3493. }
  3494. /**
  3495. * Count.
  3496. *
  3497. * @param {string} modelName
  3498. * @param {object|undefined} where
  3499. * @returns {Promise<number>}
  3500. */
  3501. count(modelName, where = void 0) {
  3502. throw new NotImplementedError(
  3503. "%s.count is not implemented.",
  3504. this.constructor.name
  3505. );
  3506. }
  3507. };
  3508. __name(_Adapter, "Adapter");
  3509. /**
  3510. * Kinds.
  3511. *
  3512. * @type {string[]}
  3513. */
  3514. __publicField(_Adapter, "kinds", [...import_js_service22.Service.kinds, ADAPTER_CLASS_NAME]);
  3515. Adapter = _Adapter;
  3516. }
  3517. });
  3518. // src/adapter/builtin/memory-adapter.js
  3519. var memory_adapter_exports = {};
  3520. __export(memory_adapter_exports, {
  3521. MemoryAdapter: () => MemoryAdapter
  3522. });
  3523. var _MemoryAdapter, MemoryAdapter;
  3524. var init_memory_adapter = __esm({
  3525. "src/adapter/builtin/memory-adapter.js"() {
  3526. "use strict";
  3527. init_adapter();
  3528. init_errors();
  3529. init_utils();
  3530. init_definition();
  3531. init_filter();
  3532. _MemoryAdapter = class _MemoryAdapter extends Adapter {
  3533. /**
  3534. * Tables.
  3535. *
  3536. * @type {Map<string, Map<number, Record<string, any>>>}
  3537. */
  3538. _tables = /* @__PURE__ */ new Map();
  3539. /**
  3540. * Last ids.
  3541. *
  3542. * @type {Map<string, number>}
  3543. */
  3544. _lastIds = /* @__PURE__ */ new Map();
  3545. /**
  3546. * Get table or create.
  3547. *
  3548. * @param {string} modelName
  3549. * @returns {Map<number, object>}
  3550. */
  3551. _getTableOrCreate(modelName) {
  3552. const tableName = this.getService(ModelDefinitionUtils).getTableNameByModelName(modelName);
  3553. let table = this._tables.get(tableName);
  3554. if (table) return table;
  3555. table = /* @__PURE__ */ new Map();
  3556. this._tables.set(tableName, table);
  3557. return table;
  3558. }
  3559. /**
  3560. * Gen next id value.
  3561. *
  3562. * @param {string} modelName
  3563. * @param {string} propName
  3564. * @returns {number}
  3565. */
  3566. _genNextIdValue(modelName, propName) {
  3567. var _a;
  3568. const modelUtils = this.getService(ModelDefinitionUtils);
  3569. const propType = modelUtils.getDataTypeByPropertyName(modelName, propName);
  3570. if (propType !== DataType.ANY && propType !== DataType.NUMBER) {
  3571. throw new InvalidArgumentError(
  3572. "The memory adapter able to generate only Number identifiers, but the primary key %v of the model %v is defined as %s. Do provide your own value for the %v property, or change the type in the primary key definition to a Number that will be generated automatically.",
  3573. propName,
  3574. modelName,
  3575. capitalize(propType),
  3576. propName
  3577. );
  3578. }
  3579. const tableName = modelUtils.getTableNameByModelName(modelName);
  3580. const table = this._getTableOrCreate(modelName);
  3581. let nextId = (_a = this._lastIds.get(tableName)) != null ? _a : 0;
  3582. do {
  3583. nextId++;
  3584. } while (table.has(nextId));
  3585. this._lastIds.set(tableName, nextId);
  3586. return nextId;
  3587. }
  3588. /**
  3589. * Update last id value if needed.
  3590. *
  3591. * Если переданное значение последнего использованного
  3592. * идентификатора больше текущего, то текущее значение
  3593. * перезаписывается полученным.
  3594. *
  3595. * @param {string} modelName
  3596. * @param {number} idValue
  3597. */
  3598. _updateLastIdValueIfNeeded(modelName, idValue) {
  3599. var _a;
  3600. const tableName = this.getService(ModelDefinitionUtils).getTableNameByModelName(modelName);
  3601. const currentLastId = (_a = this._lastIds.get(tableName)) != null ? _a : 0;
  3602. if (idValue > currentLastId) {
  3603. this._lastIds.set(tableName, idValue);
  3604. }
  3605. }
  3606. /**
  3607. * Create
  3608. *
  3609. * @param {string} modelName
  3610. * @param {object} modelData
  3611. * @param {object|undefined} filter
  3612. * @returns {Promise<object>}
  3613. */
  3614. // eslint-disable-next-line no-unused-vars
  3615. async create(modelName, modelData, filter = void 0) {
  3616. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3617. modelName
  3618. );
  3619. let idValue = modelData[pkPropName];
  3620. if (idValue == null || idValue === "" || idValue === 0) {
  3621. idValue = this._genNextIdValue(modelName, pkPropName);
  3622. } else if (typeof idValue === "number") {
  3623. this._updateLastIdValueIfNeeded(modelName, idValue);
  3624. }
  3625. const table = this._getTableOrCreate(modelName);
  3626. if (table.has(idValue))
  3627. throw new InvalidArgumentError(
  3628. "The value %v of the primary key %v already exists in the model %v.",
  3629. idValue,
  3630. pkPropName,
  3631. modelName
  3632. );
  3633. modelData = cloneDeep(modelData);
  3634. modelData[pkPropName] = idValue;
  3635. const tableData = this.getService(
  3636. ModelDefinitionUtils
  3637. ).convertPropertyNamesToColumnNames(modelName, modelData);
  3638. table.set(idValue, tableData);
  3639. return this.getService(
  3640. ModelDefinitionUtils
  3641. ).convertColumnNamesToPropertyNames(modelName, tableData);
  3642. }
  3643. /**
  3644. * Replace by id.
  3645. *
  3646. * @param {string} modelName
  3647. * @param {string|number} id
  3648. * @param {object} modelData
  3649. * @param {object|undefined} filter
  3650. * @returns {Promise<object>}
  3651. */
  3652. // eslint-disable-next-line no-unused-vars
  3653. async replaceById(modelName, id, modelData, filter = void 0) {
  3654. const table = this._getTableOrCreate(modelName);
  3655. const isExists = table.has(id);
  3656. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3657. modelName
  3658. );
  3659. if (!isExists)
  3660. throw new InvalidArgumentError(
  3661. "The value %v of the primary key %v does not exist in the model %v.",
  3662. id,
  3663. pkPropName,
  3664. modelName
  3665. );
  3666. modelData = cloneDeep(modelData);
  3667. modelData[pkPropName] = id;
  3668. const tableData = this.getService(
  3669. ModelDefinitionUtils
  3670. ).convertPropertyNamesToColumnNames(modelName, modelData);
  3671. table.set(id, tableData);
  3672. return this.getService(
  3673. ModelDefinitionUtils
  3674. ).convertColumnNamesToPropertyNames(modelName, tableData);
  3675. }
  3676. /**
  3677. * Replace or create.
  3678. *
  3679. * @param {string} modelName
  3680. * @param {object} modelData
  3681. * @param {object|undefined} filter
  3682. * @returns {Promise<object>}
  3683. */
  3684. // eslint-disable-next-line no-unused-vars
  3685. async replaceOrCreate(modelName, modelData, filter = void 0) {
  3686. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3687. modelName
  3688. );
  3689. let idValue = modelData[pkPropName];
  3690. if (idValue == null || idValue === "" || idValue === 0) {
  3691. idValue = this._genNextIdValue(modelName, pkPropName);
  3692. } else if (typeof idValue === "number") {
  3693. this._updateLastIdValueIfNeeded(modelName, idValue);
  3694. }
  3695. const table = this._getTableOrCreate(modelName);
  3696. modelData = cloneDeep(modelData);
  3697. modelData[pkPropName] = idValue;
  3698. const tableData = this.getService(
  3699. ModelDefinitionUtils
  3700. ).convertPropertyNamesToColumnNames(modelName, modelData);
  3701. table.set(idValue, tableData);
  3702. return this.getService(
  3703. ModelDefinitionUtils
  3704. ).convertColumnNamesToPropertyNames(modelName, tableData);
  3705. }
  3706. /**
  3707. * Patch.
  3708. *
  3709. * @param {string} modelName
  3710. * @param {object} modelData
  3711. * @param {object|undefined} where
  3712. * @returns {Promise<number>}
  3713. */
  3714. async patch(modelName, modelData, where = void 0) {
  3715. const table = this._getTableOrCreate(modelName);
  3716. const tableItems = Array.from(table.values());
  3717. if (!tableItems.length) return 0;
  3718. let modelItems = tableItems.map(
  3719. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  3720. modelName,
  3721. tableItem
  3722. )
  3723. );
  3724. if (where && typeof where === "object")
  3725. modelItems = this.getService(WhereClauseTool).filter(modelItems, where);
  3726. const size = modelItems.length;
  3727. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3728. modelName
  3729. );
  3730. modelData = cloneDeep(modelData);
  3731. delete modelData[pkPropName];
  3732. modelItems.forEach((existingModelData) => {
  3733. const mergedModelData = Object.assign({}, existingModelData, modelData);
  3734. const mergedTableData = this.getService(
  3735. ModelDefinitionUtils
  3736. ).convertPropertyNamesToColumnNames(modelName, mergedModelData);
  3737. const idValue = existingModelData[pkPropName];
  3738. table.set(idValue, mergedTableData);
  3739. });
  3740. return size;
  3741. }
  3742. /**
  3743. * Patch by id.
  3744. *
  3745. * @param {string} modelName
  3746. * @param {string|number} id
  3747. * @param {object} modelData
  3748. * @param {object|undefined} filter
  3749. * @returns {Promise<object>}
  3750. */
  3751. // eslint-disable-next-line no-unused-vars
  3752. async patchById(modelName, id, modelData, filter = void 0) {
  3753. const table = this._getTableOrCreate(modelName);
  3754. const existingTableData = table.get(id);
  3755. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3756. modelName
  3757. );
  3758. if (existingTableData == null)
  3759. throw new InvalidArgumentError(
  3760. "The value %v of the primary key %v does not exist in the model %v.",
  3761. id,
  3762. pkPropName,
  3763. modelName
  3764. );
  3765. modelData = cloneDeep(modelData);
  3766. delete modelData[pkPropName];
  3767. const existingModelData = this.getService(
  3768. ModelDefinitionUtils
  3769. ).convertColumnNamesToPropertyNames(modelName, existingTableData);
  3770. const mergedModelData = Object.assign({}, existingModelData, modelData);
  3771. const mergedTableData = this.getService(
  3772. ModelDefinitionUtils
  3773. ).convertPropertyNamesToColumnNames(modelName, mergedModelData);
  3774. table.set(id, mergedTableData);
  3775. return this.getService(
  3776. ModelDefinitionUtils
  3777. ).convertColumnNamesToPropertyNames(modelName, mergedTableData);
  3778. }
  3779. /**
  3780. * Find.
  3781. *
  3782. * @param {string} modelName
  3783. * @param {object|undefined} filter
  3784. * @returns {Promise<object[]>}
  3785. */
  3786. async find(modelName, filter = void 0) {
  3787. const table = this._getTableOrCreate(modelName);
  3788. const tableItems = Array.from(table.values());
  3789. let modelItems = tableItems.map(
  3790. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  3791. modelName,
  3792. tableItem
  3793. )
  3794. );
  3795. if (filter && typeof filter === "object") {
  3796. if (filter.where)
  3797. modelItems = this.getService(WhereClauseTool).filter(
  3798. modelItems,
  3799. filter.where
  3800. );
  3801. if (filter.skip || filter.limit)
  3802. modelItems = this.getService(SliceClauseTool).slice(
  3803. modelItems,
  3804. filter.skip,
  3805. filter.limit
  3806. );
  3807. if (filter.order)
  3808. this.getService(OrderClauseTool).sort(modelItems, filter.order);
  3809. }
  3810. return modelItems;
  3811. }
  3812. /**
  3813. * Find by id.
  3814. *
  3815. * @param {string} modelName
  3816. * @param {string|number} id
  3817. * @param {object|undefined} filter
  3818. * @returns {Promise<object>}
  3819. */
  3820. // eslint-disable-next-line no-unused-vars
  3821. async findById(modelName, id, filter = void 0) {
  3822. const table = this._getTableOrCreate(modelName);
  3823. const tableData = table.get(id);
  3824. const pkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3825. modelName
  3826. );
  3827. if (!tableData)
  3828. throw new InvalidArgumentError(
  3829. "The value %v of the primary key %v does not exist in the model %v.",
  3830. id,
  3831. pkPropName,
  3832. modelName
  3833. );
  3834. return this.getService(
  3835. ModelDefinitionUtils
  3836. ).convertColumnNamesToPropertyNames(modelName, tableData);
  3837. }
  3838. /**
  3839. * Delete.
  3840. *
  3841. * @param {string} modelName
  3842. * @param {object|undefined} where
  3843. * @returns {Promise<number>}
  3844. */
  3845. async delete(modelName, where = void 0) {
  3846. const table = this._getTableOrCreate(modelName);
  3847. const tableItems = Array.from(table.values());
  3848. if (!tableItems.length) return 0;
  3849. let modelItems = tableItems.map(
  3850. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  3851. modelName,
  3852. tableItem
  3853. )
  3854. );
  3855. if (where && typeof where === "object")
  3856. modelItems = this.getService(WhereClauseTool).filter(modelItems, where);
  3857. const size = modelItems.length;
  3858. const idPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  3859. modelName
  3860. );
  3861. modelItems.forEach((modelData) => {
  3862. const idValue = modelData[idPropName];
  3863. table.delete(idValue);
  3864. });
  3865. return size;
  3866. }
  3867. /**
  3868. * Delete by id.
  3869. *
  3870. * @param {string} modelName
  3871. * @param {string|number} id
  3872. * @returns {Promise<boolean>}
  3873. */
  3874. async deleteById(modelName, id) {
  3875. const table = this._getTableOrCreate(modelName);
  3876. const isExists = table.has(id);
  3877. table.delete(id);
  3878. return isExists;
  3879. }
  3880. /**
  3881. * Exists.
  3882. *
  3883. * @param {string} modelName
  3884. * @param {string|number} id
  3885. * @returns {Promise<boolean>}
  3886. */
  3887. async exists(modelName, id) {
  3888. const table = this._getTableOrCreate(modelName);
  3889. return table.has(id);
  3890. }
  3891. /**
  3892. * Count.
  3893. *
  3894. * @param {string} modelName
  3895. * @param {object|undefined} where
  3896. * @returns {Promise<number>}
  3897. */
  3898. async count(modelName, where = void 0) {
  3899. const table = this._getTableOrCreate(modelName);
  3900. const tableItems = Array.from(table.values());
  3901. let modelItems = tableItems.map(
  3902. (tableItem) => this.getService(ModelDefinitionUtils).convertColumnNamesToPropertyNames(
  3903. modelName,
  3904. tableItem
  3905. )
  3906. );
  3907. if (where && typeof where === "object")
  3908. modelItems = this.getService(WhereClauseTool).filter(modelItems, where);
  3909. return modelItems.length;
  3910. }
  3911. };
  3912. __name(_MemoryAdapter, "MemoryAdapter");
  3913. MemoryAdapter = _MemoryAdapter;
  3914. }
  3915. });
  3916. // import("./builtin/**/*-adapter.js") in src/adapter/adapter-loader.js
  3917. var globImport_builtin_adapter_js;
  3918. var init_ = __esm({
  3919. 'import("./builtin/**/*-adapter.js") in src/adapter/adapter-loader.js'() {
  3920. globImport_builtin_adapter_js = __glob({
  3921. "./builtin/memory-adapter.js": () => Promise.resolve().then(() => (init_memory_adapter(), memory_adapter_exports))
  3922. });
  3923. }
  3924. });
  3925. // src/adapter/adapter-loader.js
  3926. function findAdapterCtorInModule(module2) {
  3927. let adapterCtor;
  3928. if (!module2 || typeof module2 !== "object" || Array.isArray(module2)) return;
  3929. for (const ctor of Object.values(module2)) {
  3930. if (typeof ctor === "function" && Array.isArray(ctor.kinds) && Adapter.kinds.includes(ADAPTER_CLASS_NAME)) {
  3931. adapterCtor = ctor;
  3932. break;
  3933. }
  3934. }
  3935. return adapterCtor;
  3936. }
  3937. var import_js_service23, _AdapterLoader, AdapterLoader;
  3938. var init_adapter_loader = __esm({
  3939. "src/adapter/adapter-loader.js"() {
  3940. "use strict";
  3941. import_js_service23 = require("@e22m4u/js-service");
  3942. init_errors();
  3943. init_adapter();
  3944. init_();
  3945. _AdapterLoader = class _AdapterLoader extends import_js_service23.Service {
  3946. /**
  3947. * Load by name.
  3948. *
  3949. * @param {string} adapterName
  3950. * @param {object|undefined} settings
  3951. * @returns {Promise<Adapter>}
  3952. */
  3953. async loadByName(adapterName, settings = void 0) {
  3954. if (!adapterName || typeof adapterName !== "string")
  3955. throw new InvalidArgumentError(
  3956. "The adapter name should be a non-empty String, but %v was given.",
  3957. adapterName
  3958. );
  3959. let adapterCtor;
  3960. try {
  3961. const module2 = await globImport_builtin_adapter_js(`./builtin/${adapterName}-adapter.js`);
  3962. adapterCtor = findAdapterCtorInModule(module2);
  3963. } catch {
  3964. }
  3965. if (!adapterCtor)
  3966. try {
  3967. const module2 = await Promise.resolve().then(() => __toESM(require(`@e22m4u/js-repository-${adapterName}-adapter`)));
  3968. adapterCtor = findAdapterCtorInModule(module2);
  3969. } catch {
  3970. }
  3971. if (!adapterCtor)
  3972. throw new InvalidArgumentError(
  3973. "The adapter %v is not found.",
  3974. adapterName
  3975. );
  3976. return new adapterCtor(this.container, settings);
  3977. }
  3978. };
  3979. __name(_AdapterLoader, "AdapterLoader");
  3980. AdapterLoader = _AdapterLoader;
  3981. __name(findAdapterCtorInModule, "findAdapterCtorInModule");
  3982. }
  3983. });
  3984. // src/adapter/adapter-registry.js
  3985. var import_js_service24, _AdapterRegistry, AdapterRegistry;
  3986. var init_adapter_registry = __esm({
  3987. "src/adapter/adapter-registry.js"() {
  3988. "use strict";
  3989. init_adapter();
  3990. import_js_service24 = require("@e22m4u/js-service");
  3991. init_adapter_loader();
  3992. init_definition();
  3993. _AdapterRegistry = class _AdapterRegistry extends import_js_service24.Service {
  3994. /**
  3995. * Adapters.
  3996. *
  3997. * @type {object}
  3998. */
  3999. _adapters = {};
  4000. /**
  4001. * Get adapter.
  4002. *
  4003. * @param {string} datasourceName
  4004. * @returns {Promise<Adapter>}
  4005. */
  4006. async getAdapter(datasourceName) {
  4007. let adapter = this._adapters[datasourceName];
  4008. if (adapter) return adapter;
  4009. const datasource = this.getService(DefinitionRegistry).getDatasource(datasourceName);
  4010. const adapterName = datasource.adapter;
  4011. adapter = await this.getService(AdapterLoader).loadByName(
  4012. adapterName,
  4013. datasource
  4014. );
  4015. this._adapters[datasourceName] = adapter;
  4016. return adapter;
  4017. }
  4018. };
  4019. __name(_AdapterRegistry, "AdapterRegistry");
  4020. AdapterRegistry = _AdapterRegistry;
  4021. }
  4022. });
  4023. // src/adapter/index.js
  4024. var init_adapter2 = __esm({
  4025. "src/adapter/index.js"() {
  4026. "use strict";
  4027. init_adapter();
  4028. init_adapter_loader();
  4029. init_adapter_registry();
  4030. }
  4031. });
  4032. // src/repository/repository.js
  4033. var import_js_service25, _Repository, Repository;
  4034. var init_repository = __esm({
  4035. "src/repository/repository.js"() {
  4036. "use strict";
  4037. import_js_service25 = require("@e22m4u/js-service");
  4038. init_errors();
  4039. init_definition();
  4040. init_adapter2();
  4041. _Repository = class _Repository extends import_js_service25.Service {
  4042. /**
  4043. * Model name.
  4044. *
  4045. * @type {string}
  4046. */
  4047. _modelName;
  4048. /**
  4049. * Model name.
  4050. *
  4051. * @returns {string}
  4052. */
  4053. get modelName() {
  4054. return this._modelName;
  4055. }
  4056. /**
  4057. * Datasource name.
  4058. *
  4059. * @type {string}
  4060. */
  4061. _datasourceName;
  4062. /**
  4063. * Datasource name.
  4064. *
  4065. * @returns {string}
  4066. */
  4067. get datasourceName() {
  4068. return this._datasourceName;
  4069. }
  4070. /**
  4071. * Constructor.
  4072. *
  4073. * @typedef {import('@e22m4u/js-service').ServiceContainer} ServiceContainer
  4074. * @param {ServiceContainer} container
  4075. * @param {string} modelName
  4076. */
  4077. constructor(container, modelName) {
  4078. super(container);
  4079. this._modelName = modelName;
  4080. const modelDef = this.getService(DefinitionRegistry).getModel(modelName);
  4081. const datasourceName = modelDef.datasource;
  4082. if (!datasourceName)
  4083. throw new InvalidArgumentError(
  4084. "The model %v does not have a specified datasource.",
  4085. modelName
  4086. );
  4087. this._datasourceName = datasourceName;
  4088. }
  4089. /**
  4090. * Get adapter.
  4091. *
  4092. * @returns {Adapter}
  4093. */
  4094. async getAdapter() {
  4095. return this.getService(AdapterRegistry).getAdapter(this.datasourceName);
  4096. }
  4097. /**
  4098. * Create.
  4099. *
  4100. * @param {object} data
  4101. * @param {object|undefined} filter
  4102. * @returns {Promise<object>}
  4103. */
  4104. async create(data, filter = void 0) {
  4105. const adapter = await this.getAdapter();
  4106. return adapter.create(this.modelName, data, filter);
  4107. }
  4108. /**
  4109. * Replace by id.
  4110. *
  4111. * @param {number|string} id
  4112. * @param {object} data
  4113. * @param {object|undefined} filter
  4114. * @returns {Promise<object>}
  4115. */
  4116. async replaceById(id, data, filter = void 0) {
  4117. const adapter = await this.getAdapter();
  4118. return adapter.replaceById(this.modelName, id, data, filter);
  4119. }
  4120. /**
  4121. * Replace or create.
  4122. *
  4123. * @param {object} data
  4124. * @param {object|undefined} filter
  4125. * @returns {Promise<object>}
  4126. */
  4127. async replaceOrCreate(data, filter = void 0) {
  4128. const adapter = await this.getAdapter();
  4129. return adapter.replaceOrCreate(this.modelName, data, filter);
  4130. }
  4131. /**
  4132. * Patch.
  4133. *
  4134. * @param {object} data
  4135. * @param {object|undefined} where
  4136. * @returns {Promise<number>}
  4137. */
  4138. async patch(data, where = void 0) {
  4139. const adapter = await this.getAdapter();
  4140. return adapter.patch(this.modelName, data, where);
  4141. }
  4142. /**
  4143. * Patch by id.
  4144. *
  4145. * @param {number|string} id
  4146. * @param {object} data
  4147. * @param {object|undefined} filter
  4148. * @returns {Promise<object>}
  4149. */
  4150. async patchById(id, data, filter = void 0) {
  4151. const adapter = await this.getAdapter();
  4152. return adapter.patchById(this.modelName, id, data, filter);
  4153. }
  4154. /**
  4155. * Find.
  4156. *
  4157. * @param {object|undefined} filter
  4158. * @returns {Promise<object[]>}
  4159. */
  4160. async find(filter = void 0) {
  4161. const adapter = await this.getAdapter();
  4162. return adapter.find(this.modelName, filter);
  4163. }
  4164. /**
  4165. * Find one.
  4166. *
  4167. * @param {object|undefined} filter
  4168. * @returns {Promise<object|undefined>}
  4169. */
  4170. async findOne(filter = void 0) {
  4171. const adapter = await this.getAdapter();
  4172. filter = filter != null ? filter : {};
  4173. filter.limit = 1;
  4174. const result = await adapter.find(this.modelName, filter);
  4175. return result.length ? result[0] : void 0;
  4176. }
  4177. /**
  4178. * Find by id.
  4179. *
  4180. * @param {number|string} id
  4181. * @param {object|undefined} filter
  4182. * @returns {Promise<object>}
  4183. */
  4184. async findById(id, filter = void 0) {
  4185. const adapter = await this.getAdapter();
  4186. return adapter.findById(this.modelName, id, filter);
  4187. }
  4188. /**
  4189. * Delete.
  4190. *
  4191. * @param {object|undefined} where
  4192. * @returns {Promise<number>}
  4193. */
  4194. async delete(where = void 0) {
  4195. const adapter = await this.getAdapter();
  4196. return adapter.delete(this.modelName, where);
  4197. }
  4198. /**
  4199. * Delete by id.
  4200. *
  4201. * @param {number|string} id
  4202. * @returns {Promise<boolean>}
  4203. */
  4204. async deleteById(id) {
  4205. const adapter = await this.getAdapter();
  4206. return adapter.deleteById(this.modelName, id);
  4207. }
  4208. /**
  4209. * Exists.
  4210. *
  4211. * @param {number|string} id
  4212. * @returns {Promise<boolean>}
  4213. */
  4214. async exists(id) {
  4215. const adapter = await this.getAdapter();
  4216. return adapter.exists(this.modelName, id);
  4217. }
  4218. /**
  4219. * Count.
  4220. *
  4221. * @param {object|undefined} where
  4222. * @returns {Promise<number>}
  4223. */
  4224. async count(where = void 0) {
  4225. const adapter = await this.getAdapter();
  4226. return adapter.count(this.modelName, where);
  4227. }
  4228. };
  4229. __name(_Repository, "Repository");
  4230. Repository = _Repository;
  4231. }
  4232. });
  4233. // src/repository/repository-registry.js
  4234. var import_js_service26, _RepositoryRegistry, RepositoryRegistry;
  4235. var init_repository_registry = __esm({
  4236. "src/repository/repository-registry.js"() {
  4237. "use strict";
  4238. import_js_service26 = require("@e22m4u/js-service");
  4239. init_repository();
  4240. init_utils();
  4241. init_errors();
  4242. _RepositoryRegistry = class _RepositoryRegistry extends import_js_service26.Service {
  4243. /**
  4244. * Repositories.
  4245. *
  4246. * @type {object}
  4247. */
  4248. _repositories = {};
  4249. /**
  4250. * Repository ctor.
  4251. *
  4252. * @type {typeof Repository}
  4253. * @private
  4254. */
  4255. _repositoryCtor = Repository;
  4256. /**
  4257. * Set repository ctor.
  4258. *
  4259. * @param {typeof Repository} ctor
  4260. */
  4261. setRepositoryCtor(ctor) {
  4262. if (!ctor || typeof ctor !== "function" || !(ctor.prototype instanceof Repository)) {
  4263. throw new InvalidArgumentError(
  4264. "The first argument of RepositoryRegistry.setRepositoryCtor must inherit from Repository class, but %v was given.",
  4265. ctor
  4266. );
  4267. }
  4268. this._repositoryCtor = ctor;
  4269. }
  4270. /**
  4271. * Get repository.
  4272. *
  4273. * @param {string} modelName
  4274. * @returns {Repository}
  4275. */
  4276. getRepository(modelName) {
  4277. const modelKey = modelNameToModelKey(modelName);
  4278. let repository = this._repositories[modelKey];
  4279. if (repository) return repository;
  4280. repository = new this._repositoryCtor(this.container, modelName);
  4281. this._repositories[modelKey] = repository;
  4282. return repository;
  4283. }
  4284. };
  4285. __name(_RepositoryRegistry, "RepositoryRegistry");
  4286. RepositoryRegistry = _RepositoryRegistry;
  4287. }
  4288. });
  4289. // src/repository/index.js
  4290. var init_repository2 = __esm({
  4291. "src/repository/index.js"() {
  4292. "use strict";
  4293. init_repository();
  4294. init_repository_registry();
  4295. }
  4296. });
  4297. // src/relations/has-one-resolver.js
  4298. var import_js_service27, _HasOneResolver, HasOneResolver;
  4299. var init_has_one_resolver = __esm({
  4300. "src/relations/has-one-resolver.js"() {
  4301. "use strict";
  4302. import_js_service27 = require("@e22m4u/js-service");
  4303. init_utils();
  4304. init_errors();
  4305. init_repository2();
  4306. init_definition();
  4307. _HasOneResolver = class _HasOneResolver extends import_js_service27.Service {
  4308. /**
  4309. * Include to.
  4310. *
  4311. * @param {object[]} entities
  4312. * @param {string} sourceName
  4313. * @param {string} targetName
  4314. * @param {string} relationName
  4315. * @param {string} foreignKey
  4316. * @param {object|undefined} scope
  4317. * @returns {Promise<void>}
  4318. */
  4319. async includeTo(entities, sourceName, targetName, relationName, foreignKey, scope = void 0) {
  4320. if (!entities || !Array.isArray(entities))
  4321. throw new InvalidArgumentError(
  4322. 'The parameter "entities" of HasOneResolver.includeTo requires an Array of Object, but %v was given.',
  4323. entities
  4324. );
  4325. if (!sourceName || typeof sourceName !== "string")
  4326. throw new InvalidArgumentError(
  4327. 'The parameter "sourceName" of HasOneResolver.includeTo requires a non-empty String, but %v was given.',
  4328. sourceName
  4329. );
  4330. if (!targetName || typeof targetName !== "string")
  4331. throw new InvalidArgumentError(
  4332. 'The parameter "targetName" of HasOneResolver.includeTo requires a non-empty String, but %v was given.',
  4333. targetName
  4334. );
  4335. if (!relationName || typeof relationName !== "string")
  4336. throw new InvalidArgumentError(
  4337. 'The parameter "relationName" of HasOneResolver.includeTo requires a non-empty String, but %v was given.',
  4338. relationName
  4339. );
  4340. if (!foreignKey || typeof foreignKey !== "string")
  4341. throw new InvalidArgumentError(
  4342. 'The parameter "foreignKey" of HasOneResolver.includeTo requires a non-empty String, but %v was given.',
  4343. foreignKey
  4344. );
  4345. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4346. throw new InvalidArgumentError(
  4347. 'The provided parameter "scope" of HasOneResolver.includeTo should be an Object, but %v was given.',
  4348. scope
  4349. );
  4350. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4351. sourceName
  4352. );
  4353. const sourceIds = [];
  4354. entities.forEach((entity) => {
  4355. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4356. throw new InvalidArgumentError(
  4357. 'The parameter "entities" of HasOneResolver.includeTo requires an Array of Object, but %v was given.',
  4358. entity
  4359. );
  4360. const sourceId = entity[sourcePkPropName];
  4361. if (sourceIds.includes(sourceId)) return;
  4362. sourceIds.push(sourceId);
  4363. });
  4364. const promises = [];
  4365. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4366. scope = scope ? cloneDeep(scope) : {};
  4367. const targetBySourceId = /* @__PURE__ */ new Map();
  4368. sourceIds.forEach((sourceId) => {
  4369. const filter = cloneDeep(scope);
  4370. filter.where = {
  4371. and: [{ [foreignKey]: sourceId }, ...scope.where ? [scope.where] : []]
  4372. };
  4373. filter.limit = 1;
  4374. promises.push(
  4375. targetRepository.find(filter).then((result) => {
  4376. if (result.length) targetBySourceId.set(sourceId, result[0]);
  4377. })
  4378. );
  4379. });
  4380. await Promise.all(promises);
  4381. Array.from(targetBySourceId.keys()).forEach((sourceId) => {
  4382. const sources = entities.filter((v) => v[sourcePkPropName] === sourceId);
  4383. sources.forEach((v) => v[relationName] = targetBySourceId.get(sourceId));
  4384. });
  4385. }
  4386. /**
  4387. * Include polymorphic to.
  4388. *
  4389. * @param {object[]} entities
  4390. * @param {string} sourceName
  4391. * @param {string} targetName
  4392. * @param {string} relationName
  4393. * @param {string} foreignKey
  4394. * @param {string} discriminator
  4395. * @param {object|undefined} scope
  4396. * @returns {Promise<void>}
  4397. */
  4398. async includePolymorphicTo(entities, sourceName, targetName, relationName, foreignKey, discriminator, scope = void 0) {
  4399. if (!entities || !Array.isArray(entities))
  4400. throw new InvalidArgumentError(
  4401. 'The parameter "entities" of HasOneResolver.includePolymorphicTo requires an Array of Object, but %v was given.',
  4402. entities
  4403. );
  4404. if (!sourceName || typeof sourceName !== "string")
  4405. throw new InvalidArgumentError(
  4406. 'The parameter "sourceName" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4407. sourceName
  4408. );
  4409. if (!targetName || typeof targetName !== "string")
  4410. throw new InvalidArgumentError(
  4411. 'The parameter "targetName" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4412. targetName
  4413. );
  4414. if (!relationName || typeof relationName !== "string")
  4415. throw new InvalidArgumentError(
  4416. 'The parameter "relationName" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4417. relationName
  4418. );
  4419. if (!foreignKey || typeof foreignKey !== "string")
  4420. throw new InvalidArgumentError(
  4421. 'The parameter "foreignKey" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4422. foreignKey
  4423. );
  4424. if (!discriminator || typeof discriminator !== "string")
  4425. throw new InvalidArgumentError(
  4426. 'The parameter "discriminator" of HasOneResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4427. discriminator
  4428. );
  4429. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4430. throw new InvalidArgumentError(
  4431. 'The provided parameter "scope" of HasOneResolver.includePolymorphicTo should be an Object, but %v was given.',
  4432. scope
  4433. );
  4434. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4435. sourceName
  4436. );
  4437. const sourceIds = [];
  4438. entities.forEach((entity) => {
  4439. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4440. throw new InvalidArgumentError(
  4441. 'The parameter "entities" of HasOneResolver.includePolymorphicTo requires an Array of Object, but %v was given.',
  4442. entity
  4443. );
  4444. const sourceId = entity[sourcePkPropName];
  4445. if (sourceIds.includes(sourceId)) return;
  4446. sourceIds.push(sourceId);
  4447. });
  4448. const promises = [];
  4449. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4450. scope = scope ? cloneDeep(scope) : {};
  4451. const targetBySourceId = /* @__PURE__ */ new Map();
  4452. sourceIds.forEach((sourceId) => {
  4453. const filter = cloneDeep(scope);
  4454. filter.where = {
  4455. and: [
  4456. { [foreignKey]: sourceId, [discriminator]: sourceName },
  4457. ...scope.where ? [scope.where] : []
  4458. ]
  4459. };
  4460. filter.limit = 1;
  4461. promises.push(
  4462. targetRepository.find(filter).then((result) => {
  4463. if (result.length) targetBySourceId.set(sourceId, result[0]);
  4464. })
  4465. );
  4466. });
  4467. await Promise.all(promises);
  4468. Array.from(targetBySourceId.keys()).forEach((sourceId) => {
  4469. const sources = entities.filter((v) => v[sourcePkPropName] === sourceId);
  4470. sources.forEach((v) => v[relationName] = targetBySourceId.get(sourceId));
  4471. });
  4472. }
  4473. /**
  4474. * Include polymorphic by relation name.
  4475. *
  4476. * @param {object[]} entities
  4477. * @param {string} sourceName
  4478. * @param {string} targetName
  4479. * @param {string} relationName
  4480. * @param {string} targetRelationName
  4481. * @param {object|undefined} scope
  4482. * @returns {Promise<void>}
  4483. */
  4484. async includePolymorphicByRelationName(entities, sourceName, targetName, relationName, targetRelationName, scope = void 0) {
  4485. if (!entities || !Array.isArray(entities))
  4486. throw new InvalidArgumentError(
  4487. 'The parameter "entities" of HasOneResolver.includePolymorphicByRelationName requires an Array of Object, but %v was given.',
  4488. entities
  4489. );
  4490. if (!sourceName || typeof sourceName !== "string")
  4491. throw new InvalidArgumentError(
  4492. 'The parameter "sourceName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4493. sourceName
  4494. );
  4495. if (!targetName || typeof targetName !== "string")
  4496. throw new InvalidArgumentError(
  4497. 'The parameter "targetName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4498. targetName
  4499. );
  4500. if (!relationName || typeof relationName !== "string")
  4501. throw new InvalidArgumentError(
  4502. 'The parameter "relationName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4503. relationName
  4504. );
  4505. if (!targetRelationName || typeof targetRelationName !== "string")
  4506. throw new InvalidArgumentError(
  4507. 'The parameter "targetRelationName" of HasOneResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4508. targetRelationName
  4509. );
  4510. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4511. throw new InvalidArgumentError(
  4512. 'The provided parameter "scope" of HasOneResolver.includePolymorphicByRelationName should be an Object, but %v was given.',
  4513. scope
  4514. );
  4515. const targetRelationDef = this.getService(
  4516. ModelDefinitionUtils
  4517. ).getRelationDefinitionByName(targetName, targetRelationName);
  4518. if (targetRelationDef.type !== RelationType.BELONGS_TO)
  4519. throw new InvalidArgumentError(
  4520. 'The relation %v of the model %v is a polymorphic "hasOne" relation, so it requires the target relation %v to be a polymorphic "belongsTo", but %v type was given.',
  4521. relationName,
  4522. sourceName,
  4523. targetRelationName,
  4524. targetRelationDef.type
  4525. );
  4526. if (!targetRelationDef.polymorphic)
  4527. throw new InvalidArgumentError(
  4528. 'The relation %v of the model %v is a polymorphic "hasOne" relation, so it requires the target relation %v to be a polymorphic too.',
  4529. relationName,
  4530. sourceName,
  4531. targetRelationName
  4532. );
  4533. const foreignKey = targetRelationDef.foreignKey || `${targetRelationName}Id`;
  4534. const discriminator = targetRelationDef.discriminator || `${targetRelationName}Type`;
  4535. return this.includePolymorphicTo(
  4536. entities,
  4537. sourceName,
  4538. targetName,
  4539. relationName,
  4540. foreignKey,
  4541. discriminator,
  4542. scope
  4543. );
  4544. }
  4545. };
  4546. __name(_HasOneResolver, "HasOneResolver");
  4547. HasOneResolver = _HasOneResolver;
  4548. }
  4549. });
  4550. // src/relations/has-many-resolver.js
  4551. var import_js_service28, _HasManyResolver, HasManyResolver;
  4552. var init_has_many_resolver = __esm({
  4553. "src/relations/has-many-resolver.js"() {
  4554. "use strict";
  4555. import_js_service28 = require("@e22m4u/js-service");
  4556. init_utils();
  4557. init_errors();
  4558. init_repository2();
  4559. init_definition();
  4560. _HasManyResolver = class _HasManyResolver extends import_js_service28.Service {
  4561. /**
  4562. * Include to.
  4563. *
  4564. * @param {object[]} entities
  4565. * @param {string} sourceName
  4566. * @param {string} targetName
  4567. * @param {string} relationName
  4568. * @param {string} foreignKey
  4569. * @param {object|undefined} scope
  4570. * @returns {Promise<void>}
  4571. */
  4572. async includeTo(entities, sourceName, targetName, relationName, foreignKey, scope = void 0) {
  4573. if (!entities || !Array.isArray(entities))
  4574. throw new InvalidArgumentError(
  4575. 'The parameter "entities" of HasManyResolver.includeTo requires an Array of Object, but %v was given.',
  4576. entities
  4577. );
  4578. if (!sourceName || typeof sourceName !== "string")
  4579. throw new InvalidArgumentError(
  4580. 'The parameter "sourceName" of HasManyResolver.includeTo requires a non-empty String, but %v was given.',
  4581. sourceName
  4582. );
  4583. if (!targetName || typeof targetName !== "string")
  4584. throw new InvalidArgumentError(
  4585. 'The parameter "targetName" of HasManyResolver.includeTo requires a non-empty String, but %v was given.',
  4586. targetName
  4587. );
  4588. if (!relationName || typeof relationName !== "string")
  4589. throw new InvalidArgumentError(
  4590. 'The parameter "relationName" of HasManyResolver.includeTo requires a non-empty String, but %v was given.',
  4591. relationName
  4592. );
  4593. if (!foreignKey || typeof foreignKey !== "string")
  4594. throw new InvalidArgumentError(
  4595. 'The parameter "foreignKey" of HasManyResolver.includeTo requires a non-empty String, but %v was given.',
  4596. foreignKey
  4597. );
  4598. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4599. throw new InvalidArgumentError(
  4600. 'The provided parameter "scope" of HasManyResolver.includeTo should be an Object, but %v was given.',
  4601. scope
  4602. );
  4603. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4604. sourceName
  4605. );
  4606. const sourceIds = [];
  4607. entities.forEach((entity) => {
  4608. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4609. throw new InvalidArgumentError(
  4610. 'The parameter "entities" of HasManyResolver.includeTo requires an Array of Object, but %v was given.',
  4611. entity
  4612. );
  4613. const sourceId = entity[sourcePkPropName];
  4614. if (sourceIds.includes(sourceId)) return;
  4615. sourceIds.push(sourceId);
  4616. });
  4617. const promises = [];
  4618. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4619. scope = scope ? cloneDeep(scope) : {};
  4620. const targetsBySourceId = /* @__PURE__ */ new Map();
  4621. sourceIds.forEach((sourceId) => {
  4622. const filter = cloneDeep(scope);
  4623. filter.where = {
  4624. and: [{ [foreignKey]: sourceId }, ...scope.where ? [scope.where] : []]
  4625. };
  4626. promises.push(
  4627. targetRepository.find(filter).then((result) => {
  4628. var _a;
  4629. if (result.length) {
  4630. let targets = (_a = targetsBySourceId.get(sourceId)) != null ? _a : [];
  4631. targets = [...targets, ...result];
  4632. targetsBySourceId.set(sourceId, targets);
  4633. }
  4634. })
  4635. );
  4636. });
  4637. await Promise.all(promises);
  4638. entities.forEach((entity) => {
  4639. var _a;
  4640. const sourceId = entity[sourcePkPropName];
  4641. entity[relationName] = (_a = targetsBySourceId.get(sourceId)) != null ? _a : [];
  4642. });
  4643. }
  4644. /**
  4645. * Include polymorphic to.
  4646. *
  4647. * @param {object[]} entities
  4648. * @param {string} sourceName
  4649. * @param {string} targetName
  4650. * @param {string} relationName
  4651. * @param {string} foreignKey
  4652. * @param {string} discriminator
  4653. * @param {object|undefined} scope
  4654. * @returns {Promise<void>}
  4655. */
  4656. async includePolymorphicTo(entities, sourceName, targetName, relationName, foreignKey, discriminator, scope = void 0) {
  4657. if (!entities || !Array.isArray(entities))
  4658. throw new InvalidArgumentError(
  4659. 'The parameter "entities" of HasManyResolver.includePolymorphicTo requires an Array of Object, but %v was given.',
  4660. entities
  4661. );
  4662. if (!sourceName || typeof sourceName !== "string")
  4663. throw new InvalidArgumentError(
  4664. 'The parameter "sourceName" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4665. sourceName
  4666. );
  4667. if (!targetName || typeof targetName !== "string")
  4668. throw new InvalidArgumentError(
  4669. 'The parameter "targetName" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4670. targetName
  4671. );
  4672. if (!relationName || typeof relationName !== "string")
  4673. throw new InvalidArgumentError(
  4674. 'The parameter "relationName" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4675. relationName
  4676. );
  4677. if (!foreignKey || typeof foreignKey !== "string")
  4678. throw new InvalidArgumentError(
  4679. 'The parameter "foreignKey" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4680. foreignKey
  4681. );
  4682. if (!discriminator || typeof discriminator !== "string")
  4683. throw new InvalidArgumentError(
  4684. 'The parameter "discriminator" of HasManyResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4685. discriminator
  4686. );
  4687. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4688. throw new InvalidArgumentError(
  4689. 'The provided parameter "scope" of HasManyResolver.includePolymorphicTo should be an Object, but %v was given.',
  4690. scope
  4691. );
  4692. const sourcePkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4693. sourceName
  4694. );
  4695. const sourceIds = [];
  4696. entities.forEach((entity) => {
  4697. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4698. throw new InvalidArgumentError(
  4699. 'The parameter "entities" of HasManyResolver.includePolymorphicTo requires an Array of Object, but %v was given.',
  4700. entity
  4701. );
  4702. const sourceId = entity[sourcePkPropName];
  4703. if (sourceIds.includes(sourceId)) return;
  4704. sourceIds.push(sourceId);
  4705. });
  4706. const promises = [];
  4707. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4708. scope = scope ? cloneDeep(scope) : {};
  4709. const targetsBySourceId = /* @__PURE__ */ new Map();
  4710. sourceIds.forEach((sourceId) => {
  4711. const filter = cloneDeep(scope);
  4712. filter.where = {
  4713. and: [
  4714. { [foreignKey]: sourceId, [discriminator]: sourceName },
  4715. ...scope.where ? [scope.where] : []
  4716. ]
  4717. };
  4718. promises.push(
  4719. targetRepository.find(filter).then((result) => {
  4720. var _a;
  4721. if (result.length) {
  4722. let targets = (_a = targetsBySourceId.get(sourceId)) != null ? _a : [];
  4723. targets = [...targets, ...result];
  4724. targetsBySourceId.set(sourceId, targets);
  4725. }
  4726. })
  4727. );
  4728. });
  4729. await Promise.all(promises);
  4730. entities.forEach((entity) => {
  4731. var _a;
  4732. const sourceId = entity[sourcePkPropName];
  4733. entity[relationName] = (_a = targetsBySourceId.get(sourceId)) != null ? _a : [];
  4734. });
  4735. }
  4736. /**
  4737. * Include polymorphic by relation name.
  4738. *
  4739. * @param {object[]} entities
  4740. * @param {string} sourceName
  4741. * @param {string} targetName
  4742. * @param {string} relationName
  4743. * @param {string} targetRelationName
  4744. * @param {object|undefined} scope
  4745. * @returns {Promise<void>}
  4746. */
  4747. async includePolymorphicByRelationName(entities, sourceName, targetName, relationName, targetRelationName, scope = void 0) {
  4748. if (!entities || !Array.isArray(entities))
  4749. throw new InvalidArgumentError(
  4750. 'The parameter "entities" of HasManyResolver.includePolymorphicByRelationName requires an Array of Object, but %v was given.',
  4751. entities
  4752. );
  4753. if (!sourceName || typeof sourceName !== "string")
  4754. throw new InvalidArgumentError(
  4755. 'The parameter "sourceName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4756. sourceName
  4757. );
  4758. if (!targetName || typeof targetName !== "string")
  4759. throw new InvalidArgumentError(
  4760. 'The parameter "targetName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4761. targetName
  4762. );
  4763. if (!relationName || typeof relationName !== "string")
  4764. throw new InvalidArgumentError(
  4765. 'The parameter "relationName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4766. relationName
  4767. );
  4768. if (!targetRelationName || typeof targetRelationName !== "string")
  4769. throw new InvalidArgumentError(
  4770. 'The parameter "targetRelationName" of HasManyResolver.includePolymorphicByRelationName requires a non-empty String, but %v was given.',
  4771. targetRelationName
  4772. );
  4773. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4774. throw new InvalidArgumentError(
  4775. 'The provided parameter "scope" of HasManyResolver.includePolymorphicByRelationName should be an Object, but %v was given.',
  4776. scope
  4777. );
  4778. const targetRelationDef = this.getService(
  4779. ModelDefinitionUtils
  4780. ).getRelationDefinitionByName(targetName, targetRelationName);
  4781. if (targetRelationDef.type !== RelationType.BELONGS_TO)
  4782. throw new InvalidArgumentError(
  4783. 'The relation %v of the model %v is a polymorphic "hasMany" relation, so it requires the target relation %v to be a polymorphic "belongsTo", but %v type was given.',
  4784. relationName,
  4785. sourceName,
  4786. targetRelationName,
  4787. targetRelationDef.type
  4788. );
  4789. if (!targetRelationDef.polymorphic)
  4790. throw new InvalidArgumentError(
  4791. 'The relation %v of the model %v is a polymorphic "hasMany" relation, so it requires the target relation %v to be a polymorphic too.',
  4792. relationName,
  4793. sourceName,
  4794. targetRelationName
  4795. );
  4796. const foreignKey = targetRelationDef.foreignKey || `${targetRelationName}Id`;
  4797. const discriminator = targetRelationDef.discriminator || `${targetRelationName}Type`;
  4798. return this.includePolymorphicTo(
  4799. entities,
  4800. sourceName,
  4801. targetName,
  4802. relationName,
  4803. foreignKey,
  4804. discriminator,
  4805. scope
  4806. );
  4807. }
  4808. };
  4809. __name(_HasManyResolver, "HasManyResolver");
  4810. HasManyResolver = _HasManyResolver;
  4811. }
  4812. });
  4813. // src/relations/belongs-to-resolver.js
  4814. var import_js_service29, _BelongsToResolver, BelongsToResolver;
  4815. var init_belongs_to_resolver = __esm({
  4816. "src/relations/belongs-to-resolver.js"() {
  4817. "use strict";
  4818. import_js_service29 = require("@e22m4u/js-service");
  4819. init_errors();
  4820. init_utils();
  4821. init_repository2();
  4822. init_definition();
  4823. _BelongsToResolver = class _BelongsToResolver extends import_js_service29.Service {
  4824. /**
  4825. * Include to.
  4826. *
  4827. * @param {object[]} entities
  4828. * @param {string} sourceName
  4829. * @param {string} targetName
  4830. * @param {string} relationName
  4831. * @param {string|undefined} foreignKey
  4832. * @param {object|undefined} scope
  4833. * @returns {Promise<void>}
  4834. */
  4835. async includeTo(entities, sourceName, targetName, relationName, foreignKey = void 0, scope = void 0) {
  4836. if (!entities || !Array.isArray(entities))
  4837. throw new InvalidArgumentError(
  4838. 'The parameter "entities" of BelongsToResolver.includeTo requires an Array of Object, but %v was given.',
  4839. entities
  4840. );
  4841. if (!sourceName || typeof sourceName !== "string")
  4842. throw new InvalidArgumentError(
  4843. 'The parameter "sourceName" of BelongsToResolver.includeTo requires a non-empty String, but %v was given.',
  4844. sourceName
  4845. );
  4846. if (!targetName || typeof targetName !== "string")
  4847. throw new InvalidArgumentError(
  4848. 'The parameter "targetName" of BelongsToResolver.includeTo requires a non-empty String, but %v was given.',
  4849. targetName
  4850. );
  4851. if (!relationName || typeof relationName !== "string")
  4852. throw new InvalidArgumentError(
  4853. 'The parameter "relationName" of BelongsToResolver.includeTo requires a non-empty String, but %v was given.',
  4854. relationName
  4855. );
  4856. if (foreignKey && typeof foreignKey !== "string")
  4857. throw new InvalidArgumentError(
  4858. 'The provided parameter "foreignKey" of BelongsToResolver.includeTo should be a String, but %v was given.',
  4859. foreignKey
  4860. );
  4861. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4862. throw new InvalidArgumentError(
  4863. 'The provided parameter "scope" of BelongsToResolver.includeTo should be an Object, but %v was given.',
  4864. scope
  4865. );
  4866. if (foreignKey == null) foreignKey = `${relationName}Id`;
  4867. const targetIds = entities.reduce((acc, entity) => {
  4868. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4869. throw new InvalidArgumentError(
  4870. 'The parameter "entities" of BelongsToResolver.includeTo requires an Array of Object, but %v was given.',
  4871. entity
  4872. );
  4873. const targetId = entity[foreignKey];
  4874. return targetId != null ? [...acc, targetId] : acc;
  4875. }, []);
  4876. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4877. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4878. targetName
  4879. );
  4880. scope = scope ? cloneDeep(scope) : {};
  4881. const filter = cloneDeep(scope);
  4882. filter.where = {
  4883. and: [
  4884. { [targetPkPropName]: { inq: targetIds } },
  4885. ...scope.where ? [scope.where] : []
  4886. ]
  4887. };
  4888. const targets = await targetRepository.find(filter);
  4889. entities.forEach((entity) => {
  4890. const target = targets.find(
  4891. (e) => e[targetPkPropName] === entity[foreignKey]
  4892. );
  4893. if (target) entity[relationName] = target;
  4894. });
  4895. }
  4896. /**
  4897. * Include polymorphic to.
  4898. *
  4899. * @param {object[]} entities
  4900. * @param {string} sourceName
  4901. * @param {string} relationName
  4902. * @param {string|undefined} foreignKey
  4903. * @param {string|undefined} discriminator
  4904. * @param {object|undefined} scope
  4905. * @returns {Promise<void>}
  4906. */
  4907. async includePolymorphicTo(entities, sourceName, relationName, foreignKey = void 0, discriminator = void 0, scope = void 0) {
  4908. if (!entities || !Array.isArray(entities))
  4909. throw new InvalidArgumentError(
  4910. 'The parameter "entities" of BelongsToResolver.includePolymorphicTo requires an Array of Object, but %v was given.',
  4911. entities
  4912. );
  4913. if (!sourceName || typeof sourceName !== "string")
  4914. throw new InvalidArgumentError(
  4915. 'The parameter "sourceName" of BelongsToResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4916. sourceName
  4917. );
  4918. if (!relationName || typeof relationName !== "string")
  4919. throw new InvalidArgumentError(
  4920. 'The parameter "relationName" of BelongsToResolver.includePolymorphicTo requires a non-empty String, but %v was given.',
  4921. relationName
  4922. );
  4923. if (foreignKey && typeof foreignKey !== "string")
  4924. throw new InvalidArgumentError(
  4925. 'The provided parameter "foreignKey" of BelongsToResolver.includePolymorphicTo should be a String, but %v was given.',
  4926. foreignKey
  4927. );
  4928. if (discriminator && typeof discriminator !== "string")
  4929. throw new InvalidArgumentError(
  4930. 'The provided parameter "discriminator" of BelongsToResolver.includePolymorphicTo should be a String, but %v was given.',
  4931. discriminator
  4932. );
  4933. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  4934. throw new InvalidArgumentError(
  4935. 'The provided parameter "scope" of BelongsToResolver.includePolymorphicTo should be an Object, but %v was given.',
  4936. scope
  4937. );
  4938. if (foreignKey == null) {
  4939. const singularRelationName = singularize(relationName);
  4940. foreignKey = `${singularRelationName}Id`;
  4941. }
  4942. if (discriminator == null) {
  4943. const singularRelationName = singularize(relationName);
  4944. discriminator = `${singularRelationName}Type`;
  4945. }
  4946. const targetIdsByTargetName = {};
  4947. entities.forEach((entity) => {
  4948. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  4949. throw new InvalidArgumentError(
  4950. 'The parameter "entities" of BelongsToResolver.includePolymorphicTo requires an Array of Object, but %v was given.',
  4951. entity
  4952. );
  4953. const targetId = entity[foreignKey];
  4954. const targetName = entity[discriminator];
  4955. if (targetId == null || targetName == null) return;
  4956. if (targetIdsByTargetName[targetName] == null)
  4957. targetIdsByTargetName[targetName] = [];
  4958. if (!targetIdsByTargetName[targetName].includes(targetId))
  4959. targetIdsByTargetName[targetName].push(targetId);
  4960. });
  4961. const promises = [];
  4962. const targetNames = Object.keys(targetIdsByTargetName);
  4963. scope = scope ? cloneDeep(scope) : {};
  4964. const targetEntitiesByTargetNames = {};
  4965. targetNames.forEach((targetName) => {
  4966. let targetRepository;
  4967. try {
  4968. targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  4969. } catch (error) {
  4970. if (error instanceof InvalidArgumentError) {
  4971. if (error.message === `The model "${targetName}" is not defined.` || error.message === `The model "${targetName}" does not have a specified datasource.`) {
  4972. return;
  4973. }
  4974. } else {
  4975. throw error;
  4976. }
  4977. }
  4978. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  4979. targetName
  4980. );
  4981. const targetFilter = cloneDeep(scope);
  4982. const targetIds = targetIdsByTargetName[targetName];
  4983. targetFilter.where = {
  4984. and: [
  4985. { [targetPkPropName]: { inq: targetIds } },
  4986. ...scope.where ? [scope.where] : []
  4987. ]
  4988. };
  4989. const promise = targetRepository.find(targetFilter).then((result) => {
  4990. var _a;
  4991. targetEntitiesByTargetNames[targetName] = [
  4992. ...(_a = targetEntitiesByTargetNames[targetName]) != null ? _a : [],
  4993. ...result
  4994. ];
  4995. });
  4996. promises.push(promise);
  4997. });
  4998. await Promise.all(promises);
  4999. entities.forEach((entity) => {
  5000. var _a;
  5001. const targetId = entity[foreignKey];
  5002. const targetName = entity[discriminator];
  5003. if (targetId == null || targetName == null || targetEntitiesByTargetNames[targetName] == null) {
  5004. return;
  5005. }
  5006. const targetEntities = (_a = targetEntitiesByTargetNames[targetName]) != null ? _a : [];
  5007. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  5008. targetName
  5009. );
  5010. const target = targetEntities.find((e) => e[targetPkPropName] === targetId);
  5011. if (target) entity[relationName] = target;
  5012. });
  5013. }
  5014. };
  5015. __name(_BelongsToResolver, "BelongsToResolver");
  5016. BelongsToResolver = _BelongsToResolver;
  5017. }
  5018. });
  5019. // src/relations/references-many-resolver.js
  5020. var import_js_service30, _ReferencesManyResolver, ReferencesManyResolver;
  5021. var init_references_many_resolver = __esm({
  5022. "src/relations/references-many-resolver.js"() {
  5023. "use strict";
  5024. import_js_service30 = require("@e22m4u/js-service");
  5025. init_errors();
  5026. init_utils();
  5027. init_repository2();
  5028. init_definition();
  5029. _ReferencesManyResolver = class _ReferencesManyResolver extends import_js_service30.Service {
  5030. /**
  5031. * Include to.
  5032. *
  5033. * @param {object[]} entities
  5034. * @param {string} sourceName
  5035. * @param {string} targetName
  5036. * @param {string} relationName
  5037. * @param {string|undefined} foreignKey
  5038. * @param {object|undefined} scope
  5039. * @returns {Promise<void>}
  5040. */
  5041. async includeTo(entities, sourceName, targetName, relationName, foreignKey = void 0, scope = void 0) {
  5042. if (!entities || !Array.isArray(entities))
  5043. throw new InvalidArgumentError(
  5044. 'The parameter "entities" of ReferencesManyResolver.includeTo requires an Array of Object, but %v was given.',
  5045. entities
  5046. );
  5047. if (!sourceName || typeof sourceName !== "string")
  5048. throw new InvalidArgumentError(
  5049. 'The parameter "sourceName" of ReferencesManyResolver.includeTo requires a non-empty String, but %v was given.',
  5050. sourceName
  5051. );
  5052. if (!targetName || typeof targetName !== "string")
  5053. throw new InvalidArgumentError(
  5054. 'The parameter "targetName" of ReferencesManyResolver.includeTo requires a non-empty String, but %v was given.',
  5055. targetName
  5056. );
  5057. if (!relationName || typeof relationName !== "string")
  5058. throw new InvalidArgumentError(
  5059. 'The parameter "relationName" of ReferencesManyResolver.includeTo requires a non-empty String, but %v was given.',
  5060. relationName
  5061. );
  5062. if (foreignKey && typeof foreignKey !== "string")
  5063. throw new InvalidArgumentError(
  5064. 'The provided parameter "foreignKey" of ReferencesManyResolver.includeTo should be a String, but %v was given.',
  5065. foreignKey
  5066. );
  5067. if (scope && (typeof scope !== "object" || Array.isArray(scope)))
  5068. throw new InvalidArgumentError(
  5069. 'The provided parameter "scope" of ReferencesManyResolver.includeTo should be an Object, but %v was given.',
  5070. scope
  5071. );
  5072. if (foreignKey == null) {
  5073. const singularRelationName = singularize(relationName);
  5074. foreignKey = `${singularRelationName}Ids`;
  5075. }
  5076. const targetIds = entities.reduce((acc, entity) => {
  5077. if (!entity || typeof entity !== "object" || Array.isArray(entity))
  5078. throw new InvalidArgumentError(
  5079. 'The parameter "entities" of ReferencesManyResolver.includeTo requires an Array of Object, but %v was given.',
  5080. entity
  5081. );
  5082. const ids = entity[foreignKey];
  5083. if (Array.isArray(ids))
  5084. ids.forEach((id) => {
  5085. if (id == null || acc.includes(id)) return;
  5086. acc.push(id);
  5087. });
  5088. return acc;
  5089. }, []);
  5090. const targetRepository = this.getService(RepositoryRegistry).getRepository(targetName);
  5091. const targetPkPropName = this.getService(ModelDefinitionUtils).getPrimaryKeyAsPropertyName(
  5092. targetName
  5093. );
  5094. scope = scope ? cloneDeep(scope) : {};
  5095. const filter = cloneDeep(scope);
  5096. filter.where = {
  5097. and: [
  5098. { [targetPkPropName]: { inq: targetIds } },
  5099. ...scope.where ? [scope.where] : []
  5100. ]
  5101. };
  5102. const targets = await targetRepository.find(filter);
  5103. entities.forEach((entity) => {
  5104. const ids = entity[foreignKey];
  5105. entity[relationName] = [];
  5106. if (Array.isArray(ids))
  5107. targets.forEach((target) => {
  5108. const targetId = target[targetPkPropName];
  5109. if (ids.includes(targetId)) entity[relationName].push(target);
  5110. });
  5111. });
  5112. }
  5113. };
  5114. __name(_ReferencesManyResolver, "ReferencesManyResolver");
  5115. ReferencesManyResolver = _ReferencesManyResolver;
  5116. }
  5117. });
  5118. // src/relations/index.js
  5119. var init_relations2 = __esm({
  5120. "src/relations/index.js"() {
  5121. "use strict";
  5122. init_has_one_resolver();
  5123. init_has_many_resolver();
  5124. init_belongs_to_resolver();
  5125. init_references_many_resolver();
  5126. }
  5127. });
  5128. // src/filter/include-clause-tool.js
  5129. var import_js_service31, _IncludeClauseTool, IncludeClauseTool;
  5130. var init_include_clause_tool = __esm({
  5131. "src/filter/include-clause-tool.js"() {
  5132. "use strict";
  5133. import_js_service31 = require("@e22m4u/js-service");
  5134. init_where_clause_tool();
  5135. init_order_clause_tool();
  5136. init_slice_clause_tool();
  5137. init_errors();
  5138. init_fields_clause_tool();
  5139. init_definition();
  5140. init_relations2();
  5141. _IncludeClauseTool = class _IncludeClauseTool extends import_js_service31.Service {
  5142. /**
  5143. * Include to.
  5144. *
  5145. * @param {object[]} entities
  5146. * @param {string} modelName
  5147. * @param {IncludeClause|undefined} clause
  5148. * @returns {Promise<void>}
  5149. */
  5150. async includeTo(entities, modelName, clause) {
  5151. clause = _IncludeClauseTool.normalizeIncludeClause(clause);
  5152. const promises = [];
  5153. clause.forEach((inclusion) => {
  5154. const relDef = this.getService(
  5155. ModelDefinitionUtils
  5156. ).getRelationDefinitionByName(modelName, inclusion.relation);
  5157. switch (relDef.type) {
  5158. // BELONGS_TO
  5159. case RelationType.BELONGS_TO:
  5160. if (relDef.polymorphic) {
  5161. promises.push(
  5162. this.getService(BelongsToResolver).includePolymorphicTo(
  5163. entities,
  5164. modelName,
  5165. inclusion.relation,
  5166. relDef.foreignKey,
  5167. relDef.discriminator,
  5168. inclusion.scope
  5169. )
  5170. );
  5171. } else {
  5172. promises.push(
  5173. this.getService(BelongsToResolver).includeTo(
  5174. entities,
  5175. modelName,
  5176. relDef.model,
  5177. inclusion.relation,
  5178. relDef.foreignKey,
  5179. inclusion.scope
  5180. )
  5181. );
  5182. }
  5183. break;
  5184. // HAS_ONE
  5185. case RelationType.HAS_ONE:
  5186. if (relDef.polymorphic && typeof relDef.polymorphic === "string") {
  5187. promises.push(
  5188. this.getService(HasOneResolver).includePolymorphicByRelationName(
  5189. entities,
  5190. modelName,
  5191. relDef.model,
  5192. inclusion.relation,
  5193. relDef.polymorphic,
  5194. inclusion.scope
  5195. )
  5196. );
  5197. } else if (relDef.polymorphic) {
  5198. promises.push(
  5199. this.getService(HasOneResolver).includePolymorphicTo(
  5200. entities,
  5201. modelName,
  5202. relDef.model,
  5203. inclusion.relation,
  5204. relDef.foreignKey,
  5205. relDef.discriminator,
  5206. inclusion.scope
  5207. )
  5208. );
  5209. } else {
  5210. promises.push(
  5211. this.getService(HasOneResolver).includeTo(
  5212. entities,
  5213. modelName,
  5214. relDef.model,
  5215. inclusion.relation,
  5216. relDef.foreignKey,
  5217. inclusion.scope
  5218. )
  5219. );
  5220. }
  5221. break;
  5222. // HAS_MANY
  5223. case RelationType.HAS_MANY:
  5224. if (relDef.polymorphic && typeof relDef.polymorphic === "string") {
  5225. promises.push(
  5226. this.getService(HasManyResolver).includePolymorphicByRelationName(
  5227. entities,
  5228. modelName,
  5229. relDef.model,
  5230. inclusion.relation,
  5231. relDef.polymorphic,
  5232. inclusion.scope
  5233. )
  5234. );
  5235. } else if (relDef.polymorphic) {
  5236. promises.push(
  5237. this.getService(HasManyResolver).includePolymorphicTo(
  5238. entities,
  5239. modelName,
  5240. relDef.model,
  5241. inclusion.relation,
  5242. relDef.foreignKey,
  5243. relDef.discriminator,
  5244. inclusion.scope
  5245. )
  5246. );
  5247. } else {
  5248. promises.push(
  5249. this.getService(HasManyResolver).includeTo(
  5250. entities,
  5251. modelName,
  5252. relDef.model,
  5253. inclusion.relation,
  5254. relDef.foreignKey,
  5255. inclusion.scope
  5256. )
  5257. );
  5258. }
  5259. break;
  5260. case RelationType.REFERENCES_MANY:
  5261. promises.push(
  5262. this.getService(ReferencesManyResolver).includeTo(
  5263. entities,
  5264. modelName,
  5265. relDef.model,
  5266. inclusion.relation,
  5267. relDef.foreignKey,
  5268. inclusion.scope
  5269. )
  5270. );
  5271. break;
  5272. default:
  5273. throw new InvalidArgumentError(
  5274. "The relation type %v does not have an inclusion resolver.",
  5275. relDef.type
  5276. );
  5277. }
  5278. });
  5279. await Promise.all(promises);
  5280. }
  5281. /**
  5282. * Validate include clause.
  5283. *
  5284. * @param {IncludeClause|undefined} clause
  5285. */
  5286. static validateIncludeClause(clause) {
  5287. if (clause == null) {
  5288. } else if (clause && typeof clause === "string") {
  5289. } else if (Array.isArray(clause)) {
  5290. const relNames = [];
  5291. clause.flat(Infinity).forEach((el) => {
  5292. this.validateIncludeClause(el);
  5293. if (typeof el === "string") {
  5294. relNames.push(el);
  5295. } else if (typeof el === "object") {
  5296. Object.keys(el).forEach((key) => {
  5297. if (Object.prototype.hasOwnProperty.call(el, key))
  5298. relNames.push(key);
  5299. });
  5300. }
  5301. });
  5302. const duplicateNames = relNames.filter(
  5303. (name, i) => relNames.indexOf(name) !== i
  5304. );
  5305. if (duplicateNames.length)
  5306. throw new InvalidArgumentError(
  5307. 'The provided option "include" has duplicates of %v.',
  5308. duplicateNames[0]
  5309. );
  5310. } else if (typeof clause === "object") {
  5311. if ("relation" in clause) {
  5312. if (!clause.relation || typeof clause.relation !== "string")
  5313. throw new InvalidArgumentError(
  5314. 'The provided option "relation" should be a non-empty String, but %v was given.',
  5315. clause.relation
  5316. );
  5317. if ("scope" in clause && clause) this.validateScopeClause(clause.scope);
  5318. } else {
  5319. Object.keys(clause).forEach((key) => {
  5320. if (!Object.prototype.hasOwnProperty.call(clause, key)) return;
  5321. this.validateIncludeClause(key);
  5322. this.validateIncludeClause(clause[key]);
  5323. });
  5324. }
  5325. } else {
  5326. throw new InvalidArgumentError(
  5327. 'The provided option "include" should have a non-empty String, an Object or an Array, but %v was given.',
  5328. clause
  5329. );
  5330. }
  5331. }
  5332. /**
  5333. * Validate scope clause.
  5334. *
  5335. * @param {object|undefined} clause
  5336. */
  5337. static validateScopeClause(clause) {
  5338. if (clause == null) return;
  5339. if (typeof clause !== "object" || Array.isArray(clause))
  5340. throw new InvalidArgumentError(
  5341. 'The provided option "scope" should be an Object, but %v was given.',
  5342. clause
  5343. );
  5344. if (clause.where != null) {
  5345. WhereClauseTool.validateWhereClause(clause.where);
  5346. }
  5347. if (clause.order != null) {
  5348. OrderClauseTool.validateOrderClause(clause.order);
  5349. }
  5350. if (clause.skip != null) {
  5351. SliceClauseTool.validateSkipClause(clause.skip);
  5352. }
  5353. if (clause.limit != null) {
  5354. SliceClauseTool.validateLimitClause(clause.limit);
  5355. }
  5356. if (clause.fields != null) {
  5357. FieldsClauseTool.validateFieldsClause(clause.fields);
  5358. }
  5359. if (clause.include != null) {
  5360. _IncludeClauseTool.validateIncludeClause(clause.include);
  5361. }
  5362. }
  5363. /**
  5364. * Normalize include clause.
  5365. *
  5366. * @param {IncludeClause|undefined} clause
  5367. * @returns {object[]}
  5368. */
  5369. static normalizeIncludeClause(clause) {
  5370. let result = [];
  5371. if (clause == null) {
  5372. return result;
  5373. } else if (clause && typeof clause === "string") {
  5374. result.push({ relation: clause });
  5375. } else if (Array.isArray(clause)) {
  5376. clause.flat(Infinity).forEach((el) => {
  5377. el = this.normalizeIncludeClause(el);
  5378. result = [...result, ...el];
  5379. });
  5380. const relNames = result.map((v) => v.relation);
  5381. const duplicateNames = relNames.filter(
  5382. (name, i) => relNames.indexOf(name) !== i
  5383. );
  5384. if (duplicateNames.length)
  5385. throw new InvalidArgumentError(
  5386. 'The provided option "include" has duplicates of %v.',
  5387. duplicateNames[0]
  5388. );
  5389. } else if (typeof clause === "object") {
  5390. if ("relation" in clause) {
  5391. if (!clause.relation || typeof clause.relation !== "string")
  5392. throw new InvalidArgumentError(
  5393. 'The provided option "relation" should be a non-empty String, but %v was given.',
  5394. clause.relation
  5395. );
  5396. const normalized = { relation: clause.relation };
  5397. const scope = this.normalizeScopeClause(clause.scope);
  5398. if (scope) normalized.scope = scope;
  5399. result.push(normalized);
  5400. } else {
  5401. Object.keys(clause).forEach((key) => {
  5402. if (!Object.prototype.hasOwnProperty.call(clause, key)) return;
  5403. this.validateIncludeClause(key);
  5404. const normalized = { relation: key };
  5405. const include = this.normalizeIncludeClause(clause[key]);
  5406. if (include.length) normalized.scope = { include };
  5407. result.push(normalized);
  5408. });
  5409. }
  5410. } else {
  5411. throw new InvalidArgumentError(
  5412. 'The provided option "include" should have a non-empty String, an Object or an Array, but %v was given.',
  5413. clause
  5414. );
  5415. }
  5416. return result;
  5417. }
  5418. /**
  5419. * Normalize scope clause.
  5420. *
  5421. * @param {object|undefined} clause
  5422. * @returns {object|undefined}
  5423. */
  5424. static normalizeScopeClause(clause) {
  5425. if (clause == null) return;
  5426. if (typeof clause !== "object" || Array.isArray(clause))
  5427. throw new InvalidArgumentError(
  5428. 'The provided option "scope" should be an Object, but %v was given.',
  5429. clause
  5430. );
  5431. const result = {};
  5432. if (clause.where != null) {
  5433. WhereClauseTool.validateWhereClause(clause.where);
  5434. result.where = clause.where;
  5435. }
  5436. if (clause.order != null) {
  5437. OrderClauseTool.validateOrderClause(clause.order);
  5438. result.order = clause.order;
  5439. }
  5440. if (clause.skip != null) {
  5441. SliceClauseTool.validateSkipClause(clause.skip);
  5442. result.skip = clause.skip;
  5443. }
  5444. if (clause.limit != null) {
  5445. SliceClauseTool.validateLimitClause(clause.limit);
  5446. result.limit = clause.limit;
  5447. }
  5448. if (clause.fields != null) {
  5449. FieldsClauseTool.validateFieldsClause(clause.fields);
  5450. result.fields = clause.fields;
  5451. }
  5452. if (clause.include != null) {
  5453. result.include = this.normalizeIncludeClause(clause.include);
  5454. }
  5455. if (Object.keys(result).length) return result;
  5456. return void 0;
  5457. }
  5458. };
  5459. __name(_IncludeClauseTool, "IncludeClauseTool");
  5460. IncludeClauseTool = _IncludeClauseTool;
  5461. }
  5462. });
  5463. // src/filter/index.js
  5464. var init_filter = __esm({
  5465. "src/filter/index.js"() {
  5466. "use strict";
  5467. init_slice_clause_tool();
  5468. init_order_clause_tool();
  5469. init_where_clause_tool();
  5470. init_fields_clause_tool();
  5471. init_include_clause_tool();
  5472. init_operator_clause_tool();
  5473. }
  5474. });
  5475. // src/index.js
  5476. var index_exports = {};
  5477. __export(index_exports, {
  5478. ADAPTER_CLASS_NAME: () => ADAPTER_CLASS_NAME,
  5479. Adapter: () => Adapter,
  5480. AdapterLoader: () => AdapterLoader,
  5481. AdapterRegistry: () => AdapterRegistry,
  5482. BelongsToResolver: () => BelongsToResolver,
  5483. DEFAULT_PRIMARY_KEY_PROPERTY_NAME: () => DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  5484. DataType: () => DataType,
  5485. DatabaseSchema: () => DatabaseSchema,
  5486. DatasourceDefinitionValidator: () => DatasourceDefinitionValidator,
  5487. DefinitionRegistry: () => DefinitionRegistry,
  5488. FieldsClauseTool: () => FieldsClauseTool,
  5489. HasManyResolver: () => HasManyResolver,
  5490. HasOneResolver: () => HasOneResolver,
  5491. IncludeClauseTool: () => IncludeClauseTool,
  5492. InvalidArgumentError: () => InvalidArgumentError,
  5493. InvalidOperatorValueError: () => InvalidOperatorValueError,
  5494. ModelDataSanitizer: () => ModelDataSanitizer,
  5495. ModelDefinitionUtils: () => ModelDefinitionUtils,
  5496. ModelDefinitionValidator: () => ModelDefinitionValidator,
  5497. NotImplementedError: () => NotImplementedError,
  5498. OperatorClauseTool: () => OperatorClauseTool,
  5499. OrderClauseTool: () => OrderClauseTool,
  5500. PrimaryKeysDefinitionValidator: () => PrimaryKeysDefinitionValidator,
  5501. PropertiesDefinitionValidator: () => PropertiesDefinitionValidator,
  5502. PropertyUniqueness: () => PropertyUniqueness,
  5503. PropertyUniquenessValidator: () => PropertyUniquenessValidator,
  5504. ReferencesManyResolver: () => ReferencesManyResolver,
  5505. RelationType: () => RelationType,
  5506. RelationsDefinitionValidator: () => RelationsDefinitionValidator,
  5507. Repository: () => Repository,
  5508. RepositoryRegistry: () => RepositoryRegistry,
  5509. RequiredPropertyValidator: () => RequiredPropertyValidator,
  5510. SliceClauseTool: () => SliceClauseTool,
  5511. WhereClauseTool: () => WhereClauseTool,
  5512. capitalize: () => capitalize,
  5513. cloneDeep: () => cloneDeep,
  5514. excludeObjectKeys: () => excludeObjectKeys,
  5515. getValueByPath: () => getValueByPath,
  5516. isDeepEqual: () => isDeepEqual,
  5517. isPlainObject: () => isPlainObject,
  5518. isPromise: () => isPromise,
  5519. likeToRegexp: () => likeToRegexp,
  5520. modelNameToModelKey: () => modelNameToModelKey,
  5521. selectObjectKeys: () => selectObjectKeys,
  5522. singularize: () => singularize,
  5523. stringToRegexp: () => stringToRegexp
  5524. });
  5525. module.exports = __toCommonJS(index_exports);
  5526. init_utils();
  5527. init_errors();
  5528. init_filter();
  5529. init_adapter2();
  5530. // src/database-schema.js
  5531. var import_js_service32 = require("@e22m4u/js-service");
  5532. init_definition();
  5533. init_repository2();
  5534. var _DatabaseSchema = class _DatabaseSchema extends import_js_service32.Service {
  5535. /**
  5536. * Define datasource.
  5537. *
  5538. * @param {object} datasourceDef
  5539. * @returns {this}
  5540. */
  5541. defineDatasource(datasourceDef) {
  5542. this.getService(DefinitionRegistry).addDatasource(datasourceDef);
  5543. return this;
  5544. }
  5545. /**
  5546. * Define model.
  5547. *
  5548. * @param {object} modelDef
  5549. * @returns {this}
  5550. */
  5551. defineModel(modelDef) {
  5552. this.getService(DefinitionRegistry).addModel(modelDef);
  5553. return this;
  5554. }
  5555. /**
  5556. * Get repository.
  5557. *
  5558. * @param {string} modelName
  5559. * @returns {Repository}
  5560. */
  5561. getRepository(modelName) {
  5562. return this.getService(RepositoryRegistry).getRepository(modelName);
  5563. }
  5564. };
  5565. __name(_DatabaseSchema, "DatabaseSchema");
  5566. var DatabaseSchema = _DatabaseSchema;
  5567. // src/index.js
  5568. init_relations2();
  5569. init_definition();
  5570. init_repository2();
  5571. // Annotate the CommonJS export names for ESM import in node:
  5572. 0 && (module.exports = {
  5573. ADAPTER_CLASS_NAME,
  5574. Adapter,
  5575. AdapterLoader,
  5576. AdapterRegistry,
  5577. BelongsToResolver,
  5578. DEFAULT_PRIMARY_KEY_PROPERTY_NAME,
  5579. DataType,
  5580. DatabaseSchema,
  5581. DatasourceDefinitionValidator,
  5582. DefinitionRegistry,
  5583. FieldsClauseTool,
  5584. HasManyResolver,
  5585. HasOneResolver,
  5586. IncludeClauseTool,
  5587. InvalidArgumentError,
  5588. InvalidOperatorValueError,
  5589. ModelDataSanitizer,
  5590. ModelDefinitionUtils,
  5591. ModelDefinitionValidator,
  5592. NotImplementedError,
  5593. OperatorClauseTool,
  5594. OrderClauseTool,
  5595. PrimaryKeysDefinitionValidator,
  5596. PropertiesDefinitionValidator,
  5597. PropertyUniqueness,
  5598. PropertyUniquenessValidator,
  5599. ReferencesManyResolver,
  5600. RelationType,
  5601. RelationsDefinitionValidator,
  5602. Repository,
  5603. RepositoryRegistry,
  5604. RequiredPropertyValidator,
  5605. SliceClauseTool,
  5606. WhereClauseTool,
  5607. capitalize,
  5608. cloneDeep,
  5609. excludeObjectKeys,
  5610. getValueByPath,
  5611. isDeepEqual,
  5612. isPlainObject,
  5613. isPromise,
  5614. likeToRegexp,
  5615. modelNameToModelKey,
  5616. selectObjectKeys,
  5617. singularize,
  5618. stringToRegexp
  5619. });