@prunellejs/icons 0.1.1 → 0.7.3

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kaynooo
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/llms.txt CHANGED
@@ -12,9 +12,10 @@
12
12
  ## Plugin Setup (`icons(options?)`)
13
13
 
14
14
  - `sets`: optional `Record<string, IconSet>` of custom in-memory sets keyed by prefix.
15
- - `dirs`: optional `Record<string, string>` mapping prefixes to local `.svg` folders relative to app root (e.g. `{ brand: 'assets/brand' }`). `src/icons` is automatically mounted as `~icons/local/<name>` unless overridden; edited files reload in `prunelle dev`.
15
+ - `dirs`: optional `Record<string, string>` mapping prefixes to local `.svg` folders relative to app root (e.g. `{ brand: 'assets/brand' }`). `src/icons` is automatically mounted as `~icons/local/<name>` unless overridden; edited files reload in `prunelle dev`. A file is inlined as is: `prunelle check` warns `[icons/svg-script]` on a `<script>`, an `on*` attribute or a `javascript:` URL in one, and the root paint attributes are escaped.
16
+ - `credited`: optional `readonly string[]` of installed Iconify set prefixes whose licence terms the app has already satisfied (e.g. credited on the legal notice page), silencing `[icons/licence]`.
16
17
  - Install Iconify icon packs as dev dependencies (e.g. `bun add -d @iconify-json/tabler`), then import `~icons/tabler/home`.
17
- - CLI & checks: run `prunelle icons-find <words> [--set <prefix>] [--limit <n>]` instead of guessing names. `prunelle check` and `prunelle build` fail on missing/invalid icons and suggest closest matches.
18
+ - CLI & checks: run `prunelle icons-find <words> [--set <prefix>] [--limit <n>]` instead of guessing names. `prunelle check` and `prunelle build` fail on missing/invalid icons and suggest closest matches; `prunelle check` warns `[icons/licence]` at the first import of any installed set outside the permissive allowlist (MIT, Apache-2.0, ISC, BSD, OFL, MPL, CC0, Unlicense).
18
19
 
19
20
  ## `<Icon>` Component
20
21
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@prunellejs/icons",
3
- "version": "0.1.1",
3
+ "version": "0.7.3",
4
4
  "description": "Compile-time Iconify SVG icon plugin (~icons/<set>/<name>) for Prunelle",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -24,6 +24,6 @@
24
24
  "directory": "packages/plugin-icons"
25
25
  },
26
26
  "peerDependencies": {
27
- "prunelle": "^0.1.1"
27
+ "prunelle": "^0.7.3"
28
28
  }
29
29
  }
package/src/licence.ts ADDED
@@ -0,0 +1,28 @@
1
+ // What an installed Iconify set's licence asks of an app that inlines its icons: nothing for MIT, Apache, ISC, BSD, OFL, MPL, CC0 or the Unlicense, a credit or more for the others.
2
+
3
+ import type { SetInfo } from './sets'
4
+
5
+ const NON_COMMERCIAL_RE = /(?:^|[- ])NC(?:-|$| )/i
6
+ const COPYLEFT_RE = /^(?:A?GPL|LGPL)(?:-|\s|$)|(?:^|[- ])SA(?:-|$| )/i
7
+ const ATTRIBUTION_RE = /^CC[- ]BY(?:[- ]|$)/i
8
+ const PERMISSIVE_SPDX_RE = /^(?:MIT(?:-0)?|Apache-2\.0|ISC|0BSD|BSD-[A-Za-z0-9.-]+|OFL-[A-Za-z0-9.-]+|MPL-[A-Za-z0-9.-]+|CC0-[A-Za-z0-9.-]+|Unlicense)$/i
9
+ const FREE_ALTERNATIVE = 'or use a set under MIT or Apache-2.0'
10
+
11
+ /** Why the set `prefix` needs a look before its icons ship, as the detail and the fix of a warning; undefined when its licence asks nothing. */
12
+ export function licenceProblem(prefix: string, info: SetInfo | undefined): { detail: string, fix: string } | undefined {
13
+ const spdx = info?.license?.spdx?.trim() ?? ''
14
+ const named = `the icon set "${prefix}"${info?.name === undefined ? '' : ` (${info.name})`}`
15
+ if (spdx === '')
16
+ return { detail: `${named} names no licence, so nothing grants the app the use of its icons`, fix: `ask its author for terms, ${FREE_ALTERNATIVE}` }
17
+ const licence = `${named} is under ${info?.license?.title ?? spdx}${info?.license?.url === undefined ? '' : ` (${info.license.url})`}`
18
+ const author = info?.author?.name === undefined ? 'its author' : `${info.author.name}${info.author.url === undefined ? '' : ` (${info.author.url})`}`
19
+ if (NON_COMMERCIAL_RE.test(spdx))
20
+ return { detail: `${licence}, which forbids commercial use`, fix: `use it on a non-commercial site only, ${FREE_ALTERNATIVE}` }
21
+ if (COPYLEFT_RE.test(spdx))
22
+ return { detail: `${licence}, which asks that a work including its icons be shared under the same licence${ATTRIBUTION_RE.test(spdx) ? `, crediting ${author}` : ''}`, fix: `check the app may be, ${FREE_ALTERNATIVE}` }
23
+ if (ATTRIBUTION_RE.test(spdx))
24
+ return { detail: `${licence}, which asks for credit to ${author} wherever its icons show`, fix: `credit it (for instance on the legal notice page) and list "${prefix}" in icons({ credited: [...] }), ${FREE_ALTERNATIVE}` }
25
+ if (PERMISSIVE_SPDX_RE.test(spdx))
26
+ return undefined
27
+ return { detail: `${licence}, which is not a known permissive licence`, fix: `check its terms and list "${prefix}" in icons({ credited: [...] }) once cleared, ${FREE_ALTERNATIVE}` }
28
+ }
package/src/plugin.ts CHANGED
@@ -13,7 +13,8 @@ import { definePlugin } from 'prunelle/config'
13
13
  import { iconData } from './icon-data'
14
14
  import { iconProblem } from './diagnose'
15
15
  import { iconsFind } from './find'
16
- import { installedPrefixes, isSetPrefix, setFile } from './sets'
16
+ import { licenceProblem } from './licence'
17
+ import { installedPrefixes, isSetPrefix, setFile, setInfo } from './sets'
17
18
  import { readSvgDir } from './svg-dir'
18
19
 
19
20
  const ICON_SPEC_RE = /^~icons\/([^/]+)\/(.+)$/
@@ -45,6 +46,8 @@ export interface IconsPluginOptions {
45
46
  sets?: Record<string, IconSet> | undefined
46
47
  /** Folders of `.svg` files read as sets, keyed by prefix, relative to the app root (e.g. `{ brand: 'assets/brand' }`). `src/icons` is the set `local` unless named here. */
47
48
  dirs?: Record<string, string> | undefined
49
+ /** Installed Iconify set prefixes whose licence terms the app has already satisfied (e.g. credited on the legal notice page), silencing `[icons/licence]`. */
50
+ credited?: readonly string[] | undefined
48
51
  }
49
52
 
50
53
  interface PluginLookup extends IconLookup {
@@ -119,10 +122,15 @@ export function icons(options: IconsPluginOptions = {}): PrunellePlugin {
119
122
  ctx.error(`@prunellejs/icons: icons({ dirs }) reads the set "${prefix}" from ${dir}, which does not exist.`)
120
123
  }
121
124
  for (const prefix of lookup.dirs.keys()) {
122
- for (const [name, problem] of (await lookup.dirSet(prefix))?.problems ?? [])
125
+ const dirSet = await lookup.dirSet(prefix)
126
+ for (const [name, problem] of dirSet?.problems ?? [])
123
127
  ctx.error(`${relative(ctx.root, join(lookup.dirs.get(prefix)!, `${name}.svg`))}:1:1: error: @prunellejs/icons: this file ${problem}.`)
128
+ for (const [name, hazard] of dirSet?.hazards ?? [])
129
+ ctx.warn(`${relative(ctx.root, join(lookup.dirs.get(prefix)!, `${name}.svg`))}:1:1: warning: [icons/svg-script] this file holds ${hazard}, which runs once the icon is inlined in a page: remove it from the file, or take the icon from a source you trust.`)
124
130
  }
125
- for (const file of new Bun.Glob('src/**/*.{ts,tsx,mts}').scanSync({ cwd: ctx.root })) {
131
+ // Where each installed set is first imported, for the one warning its licence may need.
132
+ const firstImport = new Map<string, string>()
133
+ for (const file of [...new Bun.Glob('src/**/*.{ts,tsx,mts}').scanSync({ cwd: ctx.root })].sort()) {
126
134
  const code = await Bun.file(join(ctx.root, file)).text()
127
135
  const imported = importedIcons(code, file)
128
136
  for (const found of code.matchAll(ICON_IMPORT_RE)) {
@@ -133,11 +141,22 @@ export function icons(options: IconsPluginOptions = {}): PrunellePlugin {
133
141
  // A broken file is reported once above, not at each import.
134
142
  if (await fileProblem(lookup, ctx.root, prefix!, name!) !== undefined)
135
143
  continue
144
+ const at = `${file}:${lineAndColumn(code, found.index + found[0].length - found[2]!.length - 2)}`
136
145
  const problem = await iconProblem(prefix!, name!, '', lookup)
137
146
  if (problem !== undefined)
138
- ctx.error(`${file}:${lineAndColumn(code, found.index + found[0].length - found[2]!.length - 2)}: error: @prunellejs/icons: ${problem}`)
147
+ ctx.error(`${at}: error: @prunellejs/icons: ${problem}`)
148
+ else if (!lookup.dirs.has(prefix!) && options.sets?.[prefix!] === undefined && !firstImport.has(prefix!))
149
+ firstImport.set(prefix!, at)
139
150
  }
140
151
  }
152
+ const credited = new Set(options.credited ?? [])
153
+ for (const [prefix, at] of firstImport) {
154
+ if (credited.has(prefix))
155
+ continue
156
+ const licence = licenceProblem(prefix, await setInfo(prefix, ctx.root))
157
+ if (licence !== undefined)
158
+ ctx.warn(`${at}: warning: [icons/licence] ${licence.detail}: ${licence.fix}.`)
159
+ }
141
160
  },
142
161
  watchPaths: root => [...lookupIn(root).dirs.values()],
143
162
  bunPlugins: ({ root, target }): BunPlugin[] => [{
package/src/sets.ts CHANGED
@@ -33,6 +33,24 @@ export function setFile(prefix: string, root: string): string | undefined {
33
33
  return undefined
34
34
  }
35
35
 
36
+ /** The metadata of an installed set: Iconify writes it beside `icons.json` as `info.json`, or under `info` in an `@iconify/json` set. */
37
+ export interface SetInfo {
38
+ name?: string | undefined
39
+ author?: { name?: string | undefined, url?: string | undefined } | undefined
40
+ license?: { title?: string | undefined, spdx?: string | undefined, url?: string | undefined } | undefined
41
+ }
42
+
43
+ /** The metadata of the set `prefix` installed for the app at `root`, undefined when it is not installed or carries none. */
44
+ export async function setInfo(prefix: string, root: string): Promise<SetInfo | undefined> {
45
+ const file = setFile(prefix, root)
46
+ if (file === undefined)
47
+ return undefined
48
+ if (basename(file) !== 'icons.json')
49
+ return (await Bun.file(file).json() as { info?: SetInfo }).info
50
+ const info = join(dirname(file), 'info.json')
51
+ return existsSync(info) ? await Bun.file(info).json() as SetInfo : undefined
52
+ }
53
+
36
54
  /** The prefix of every set installed for the app at `root`. */
37
55
  export function installedPrefixes(root: string): string[] {
38
56
  const found = new Set<string>()
package/src/svg-dir.ts CHANGED
@@ -4,8 +4,10 @@ import type { IconifyIcon, IconSet } from './types'
4
4
  import { existsSync } from 'node:fs'
5
5
  import { join } from 'node:path'
6
6
 
7
- const SVG_RE = /<svg\b([^>]*)>([\s\S]*)<\/svg\s*>/i
7
+ const SVG_RE = /<svg\b((?:[^>"']|"[^"]*"|'[^']*')*)>([\s\S]*)<\/svg\s*>/i
8
8
  const ATTR_RE = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g
9
+ const TAG_RE = /<[a-z][\w:-]*(?:[^>"']|"[^"]*"|'[^']*')*>/gi
10
+ const TAG_ATTR_RE = /([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+))/g
9
11
  const COMMENT_RE = /<!--[\s\S]*?-->/g
10
12
  const NUMBER_RE = /^\s*(-?[\d.]+)(?:px)?\s*$/
11
13
  const BOX_SEPARATOR_RE = /[\s,]+/
@@ -16,6 +18,25 @@ export interface SvgDirSet {
16
18
  set: IconSet
17
19
  /** Why a file is not an icon, keyed by the icon name it would have. */
18
20
  problems: Map<string, string>
21
+ /** What a file holds that runs script once inlined, keyed by the icon name; the icon still loads. */
22
+ hazards: Map<string, string>
23
+ }
24
+
25
+ const SCRIPT_TAG_RE = /<script\b/i
26
+ const EVENT_ATTR_RE = /(?:[\s/"'])on[a-z]+\s*=/i
27
+ const HTML_ENTITY_RE = /&(?:#x([0-9a-f]+);?|#(\d+);?|([a-z]+);)/gi
28
+ const JAVASCRIPT_URL_RE = /(?:^|;)javascript:/i
29
+ const VBSCRIPT_URL_RE = /(?:^|;)vbscript:/i
30
+ const DATA_HTML_URL_RE = /(?:^|;)data:text\/html/i
31
+ const NAMED_ENTITIES: Record<string, string> = {
32
+ colon: ':',
33
+ tab: '\t',
34
+ newline: '\n',
35
+ amp: '&',
36
+ lt: '<',
37
+ gt: '>',
38
+ quot: '"',
39
+ apos: '\'',
19
40
  }
20
41
 
21
42
  function attributes(source: string): Map<string, string> {
@@ -30,6 +51,58 @@ function number(value: string | undefined): number | undefined {
30
51
  return match === null ? undefined : Number(match[1])
31
52
  }
32
53
 
54
+ function decodeHtmlEntities(value: string): string {
55
+ return value.replace(HTML_ENTITY_RE, (full, hex?: string, dec?: string, named?: string) => {
56
+ if (hex !== undefined || dec !== undefined) {
57
+ const code = hex !== undefined ? Number.parseInt(hex, 16) : Number.parseInt(dec!, 10)
58
+ return Number.isFinite(code) && code >= 0 && code <= 0x10FFFF ? String.fromCodePoint(code) : ''
59
+ }
60
+ return NAMED_ENTITIES[named!.toLowerCase()] ?? full
61
+ })
62
+ }
63
+
64
+ function stripAsciiControlAndSpace(value: string): string {
65
+ let out = ''
66
+ for (let i = 0; i < value.length; i++) {
67
+ if (value.charCodeAt(i) > 0x20)
68
+ out += value[i]
69
+ }
70
+ return out
71
+ }
72
+
73
+ function urlHazard(rawValue: string): string | undefined {
74
+ const normalized = stripAsciiControlAndSpace(decodeHtmlEntities(rawValue))
75
+ if (JAVASCRIPT_URL_RE.test(normalized))
76
+ return 'a javascript: URL'
77
+ if (VBSCRIPT_URL_RE.test(normalized))
78
+ return 'a vbscript: URL'
79
+ if (DATA_HTML_URL_RE.test(normalized))
80
+ return 'a data:text/html URL'
81
+ return undefined
82
+ }
83
+
84
+ /** What an SVG file's source holds that runs script once the icon is inlined in a page, undefined when it holds none. */
85
+ export function svgHazard(source: string): string | undefined {
86
+ const text = source.replace(COMMENT_RE, '')
87
+ if (SCRIPT_TAG_RE.test(text))
88
+ return 'a <script> element'
89
+ for (const [tag] of text.matchAll(TAG_RE)) {
90
+ const inner = tag.slice(1, -1)
91
+ if (EVENT_ATTR_RE.test(inner))
92
+ return 'an on* event attribute'
93
+ for (const [, , double, single, unquoted] of inner.matchAll(TAG_ATTR_RE)) {
94
+ const hazard = urlHazard(double ?? single ?? unquoted ?? '')
95
+ if (hazard !== undefined)
96
+ return hazard
97
+ }
98
+ }
99
+ return undefined
100
+ }
101
+
102
+ function escapeAttr(value: string): string {
103
+ return value.replaceAll('"', '&quot;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
104
+ }
105
+
33
106
  /** The icon drawn by an SVG file's source, or why it cannot be one. */
34
107
  export function svgIcon(source: string): IconifyIcon | string {
35
108
  const svg = SVG_RE.exec(source.replace(COMMENT_RE, ''))
@@ -41,7 +114,7 @@ export function svgIcon(source: string): IconifyIcon | string {
41
114
  if (width === undefined || height === undefined || width <= 0 || height <= 0)
42
115
  return 'has no viewBox, nor a width and height, to size it: add viewBox="0 0 <width> <height>" to its <svg>'
43
116
 
44
- const paint = [...attrs].filter(([name]) => PAINT_ATTR_RE.test(name)).map(([name, value]) => ` ${name}="${value}"`).join('')
117
+ const paint = [...attrs].filter(([name]) => PAINT_ATTR_RE.test(name)).map(([name, value]) => ` ${name}="${escapeAttr(value)}"`).join('')
45
118
  const body = svg[2]!.trim()
46
119
  return { body: paint === '' ? body : `<g${paint}>${body}</g>`, left: left!, top: top!, width, height }
47
120
  }
@@ -52,13 +125,19 @@ export async function readSvgDir(prefix: string, dir: string): Promise<SvgDirSet
52
125
  return undefined
53
126
  const set: IconSet = { prefix, icons: {} }
54
127
  const problems = new Map<string, string>()
128
+ const hazards = new Map<string, string>()
55
129
  for (const file of new Bun.Glob('*.svg').scanSync({ cwd: dir })) {
56
130
  const name = file.slice(0, -'.svg'.length)
57
- const icon = svgIcon(await Bun.file(join(dir, file)).text())
58
- if (typeof icon === 'string')
131
+ const source = await Bun.file(join(dir, file)).text()
132
+ const icon = svgIcon(source)
133
+ if (typeof icon === 'string') {
59
134
  problems.set(name, icon)
60
- else
61
- set.icons[name] = icon
135
+ continue
136
+ }
137
+ set.icons[name] = icon
138
+ const hazard = svgHazard(source)
139
+ if (hazard !== undefined)
140
+ hazards.set(name, hazard)
62
141
  }
63
- return { set, problems }
142
+ return { set, problems, hazards }
64
143
  }