Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix ESLint config & boilerplate files #20

Merged
merged 1 commit into from
Aug 5, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
51 changes: 23 additions & 28 deletions blueprints/@kaliber5/k5-ember-boilerplate/files/.eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,20 @@ module.exports = {
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module',
project: ['./tsconfig.json', './tsconfig-node.json'],
},
plugins: ['@typescript-eslint', 'ember', 'prettier'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
'plugin:ember/recommended',
'standard',

'prettier/@typescript-eslint',
'prettier/standard',

// This one should come last
'plugin:prettier/recommended',
],
env: {
browser: true,
},
rules: {
'@typescript-eslint/ban-ts-ignore': 'off', // Can't fully get rid of it due to TS quirks and issues with third-party depenecies
'@typescript-eslint/camelcase': 'off', // Allow two levels of separation, e. g. ProductWizard_SidebarConfig_ListWithHeader_Component_Args
'@typescript-eslint/class-name-casing': 'off', // Allow two levels of separation, e. g. ProductWizard_SidebarConfig_ListWithHeader_Component_Args
'@typescript-eslint/no-empty-interface': 'off', // Required for simplified typing of Mirage and Ember Data
'@typescript-eslint/no-non-null-assertion': 'off', // When I do it, I mean it.
'@typescript-eslint/no-unused-expressions': 'error',
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],

// As this rule would freak out on JS files (by design!),
// it has to be enabled only for .ts in the overrides section,
// See https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/explicit-function-return-type.md#configuring-in-a-mixed-jsts-codebase
'@typescript-eslint/explicit-function-return-type': 'off',

camelcase: 'off', // Have to keep this off for the TS equivalent to take precedence
'no-console': ['error', { allow: ['debug', 'error', 'info', 'warn'] }],
'no-unused-expressions': 'off',
Expand All @@ -48,6 +28,29 @@ module.exports = {
'prettier/prettier': 'error',
},
overrides: [
// TypeScript
{
files: ['*.ts'],
parserOptions: {
project: ['./tsconfig.json'],
},
extends: [
'plugin:@typescript-eslint/eslint-recommended',
'plugin:@typescript-eslint/recommended',
'plugin:@typescript-eslint/recommended-requiring-type-checking',
'prettier/@typescript-eslint',
],
rules: {
'@typescript-eslint/ban-ts-ignore': 'off', // Can't fully get rid of it due to TS quirks and issues with third-party depenecies
'@typescript-eslint/camelcase': 'off', // Allow two levels of separation, e. g. ProductWizard_SidebarConfig_ListWithHeader_Component_Args
'@typescript-eslint/class-name-casing': 'off', // Allow two levels of separation, e. g. ProductWizard_SidebarConfig_ListWithHeader_Component_Args
'@typescript-eslint/no-empty-interface': 'off', // Required for simplified typing of Mirage and Ember Data
'@typescript-eslint/no-non-null-assertion': 'off', // When I do it, I mean it.
'@typescript-eslint/no-unused-expressions': 'error',
'@typescript-eslint/no-unused-vars': ['error', { argsIgnorePattern: '^_' }],
'@typescript-eslint/explicit-function-return-type': 'error', // We want to be strict with types
},
},
// node files
{
files: [
Expand Down Expand Up @@ -75,8 +78,6 @@ module.exports = {
// this can be removed once the following is fixed
// https://github.com/mysticatea/eslint-plugin-node/issues/77
'node/no-unpublished-require': 'off',

'@typescript-eslint/no-var-requires': 'off',
}),
},
{
Expand All @@ -91,11 +92,5 @@ module.exports = {
'node/no-unpublished-require': 'off', // dependencies are installed into the app's package.json
},
},
{
files: ['*.ts'],
rules: {
'@typescript-eslint/explicit-function-return-type': 'error', // We want to be strict with types
},
},
],
};
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import DS from 'ember-data';
import JSONAPIAdapter from '@ember-data/adapter/json-api';
import config from '<%= dasherizedPackageName %>/config/environment';

export default class Application extends DS.JSONAPIAdapter {
export default class Application extends JSONAPIAdapter {
namespace = config.apiNamespace;
host = config.apiHost;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { assert } from '@ember/debug';
import { getOwner } from '@ember/application';
import ApplicationInstance from '@ember/application/instance';
import FlashMessageService from 'ember-cli-flash/services/flash-messages';
import Intl from 'ember-intl/services/intl';
import translateError from '../t-error';
Expand All @@ -17,18 +18,19 @@ export default function flashMessage(messageSuccess: string, messageError?: stri
return function (_target: unknown, _propertyKey: string, desc: PropertyDescriptor): void {
assert('flashMessage decorator can only be applied to methods.', typeof desc.value === 'function');

const orig = desc.value;
// eslint-disable-next-line @typescript-eslint/ban-types
const orig = desc.value as Function;

desc.value = async function (...args: unknown[]): Promise<void> {
const owner = getOwner(this);
desc.value = async function (...args: unknown[]): Promise<unknown> {
const owner = getOwner(this) as ApplicationInstance;
assert('Target for flashMessage decorator must have an owner', !!owner);
const flashMessages: FlashMessageService = owner.lookup('service:flash-messages');
const flashMessages = owner.lookup('service:flash-messages') as FlashMessageService;
assert('No flashMessage service found.', !!flashMessages);
const intl: Intl = owner.lookup('service:intl');
const intl = owner.lookup('service:intl') as Intl;
assert('No intl service found.', !!intl);

try {
const result = await orig.apply(this, args);
const result = (await orig.apply(this, args)) as unknown;
flashMessages.success(translateIfAvailable(intl, messageSuccess) || messageSuccess);
return result;
} catch (e) {
Expand All @@ -46,18 +48,19 @@ export function errorMessage(messageError?: string): MethodDecorator {
return function (_target: unknown, _propertyKey: string, desc: PropertyDescriptor): void {
assert('flashMessage decorator can only be applied to methods.', typeof desc.value === 'function');

const orig = desc.value;
// eslint-disable-next-line @typescript-eslint/ban-types
const orig = desc.value as Function;

desc.value = async function (...args: unknown[]): Promise<void> {
const owner = getOwner(this);
desc.value = async function (...args: unknown[]): Promise<unknown> {
const owner = getOwner(this) as ApplicationInstance;
assert('Target for flashMessage decorator must have an owner', !!owner);
const flashMessages: FlashMessageService = owner.lookup('service:flash-messages');
const flashMessages = owner.lookup('service:flash-messages') as FlashMessageService;
assert('No flashMessage service found.', !!flashMessages);
const intl: Intl = owner.lookup('service:intl');
const intl = owner.lookup('service:intl') as Intl;
assert('No intl service found.', !!intl);

try {
return await orig.apply(this, args);
return (await orig.apply(this, args)) as unknown;
} catch (e) {
const m =
(messageError && translateIfAvailable(intl, messageError)) ||
Expand All @@ -69,6 +72,8 @@ export function errorMessage(messageError?: string): MethodDecorator {
run(() => {
throw e;
});

return undefined;
}
};
};
Expand Down
Original file line number Diff line number Diff line change
@@ -1,25 +1,31 @@
import DS from 'ember-data';
import Intl from 'ember-intl/services/intl';
import EmberError from '@ember/error';
import AccessDeniedError from './errors/access-denied';
import CredentialsError from './errors/credentials';
import HttpResponseError from './errors/http-response';
import NotFoundError from './errors/not-found';
import OfflineError from './errors/offline';
import AdapterError, {
UnauthorizedError as DataUnauthorizedError,
ForbiddenError as DataForbiddenError,
NotFoundError as DataNotFoundError,
ServerError as DataServerError,
} from '@ember-data/adapter/error';

const ErrorMapping = [
[DS.UnauthorizedError, 'unauthorized'],
[DS.ForbiddenError, 'forbidden'],
[DS.NotFoundError, 'not_found'],
[DS.ServerError, 'server_error'],
// eslint-disable-next-line @typescript-eslint/ban-types
const ErrorMapping: [Function, string][] = [
[DataUnauthorizedError, 'unauthorized'],
[DataForbiddenError, 'forbidden'],
[DataNotFoundError, 'not_found'],
[DataServerError, 'server_error'],
];

export type AnyError =
| EmberError
| DS.UnauthorizedError
| DS.ForbiddenError
| DS.NotFoundError
| DS.ServerError
| DataUnauthorizedError
| DataForbiddenError
| DataNotFoundError
| DataServerError
| AccessDeniedError
| CredentialsError
| HttpResponseError
Expand All @@ -36,8 +42,7 @@ export function errorTranslationKey(intl: Intl, error: AnyError, keyPrefix = 'ex
}

// check if error is an ember-data error with a known mapping
if (error instanceof DS.AdapterError) {
// @ts-ignore
if (error instanceof AdapterError) {
const found = ErrorMapping.find(([klass]) => error instanceof klass);
if (found) {
key = `${keyPrefix}.${found[1]}`;
Expand All @@ -49,7 +54,7 @@ export function errorTranslationKey(intl: Intl, error: AnyError, keyPrefix = 'ex

// try translation of error.messageKey
if ('messageKey' in error) {
key = `${keyPrefix}.${error.messageKey}`;
key = `${keyPrefix}.${error.messageKey ?? ''}`;
if (intl.exists(key)) {
return key;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,13 @@ export default function waitForInTests(_target: unknown, _propertyKey: string, d
return;
}

const orig = desc.value;
// eslint-disable-next-line @typescript-eslint/ban-types
const orig = desc.value as Function;

desc.value = async function (...args: unknown[]): Promise<unknown> {
pending++;
try {
return await orig.apply(this, args);
return (await orig.apply(this, args)) as unknown;
} finally {
pending--;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,7 @@ import Ember from 'ember';

let originalErrorHandler: (error: Error) => void | null | undefined;

// ToDo: fix error typing
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function throwUnlessMatches(error: any, code?: string | number): void {
function throwUnlessMatches(error: Error & { errors?: { status?: string }[] }, code?: string | number): void {
// eslint-disable-next-line eqeqeq
if (code && error.errors && error.errors[0] && error.errors[0].status != code) {
throw error;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,17 +1,13 @@
// @ts-ignore
import yadda from 'yadda';

// @ts-ignore
import { composeSteps, labelMap, opinionatedSteps, setupDictionary } from 'ember-cli-yadda-opinionated/test-support';
// @ts-ignore
import * as yadda from 'yadda';
import { composeSteps, setLabel, opinionatedSteps, setupDictionary } from 'ember-cli-yadda-opinionated/test-support';
import powerSelectSteps from 'ember-cli-yadda-opinionated/test-support/steps/power-select';
// import powerDatePickerSteps from 'ember-cli-yadda-opinionated/test-support/steps/power-date-picker';
import errorHandlingSteps from './_error-handling';
import windowSteps from './_window';

type YaddaEvent = { data: { step: string }; name: string };

labelMap.set('Bootstrap-Field-Error', '.help-block');
setLabel('Bootstrap-Field-Error', '.help-block');

export const dictionary = new yadda.Dictionary().define('number', /(\d+)/, yadda.converters.integer);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
/* eslint-disable @typescript-eslint/unbound-method */
import sinon from 'sinon';
import window from 'ember-window-mock';
import { setupWindowMock } from 'ember-window-mock/test-support';

export default function mockWindow(hooks: NestedHooks): void {
setupWindowMock(hooks);
hooks.beforeEach(function(): void {
hooks.beforeEach(function (): void {
window.print = sinon.spy();
window.location.reload = sinon.spy();
});
Expand Down
37 changes: 0 additions & 37 deletions blueprints/@kaliber5/k5-ember-boilerplate/files/tsconfig-node.json

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,9 @@

import MirageModelRegistry from 'ember-cli-mirage/types/registries/model';
import MirageSchemaRegistry from 'ember-cli-mirage/types/registries/schema';
// eslint-disable-next-line ember/use-ember-data-rfc-395-imports
import DS from 'ember-data';
// eslint-disable-next-line ember/use-ember-data-rfc-395-imports
import EmberDataModelRegistry from 'ember-data/types/registries/model';

export { default as faker } from 'faker';
Expand Down Expand Up @@ -244,7 +246,7 @@ export type TraitOptions<M> = AnyAttrs & {
afterCreate?: (obj: ModelInstance<M>, svr: Server) => void;
};

export interface Trait<O extends TraitOptions = {}> {
export interface Trait<O extends TraitOptions = unknown> {
extension: O;
__isTrait__: true;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// some very rudimentary type definitions to make TS happy

declare module 'ember-cli-yadda-opinionated/test-support' {
import * as yadda from 'yadda';

// eslint-disable-next-line @typescript-eslint/ban-types
type StepDefinition = Record<string, Function>;

export function setLabel(label: string, selector: string): void;
export function hasLabel(label: string): boolean;
export function getLabel(label: string): string;
export function deleteLabel(label: string): void;
export function clearLabels(): void;

// eslint-disable-next-line @typescript-eslint/ban-types
export function composeSteps(libraryFactory: Function, ...steps: StepDefinition[]): unknown;
export function setupDictionary(dictionary: yadda.Dictionary): yadda.Dictionary;
export const opinionatedSteps: StepDefinition;
}
declare module 'ember-cli-yadda-opinionated/test-support/steps/power-select';
declare module 'ember-cli-yadda-opinionated/test-support/steps/power-date-picker';
5 changes: 3 additions & 2 deletions blueprints/@kaliber5/k5-ember-boilerplate/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,10 @@ module.exports = {
{ name: '@types/ember-data' },
{ name: '@types/ember-data__adapter' },
{ name: '@types/ember-data__model' },
{ name: '@types/ember-data_serializer' },
{ name: '@types/ember-data__serializer' },
{ name: '@types/ember-data__store' },
{ name: '@types/ember-qunit' },
{ name: '@types/ember-resolver' },
{ name: '@types/ember-test-helpers' },
{ name: '@types/ember-testing-helpers' },
{ name: '@types/ember__test-helpers' },
Expand All @@ -63,9 +64,9 @@ module.exports = {
{ name: '@types/rsvp' },
{ name: '@types/sinon' },
{ name: '@types/sinon-chai' },
{ name: '@types/yadda' },
{ name: '@typescript-eslint/eslint-plugin' },
{ name: '@typescript-eslint/parser' },
{ name: 'bootstrap' },
{ name: 'chai' },
{ name: 'chai-as-promised' },
{ name: 'chai-dom' },
Expand Down