@sixbell-telco/eslint-plugin-sdk 0.0.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,216 @@
1
+ /**
2
+ * Loads the @sixbell-telco/sdk component manifest (`@sixbell-telco/sdk/manifest.json`) that the
3
+ * rules check against, and indexes it.
4
+ *
5
+ * Resolution order: `settings.sixbellSdk.manifest` (a path, or the manifest object itself), then
6
+ * `@sixbell-telco/sdk/manifest.json` resolved from the linted project's cwd.
7
+ */
8
+ import { BindingType, CssSelector, SelectorMatcher } from '@angular-eslint/bundled-angular-compiler';
9
+ import { readFileSync } from 'node:fs';
10
+ import { createRequire } from 'node:module';
11
+ import { join, resolve } from 'node:path';
12
+
13
+ /**
14
+ * @typedef {import('./types.js').Manifest} Manifest
15
+ * @typedef {import('./types.js').ManifestIndex} ManifestIndex
16
+ * @typedef {import('./types.js').ManifestDeclaration} ManifestDeclaration
17
+ * @typedef {import('./types.js').TemplateElement} TemplateElement
18
+ * @typedef {import('./types.js').TemplateBoundAttribute} TemplateBoundAttribute
19
+ * @typedef {{ settings?: import('./types.js').SdkSettings, cwd?: string }} RuleContextLike
20
+ */
21
+
22
+ /** @type {Map<string | Manifest, ManifestIndex>} */
23
+ const cache = new Map();
24
+
25
+ /** Angular DOM-level bindings that are never component inputs. */
26
+ const BINDING_PREFIXES = ['attr.', 'class.', 'style.'];
27
+ const NON_INPUT_BINDINGS = new Set([
28
+ 'class',
29
+ 'style',
30
+ 'ngClass',
31
+ 'ngStyle',
32
+ 'id',
33
+ 'title',
34
+ 'hidden',
35
+ 'innerHTML',
36
+ 'textContent',
37
+ 'tabIndex',
38
+ 'tabindex',
39
+ 'role',
40
+ ]);
41
+
42
+ /** Inputs of common Angular and CDK directives that may sit on a kit element. */
43
+ export const KNOWN_DIRECTIVE_INPUTS = new Set([
44
+ 'formControl',
45
+ 'formControlName',
46
+ 'formGroup',
47
+ 'formGroupName',
48
+ 'formArrayName',
49
+ 'ngModel',
50
+ 'ngModelOptions',
51
+ 'routerLink',
52
+ 'routerLinkActive',
53
+ 'routerLinkActiveOptions',
54
+ 'queryParams',
55
+ 'queryParamsHandling',
56
+ 'fragment',
57
+ 'state',
58
+ 'replaceUrl',
59
+ 'skipLocationChange',
60
+ 'cdkDrag',
61
+ 'cdkDragData',
62
+ 'cdkDropList',
63
+ 'cdkDropListData',
64
+ 'ngTemplateOutlet',
65
+ 'ngTemplateOutletContext',
66
+ ]);
67
+
68
+ /** Prefixes of attribute and output names that belong to app or third-party directives. */
69
+ const FOREIGN_PREFIXES = /^(?:app|ngx|cdk|mat|tui|nz|ion|mdc)[A-Z]/;
70
+
71
+ /**
72
+ * A camelCase attribute or output that may belong to another directive: a conventional directive
73
+ * prefix (`appResize`, `ngxClipboard`), or a name listed in `settings.sixbellSdk.knownAttributes`
74
+ * (sdk-tools fills it with the selectors, inputs and outputs of the project's own directives).
75
+ */
76
+ /**
77
+ * @param {string} name
78
+ * @param {RuleContextLike} context
79
+ */
80
+ export function isForeignDirectiveName(name, context) {
81
+ return FOREIGN_PREFIXES.test(name) || (context.settings?.sixbellSdk?.knownAttributes ?? []).includes(name);
82
+ }
83
+
84
+ /**
85
+ * A binding that never targets a component input: `[attr.x]`, `[class.x]`, `[style.x]`
86
+ * (the parser strips the prefix, so read the binding type), `[@anim]`, or a DOM-only name.
87
+ * @param {string | TemplateBoundAttribute} binding
88
+ */
89
+ export function isDomBinding(binding) {
90
+ const name = typeof binding === 'string' ? binding : binding.name;
91
+ if (typeof binding === 'object') {
92
+ // The ESLint AST keeps Angular's binding type in __originalType (`type` is the node name).
93
+ const kind = typeof binding.type === 'number' ? binding.type : binding.__originalType;
94
+ if (kind !== BindingType.Property && kind !== BindingType.TwoWay) return true;
95
+ }
96
+ return NON_INPUT_BINDINGS.has(name) || BINDING_PREFIXES.some((prefix) => name.startsWith(prefix));
97
+ }
98
+
99
+ /**
100
+ * @param {Manifest} manifest
101
+ * @param {string} source
102
+ * @returns {ManifestIndex}
103
+ */
104
+ function indexManifest(manifest, source) {
105
+ /** @type {SelectorMatcher<ManifestDeclaration>} */
106
+ const matcher = new SelectorMatcher();
107
+ /** @type {Set<string>} */
108
+ const elementNames = new Set();
109
+ for (const declaration of manifest.declarations) {
110
+ if (!declaration.selector) continue;
111
+ for (const selector of CssSelector.parse(declaration.selector)) {
112
+ matcher.addSelectables([selector], declaration);
113
+ if (selector.element) elementNames.add(selector.element);
114
+ }
115
+ }
116
+ return {
117
+ source,
118
+ manifest,
119
+ matcher,
120
+ elementNames: [...elementNames].sort(),
121
+ entryPoints: new Set(manifest.entryPoints.map((e) => e.name)),
122
+ tokens: new Map(manifest.tokens.map((t) => [t.name, t])),
123
+ };
124
+ }
125
+
126
+ /**
127
+ * @param {string} path
128
+ * @returns {ManifestIndex}
129
+ */
130
+ function readManifest(path) {
131
+ let index = cache.get(path);
132
+ if (!index) {
133
+ index = indexManifest(JSON.parse(readFileSync(path, 'utf8')), path);
134
+ cache.set(path, index);
135
+ }
136
+ return index;
137
+ }
138
+
139
+ /**
140
+ * The indexed manifest for a rule context, or null when none can be found.
141
+ * @param {RuleContextLike} context
142
+ * @returns {ManifestIndex | null}
143
+ */
144
+ export function manifestFor(context) {
145
+ const setting = context.settings?.sixbellSdk?.manifest;
146
+ if (setting && typeof setting === 'object') {
147
+ let index = cache.get(setting);
148
+ if (!index) {
149
+ index = indexManifest(setting, 'settings');
150
+ cache.set(setting, index);
151
+ }
152
+ return index;
153
+ }
154
+ const cwd = context.cwd ?? process.cwd();
155
+ if (typeof setting === 'string') return readManifest(resolve(cwd, setting));
156
+ try {
157
+ return readManifest(createRequire(join(cwd, 'noop.js')).resolve('@sixbell-telco/sdk/manifest.json'));
158
+ } catch {
159
+ return null;
160
+ }
161
+ }
162
+
163
+ /**
164
+ * Declarations whose selector matches a template element (its name, static attributes and bound inputs).
165
+ * @param {ManifestIndex} index
166
+ * @param {TemplateElement} element
167
+ * @returns {ManifestDeclaration[]}
168
+ */
169
+ export function declarationsFor(index, element) {
170
+ const css = new CssSelector();
171
+ css.setElement(element.name);
172
+ for (const attribute of element.attributes) css.addAttribute(attribute.name, attribute.value ?? '');
173
+ for (const input of element.inputs) if (!isDomBinding(input)) css.addAttribute(input.name, '');
174
+ const classAttribute = element.attributes.find((a) => a.name === 'class');
175
+ for (const name of classAttribute?.value.split(/\s+/).filter(Boolean) ?? []) css.addClassName(name);
176
+ /** @type {ManifestDeclaration[]} */
177
+ const found = [];
178
+ index.matcher.match(css, (_selector, declaration) => {
179
+ if (!found.includes(declaration)) found.push(declaration);
180
+ });
181
+ return found;
182
+ }
183
+
184
+ /**
185
+ * Levenshtein distance, for "did you mean" suggestions.
186
+ * @param {string} a
187
+ * @param {string} b
188
+ */
189
+ function distance(a, b) {
190
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
191
+ for (let i = 1; i <= a.length; i++) {
192
+ let previous = row[0];
193
+ row[0] = i;
194
+ for (let j = 1; j <= b.length; j++) {
195
+ const current = row[j];
196
+ row[j] = Math.min(row[j] + 1, row[j - 1] + 1, previous + (a[i - 1] === b[j - 1] ? 0 : 1));
197
+ previous = current;
198
+ }
199
+ }
200
+ return row[b.length];
201
+ }
202
+
203
+ /**
204
+ * @param {string} name
205
+ * @param {Iterable<string>} candidates
206
+ * @returns {string | null}
207
+ */
208
+ export function closest(name, candidates, max = 3) {
209
+ /** @type {{ candidate: string, d: number } | null} */
210
+ let best = null;
211
+ for (const candidate of candidates) {
212
+ const d = distance(name.toLowerCase(), candidate.toLowerCase());
213
+ if (d <= max && (!best || d < best.d)) best = { candidate, d };
214
+ }
215
+ return best?.candidate ?? null;
216
+ }
@@ -0,0 +1,353 @@
1
+ /**
2
+ * TypeScript rules for app conventions (kit APIs, routes, navigation, the Enghouse runtime
3
+ * contracts), ported from the MFE validators with their original rule ids.
4
+ */
5
+ import { basename } from 'node:path';
6
+ import { appKind, appPath, idRule, languageCount, neighbourText, themeCount } from './app-support.mjs';
7
+
8
+ /**
9
+ * ESTree nodes are read by shape.
10
+ * @typedef {any} Node
11
+ * @typedef {import('eslint').Rule.RuleContext} RuleContext
12
+ */
13
+
14
+ /**
15
+ * Reports the first match of `pattern` in the file, or the file start when `pattern` is null or
16
+ * does not match.
17
+ * @param {RuleContext} context
18
+ * @param {RegExp | null} pattern
19
+ * @param {string} messageId
20
+ */
21
+ function reportAt(context, pattern, messageId) {
22
+ const { sourceCode } = context;
23
+ const match = pattern?.exec(sourceCode.getText());
24
+ const start = match ? match.index : 0;
25
+ const end = match ? start + match[0].length : 0;
26
+ context.report({ loc: { start: sourceCode.getLocFromIndex(start), end: sourceCode.getLocFromIndex(end) }, messageId });
27
+ }
28
+
29
+ /** @param {Node} node */
30
+ const stringValue = (node) => {
31
+ if (node?.type === 'Literal' && typeof node.value === 'string') return node.value;
32
+ if (node?.type === 'TemplateLiteral' && node.expressions.length === 0) return node.quasis[0].value.cooked ?? '';
33
+ return null;
34
+ };
35
+
36
+ /** @param {Node} node */
37
+ const keyName = (node) => (node?.key?.type === 'Identifier' ? node.key.name : stringValue(node?.key));
38
+
39
+ /** SDK_UI_002: Sonner's toast takes a message, not an options object. */
40
+ export const sonnerToastApi = idRule({
41
+ name: 'sonner-toast-api',
42
+ description: 'Call toast.success/info/error(message), not toast({ ... })',
43
+ messages: { SDK_UI_002: 'toast({ ... }) is not the Sonner API: call toast.success(message), toast.info(message) or toast.error(message).' },
44
+ create(context) {
45
+ return {
46
+ /** @param {Node} node */
47
+ CallExpression(node) {
48
+ if (node.callee.type === 'Identifier' && node.callee.name === 'toast' && node.arguments[0]?.type === 'ObjectExpression') {
49
+ context.report({ node, messageId: 'SDK_UI_002' });
50
+ }
51
+ },
52
+ };
53
+ },
54
+ });
55
+
56
+ /** SDK_UI_007: st-* selectors belong to the kit. */
57
+ export const noLocalStSelector = idRule({
58
+ name: 'no-local-st-selector',
59
+ description: 'Reserve the st- selector prefix for kit components',
60
+ messages: { SDK_UI_007: 'Selector "{{selector}}": st-* is reserved for @sixbell-telco/sdk. Use the app prefix (app-*).' },
61
+ create(context) {
62
+ return {
63
+ /** @param {Node} node */
64
+ 'Decorator Property'(node) {
65
+ const selector = stringValue(node.value);
66
+ // A bare st-* element selector declares a new element; `st-button[appX]` only decorates a kit element.
67
+ const declaresElement = selector?.split(',').some((/** @type {string} */ part) => /^\s*st-[\w-]+\s*$/.test(part));
68
+ if (keyName(node) === 'selector' && declaresElement) context.report({ node: node.value, messageId: 'SDK_UI_007', data: { selector } });
69
+ },
70
+ };
71
+ },
72
+ });
73
+
74
+ const DAYJS = /^dayjs(\/.*)?$/;
75
+
76
+ /** MFE_KIT_UTIL_001: use the kit's DateUtils instead of dayjs. */
77
+ export const noDirectDayjs = idRule({
78
+ name: 'no-direct-dayjs',
79
+ description: 'Use DateUtils from @sixbell-telco/sdk/utils/date instead of importing dayjs',
80
+ messages: {
81
+ MFE_KIT_UTIL_001:
82
+ '"{{source}}" imported directly: use DateUtils from @sixbell-telco/sdk/utils/date (format, isValidDate, today, toISODate, addTime, diff ...) or the st-date pipe from @sixbell-telco/sdk/utils/formatting.',
83
+ },
84
+ create(context) {
85
+ /** @param {Node} source */
86
+ const check = (source) => {
87
+ const value = stringValue(source);
88
+ if (value && DAYJS.test(value)) context.report({ node: source, messageId: 'MFE_KIT_UTIL_001', data: { source: value } });
89
+ };
90
+ return {
91
+ /** @param {Node} node */
92
+ ImportDeclaration: (node) => check(node.source),
93
+ /** @param {Node} node */
94
+ ImportExpression: (node) => check(node.source),
95
+ /** @param {Node} node */
96
+ CallExpression(node) {
97
+ if (node.callee.type === 'Identifier' && node.callee.name === 'require') check(node.arguments[0]);
98
+ },
99
+ };
100
+ },
101
+ });
102
+
103
+ /** @param {RuleContext} context */
104
+ const isRoutesFile = (context) => /(^|\/)[^/]*\.routes\.ts$/.test(appPath(context));
105
+
106
+ /** MFE_ROUTE_001, MFE_ROUTE_002, MFE_ROUTE_003: route titles and banner subtitles are set. */
107
+ export const routeMetadata = idRule({
108
+ name: 'route-metadata',
109
+ description: 'Give routes a non-empty title, and banner routes a subtitle',
110
+ messages: {
111
+ MFE_ROUTE_001: 'Route title is empty: set the i18n key of the page title.',
112
+ MFE_ROUTE_002: 'Route data.subtitle is empty: set the i18n key of the page subtitle.',
113
+ MFE_ROUTE_003: 'Routes rendered under GeneralBannerComponent must provide data.subtitle.',
114
+ },
115
+ create(context) {
116
+ if (!isRoutesFile(context)) return {};
117
+ return {
118
+ /** @param {Node} node */
119
+ Property(node) {
120
+ const key = keyName(node);
121
+ const value = stringValue(node.value);
122
+ if (value === null || value.trim() !== '') return;
123
+ if (key === 'title') context.report({ node: node.value, messageId: 'MFE_ROUTE_001' });
124
+ if (key === 'subtitle') context.report({ node: node.value, messageId: 'MFE_ROUTE_002' });
125
+ },
126
+ /** @param {Node} node */
127
+ ObjectExpression(node) {
128
+ const banner = node.properties.find(
129
+ (/** @type {Node} */ property) =>
130
+ keyName(property) === 'component' && property.value?.type === 'Identifier' && property.value.name === 'GeneralBannerComponent',
131
+ );
132
+ if (!banner) return;
133
+ // Lazy children (loadChildren) declare their own data.subtitle in their routes file.
134
+ const text = context.sourceCode.getText(node);
135
+ if (!/\bsubtitle\b/.test(text) && !/\bloadChildren\b/.test(text)) context.report({ node: banner, messageId: 'MFE_ROUTE_003' });
136
+ },
137
+ };
138
+ },
139
+ });
140
+
141
+ /** MFE_ROUTE_006: a PermissionsGuard route declares the permissions it needs. */
142
+ export const routePermissions = idRule({
143
+ name: 'route-permissions',
144
+ type: 'suggestion',
145
+ description: 'Declare data.permissionsRequired on routes guarded by PermissionsGuard',
146
+ messages: {
147
+ MFE_ROUTE_006: 'Route uses PermissionsGuard without data.permissionsRequired (on it or its children): the guard has nothing to check.',
148
+ },
149
+ create(context) {
150
+ if (!isRoutesFile(context)) return {};
151
+ return {
152
+ /** @param {Node} node */
153
+ ObjectExpression(node) {
154
+ const guard = node.properties.find(
155
+ (/** @type {Node} */ property) =>
156
+ ['canActivate', 'canActivateChild'].includes(keyName(property) ?? '') &&
157
+ property.value?.type === 'ArrayExpression' &&
158
+ property.value.elements.some((/** @type {Node} */ element) => element?.type === 'Identifier' && element.name === 'PermissionsGuard'),
159
+ );
160
+ if (guard && !context.sourceCode.getText(node).includes('permissionsRequired')) context.report({ node: guard, messageId: 'MFE_ROUTE_006' });
161
+ },
162
+ };
163
+ },
164
+ });
165
+
166
+ const MENU_PARAM_EXEMPT_TARGET = /(?:auth|logout|offline|server-error|change-password)/i;
167
+ const MENU_PARAM_EXEMPT_CONTEXT = /\bAUTH_EVENTS\b/;
168
+
169
+ /** MFE_NAV_001: in-section navigations keep the `menu` query param (sidebar highlight under a menu-id host). */
170
+ export const navigatePreserveMenu = idRule({
171
+ name: 'navigate-preserve-menu',
172
+ type: 'suggestion',
173
+ description: 'Keep the menu query param on router.navigate (queryParamsHandling)',
174
+ messages: {
175
+ MFE_NAV_001:
176
+ 'Navigation drops the `menu` query param: under a `menu-id` host (SBP) the sidebar item loses its highlight. Add queryParamsHandling: "preserve" (or "merge" when the target sets its own params).',
177
+ },
178
+ create(context) {
179
+ if (/\.(spec|stories)\.ts$/.test(context.physicalFilename)) return {};
180
+ return {
181
+ /** @param {Node} node */
182
+ CallExpression(node) {
183
+ if (node.callee.type !== 'MemberExpression' || node.callee.property?.name !== 'navigate') return;
184
+ const text = context.sourceCode.getText(node);
185
+ const before = context.sourceCode.getText().slice(Math.max(0, node.range[0] - 240), node.range[0]);
186
+ if (text.includes('queryParamsHandling') || MENU_PARAM_EXEMPT_TARGET.test(text) || MENU_PARAM_EXEMPT_CONTEXT.test(before)) return;
187
+ context.report({ node, messageId: 'MFE_NAV_001' });
188
+ },
189
+ };
190
+ },
191
+ });
192
+
193
+ /** @param {RuleContext} context */
194
+ const isNavigationService = (context) => /(^|\/)navigation\/navigation\.service\.ts$/.test(appPath(context));
195
+
196
+ /** MFE_NAV_002: NavigationService never translates an empty title or subtitle key. */
197
+ export const navigationKeyGuard = idRule({
198
+ name: 'navigation-key-guard',
199
+ description: 'Guard empty title and subtitle keys before translation.instant() in NavigationService',
200
+ messages: { MFE_NAV_002: "NavigationService calls instant() without guarding an empty title/subtitle key: return '' for an empty key first." },
201
+ create(context) {
202
+ if (!isNavigationService(context)) return {};
203
+ return {
204
+ Program() {
205
+ const source = context.sourceCode.getText();
206
+ if (!source.includes('.instant(')) return;
207
+ if (/if\s*\([^)]*(key|title|subtitle)[^)]*\)|\?\?|\|\||\b(key|title|subtitle)\w*\s*\?[^.]/i.test(source)) return;
208
+ reportAt(context, /\.instant\(/, 'MFE_NAV_002');
209
+ },
210
+ };
211
+ },
212
+ });
213
+
214
+ /**
215
+ * The body text of a class method, or null when absent.
216
+ * @param {Node} program
217
+ * @param {RuleContext} context
218
+ * @param {string} name
219
+ */
220
+ function methodBody(program, context, name) {
221
+ /** @type {string | null} */
222
+ let found = null;
223
+ /** @param {Node} node */
224
+ const visit = (node) => {
225
+ if (found !== null || !node || typeof node.type !== 'string') return;
226
+ if (node.type === 'MethodDefinition' && node.key?.name === name) {
227
+ found = context.sourceCode.getText(node.value.body);
228
+ return;
229
+ }
230
+ for (const key of ['body', 'declaration']) {
231
+ const child = node[key];
232
+ if (Array.isArray(child)) child.forEach(visit);
233
+ else if (child && typeof child === 'object') visit(child);
234
+ }
235
+ };
236
+ visit(program);
237
+ // `found` is assigned inside the closure, which the type checker does not follow.
238
+ return /** @type {string | null} */ (/** @type {unknown} */ (found));
239
+ }
240
+
241
+ const SET_TOPIC = /PAGE_HEADER_SET|PAGE_HEADER\.SET/;
242
+ const CLEAR_TOPIC = /PAGE_HEADER_CLEAR|PAGE_HEADER\.CLEAR/;
243
+ /** A publish behind a mount check (`if (this.isUnderHostMountPrefix())`, `shouldPublishPageHeaderToHost() &&` ...). */
244
+ const GATED_PUBLISH = /(\bif\s*\([^\n]*\)|&&|\?)\s*\{?\s*PubSub\.publish/;
245
+
246
+ /**
247
+ * MFE_PAGE_HEADER_001, MFE_PAGE_HEADER_002, MFE_PAGE_HEADER_003: the PAGE_HEADER contract between a
248
+ * child's NavigationService (defines the topics, publishes when mounted) and the host's (subscribes).
249
+ */
250
+ export const pageHeaderTopics = idRule({
251
+ name: 'page-header-topics',
252
+ description: 'Keep the PAGE_HEADER publish/subscribe contract in NavigationService',
253
+ messages: {
254
+ MFE_PAGE_HEADER_001: 'PAGE_HEADER_SET / PAGE_HEADER_CLEAR topics are not defined (mfe-page-header.events.ts or an inline enum).',
255
+ MFE_PAGE_HEADER_002:
256
+ 'Child NavigationService must have setPageHeader and clearPageHeader, each publishing with PubSub.publish only when mounted under the host.',
257
+ MFE_PAGE_HEADER_003: 'Host NavigationService.init() must subscribe to the PAGE_HEADER SET and CLEAR topics.',
258
+ },
259
+ create(context) {
260
+ if (!isNavigationService(context)) return {};
261
+ return {
262
+ /** @param {Node} program */
263
+ Program(program) {
264
+ const source = context.sourceCode.getText();
265
+ const kind = appKind(context);
266
+ if (kind === 'child') {
267
+ const combined = `${source}\n${neighbourText(context, 'mfe-page-header.events.ts')}`;
268
+ if (!SET_TOPIC.test(combined) || !CLEAR_TOPIC.test(combined)) reportAt(context, /\bclass\s+NavigationService\b/, 'MFE_PAGE_HEADER_001');
269
+ const bodies = ['setPageHeader', 'clearPageHeader'].map((name) => methodBody(program, context, name));
270
+ if (bodies.some((body) => body === null || !body.includes('PubSub.publish') || !GATED_PUBLISH.test(body))) {
271
+ reportAt(context, /\bsetPageHeader\b|\bclass\s+NavigationService\b/, 'MFE_PAGE_HEADER_002');
272
+ }
273
+ } else if (kind === 'host') {
274
+ const init = methodBody(program, context, 'init') ?? source;
275
+ const helper = /subscribeToPageHeaderEvents/.test(init) ? (methodBody(program, context, 'subscribeToPageHeaderEvents') ?? '') : init;
276
+ if (!SET_TOPIC.test(helper) || !CLEAR_TOPIC.test(helper))
277
+ reportAt(context, /\binit\s*\(|\bclass\s+NavigationService\b/, 'MFE_PAGE_HEADER_003');
278
+ }
279
+ },
280
+ };
281
+ },
282
+ });
283
+
284
+ /** MFE_CHILD_PREF_001: a child's preferences do not show a selector with a single option. */
285
+ export const childPreferenceSelectors = idRule({
286
+ name: 'child-preference-selectors',
287
+ description: 'Hide the child preference selectors when only one language or theme is configured',
288
+ messages: {
289
+ MFE_CHILD_PREF_001: 'Only one {{what}} is configured: set {{flag}} = false.',
290
+ },
291
+ create(context) {
292
+ if (!/(^|\/)core\/preferences\/preferences\.ts$/.test(appPath(context))) return {};
293
+ return {
294
+ /** @param {Node} node */
295
+ 'PropertyDefinition, AssignmentExpression, Property, VariableDeclarator'(node) {
296
+ const name = node.key?.name ?? node.left?.property?.name ?? node.left?.name ?? node.id?.name;
297
+ const value = node.value ?? node.right ?? node.init;
298
+ if (value?.type !== 'Literal' || value.value !== true) return;
299
+ const count = name === 'showLanguageSelector' ? languageCount(context) : name === 'showThemeSelector' ? themeCount(context) : null;
300
+ if (count === null || count > 1) return;
301
+ context.report({
302
+ node,
303
+ messageId: 'MFE_CHILD_PREF_001',
304
+ data: { what: name === 'showLanguageSelector' ? 'language' : 'theme', flag: name },
305
+ });
306
+ },
307
+ };
308
+ },
309
+ });
310
+
311
+ /** MFE_STATUS_001: status pages resolve Home from the menus only. */
312
+ export const statusPageHome = idRule({
313
+ name: 'status-page-home',
314
+ description: 'Resolve the status pages Home route from the menus only, without permissions',
315
+ messages: {
316
+ MFE_STATUS_001: 'Status pages resolve Home from the menus only: do not pass or read permissions (resolveFirstAccessibleRoute(menus)).',
317
+ },
318
+ create(context) {
319
+ if (!/(^|\/)features\/(no-access|not-found|offline|server-error)\//.test(appPath(context))) return {};
320
+ return {
321
+ Program() {
322
+ const pattern = /resolveFirstAccessibleRoute\([^)]*permissions|resolveFirstAccessibleRoute\(\s*menus\s*,|sessionService\.permissions\(\)/i;
323
+ if (pattern.test(context.sourceCode.getText())) reportAt(context, pattern, 'MFE_STATUS_001');
324
+ },
325
+ };
326
+ },
327
+ });
328
+
329
+ /** MFE_TEST_SDK_MOCK_001: the Jest setup does not mock SDK entry points globally. */
330
+ export const testSetupSdkMock = idRule({
331
+ name: 'test-setup-sdk-mock',
332
+ type: 'suggestion',
333
+ description: 'Do not mock @sixbell-telco/sdk entry points in the global Jest setup',
334
+ messages: {
335
+ MFE_TEST_SDK_MOCK_001:
336
+ '{{file}} mocks {{source}} globally: the copy drifts with every SDK release and hides NG0303 in every spec. Mock per spec with ng-mocks, or render the real component.',
337
+ },
338
+ create(context) {
339
+ const file = basename(context.physicalFilename);
340
+ if (!['setup-jest.ts', 'test-setup.ts'].includes(file)) return {};
341
+ return {
342
+ /** @param {Node} node */
343
+ CallExpression(node) {
344
+ const { callee } = node;
345
+ if (callee.type !== 'MemberExpression' || callee.object?.name !== 'jest' || callee.property?.name !== 'mock') return;
346
+ const source = stringValue(node.arguments[0]);
347
+ if (source === '@sixbell-telco/sdk' || source?.startsWith('@sixbell-telco/sdk/')) {
348
+ context.report({ node: node.arguments[0], messageId: 'MFE_TEST_SDK_MOCK_001', data: { file, source } });
349
+ }
350
+ },
351
+ };
352
+ },
353
+ });