Skip to content

Commit

Permalink
Strictly apply lint rules (#268)
Browse files Browse the repository at this point in the history
* Strictly apply lint rules

* Fix missing lint warning
  • Loading branch information
daogrady authored Jul 1, 2024
1 parent 7a53f9d commit e2a0d42
Show file tree
Hide file tree
Showing 33 changed files with 239 additions and 237 deletions.
8 changes: 4 additions & 4 deletions cds-plugin.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ const rmDirIfExists = dir => {
* @param {string[]} exts - The extensions to remove.
* @returns {Promise<void>}
*/
const rmFiles = async (dir, exts) => fs.existsSync(dir)
const rmFiles = async (dir, exts) => fs.existsSync(dir)
? Promise.all(
(await readdir(dir))
.map(async file => {
Expand Down Expand Up @@ -66,7 +66,7 @@ cds.build?.register?.('typescript', class extends cds.build.Plugin {
get #modelDirectoryName () {
try {
// expected format: { '#cds-models/*': [ './@cds-models/*/index.ts' ] }
// ^^^^^^^^^^^^^^^
// ^^^^^^^^^^^^^^^
// relevant part - may be changed by user
const config = JSON.parse(fs.readFileSync ('tsconfig.json', 'utf8'))
const alias = config.compilerOptions.paths['#cds-models/*'][0]
Expand Down Expand Up @@ -118,8 +118,8 @@ cds.build?.register?.('typescript', class extends cds.build.Plugin {
await rmFiles(this.task.dest, ['.js', '.ts'])

try {
await (buildConfigExists()
? this.#buildWithConfig()
await (buildConfigExists()
? this.#buildWithConfig()
: this.#buildWithoutConfig()
)
} catch (error) {
Expand Down
3 changes: 2 additions & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ module.exports = [
'no-sparse-arrays': 'error',
'no-template-curly-in-string': 'error',
'no-this-before-super': 'error',
'no-trailing-spaces': 'warn',
'no-undef': 'error',
'no-unexpected-multiline': 'error',
'no-unmodified-loop-condition': 'error',
Expand All @@ -70,7 +71,7 @@ module.exports = [
'no-unsafe-negation': [ 'error', { enforceForOrderingRelations: true } ],
'no-unsafe-optional-chaining': [ 'error', { disallowArithmeticOperators: true } ],
'no-unused-private-class-members': 'warn',
'no-unused-vars': [ 'warn', { ignoreRestSiblings: true } ],
'no-unused-vars': [ 'warn', { ignoreRestSiblings: true, argsIgnorePattern: '^_' } ],
'no-use-before-define': ['error', {classes: false, functions: false}],
'no-useless-assignment': 'error',
'no-useless-backreference': 'error',
Expand Down
24 changes: 12 additions & 12 deletions lib/components/enum.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const { normalise } = require('./identifier')
/**
* Extracts all unique values from a list of enum key-value pairs.
* If the value is an object, then the `.val` property is used.
* @param {[string, any | {val: any}][]} kvs
* @param {[string, any | {val: any}][]} kvs - key value pairs
*/
const uniqueValues = kvs => new Set(kvs.map(([,v]) => v?.val ?? v)) // in case of wrapped vals we need to unwrap here for the type

Expand Down Expand Up @@ -44,10 +44,10 @@ const enumVal = (key, value, enumType) => enumType === 'cds.String' ? JSON.strin
* @param {Buffer} buffer - Buffer to write into
* @param {string} name - local name of the enum, i.e. the name under which it should be created in the .ts file
* @param {[string, string][]} kvs - list of key-value pairs
* @param {object} options
* @param {object} options - options for printing the enum
*/
function printEnum(buffer, name, kvs, options = {}) {
const opts = {...{export: true}, ...options}
const opts = {...{export: true}, ...options}
buffer.add('// enum')
buffer.addIndentedBlock(`${opts.export ? 'export ' : ''}const ${name} = {`, () =>
kvs.forEach(([k, v]) => { buffer.add(`${normalise(k)}: ${v},`) })
Expand All @@ -60,14 +60,14 @@ function printEnum(buffer, name, kvs, options = {}) {
* Converts a CSN type describing an enum into a list of kv-pairs.
* Values from CSN are unwrapped from their `.val` structure and
* will fall back to the key if no value is provided.
* @param {{enum: {[key: name]: string}, type: string}} enumCsn
* @param {{enum: {[key: name]: string}, type: string}} enumCsn - the CSN type describing the enum
* @param {{unwrapVals: boolean}} options - if `unwrapVals` is passed,
* then the CSN structure `{val:x}` is flattened to just `x`.
* Retaining `val` is closer to the actual CSN structure and should be used where we want
* to mimic the runtime as closely as possible (inline enum types).
* Stripping that additional wrapper would be more readable for users.
* @example
* ```ts
* ```ts
* const csn = {enum: {X: {val: 'a'}, Y: {val: 'b'}, Z: {}}}
* csnToEnumPairs(csn) // -> [['X', 'a'], ['Y': 'b'], ['Z': 'Z']]
* csnToEnumPairs(csn, {unwrapVals: false}) // -> [['X', {val:'a'}], ['Y': {val:'b'}], ['Z':'Z']]
Expand All @@ -82,17 +82,17 @@ const csnToEnumPairs = ({enum: enm, type}, options = {}) => {
}

/**
* @param {string} entity
* @param {string} property
* @param {string} entity - the entity to which the property belongs
* @param {string} property - the property name
*/
const propertyToInlineEnumName = (entity, property) => `${entity}_${property}`

/**
* A type is considered to be an inline enum, iff it has a `.enum` property
* _and_ its type is a CDS primitive, i.e. it is not contained in `cds.definitions`.
* If it is contained there, then it is a standard enum declaration that has its own name.
* @param {{type: string}} element
* @param {object} csn
* @param {{type: string}} element - the element to check
* @param {object} csn - the CSN model
* @returns boolean
*/
const isInlineEnumType = (element, csn) => element.enum && !(element.type in csn.definitions)
Expand All @@ -107,12 +107,12 @@ const isInlineEnumType = (element, csn) => element.enum && !(element.type in csn
* }
* ```
* becomes
*
*
* ```js
* module.exports.Language = { DE: "German", EN: "English", FR: "FR" }
* ```
* @param {string} name
* @param {[string, string][]} kvs - a list of key-value pairs. Values that are falsey are replaced by
* @param {string} name - the enum name
* @param {[string, string][]} kvs - a list of key-value pairs. Values that are falsey are replaced by
*/
// ??= for inline enums. If there is some static property of that name, we don't want to override it (for example: ".actions"
const stringifyEnumImplementation = (name, kvs) => `module.exports.${name} ??= { ${kvs.map(([k,v]) => `${normalise(k)}: ${v}`).join(', ')} }`
Expand Down
6 changes: 3 additions & 3 deletions lib/components/inline.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ class InlineDeclarationResolver {
* b: number
* }
* }
*
*
* T['a']['b'] // number
* ```
* but especially with inline declarations, the access will differ between flattened and nested representations.
Expand Down Expand Up @@ -189,9 +189,9 @@ class FlatInlineDeclarationResolver extends InlineDeclarationResolver {
* ```
*/
class StructuredInlineDeclarationResolver extends InlineDeclarationResolver {
constructor(visitor) {
constructor(visitor) {
super(visitor)
this.printDepth = 0
this.printDepth = 0
}

flatten(name, type, buffer, statementEnd = ';') {
Expand Down
16 changes: 8 additions & 8 deletions lib/components/wrappers.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,35 @@ const base = '__'

/**
* Wraps type into association to scalar.
* @param {string} t - the singular type name.
* @param {string} t - the singular type name.
* @returns {string}
*/
const createToOneAssociation = t => `${base}.Association.to<${t}>`

/**
* Wraps type into association to vector.
* @param {string} t - the singular type name.
* @param {string} t - the singular type name.
* @returns {string}
*/
const createToManyAssociation = t => `${base}.Association.to.many<${t}>`

/**
* Wraps type into composition of scalar.
* @param {string} t - the singular type name.
* @param {string} t - the singular type name.
* @returns {string}
*/
const createCompositionOfOne = t => `${base}.Composition.of<${t}>`

/**
* Wraps type into composition of vector.
* @param {string} t - the singular type name.
* @param {string} t - the singular type name.
* @returns {string}
*/
const createCompositionOfMany = t => `${base}.Composition.of.many<${t}>`

/**
* Wraps type into an array.
* @param {string} t - the singular type name.
* @param {string} t - the singular type name.
* @returns {string}
*/
const createArrayOf = t => `Array<${t}>`
Expand All @@ -47,7 +47,7 @@ const createObjectOf = t => `{${t}}`

/**
* Wraps type into a deep require (removes all posibilities of undefined recursively).
* @param {string} t - the singular type name.
* @param {string} t - the singular type name.
* @param {string?} lookup - a property lookup of the required type (`['Foo']`)
* @returns {string}
*/
Expand All @@ -59,8 +59,8 @@ const deepRequire = (t, lookup = '') => `${base}.DeepRequired<${t}>${lookup}`
* @returns {string[]} an array of lines wrapped in doc format. The result is not
* concatenated to be properly indented by `buffer.add(...)`.
*/
const docify = doc => doc
? ['/**'].concat(doc.split('\n').map(line => `* ${line}`)).concat(['*/'])
const docify = doc => doc
? ['/**'].concat(doc.split('\n').map(line => `* ${line}`)).concat(['*/'])
: []

module.exports = {
Expand Down
28 changes: 14 additions & 14 deletions lib/csn.js
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class DraftUnroller {
/** @type {{[key: string]: boolean}} */
#draftable = {}
/** @type {{[key: string]: string}} */
#projections
#projections
/** @type {object[]} */
#entities
#csn
Expand All @@ -68,7 +68,7 @@ class DraftUnroller {
* @param {object | string} entity - entity to set draftable annotation for.
* @param {boolean} value - whether the entity is draftable.
*/
#setDraftable(entity, value) {
#setDraftable(entity, value) {
if (typeof entity === 'string') entity = this.#getDefinition(entity)
if (!entity) return // inline definition -- not found in definitions
entity[annotation] = value
Expand All @@ -87,10 +87,10 @@ class DraftUnroller {
#getDraftable(entityOrName) {
const entity = (typeof entityOrName === 'string')
? this.#getDefinition(entityOrName)
: entityOrName
: entityOrName
// assert(typeof entity !== 'string')
const name = entity?.name ?? entityOrName
return this.#draftable[name] ??= this.#propagateInheritance(entity)
return this.#draftable[name] ??= this.#propagateInheritance(entity)
}

/**
Expand Down Expand Up @@ -168,7 +168,7 @@ class DraftUnroller {
/**
* We are unrolling the @odata.draft.enabled annotations into related entities manually.
* This includes three scenarios:
*
*
* (a) aspects via `A: B`, where `B` is draft enabled.
* Note that when an entity extends two other entities of which one has drafts enabled and
* one has not, then the one that is later in the list of mixins "wins":
Expand All @@ -182,17 +182,17 @@ class DraftUnroller {
* entity A: T,F {} // draft not enabled
* entity B: F,T {} // draft enabled
* ```
*
*
* (b) Draft enabled projections make the entity we project on draft enabled.
* @example
* ```ts
* @odata.draft.enabled: true
* entity A as projection on B {}
* entity B {} // draft enabled
* ```
*
*
* (c) Entities that are draft enabled propagate this property down through compositions:
*
*
* ```ts
* @odata.draft.enabled: true
* entity A {
Expand Down Expand Up @@ -221,10 +221,10 @@ function unrollDraftability(csn) {
* ```
* must yield
* ```ts
* class A {
* class A {
* ID: UUID // inherited from cuid
* name: String;
* }
* }
* class B {
* ref: Association.to<A>
* ref_ID: UUID
Expand All @@ -247,7 +247,7 @@ function propagateForeignKeys(csn) {
const remoteKeys = Object.entries(this.associations ?? {})
.filter(([,{key}]) => key) // only follow associations that are keys, that way we avoid cycles
.flatMap(([kname, key]) => Object.entries(csn.definitions[key.target].keys)
.map(([ckname, ckey]) => [`${kname}_${ckname}`, ckey]))
.map(([ckname, ckey]) => [`${kname}_${ckname}`, ckey]))

this.__keys = Object.fromEntries(ownKeys
.concat(inheritedKeys)
Expand Down Expand Up @@ -286,9 +286,9 @@ const getProjectionAliases = entity => {
return { aliases, all }
}

module.exports = {
amendCSN,
isView,
module.exports = {
amendCSN,
isView,
isProjection,
isDraftEnabled,
isEntity,
Expand Down
Loading

0 comments on commit e2a0d42

Please sign in to comment.