@open-xchange/app-suite-ui-sdk 0.1.3 → 0.1.5

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.
package/README.md CHANGED
@@ -12,7 +12,7 @@ pnpm exec ui-sdk doctor --fix
12
12
  pnpm install
13
13
  ```
14
14
 
15
- `doctor --fix` removes the tooling the SDK provides from `package.json`, points the scripts at `ui-sdk`, and writes the pnpm settings the SDK needs into `pnpm-workspace.yaml`.
15
+ `doctor --fix` removes the tooling the SDK provides from `package.json`, points the scripts at `ui-sdk`, and writes the pnpm settings the SDK needs into `pnpm-workspace.yaml`. [docs/migration.md](docs/migration.md) walks through moving an existing project, including what doctor leaves to you.
16
16
 
17
17
  For renovate, the project's `renovate.json` only extends the SDK preset:
18
18
 
@@ -36,7 +36,7 @@ The preset automerges updates, and after an SDK bump it runs `ui-sdk doctor --fi
36
36
  | `ui-sdk stylelint` | stylelint | `src/**/*.{scss,css} --allow-empty-input` |
37
37
  | `ui-sdk msgmerge [po] [pot]` | gettext `msgmerge` for each po file | `src/i18n/*.po dist/ox.pot` |
38
38
  | `ui-sdk doctor [--fix]` | checks the project setup, `--fix` writes the changes | |
39
- | `ui-sdk audit [--fix]` | `pnpm audit`, `--fix` applies the SDK security overrides and reinstalls first | |
39
+ | `ui-sdk audit [--fix]` | `pnpm audit`, `--fix` first writes only the SDK security overrides into `pnpm-workspace.yaml` and reinstalls | |
40
40
 
41
41
  Arguments after the command replace the defaults and go straight to the tool, for example `ui-sdk lint src spec --fix`. `msgmerge` needs gettext installed.
42
42
 
@@ -59,6 +59,19 @@ export default defineConfig({
59
59
  })
60
60
  ```
61
61
 
62
+ To copy files into place when vite starts, for example assets from `node_modules` into `public/`, pass `copy` targets. Each match of `src` lands in `dest` under its own name, folders are copied as folders, and `rename` and `transform` change the file name and content:
63
+
64
+ ```js
65
+ defineConfig({
66
+ copy: [
67
+ { src: 'node_modules/pdfjs-dist/cmaps', dest: 'public/pdfjs' },
68
+ { src: 'node_modules/flag-icons/flags/4x3/*', dest: 'public/flags', rename: name => `${name}.webp`, transform: svg => toWebp(svg) }
69
+ ]
70
+ })
71
+ ```
72
+
73
+ With an own vite config, `import copyPlugin from '@open-xchange/app-suite-ui-sdk/vite-plugin-copy'` gives the same plugin.
74
+
62
75
  `defineConfig` builds the usual plugin setup: `src` as root and `dist` as output, the dev proxy to `SERVER` from `.env`, manifests, `$` externals, css and po2json. Vitest runs with jsdom on `spec/**/*_test.{js,mjs}` and `src/**/*.test.{js,mjs}`. `options.vite` and `options.test` are merged over the defaults.
63
76
 
64
77
  ```js
@@ -84,12 +97,13 @@ extends:
84
97
  ## What doctor checks
85
98
 
86
99
  - `packageManager` and `engines.node` match the SDK.
87
- - `package.json` lists no tooling that the SDK or `@open-xchange/lint` provides, and none of the tools the SDK replaced (release-it, lint-staged, simple-git-hooks, husky, eslint-config-standard).
88
- - Scripts call `ui-sdk` instead of the tools. `--fix` rewrites simple cases like `vite build` or `eslint src` and keeps their arguments. Chained scripts get a warning and need a manual change.
89
- - `pnpm-workspace.yaml` has `publicHoistPattern` (so editors and test files find eslint, stylelint, typescript, vite and vitest), `allowBuilds`, `minimumReleaseAgeExclude` for `@open-xchange/*` (pnpm otherwise refuses a freshly released SDK version, which blocks the renovate bump), and the SDK security overrides.
90
- - `lefthook.yml` extends the SDK config.
91
- - `renovate.json` extends the `app-suite-ui-sdk` preset. `--fix` creates the file when it is missing. An existing file without the preset only gets a warning, because projects keep their own rules there.
92
- - rlsy is installed globally. That is a warning only.
100
+ - `devDependencies` lists no tooling that the SDK or `@open-xchange/lint` provides, and none of the tools the SDK replaced (release-it, lint-staged, simple-git-hooks, husky, eslint-config-standard). The same packages in `dependencies` only get a warning, because the project may need them at runtime.
101
+ - Workspace packages from the `packages` list in `pnpm-workspace.yaml` get the same dependency check. Their scripts only get warnings, because the SDK is a dependency of the workspace root. A package without `"private": true` is published and builds on its own, so it keeps its tooling and only gets warnings.
102
+ - Scripts call `ui-sdk` instead of the tools. `--fix` rewrites single commands like `vite build` or `eslint src` and keeps their arguments. Scripts that chain commands, pipe or redirect get a warning and need a manual change.
103
+ - `pnpm-workspace.yaml` has `publicHoistPattern` (so editors and test files find eslint, stylelint, typescript, vite and vitest, and the project's own configs still find every SDK package doctor removed from `package.json`), `allowBuilds`, `minimumReleaseAgeExclude` for `@open-xchange/*` (pnpm otherwise refuses a freshly released SDK version, which blocks the renovate bump), and the SDK security overrides.
104
+ - `lefthook.yml` (or `.lefthook.yml`) extends the SDK config.
105
+ - `renovate.json` (or `.renovaterc.json`, `renovate.json5` and the other names renovate reads) extends the `app-suite-ui-sdk` preset. `--fix` creates the file when it is missing. An existing file without the preset only gets a warning, because projects keep their own rules there.
106
+ - rlsy is installed globally, unless the project has its own `release` script. That is a warning only.
93
107
 
94
108
  `ui-sdk doctor` exits non-zero while errors remain, so a CI job that runs it fails on drift. Add that job to the project's pipeline.
95
109
 
@@ -105,7 +119,7 @@ To add an override by hand, add it here and commit it with the `Security:` prefi
105
119
 
106
120
  Releasing stays out of the SDK. Projects release with a globally installed [rlsy](https://gitlab.com/openxchange/appsuite/web-foundation/rlsy) (`pnpm add -g rlsy`) and get no `release` script.
107
121
 
108
- The SDK itself releases once a week. A scheduled pipeline on `main` runs `rlsy --yes`, which picks the version from the commits since the last release and counts renovate's "Update dependency" commits as changes. A security change does not wait: when a push to `main` brings a commit with `[SECURITY]` (renovate's security updates) or a `Security:` commit, the release job releases right away. Running a pipeline on `main` by hand also releases. The tag the release job pushes starts the publish job.
122
+ The SDK itself releases once a week. A scheduled pipeline on `main` runs `rlsy --yes`, which picks the version from the commits since the last release and counts renovate's "Update dependency" commits as changes. A security change does not wait: when a push to `main` brings a commit with `[SECURITY]` (renovate's security updates) or a `Security:` commit, the release job releases right away. Running a pipeline on `main` by hand also releases, from the GitLab UI or with `glab ci run -b main`. The tag the release job pushes starts the publish job.
109
123
 
110
124
  ## Decisions
111
125
 
@@ -138,6 +152,7 @@ pnpm test:projects vite-vue # only one project
138
152
  - `customer-plugin`: a drifted customer plugin with eslint 8, release-it and no build.
139
153
  - `vite-vue`: vite with Vue, scss, po files and a unit test.
140
154
  - `vite-tailwind`: vite with Tailwind.
155
+ - `ui-like`: shaped like core ui, with a workspace package, its own lefthook and renovate files, a chained build script, a runtime dependency and no vite config.
141
156
 
142
157
  ## License
143
158
 
package/bin/ui-sdk.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { commands } from '../lib/commands.js'
3
- import { doctor } from '../lib/doctor.js'
3
+ import { doctor, syncSecurityOverrides } from '../lib/doctor.js'
4
4
  import { runCommand, sdkPackage } from '../lib/tools.js'
5
5
 
6
6
  const USAGE = `ui-sdk ${sdkPackage.version}
@@ -14,20 +14,23 @@ Usage: ui-sdk <command> [args]
14
14
  stylelint run stylelint (default: src/**/*.{scss,css})
15
15
  msgmerge [po] [pot] merge po files with the pot (default: src/i18n/*.po dist/ox.pot)
16
16
  doctor [--fix] check the project setup against the SDK, --fix writes the changes
17
- audit [--fix] run pnpm audit, --fix applies the SDK security overrides first
17
+ audit [--fix] run pnpm audit, --fix first writes the SDK security overrides and reinstalls
18
18
 
19
19
  Arguments after the command are passed to the underlying tool.`
20
20
 
21
21
  const [name, ...args] = process.argv.slice(2)
22
22
  const cwd = process.cwd()
23
23
 
24
- function audit (fix) {
24
+ function audit (args) {
25
+ const fix = args.includes('--fix')
26
+ const auditArgs = args.filter(arg => arg !== '--fix')
25
27
  if (fix) {
26
- doctor(cwd, { fix: true })
27
- const status = runCommand('pnpm', ['install', '--no-frozen-lockfile'], { cwd })
28
+ const status = syncSecurityOverrides(cwd, { fix: true })
28
29
  if (status !== 0) return status
30
+ const installStatus = runCommand('pnpm', ['install', '--no-frozen-lockfile'], { cwd })
31
+ if (installStatus !== 0) return installStatus
29
32
  }
30
- return runCommand('pnpm', ['audit'], { cwd })
33
+ return runCommand('pnpm', ['audit', ...auditArgs], { cwd })
31
34
  }
32
35
 
33
36
  let status
@@ -40,7 +43,7 @@ if (!name || name === '--help' || name === '-h') {
40
43
  } else if (name === 'doctor') {
41
44
  status = doctor(cwd, { fix: args.includes('--fix') })
42
45
  } else if (name === 'audit') {
43
- status = audit(args.includes('--fix'))
46
+ status = audit(args)
44
47
  } else if (commands[name]) {
45
48
  status = commands[name](cwd, args)
46
49
  } else {
@@ -0,0 +1,35 @@
1
+ import { cp, glob, mkdir, readFile, stat, writeFile } from 'node:fs/promises'
2
+ import path from 'node:path'
3
+
4
+ async function copyMatch (match, { dest, rename, transform }) {
5
+ const { name, ext, base } = path.parse(match)
6
+ const target = path.join(dest, rename ? rename(name, ext.slice(1), match) : base)
7
+ if ((await stat(match)).isDirectory()) {
8
+ await cp(match, target, { recursive: true })
9
+ return
10
+ }
11
+ await mkdir(path.dirname(target), { recursive: true })
12
+ const contents = await readFile(match)
13
+ await writeFile(target, transform ? await transform(contents, base) : contents)
14
+ }
15
+
16
+ /**
17
+ * Copies files and folders into place when vite starts, for dev and build.
18
+ * Every match of a target's `src` globs lands in `dest` under its own name.
19
+ *
20
+ * @param {Array<{src: string|string[], dest: string, rename?: Function, transform?: Function}>} targets
21
+ */
22
+ export default function copyPlugin (targets) {
23
+ return {
24
+ name: 'ox-copy',
25
+ async config () {
26
+ for (const target of targets) {
27
+ for (const pattern of [target.src].flat()) {
28
+ for await (const match of glob(pattern.replace(/\/$/, ''))) {
29
+ await copyMatch(match, target)
30
+ }
31
+ }
32
+ }
33
+ }
34
+ }
35
+ }
package/configs/vite.js CHANGED
@@ -8,6 +8,7 @@ import vitePluginOxExternals from '@open-xchange/vite-plugin-ox-externals'
8
8
  import vitePluginProxy from '@open-xchange/vite-plugin-proxy'
9
9
  import vitePluginOxCss from '@open-xchange/vite-plugin-ox-css'
10
10
  import gettextPlugin from '@open-xchange/vite-plugin-po2json'
11
+ import copyPlugin from './vite-plugin-copy.js'
11
12
 
12
13
  function loadEnv () {
13
14
  for (const file of ['.env', '.env.defaults']) {
@@ -66,6 +67,7 @@ export function proxyConfig (env) {
66
67
  * @param {boolean} [options.tailwind] add @tailwindcss/vite
67
68
  * @param {false|object} [options.gettext] options for @open-xchange/vite-plugin-po2json, false to disable; on by default when src/i18n has po files
68
69
  * @param {object} [options.meta] extra manifest meta data
70
+ * @param {Array} [options.copy] targets for the copy plugin, copied when vite starts
69
71
  * @param {object} [options.test] vitest options, merged over the defaults
70
72
  * @param {import('vite').UserConfig | ((env: import('vite').ConfigEnv) => import('vite').UserConfig)} [options.vite] merged over the generated config
71
73
  */
@@ -73,11 +75,12 @@ export function defineConfig (options = {}) {
73
75
  const {
74
76
  id = readProjectName(),
75
77
  name = id,
76
- entryPoints = ['src/**/*.js'],
78
+ entryPoints = ['src/**/*.js', '!src/**/*.test.js', '!src/**/*.spec.js'],
77
79
  vue = true,
78
80
  tailwind = false,
79
81
  gettext = globSync('src/i18n/*.po').length > 0 && { poFiles: 'src/i18n/*.po', outFile: 'ox.pot', defaultDictionary: id, defaultLanguage: 'en_US' },
80
82
  meta = {},
83
+ copy = [],
81
84
  test = {},
82
85
  vite = {}
83
86
  } = options
@@ -112,12 +115,12 @@ export function defineConfig (options = {}) {
112
115
  },
113
116
  server: {
114
117
  port: env.port,
115
- hmr: { overlay: env.hmr },
118
+ hmr: env.hmr && { overlay: true },
116
119
  https: serving ? { key: env.hostKey, cert: env.hostCrt } : undefined,
117
120
  fs: { strict: env.strictFilesystem }
118
121
  },
119
122
  resolve: {
120
- alias: [{ find: '@/', replacement: '/' }]
123
+ alias: [{ find: '@/', replacement: `${path.resolve('src')}/` }]
121
124
  },
122
125
  plugins: [
123
126
  vue && vitePluginVue(),
@@ -139,7 +142,8 @@ export function defineConfig (options = {}) {
139
142
  }),
140
143
  vitePluginOxExternals({ prefix: '$' }),
141
144
  !testing && vitePluginOxCss(),
142
- gettext && gettextPlugin(gettext)
145
+ gettext && gettextPlugin(gettext),
146
+ !testing && copy.length > 0 && copyPlugin(copy)
143
147
  ].filter(Boolean),
144
148
  test: mergeConfig({
145
149
  root: '.',
package/lib/commands.js CHANGED
@@ -1,14 +1,33 @@
1
- import { globSync } from 'node:fs'
1
+ import { globSync, readFileSync } from 'node:fs'
2
2
  import path from 'node:path'
3
3
  import { findConfig, resolveBin, runCommand, runNode, sdkRoot } from './tools.js'
4
4
 
5
- const VITE_CONFIGS = ['vite.config.js', 'vite.config.mjs', 'vite.config.ts']
6
- const VITEST_CONFIGS = ['vitest.config.js', 'vitest.config.mjs', 'vitest.config.ts', ...VITE_CONFIGS]
7
- const ESLINT_CONFIGS = ['eslint.config.js', 'eslint.config.mjs', 'eslint.config.cjs', 'eslint.config.ts']
8
- const STYLELINT_CONFIGS = ['stylelint.config.js', 'stylelint.config.mjs', '.stylelintrc.json', '.stylelintrc']
5
+ const SCRIPT_EXTENSIONS = ['js', 'mjs', 'cjs', 'ts', 'mts', 'cts']
6
+ const withExtensions = base => SCRIPT_EXTENSIONS.map(ext => `${base}.${ext}`)
9
7
 
10
- function withConfig (cwd, names, fallback, args) {
11
- if (args.includes('--config') || args.includes('-c') || findConfig(cwd, names)) return args
8
+ export const VITE_CONFIGS = withExtensions('vite.config')
9
+ export const VITEST_CONFIGS = [...withExtensions('vitest.config'), ...VITE_CONFIGS]
10
+ export const ESLINT_CONFIGS = withExtensions('eslint.config')
11
+ export const STYLELINT_CONFIGS = [
12
+ ...withExtensions('stylelint.config'),
13
+ ...['', '.json', '.yml', '.yaml', '.js', '.mjs', '.cjs'].map(ext => `.stylelintrc${ext}`)
14
+ ]
15
+
16
+ function hasConfigArg (args) {
17
+ return args.some(arg => arg === '--config' || arg === '-c' || arg.startsWith('--config=') || arg.startsWith('-c='))
18
+ }
19
+
20
+ function hasPackageJsonKey (cwd, key) {
21
+ try {
22
+ return key in JSON.parse(readFileSync(path.join(cwd, 'package.json'), 'utf8'))
23
+ } catch {
24
+ return false
25
+ }
26
+ }
27
+
28
+ export function withConfig (cwd, names, fallback, args, { packageJsonKey } = {}) {
29
+ if (hasConfigArg(args) || findConfig(cwd, names)) return args
30
+ if (packageJsonKey && hasPackageJsonKey(cwd, packageJsonKey)) return args
12
31
  return ['--config', path.join(sdkRoot, 'configs', fallback), ...args]
13
32
  }
14
33
 
@@ -33,7 +52,7 @@ export const commands = {
33
52
 
34
53
  stylelint: (cwd, args) => {
35
54
  const stylelintArgs = args.length ? args : ['src/**/*.{scss,css}', '--allow-empty-input']
36
- return runNode(resolveBin('stylelint'), withConfig(cwd, STYLELINT_CONFIGS, 'stylelint.js', stylelintArgs), { cwd })
55
+ return runNode(resolveBin('stylelint'), withConfig(cwd, STYLELINT_CONFIGS, 'stylelint.js', stylelintArgs, { packageJsonKey: 'stylelint' }), { cwd })
37
56
  },
38
57
 
39
58
  msgmerge: (cwd, args) => {
package/lib/doctor.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from 'node:child_process'
2
- import { existsSync, readFileSync, writeFileSync } from 'node:fs'
2
+ import { existsSync, globSync, readFileSync, writeFileSync } from 'node:fs'
3
3
  import { createRequire } from 'node:module'
4
4
  import path from 'node:path'
5
5
  import { isMap, isScalar, parseDocument, Scalar } from 'yaml'
@@ -15,6 +15,12 @@ export const ALLOW_BUILDS = ['@parcel/watcher', 'lefthook']
15
15
 
16
16
  export const RELEASE_AGE_EXCLUDE = ['@open-xchange/*']
17
17
 
18
+ export const RENOVATE_PRESET = 'local>openxchange/appsuite/web-foundation/renovate:app-suite-ui-sdk'
19
+
20
+ const RENOVATE_FILES = ['renovate.json', 'renovate.json5', '.renovaterc', '.renovaterc.json', '.renovaterc.json5', '.github/renovate.json', '.gitlab/renovate.json']
21
+
22
+ const LEFTHOOK_FILES = ['lefthook.yml', 'lefthook.yaml', '.lefthook.yml', '.lefthook.yaml']
23
+
18
24
  const REPLACED_PACKAGES = [
19
25
  'release-it',
20
26
  '@j-ulrich/release-it-regex-bumper',
@@ -28,75 +34,103 @@ const REPLACED_PACKAGES = [
28
34
  'eslint-plugin-promise'
29
35
  ]
30
36
 
37
+ const SINGLE_ARGS = String.raw`(?:\s+([^&|;<>]*?))?\s*$`
38
+
31
39
  const TOOL_SCRIPTS = {
32
- dev: /^(?:npx )?vite(?:\s+(?!build\b)(.*))?$/,
33
- build: /^(?:npx )?vite build(?:\s+(.*))?$/,
34
- test: /^(?:npx )?vitest(?:\s+(.*))?$|^true$/,
35
- lint: /^(?:npx )?eslint(?:\s+(.*))?$/,
36
- stylelint: /^(?:npx )?stylelint(?:\s+(.*))?$/
40
+ dev: new RegExp(String.raw`^(?:npx )?vite(?!\s+build\b)` + SINGLE_ARGS),
41
+ build: new RegExp(String.raw`^(?:npx )?vite build` + SINGLE_ARGS),
42
+ test: new RegExp(String.raw`^(?:npx )?vitest` + SINGLE_ARGS + '|^true$'),
43
+ lint: new RegExp(String.raw`^(?:npx )?eslint` + SINGLE_ARGS),
44
+ stylelint: new RegExp(String.raw`^(?:npx )?stylelint` + SINGLE_ARGS)
37
45
  }
38
46
 
47
+ const DIRECT_TOOL_CALL = /(?:^|[\s&;|(])(?:npx )?(?:vite|vitest|eslint|stylelint)\b/
48
+
39
49
  function lintDependencies () {
40
50
  const manifest = JSON.parse(readFileSync(require.resolve('@open-xchange/lint/package.json'), 'utf8'))
41
51
  return Object.keys(manifest.dependencies || {})
42
52
  }
43
53
 
54
+ export function installedPackages () {
55
+ return new Set([...Object.keys(sdkPackage.dependencies), ...lintDependencies()])
56
+ }
57
+
44
58
  export function providedPackages () {
45
- return new Set([
46
- ...Object.keys(sdkPackage.dependencies),
47
- ...lintDependencies(),
48
- ...REPLACED_PACKAGES
49
- ])
59
+ return new Set([...installedPackages(), ...REPLACED_PACKAGES])
50
60
  }
51
61
 
52
62
  export function securityOverrides () {
53
63
  return JSON.parse(readFileSync(path.join(sdkRoot, 'security-overrides.json'), 'utf8'))
54
64
  }
55
65
 
56
- export function checkPackageJson (pkg, { provided = providedPackages() } = {}) {
66
+ function asList (value) {
67
+ if (value === undefined || value === null) return []
68
+ return Array.isArray(value) ? value : [value]
69
+ }
70
+
71
+ function packageManagerMatches (actual, expected) {
72
+ return typeof actual === 'string' && actual.split('+')[0] === expected
73
+ }
74
+
75
+ export function checkPackageJson (pkg, { provided = providedPackages(), installed = installedPackages(), root = true } = {}) {
76
+ if (!toolchain.packageManager || !toolchain.node) {
77
+ throw new Error('The SDK package has no toolchain.json; reinstall @open-xchange/app-suite-ui-sdk')
78
+ }
57
79
  const findings = []
80
+ const hoist = new Set()
58
81
  const fixed = structuredClone(pkg)
59
82
 
60
- if (pkg.packageManager !== toolchain.packageManager) {
83
+ if (root && !packageManagerMatches(pkg.packageManager, toolchain.packageManager)) {
61
84
  findings.push({ level: 'error', fixable: true, message: `packageManager is ${pkg.packageManager ?? 'unset'}, expected ${toolchain.packageManager}` })
62
85
  fixed.packageManager = toolchain.packageManager
63
86
  }
64
87
 
65
- if (pkg.engines?.node !== toolchain.node) {
88
+ if (root && pkg.engines?.node !== toolchain.node) {
66
89
  findings.push({ level: 'error', fixable: true, message: `engines.node is ${pkg.engines?.node ?? 'unset'}, expected ${toolchain.node}` })
67
90
  fixed.engines = { ...pkg.engines, node: toolchain.node }
68
91
  }
69
92
 
70
- for (const field of ['dependencies', 'devDependencies']) {
71
- for (const name of Object.keys(pkg[field] || {})) {
72
- if (!provided.has(name)) continue
73
- findings.push({ level: 'error', fixable: true, message: `${field} lists ${name}, which the SDK provides` })
74
- delete fixed[field][name]
93
+ const published = !root && pkg.private !== true
94
+ for (const name of Object.keys(pkg.devDependencies || {})) {
95
+ if (!provided.has(name)) continue
96
+ if (published) {
97
+ findings.push({ level: 'warn', fixable: false, message: `devDependencies lists ${name}, which the SDK provides; kept, because the package is published and builds on its own` })
98
+ continue
75
99
  }
100
+ findings.push({ level: 'error', fixable: true, message: `devDependencies lists ${name}, which the SDK provides` })
101
+ delete fixed.devDependencies[name]
102
+ if (installed.has(name)) hoist.add(name)
76
103
  }
77
104
 
78
- if (!pkg.devDependencies?.[sdkPackage.name] && !pkg.dependencies?.[sdkPackage.name]) {
105
+ for (const name of Object.keys(pkg.dependencies || {})) {
106
+ if (!provided.has(name)) continue
107
+ findings.push({ level: 'warn', fixable: false, message: `dependencies lists ${name}, which the SDK also provides; keep it if the project needs it at runtime, otherwise remove it by hand` })
108
+ }
109
+
110
+ if (root && !pkg.devDependencies?.[sdkPackage.name] && !pkg.dependencies?.[sdkPackage.name]) {
79
111
  findings.push({ level: 'error', fixable: true, message: `devDependencies does not list ${sdkPackage.name}` })
80
112
  fixed.devDependencies = { ...fixed.devDependencies, [sdkPackage.name]: sdkPackage.version }
81
113
  }
82
114
 
83
115
  for (const [name, command] of Object.entries(pkg.scripts || {})) {
84
116
  const pattern = TOOL_SCRIPTS[name]
85
- if (pattern) {
86
- const match = command.match(pattern)
87
- if (match) {
88
- const args = match[1]
89
- fixed.scripts[name] = args ? `ui-sdk ${name} ${args}` : `ui-sdk ${name}`
90
- findings.push({ level: 'error', fixable: true, message: command === 'true' ? `script "${name}" is a placeholder` : `script "${name}" runs the tool directly: ${command}` })
91
- continue
92
- }
117
+ const match = pattern && command.match(pattern)
118
+ if (match && !root) {
119
+ findings.push({ level: 'warn', fixable: false, message: `script "${name}" runs the tool directly; the SDK is only a dependency of the workspace root: ${command}` })
120
+ continue
121
+ }
122
+ if (match) {
123
+ const args = match[1]
124
+ fixed.scripts[name] = args ? `ui-sdk ${name} ${args}` : `ui-sdk ${name}`
125
+ findings.push({ level: 'error', fixable: true, message: command === 'true' ? `script "${name}" is a placeholder` : `script "${name}" runs the tool directly: ${command}` })
126
+ continue
93
127
  }
94
128
  if (/\b(?:release-it|simple-git-hooks|husky|lint-staged)\b/.test(command)) {
95
129
  delete fixed.scripts[name]
96
130
  findings.push({ level: 'error', fixable: true, message: `script "${name}" uses a tool the SDK replaced: ${command}` })
97
131
  continue
98
132
  }
99
- if (!command.startsWith('ui-sdk ') && /(?:^|[\s&;|])(?:npx )?(?:vite|vitest|eslint|stylelint)\b/.test(command)) {
133
+ if (DIRECT_TOOL_CALL.test(command.replace(/\bui-sdk \w+/g, ''))) {
100
134
  findings.push({ level: 'warn', fixable: false, message: `script "${name}" calls a tool directly, switch it to ui-sdk by hand: ${command}` })
101
135
  }
102
136
  }
@@ -104,12 +138,23 @@ export function checkPackageJson (pkg, { provided = providedPackages() } = {}) {
104
138
  if (fixed.devDependencies && !Object.keys(fixed.devDependencies).length) delete fixed.devDependencies
105
139
  if (fixed.dependencies && !Object.keys(fixed.dependencies).length) delete fixed.dependencies
106
140
 
107
- return { findings, fixed }
141
+ return { findings, fixed, hoist: [...hoist].sort() }
142
+ }
143
+
144
+ function globToRegExp (pattern) {
145
+ return new RegExp('^' + pattern.split('*').map(part => part.replace(/[.+?^${}()|[\]\\/]/g, '\\$&')).join('.*') + '$')
146
+ }
147
+
148
+ function coveredBy (entry, patterns) {
149
+ return patterns.some(pattern => pattern === entry || (pattern.includes('*') && globToRegExp(pattern).test(entry)))
108
150
  }
109
151
 
110
152
  function ensureList (doc, key, required, findings) {
111
- const current = doc.get(key)?.toJSON?.() ?? []
112
- const missing = required.filter(entry => !current.includes(entry))
153
+ const current = asList(doc.get(key)?.toJSON?.() ?? doc.get(key))
154
+ const missing = []
155
+ for (const entry of required) {
156
+ if (!coveredBy(entry, [...current, ...missing])) missing.push(entry)
157
+ }
113
158
  if (!missing.length) return
114
159
  findings.push({ level: 'error', fixable: true, message: `${key} misses ${missing.join(', ')}` })
115
160
  doc.set(key, [...current, ...missing])
@@ -127,6 +172,11 @@ function isManaged (node) {
127
172
  return isScalar(node) && node.comment?.trim() === MANAGED_MARK
128
173
  }
129
174
 
175
+ function markManaged (node) {
176
+ node.comment = ` ${MANAGED_MARK}`
177
+ return node
178
+ }
179
+
130
180
  function syncOverrides (doc, wanted, findings) {
131
181
  let overrides = doc.get('overrides', true)
132
182
  if (!isMap(overrides)) {
@@ -144,8 +194,11 @@ function syncOverrides (doc, wanted, findings) {
144
194
 
145
195
  for (const [key, version] of Object.entries(wanted)) {
146
196
  const node = overrides.get(key, true)
147
- if (isScalar(node) && node.value === version) {
148
- if (!isManaged(node)) findings.push({ level: 'warn', fixable: false, message: `override ${key} matches the SDK but is not marked as managed` })
197
+ if (isScalar(node) && String(node.value) === version) {
198
+ if (!isManaged(node)) {
199
+ findings.push({ level: 'error', fixable: true, message: `override ${key} matches the SDK and becomes managed` })
200
+ markManaged(node)
201
+ }
149
202
  continue
150
203
  }
151
204
  if (node && !isManaged(node)) {
@@ -153,42 +206,40 @@ function syncOverrides (doc, wanted, findings) {
153
206
  continue
154
207
  }
155
208
  findings.push({ level: 'error', fixable: true, message: `security override ${key}: ${version} is missing` })
156
- const scalar = new Scalar(version)
157
- scalar.comment = ` ${MANAGED_MARK}`
158
- overrides.set(key, scalar)
209
+ overrides.set(key, markManaged(new Scalar(version)))
159
210
  }
160
211
 
161
212
  if (!overrides.items.length) doc.delete('overrides')
162
213
  }
163
214
 
164
- export function checkWorkspace (source, { overrides = securityOverrides() } = {}) {
215
+ export function checkWorkspace (source, { overrides = securityOverrides(), hoist = [], settings = true } = {}) {
165
216
  const findings = []
166
217
  const doc = parseDocument(source || '')
167
218
  if (doc.contents === null) doc.contents = doc.createNode({})
168
- ensureList(doc, 'publicHoistPattern', PUBLIC_HOIST_PATTERN, findings)
169
- ensureList(doc, 'minimumReleaseAgeExclude', RELEASE_AGE_EXCLUDE, findings)
170
- ensureAllowBuilds(doc, findings)
219
+ if (settings) {
220
+ ensureList(doc, 'publicHoistPattern', [...PUBLIC_HOIST_PATTERN, ...hoist], findings)
221
+ ensureList(doc, 'minimumReleaseAgeExclude', RELEASE_AGE_EXCLUDE, findings)
222
+ ensureAllowBuilds(doc, findings)
223
+ }
171
224
  syncOverrides(doc, overrides, findings)
172
225
  return { findings, fixed: doc.toString({ singleQuote: true }) }
173
226
  }
174
227
 
175
- export function checkLefthook (source) {
228
+ export function checkLefthook (source, name = 'lefthook.yml') {
176
229
  const extendsPath = `node_modules/${sdkPackage.name}/configs/lefthook.yml`
177
230
  if (source === undefined) {
178
231
  return {
179
- findings: [{ level: 'error', fixable: true, message: 'lefthook.yml is missing' }],
232
+ findings: [{ level: 'error', fixable: true, message: `${name} is missing` }],
180
233
  fixed: `extends:\n - ${extendsPath}\n`
181
234
  }
182
235
  }
183
236
  const doc = parseDocument(source)
184
- const current = doc.get('extends')?.toJSON?.() ?? []
237
+ const current = asList(doc.get('extends')?.toJSON?.() ?? doc.get('extends'))
185
238
  if (current.includes(extendsPath)) return { findings: [], fixed: source }
186
- return { findings: [{ level: 'warn', fixable: false, message: `lefthook.yml does not extend ${extendsPath}` }], fixed: source }
239
+ return { findings: [{ level: 'warn', fixable: false, message: `${name} does not extend ${extendsPath}` }], fixed: source }
187
240
  }
188
241
 
189
- export const RENOVATE_PRESET = 'local>openxchange/appsuite/web-foundation/renovate:app-suite-ui-sdk'
190
-
191
- export function checkRenovate (source) {
242
+ export function checkRenovate (source, name = 'renovate.json') {
192
243
  if (source === undefined) {
193
244
  return {
194
245
  findings: [{ level: 'error', fixable: true, message: 'renovate.json is missing' }],
@@ -198,58 +249,99 @@ export function checkRenovate (source) {
198
249
  }, null, 2) + '\n'
199
250
  }
200
251
  }
252
+ if (name.endsWith('.json5') || name === '.renovaterc') {
253
+ if (source.includes(RENOVATE_PRESET)) return { findings: [], fixed: source }
254
+ return { findings: [{ level: 'warn', fixable: false, message: `${name} does not mention ${RENOVATE_PRESET}` }], fixed: source }
255
+ }
201
256
  let config
202
257
  try {
203
258
  config = JSON.parse(source)
204
259
  } catch {
205
- return { findings: [{ level: 'error', fixable: false, message: 'renovate.json is not valid JSON' }], fixed: source }
260
+ return { findings: [{ level: 'error', fixable: false, message: `${name} is not valid JSON` }], fixed: source }
206
261
  }
207
- if ((config.extends || []).includes(RENOVATE_PRESET)) return { findings: [], fixed: source }
208
- return { findings: [{ level: 'warn', fixable: false, message: `renovate.json does not extend ${RENOVATE_PRESET}` }], fixed: source }
262
+ if (asList(config.extends).includes(RENOVATE_PRESET)) return { findings: [], fixed: source }
263
+ return { findings: [{ level: 'warn', fixable: false, message: `${name} does not extend ${RENOVATE_PRESET}` }], fixed: source }
209
264
  }
210
265
 
211
266
  function readIfExists (file) {
212
267
  return existsSync(file) ? readFileSync(file, 'utf8') : undefined
213
268
  }
214
269
 
270
+ function firstExisting (cwd, names) {
271
+ return names.find(name => existsSync(path.join(cwd, name)))
272
+ }
273
+
215
274
  function hasCommand (name) {
216
275
  return spawnSync(process.platform === 'win32' ? 'where' : 'which', [name], { stdio: 'ignore' }).status === 0
217
276
  }
218
277
 
219
- export function doctor (cwd, { fix = false, log = console.log } = {}) {
220
- const files = {
221
- 'package.json': path.join(cwd, 'package.json'),
222
- 'pnpm-workspace.yaml': path.join(cwd, 'pnpm-workspace.yaml'),
223
- 'lefthook.yml': path.join(cwd, 'lefthook.yml'),
224
- 'renovate.json': path.join(cwd, 'renovate.json')
225
- }
226
-
227
- const pkgSource = readFileSync(files['package.json'], 'utf8')
228
- const results = {
229
- 'package.json': (() => {
230
- const { findings, fixed } = checkPackageJson(JSON.parse(pkgSource))
231
- return { findings, fixed: JSON.stringify(fixed, null, 2) + '\n' }
232
- })(),
233
- 'pnpm-workspace.yaml': checkWorkspace(readIfExists(files['pnpm-workspace.yaml'])),
234
- 'lefthook.yml': checkLefthook(readIfExists(files['lefthook.yml'])),
235
- 'renovate.json': checkRenovate(readIfExists(files['renovate.json']))
236
- }
237
-
238
- const general = []
239
- if (!hasCommand('rlsy')) general.push({ level: 'warn', fixable: false, message: 'rlsy is not installed globally (pnpm add -g rlsy); releases need it' })
278
+ export function workspacePackages (cwd, workspaceSource) {
279
+ const patterns = asList(parseDocument(workspaceSource || '').toJSON()?.packages)
280
+ const include = patterns.filter(p => !p.startsWith('!'))
281
+ const exclude = patterns.filter(p => p.startsWith('!')).map(p => p.slice(1))
282
+ if (!include.length) return []
283
+ const manifests = globSync(include.map(p => `${p.replace(/\/$/, '')}/package.json`), { cwd, exclude: exclude.map(p => `${p.replace(/\/$/, '')}/package.json`) })
284
+ return manifests.filter(file => !file.split(path.sep).includes('node_modules')).sort()
285
+ }
240
286
 
287
+ function report (results, { fix, log }) {
241
288
  let remainingErrors = 0
242
- for (const [name, { findings, fixed }] of Object.entries(results)) {
289
+ for (const { label, file, findings, fixed } of results) {
243
290
  for (const finding of findings) {
244
291
  const applied = fix && finding.fixable
245
292
  if (finding.level === 'error' && !applied) remainingErrors++
246
- log(`${applied ? 'fixed' : finding.level} ${name}: ${finding.message}`)
293
+ log(`${applied ? 'fixed' : finding.level} ${label}: ${finding.message}`)
247
294
  }
248
- if (fix && findings.some(finding => finding.fixable)) writeFileSync(files[name], fixed)
295
+ if (fix && file && findings.some(finding => finding.fixable)) writeFileSync(file, fixed)
249
296
  }
250
- for (const finding of general) log(`${finding.level} ${finding.message}`)
297
+ return remainingErrors
298
+ }
299
+
300
+ function toJson (value) {
301
+ return JSON.stringify(value, null, 2) + '\n'
302
+ }
303
+
304
+ export function syncSecurityOverrides (cwd, { fix = false, log = console.log } = {}) {
305
+ const file = path.join(cwd, 'pnpm-workspace.yaml')
306
+ const result = checkWorkspace(readIfExists(file), { settings: false })
307
+ return report([{ label: 'pnpm-workspace.yaml', file, ...result }], { fix, log }) ? 1 : 0
308
+ }
309
+
310
+ export function doctor (cwd, { fix = false, log = console.log } = {}) {
311
+ const workspaceFile = path.join(cwd, 'pnpm-workspace.yaml')
312
+ const workspaceSource = readIfExists(workspaceFile)
313
+ const rootManifest = path.join(cwd, 'package.json')
314
+ const rootPkg = JSON.parse(readFileSync(rootManifest, 'utf8'))
315
+
316
+ const results = []
317
+ const hoist = new Set()
318
+
319
+ const rootResult = checkPackageJson(rootPkg)
320
+ rootResult.hoist.forEach(name => hoist.add(name))
321
+ results.push({ label: 'package.json', file: rootManifest, findings: rootResult.findings, fixed: toJson(rootResult.fixed) })
322
+
323
+ for (const relative of workspacePackages(cwd, workspaceSource)) {
324
+ const file = path.join(cwd, relative)
325
+ const result = checkPackageJson(JSON.parse(readFileSync(file, 'utf8')), { root: false })
326
+ result.hoist.forEach(name => hoist.add(name))
327
+ results.push({ label: relative, file, findings: result.findings, fixed: toJson(result.fixed) })
328
+ }
329
+
330
+ results.push({ label: 'pnpm-workspace.yaml', file: workspaceFile, ...checkWorkspace(workspaceSource, { hoist: [...hoist].sort() }) })
331
+
332
+ const lefthookName = firstExisting(cwd, LEFTHOOK_FILES) ?? 'lefthook.yml'
333
+ results.push({ label: lefthookName, file: path.join(cwd, lefthookName), ...checkLefthook(readIfExists(path.join(cwd, lefthookName)), lefthookName) })
334
+
335
+ const renovateName = firstExisting(cwd, RENOVATE_FILES) ?? 'renovate.json'
336
+ results.push({ label: renovateName, file: path.join(cwd, renovateName), ...checkRenovate(readIfExists(path.join(cwd, renovateName)), renovateName) })
337
+
338
+ if (!rootPkg.scripts?.release && !hasCommand('rlsy')) {
339
+ results.push({ label: 'release', findings: [{ level: 'warn', fixable: false, message: 'rlsy is not installed globally (pnpm add -g rlsy); releases need it' }] })
340
+ }
341
+
342
+ const remainingErrors = report(results, { fix, log })
251
343
 
252
- if (fix && results['package.json'].findings.some(finding => finding.fixable)) {
344
+ if (fix && results.some(({ file, findings }) => file?.endsWith('package.json') && findings.some(finding => finding.fixable))) {
253
345
  log('Run pnpm install to apply the changes.')
254
346
  }
255
347
  return remainingErrors ? 1 : 0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@open-xchange/app-suite-ui-sdk",
3
- "version": "0.1.3",
3
+ "version": "0.1.5",
4
4
  "description": "Shared build, lint and test tooling for OX App Suite UI projects",
5
5
  "type": "module",
6
6
  "bin": {
@@ -8,6 +8,7 @@
8
8
  },
9
9
  "exports": {
10
10
  "./vite": "./configs/vite.js",
11
+ "./vite-plugin-copy": "./configs/vite-plugin-copy.js",
11
12
  "./eslint": "./configs/eslint.js",
12
13
  "./stylelint": "./configs/stylelint.js",
13
14
  "./lefthook.yml": "./configs/lefthook.yml",
@@ -37,22 +38,22 @@
37
38
  "@open-xchange/vite-plugin-ox-bundle": "1.0.1",
38
39
  "@open-xchange/vite-plugin-ox-css": "1.0.2",
39
40
  "@open-xchange/vite-plugin-ox-externals": "1.0.1",
40
- "@open-xchange/vite-plugin-ox-manifests": "1.0.6",
41
- "@open-xchange/vite-plugin-po2json": "1.1.6",
41
+ "@open-xchange/vite-plugin-ox-manifests": "1.0.7",
42
+ "@open-xchange/vite-plugin-po2json": "1.1.7",
42
43
  "@open-xchange/vite-plugin-proxy": "1.0.5",
43
44
  "@tailwindcss/vite": "4.3.3",
44
45
  "@vitejs/plugin-vue": "6.0.10",
45
46
  "@vitest/coverage-v8": "5.0.5",
46
47
  "jsdom": "30.1.3",
47
48
  "lefthook": "2.2.2",
48
- "postcss": "8.5.30",
49
- "sass": "1.105.1",
49
+ "postcss": "8.5.32",
50
+ "sass": "1.107.1",
50
51
  "stylelint": "17.16.0",
51
52
  "stylelint-config-standard": "40.0.0",
52
53
  "stylelint-config-standard-scss": "17.0.0",
53
54
  "tailwindcss": "4.3.3",
54
55
  "typescript": "7.0.2",
55
- "vite": "8.3.4",
56
+ "vite": "8.3.5",
56
57
  "vitest": "5.0.5",
57
58
  "yaml": "2.9.1"
58
59
  },
@@ -61,7 +62,7 @@
61
62
  },
62
63
  "scripts": {
63
64
  "lint": "node bin/ui-sdk.js lint",
64
- "test": "vitest --run",
65
+ "test": "vitest --run --dir test",
65
66
  "test:projects": "node scripts/test-projects.js",
66
67
  "security:overrides": "node scripts/security-overrides.js"
67
68
  }