directus-extension-models
Version:
Generate .d.ts files from your directus schema
3 lines (2 loc) • 9.98 kB
JavaScript
;var e=require("node:fs/promises"),o=require("node:path");"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self&&self;var t={};!function(e,o){!function(o,t){e.exports=t()}(0,(function(){var e=[],o=[],t={},i={},n={};function a(e){return"string"==typeof e?new RegExp("^"+e+"$","i"):e}function s(e,o){return e===o?o:e===e.toLowerCase()?o.toLowerCase():e===e.toUpperCase()?o.toUpperCase():e[0]===e[0].toUpperCase()?o.charAt(0).toUpperCase()+o.substr(1).toLowerCase():o.toLowerCase()}function r(e,o){return e.replace(o[0],(function(t,i){var n,a,r=(n=o[1],a=arguments,n.replace(/\$(\d{1,2})/g,(function(e,o){return a[o]||""})));return s(""===t?e[i-1]:t,r)}))}function l(e,o,i){if(!e.length||t.hasOwnProperty(e))return o;for(var n=i.length;n--;){var a=i[n];if(a[0].test(o))return r(o,a)}return o}function c(e,o,t){return function(i){var n=i.toLowerCase();return o.hasOwnProperty(n)?s(i,n):e.hasOwnProperty(n)?s(i,e[n]):l(n,i,t)}}function u(e,o,t,i){return function(i){var n=i.toLowerCase();return!!o.hasOwnProperty(n)||!e.hasOwnProperty(n)&&l(n,n,t)===n}}function d(e,o,t){return(t?o+" ":"")+(1===o?d.singular(e):d.plural(e))}return d.plural=c(n,i,e),d.isPlural=u(n,i,e),d.singular=c(i,n,o),d.isSingular=u(i,n,o),d.addPluralRule=function(o,t){e.push([a(o),t])},d.addSingularRule=function(e,t){o.push([a(e),t])},d.addUncountableRule=function(e){"string"!=typeof e?(d.addPluralRule(e,"$0"),d.addSingularRule(e,"$0")):t[e.toLowerCase()]=!0},d.addIrregularRule=function(e,o){o=o.toLowerCase(),e=e.toLowerCase(),n[e]=o,i[o]=e},[["I","we"],["me","us"],["he","they"],["she","they"],["them","them"],["myself","ourselves"],["yourself","yourselves"],["itself","themselves"],["herself","themselves"],["himself","themselves"],["themself","themselves"],["is","are"],["was","were"],["has","have"],["this","these"],["that","those"],["echo","echoes"],["dingo","dingoes"],["volcano","volcanoes"],["tornado","tornadoes"],["torpedo","torpedoes"],["genus","genera"],["viscus","viscera"],["stigma","stigmata"],["stoma","stomata"],["dogma","dogmata"],["lemma","lemmata"],["schema","schemata"],["anathema","anathemata"],["ox","oxen"],["axe","axes"],["die","dice"],["yes","yeses"],["foot","feet"],["eave","eaves"],["goose","geese"],["tooth","teeth"],["quiz","quizzes"],["human","humans"],["proof","proofs"],["carve","carves"],["valve","valves"],["looey","looies"],["thief","thieves"],["groove","grooves"],["pickaxe","pickaxes"],["passerby","passersby"]].forEach((function(e){return d.addIrregularRule(e[0],e[1])})),[[/s?$/i,"s"],[/[^\u0000-\u007F]$/i,"$0"],[/([^aeiou]ese)$/i,"$1"],[/(ax|test)is$/i,"$1es"],[/(alias|[^aou]us|t[lm]as|gas|ris)$/i,"$1es"],[/(e[mn]u)s?$/i,"$1s"],[/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i,"$1"],[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i,"$1i"],[/(alumn|alg|vertebr)(?:a|ae)$/i,"$1ae"],[/(seraph|cherub)(?:im)?$/i,"$1im"],[/(her|at|gr)o$/i,"$1oes"],[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i,"$1a"],[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i,"$1a"],[/sis$/i,"ses"],[/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i,"$1$2ves"],[/([^aeiouy]|qu)y$/i,"$1ies"],[/([^ch][ieo][ln])ey$/i,"$1ies"],[/(x|ch|ss|sh|zz)$/i,"$1es"],[/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i,"$1ices"],[/\b((?:tit)?m|l)(?:ice|ouse)$/i,"$1ice"],[/(pe)(?:rson|ople)$/i,"$1ople"],[/(child)(?:ren)?$/i,"$1ren"],[/eaux$/i,"$0"],[/m[ae]n$/i,"men"],["thou","you"]].forEach((function(e){return d.addPluralRule(e[0],e[1])})),[[/s$/i,""],[/(ss)$/i,"$1"],[/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i,"$1fe"],[/(ar|(?:wo|[ae])l|[eo][ao])ves$/i,"$1f"],[/ies$/i,"y"],[/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i,"$1ie"],[/\b(mon|smil)ies$/i,"$1ey"],[/\b((?:tit)?m|l)ice$/i,"$1ouse"],[/(seraph|cherub)im$/i,"$1"],[/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i,"$1"],[/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i,"$1sis"],[/(movie|twelve|abuse|e[mn]u)s$/i,"$1"],[/(test)(?:is|es)$/i,"$1is"],[/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i,"$1us"],[/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i,"$1um"],[/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i,"$1on"],[/(alumn|alg|vertebr)ae$/i,"$1a"],[/(cod|mur|sil|vert|ind)ices$/i,"$1ex"],[/(matr|append)ices$/i,"$1ix"],[/(pe)(rson|ople)$/i,"$1rson"],[/(child)ren$/i,"$1"],[/(eau)x?$/i,"$1"],[/men$/i,"man"]].forEach((function(e){return d.addSingularRule(e[0],e[1])})),["adulthood","advice","agenda","aid","aircraft","alcohol","ammo","analytics","anime","athletics","audio","bison","blood","bream","buffalo","butter","carp","cash","chassis","chess","clothing","cod","commerce","cooperation","corps","debris","diabetes","digestion","elk","energy","equipment","excretion","expertise","firmware","flounder","fun","gallows","garbage","graffiti","hardware","headquarters","health","herpes","highjinks","homework","housework","information","jeans","justice","kudos","labour","literature","machinery","mackerel","mail","media","mews","moose","music","mud","manga","news","only","personnel","pike","plankton","pliers","police","pollution","premises","rain","research","rice","salmon","scissors","series","sewage","shambles","shrimp","software","species","staff","swine","tennis","traffic","transportation","trout","tuna","wealth","welfare","whiting","wildebeest","wildlife","you",/pok[eé]mon$/i,/[^aeiou]ese$/i,/deer$/i,/fish$/i,/measles$/i,/o[iu]s$/i,/pox$/i,/sheep$/i].forEach(d.addUncountableRule),d}))}({get exports(){return t},set exports(e){t=e}});var i=t;function n(e){const o=e.collection,t=i.singular(o);return t.split("_").map((e=>e[0].toUpperCase()+e.substring(1).toLowerCase())).join("")}function a(e,o,t){var i,a;const s=t.relations.find((t=>t.collection===o.collection&&t.field===e.field));if(!s)return null;if(s.related_collection){const o=n(t.collections[s.related_collection]);return`${o} | ${(null==(i=null==s?void 0:s.schema)?void 0:i.foreign_key_column)?`${o}["${s.schema.foreign_key_column}"]`:r(e)}`}if(null==(a=s.meta.one_allowed_collections)?void 0:a.length){return s.meta.one_allowed_collections.map((e=>{const o=t.collections[e],i=n(o);return`${i} | ${i}["${o.primary}"]`})).join(" | ")}throw new Error(`Failed to get type for relation ${JSON.stringify(s)}`)}function s(e,o,t){const i=t.relations.find((t=>{var i,n;return(null==(i=null==t?void 0:t.meta)?void 0:i.one_collection)===o.collection&&(null==(n=null==t?void 0:t.meta)?void 0:n.one_field)===e.field}));return i?`${n(t.collections[i.meta.many_collection])}[]`:null}function r(e,o){switch(e.type){case"boolean":return"boolean";case"integer":case"float":case"decimal":case"bigInteger":return"number";case"dateTime":case"date":case"time":case"timestamp":case"text":case"string":case"uuid":case"hash":return"string";case"json":return"any";case"csv":return"string[]";default:throw new Error("Unknown type")}}async function l(e,o,t,i,l,u){var d,m,f,p,h,$;let g=`${l} interface ${n(e)} {\n`;const v=new t.ItemsService("directus_fields",{knex:i,schema:o}),y=u?Object.values(e.fields).sort(c("field")):Object.values(e.fields);for(const t of y){let i;try{let n=t.alias?s(t,e,o):a(t,e,o);if(n)i=n;else{const o=(await v.readByQuery({filter:{collection:{_eq:e.collection},field:{_eq:t.field}},limit:1}))[0];(null==(m=null==(d=null==o?void 0:o.options)?void 0:d.choices)?void 0:m.length)?(i=null==(h=null==(p=null==(f=null==o?void 0:o.options)?void 0:f.choices)?void 0:p.map((e=>"string"==typeof e.value?`'${e.value.replaceAll("'","\\'")}'`:e.value)))?void 0:h.join(" | "),(null==($=null==o?void 0:o.interface)?void 0:$.includes("multiple"))&&(i=`(${i})[]`)):i=r(t)}t.nullable&&(i=`${i} | null`)}catch(o){console.error(`\n== Missing Field ==\nFailed to get the type for ${e.collection}.${t.field}. Setting to "never".\nPlease report this error: https://github.com/ChappIO/directus-extension-models/issues.\n\n\nStack Trace:`,o,"\n\nModel generation will still continue, no worries.\n"),i="never"}g+=`\n /**\n * ${t.note||"No description."}\n *\n * Type in directus: ${t.type}\n * Type in database: ${t.dbType||"no column"}\n */\n ${t.field}: ${i};\n`}return g+="}\n",g}function c(e){return(o,t)=>o[e]>t[e]?1:-1}var u=async({init:t},{services:i,getSchema:a,database:s,logger:r})=>{t("cli.after",(({program:t})=>{t.command("models").description("Export the currently connected database to .d.ts files").command("snapshot").description("Export the currently connected database to .d.ts files into <file>").arguments("<file>").option("-g, --global","Generate a file with global declarations instead of exports. Just snapshot it into your typescript project as a .d.ts file.",!1).option("--no-sort","Set --no-sort to disable alphabetic sorting of fields and collection. This defaults to sorting to make git diffs more consistent.",!0).action((async function(t,u){const d=await a(),m=d.collections;r.info(`Exporting models to ${t}`),await e.mkdir(o.dirname(t),{recursive:!0});let f="";const p=u.global?"declare":"export",h=u.sort?Object.values(m).sort(c("collection")):Object.values(m);for(let e of h)f+=await l(e,d,i,s,p,u.sort)+"\n";f+=function(e,o){let t="";return t+=`\n${o} type Collections = {\n`,e.forEach((e=>{t+=` ${e.collection}: ${n(e)}${e.singleton?"":"[]"};\n`})),t+="}\n",t}(h,p),f+=`\n\n${p} type CollectionName = keyof Collections;\n\n${p} type ItemIn<CollectionKey extends CollectionName> =\n Collections[CollectionKey] extends (infer Item extends Record<string, any>)[]\n ? Item\n : Collections[CollectionKey]\n\n`,await e.writeFile(t,f),process.exit(0)}))}))};module.exports=u;
//# sourceMappingURL=index.js.map