@driftime/sanity-plugin-icon 0.4.3 → 0.5.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.
- package/README.md +2 -0
- package/dist/{adapters-Bx_MyEX_.js → adapters-Dw6yeA3A.js} +2 -3
- package/dist/{adapters-Bx_MyEX_.js.map → adapters-Dw6yeA3A.js.map} +1 -1
- package/dist/index.js +3 -4
- package/dist/index.js.map +1 -1
- package/dist/loader-2g6inuO6.js +96 -0
- package/dist/loader-2g6inuO6.js.map +1 -0
- package/dist/next-loader.d.ts.map +1 -1
- package/dist/next-loader.js +3 -72
- package/dist/next-loader.js.map +1 -1
- package/dist/next.d.ts +3 -2
- package/dist/next.d.ts.map +1 -1
- package/dist/next.js +9 -8
- package/dist/next.js.map +1 -1
- package/dist/{nodes-DAzj56Xn.js → nodes-Bn7fLVZO.js} +47 -3
- package/dist/nodes-Bn7fLVZO.js.map +1 -0
- package/dist/read-worker.js +2 -2
- package/dist/render.js +2 -3
- package/dist/render.js.map +1 -1
- package/dist/{sets-B2lHNI7c.js → sets-B5arQvrZ.js} +58 -6
- package/dist/sets-B5arQvrZ.js.map +1 -0
- package/dist/{sets-BFcRq7dc.js → sets-DH5UbUV_.js} +13 -4
- package/dist/sets-DH5UbUV_.js.map +1 -0
- package/dist/{types-v7Qz7ogk.js → types-CmTEhJK6.js} +3 -5
- package/dist/{types-v7Qz7ogk.js.map → types-CmTEhJK6.js.map} +1 -1
- package/dist/vite.js +2 -3
- package/dist/vite.js.map +1 -1
- package/package.json +1 -1
- package/dist/nodes-DAzj56Xn.js.map +0 -1
- package/dist/registry-B0Dxiwhh.js +0 -68
- package/dist/registry-B0Dxiwhh.js.map +0 -1
- package/dist/registry-BEEpqK3z.js +0 -13
- package/dist/registry-BEEpqK3z.js.map +0 -1
- package/dist/sets-B2lHNI7c.js.map +0 -1
- package/dist/sets-BFcRq7dc.js.map +0 -1
- package/dist/utils-COPacfAq.js +0 -48
- package/dist/utils-COPacfAq.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types-v7Qz7ogk.js","names":["isDefined","ComponentProps","ReactElement","createElement","IconDrawing","IconElement","iconSvgAttributes","toProps","style","attributes","Record","declarations","split","flatMap","declaration","property","value","name","trim","joined","join","key","startsWith","replace","replaceAll","_match","letter","toUpperCase","Object","fromEntries","renderChild","child","index","element","children","String","map","nested","position","DrawingProps","Omit","drawing","Drawing","props","root","node","iconRegistry","convertCase","isDefined","IconDrawing","getIconSetKey","parseIconSet","LibraryIcon","name","label","tags","drawing","terms","LibraryProblem","title","description","LibraryResult","icons","problem","normalizeTerms","value","toLowerCase","replaceAll","trim","splitMatches","text","query","start","match","pattern","split","map","word","String","raw","join","parts","RegExp","part","index","slice","length","selectIcons","library","names","byName","Map","icon","Set","flatMap","get","formatList","identifiers","identifier","describeMissingLibrary","packageName","family","listed","sitePackage","readLibrary","style","Promise","ready","info","libraries","Object","keys","packagePrefix","styles","installed","resolvedStyle","loader","sets","module","set","default","keywords","node","root","libraryRequests","requestLibrary","key","request","result","SanityIconNames","iconLibraryStyles","iconTypeName","SanityIcon","_type","library","style","name","node","IconLibraryStyles","SanityIconLibrary","SanityIconStyle","Library","SanityIconName","ListedLibraryId","NonNullable","Extract","IconLibraryId"],"sources":["../src/components/drawing.tsx","../src/lib/library.ts","../src/types.ts"],"sourcesContent":["// Consumers render this in server components, where the compiler's memo cache hook can't run.\n\"use no memo\";\n\nimport { isDefined } from \"@repo/lib/utils\";\nimport type { ComponentProps, ReactElement } from \"react\";\nimport { createElement } from \"react\";\n\nimport type { IconDrawing, IconElement } from \"@/lib/nodes\";\nimport { iconSvgAttributes } from \"@/lib/nodes\";\n\n/**\n * Converts stored attributes to React props, turning a `style` attribute into the object React expects.\n *\n * @param attributes - The stored attributes.\n * @returns The props.\n */\nfunction toProps({ style, ...attributes }: Record<string, string>) {\n if (!isDefined(style)) return attributes;\n\n const declarations = style.split(\";\").flatMap((declaration): [string, string][] => {\n const [property = \"\", ...value] = declaration.split(\":\");\n const name = property.trim();\n const joined = value.join(\":\").trim();\n if (!isDefined(name) || !isDefined(joined)) return [];\n\n const key = name.startsWith(\"--\")\n ? name\n : name\n .replace(/^-ms-/u, \"ms-\")\n .replaceAll(/-(?<letter>[a-z])/gu, (_match, letter: string) => letter.toUpperCase());\n\n return [[key, joined]];\n });\n\n return { ...attributes, style: Object.fromEntries(declarations) };\n}\n\n/**\n * Draws one element of a stored drawing, with its children.\n *\n * @param child - The element, or text inside one.\n * @param index - Its position among its siblings.\n * @returns The element.\n */\nfunction renderChild(child: IconElement | string, index: number): ReactElement | string {\n if (typeof child === \"string\") return child;\n\n const [element, attributes, children] = child;\n\n return createElement(\n element,\n { ...toProps(attributes), key: String(index) },\n children?.map((nested, position) => renderChild(nested, position)),\n );\n}\n\nexport type DrawingProps = Omit<ComponentProps<\"svg\">, \"children\"> & { drawing: IconDrawing | undefined };\n\nexport function Drawing({ drawing, ...props }: DrawingProps) {\n if (!isDefined(drawing)) return null;\n\n // Stored roots only hold checked attribute names, but their values are text, not React's literal types.\n const root = toProps(drawing.root) as ComponentProps<\"svg\">;\n\n return (\n <svg {...iconSvgAttributes} {...root} aria-hidden=\"true\" {...props}>\n {drawing.node.map((child, index) => renderChild(child, index))}\n </svg>\n );\n}\n","import { iconRegistry } from \"@driftime/sanity-plugin-icon/sets\";\nimport { convertCase, isDefined } from \"@repo/lib/utils\";\n\nimport type { IconDrawing } from \"@/lib/nodes\";\nimport { getIconSetKey } from \"@/lib/registry\";\nimport { parseIconSet } from \"@/lib/sets\";\n\n/** Icon in the library, with the terms a search matches against. */\nexport interface LibraryIcon {\n /** Name of the icon in its library. */\n name: string;\n /** Readable form of the name. */\n label: string;\n /** Keywords describing the icon, as a comma-separated list. */\n tags: string;\n /** The icon's shapes and the SVG attributes they're drawn inside. */\n drawing: IconDrawing;\n /** Name and keywords, normalised for search. */\n terms: string;\n}\n\n/** Why a library's icons can't be shown, and what to do about it, with code marked by backticks. */\nexport interface LibraryProblem {\n /** What's wrong, in a few words. */\n title: string;\n /** What to do about it. */\n description: string;\n}\n\n/** Outcome of loading a library: its icons, or why they can't be shown. */\nexport type LibraryResult =\n | { icons: LibraryIcon[]; problem?: undefined }\n | { icons?: undefined; problem: LibraryProblem };\n\n/**\n * Normalises text for search, so hyphenated names and multi-word keywords match the same way.\n *\n * @param value - The text.\n * @returns The normalised text.\n */\nexport function normalizeTerms(value: string) {\n return value\n .toLowerCase()\n .replaceAll(/[\\s-]+/gu, \" \")\n .trim();\n}\n\n/**\n * Splits text into the parts a search matches and the parts it doesn't, matching the way search does: ignoring case,\n * and treating spaces and hyphens alike.\n *\n * @param text - The text to split.\n * @param query - The normalised search.\n * @returns The parts in order, each with where it starts in the text and whether it matches.\n */\nexport function splitMatches(text: string, query: string) {\n if (!isDefined(query)) return [{ text, start: 0, match: false }];\n\n const pattern = query\n .split(\" \")\n .map((word) => word.replaceAll(/[$()*+.?[\\\\\\]^{|}]/gu, String.raw`\\$&`))\n .join(String.raw`[\\s-]+`);\n\n const parts = text.split(new RegExp(`(${pattern})`, \"giu\"));\n\n return parts.map((part, index) => ({\n text: part,\n start: parts.slice(0, index).join(\"\").length,\n match: index % 2 === 1,\n }));\n}\n\n/**\n * Narrows the library to the named icons, in the order given. Unknown names are skipped, so a list keeps working\n * across library releases.\n *\n * @param library - Every icon in the library.\n * @param names - The icons to offer, or undefined for all of them.\n * @returns The icons to offer.\n */\nexport function selectIcons(library: LibraryIcon[], names: string[] | undefined) {\n if (!isDefined(names)) return library;\n\n const byName = new Map(library.map((icon) => [icon.name, icon]));\n\n return [...new Set(names)].flatMap((name) => {\n const icon = byName.get(name);\n\n return isDefined(icon) ? [icon] : [];\n });\n}\n\n/**\n * Lists identifiers as inline code, separated by commas.\n *\n * @param identifiers - The identifiers.\n * @returns The list.\n */\nfunction formatList(identifiers: string[]) {\n return identifiers.map((identifier) => `\\`${identifier}\\``).join(\", \");\n}\n\n/**\n * Describes why a library the project hasn't installed can't be shown, and what to add.\n *\n * @param label - Readable name of the library.\n * @param packageName - Package the library is read from, or an example of one for a family of packages.\n * @param family - Whether the library is a family of packages, one per style.\n * @param listed - Whether the project's `package.json` lists the package.\n * @param sitePackage - Another package of the library the project lists, or undefined when there's none.\n * @returns The problem.\n */\nfunction describeMissingLibrary(\n label: string,\n packageName: string,\n family: boolean,\n listed: boolean,\n sitePackage: string | undefined,\n): LibraryProblem {\n if (listed) {\n return {\n title: `${label} isn't installed yet`,\n description: `\\`${packageName}\\` is in \\`package.json\\` but not in \\`node_modules\\`. Reinstall the project's dependencies.`,\n };\n }\n\n if (isDefined(sitePackage)) {\n return {\n title: `${label} needs \\`${packageName}\\``,\n description: `The Studio reads ${label} from \\`${packageName}\\`, not \\`${sitePackage}\\`. Add it as a dev dependency.`,\n };\n }\n\n return {\n title: `${label} isn't installed`,\n description: family\n ? `Install a ${label} style package, such as \\`${packageName}\\`.`\n : `Install \\`${packageName}\\` in the project.`,\n };\n}\n\n/**\n * Loads one library style from the sets the build step converted.\n *\n * @param library - Identifier of the library, or undefined when none is set.\n * @param style - Identifier of the style, or undefined for the library's default.\n * @returns The icons, or why they can't be shown.\n */\nasync function readLibrary(library: string | undefined, style: string | undefined): Promise<LibraryResult> {\n if (!isDefined(library)) {\n return {\n problem: {\n title: \"No icon library set\",\n description: \"Set `library` in the icon plugin's configuration or in the field's options.\",\n },\n };\n }\n\n if (!iconRegistry.ready) {\n return {\n problem: {\n title: \"Icons aren't set up\",\n description: \"Add `withIcons()` to the Studio's build configuration, then restart the Studio.\",\n },\n };\n }\n\n const info = iconRegistry.libraries[library];\n if (!isDefined(info)) {\n return {\n problem: {\n title: \"Unknown icon library\",\n description: `There's no icon library called \\`${library}\\`. Use one of: ${formatList(Object.keys(iconRegistry.libraries))}.`,\n },\n };\n }\n\n const { label, packageName, packagePrefix, styles, listed, installed, sitePackage } = info;\n if (!installed) {\n return { problem: describeMissingLibrary(label, packageName, isDefined(packagePrefix), listed, sitePackage) };\n }\n\n const resolvedStyle = style ?? styles[0] ?? \"\";\n const loader = iconRegistry.sets[getIconSetKey(library, resolvedStyle)];\n if (!isDefined(loader)) {\n return {\n problem: isDefined(packagePrefix)\n ? {\n title: `${label} style \\`${resolvedStyle}\\` isn't installed`,\n description: `Install \\`${packagePrefix}${resolvedStyle}\\` in the project.`,\n }\n : {\n title: `Unknown ${label} style`,\n description: `${label} has no \\`${resolvedStyle}\\` style. Use one of: ${formatList(styles)}.`,\n },\n };\n }\n\n const module = await loader();\n const set = parseIconSet(module.default);\n if (!isDefined(set)) {\n return { problem: { title: `Couldn't load ${label}`, description: \"Restart the Studio and try again.\" } };\n }\n\n return {\n icons: set.icons.map(({ name, keywords, node, root }) => ({\n name,\n label: convertCase(name, \"title\"),\n tags: keywords.join(\", \"),\n drawing: { root: root ?? set.root, node },\n terms: normalizeTerms([name, ...keywords].join(\" \")),\n })),\n };\n}\n\n/** Library requests shared by every field in the session, keyed by library and style, since the data never changes. */\nconst libraryRequests = new Map<string, Promise<LibraryResult>>();\n\n/**\n * Loads a library style, reusing a request already in progress.\n *\n * @param library - Identifier of the library, or undefined when none is set.\n * @param style - Identifier of the style, or undefined for the library's default.\n * @returns The icons, or why they can't be shown.\n */\nexport async function requestLibrary(library: string | undefined, style: string | undefined) {\n const key = getIconSetKey(library ?? \"\", style ?? \"\");\n let request = libraryRequests.get(key);\n\n if (!isDefined(request)) {\n request = readLibrary(library, style);\n libraryRequests.set(key, request);\n }\n\n const result = await request;\n\n return result;\n}\n","import type { SanityIconNames } from \"@driftime/sanity-plugin-icon/names\";\n\nimport type { iconLibraryStyles } from \"@/lib/libraries\";\n\n/** Schema type name of the icon object. */\nexport const iconTypeName = \"icon\";\n\n/**\n * Stored icon: which library it came from, its name, and the shapes it's drawn from.\n *\n * @public\n */\nexport interface SanityIcon {\n _type: typeof iconTypeName;\n /** Identifier of the library the icon came from. */\n library?: string;\n /** Identifier of the library style the icon came from. */\n style?: string;\n /** Name of the icon in its library. */\n name?: string;\n /** Shapes the icon is drawn from, saved when it's chosen. */\n node?: string;\n}\n\n/** Styles of each supported library, from the plugin's own list. */\ntype IconLibraryStyles = typeof iconLibraryStyles;\n\n/**\n * Identifier of a library the plugin supports.\n *\n * @public\n */\nexport type SanityIconLibrary = keyof IconLibraryStyles;\n\n/**\n * Styles a library offers. The project's own icon folders have one style, `default`.\n *\n * @public\n */\nexport type SanityIconStyle<Library extends string> = Library extends SanityIconLibrary\n ? IconLibraryStyles[Library][number]\n : \"default\";\n\n/**\n * Names of a library's icons, once the build step has listed the installed version's, or any name before then.\n *\n * @public\n */\nexport type SanityIconName<Library extends string> = Library extends keyof SanityIconNames\n ? SanityIconNames[Library]\n : string;\n\n/** Libraries the build step has listed, or any identifier before it has, so the project's own folders can be named. */\nexport type ListedLibraryId = [keyof SanityIconNames] extends [never]\n ? string & NonNullable<unknown>\n : Extract<keyof SanityIconNames, string>;\n\n/** Libraries a field can name: the supported ones, plus the project's own folders. */\nexport type IconLibraryId = SanityIconLibrary | ListedLibraryId;\n"],"mappings":";;;;;;;;;;;;;AAgBA,SAASO,QAAQ,EAAEC,OAAO,GAAGC,cAAsC;CACjE,IAAI,CAACT,UAAUQ,KAAK,GAAG,OAAOC;CAE9B,IAAME,eAAeH,MAAMI,MAAM,GAAG,CAAC,CAACC,SAASC,gBAAoC;EACjF,IAAM,CAACC,WAAW,IAAI,GAAGC,SAASF,YAAYF,MAAM,GAAG,GACjDK,OAAOF,SAASG,KAAK,GACrBC,SAASH,MAAMI,KAAK,GAAG,CAAC,CAACF,KAAK;EASpC,OARI,CAAClB,UAAUiB,IAAI,KAAK,CAACjB,UAAUmB,MAAM,IAAU,CAAA,IAQ5C,CAAC,CANIF,KAAKK,WAAW,IAAI,IAC5BL,OACAA,KACGM,QAAQ,UAAU,KAAK,CAAC,CACxBC,WAAW,wBAAwBC,QAAQC,WAAmBA,OAAOC,YAAY,CAAC,GAE3ER,MAAM,CAAC;CACvB,CAAC;CAED,OAAO;EAAE,GAAGV;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Y5G;;AAGA,MAAMgE,kCAAkB,IAAIjC,IAAoC;;;;;;;;AAShE,eAAsBkC,eAAerC,SAA6BiB,OAA2B;CAC3F,IAAMqB,MAAM5E,cAAcsC,WAAW,IAAIiB,SAAS,EAAE,GAChDsB,UAAUH,gBAAgB7B,IAAI+B,GAAG;CASrC,OAPK9E,UAAU+E,OAAO,MACpBA,UAAUvB,YAAYhB,SAASiB,KAAK,GACpCmB,gBAAgBL,IAAIO,KAAKC,OAAO,IAK3BC,MAFcD;AAGvB;;ACxOA,MAAaI,eAAe"}
|
|
1
|
+
{"version":3,"file":"types-CmTEhJK6.js","names":["isDefined","ComponentProps","ReactElement","createElement","IconDrawing","IconElement","iconSvgAttributes","toProps","style","attributes","Record","declarations","split","flatMap","declaration","property","value","name","trim","joined","join","key","startsWith","replace","replaceAll","_match","letter","toUpperCase","Object","fromEntries","renderChild","child","index","element","children","String","map","nested","position","DrawingProps","Omit","drawing","Drawing","props","root","node","iconRegistry","convertCase","isDefined","IconDrawing","getIconSetKey","parseIconSet","LibraryIcon","name","label","tags","drawing","terms","LibraryProblem","title","description","LibraryResult","icons","problem","normalizeTerms","value","toLowerCase","replaceAll","trim","splitMatches","text","query","start","match","pattern","split","map","word","String","raw","join","parts","RegExp","part","index","slice","length","selectIcons","library","names","byName","Map","icon","Set","flatMap","get","formatList","identifiers","identifier","describeMissingLibrary","packageName","family","listed","sitePackage","readLibrary","style","Promise","ready","info","libraries","Object","keys","packagePrefix","styles","installed","resolvedStyle","loader","sets","module","set","default","keywords","node","root","libraryRequests","requestLibrary","key","request","result","SanityIconNames","iconLibraryStyles","iconTypeName","SanityIcon","_type","library","style","name","node","IconLibraryStyles","SanityIconLibrary","SanityIconStyle","Library","SanityIconName","ListedLibraryId","NonNullable","Extract","IconLibraryId"],"sources":["../src/components/drawing.tsx","../src/lib/library.ts","../src/types.ts"],"sourcesContent":["// Consumers render this in server components, where the compiler's memo cache hook can't run.\n\"use no memo\";\n\nimport { isDefined } from \"@repo/lib/utils\";\nimport type { ComponentProps, ReactElement } from \"react\";\nimport { createElement } from \"react\";\n\nimport type { IconDrawing, IconElement } from \"@/lib/nodes\";\nimport { iconSvgAttributes } from \"@/lib/nodes\";\n\n/**\n * Converts stored attributes to React props, turning a `style` attribute into the object React expects.\n *\n * @param attributes - The stored attributes.\n * @returns The props.\n */\nfunction toProps({ style, ...attributes }: Record<string, string>) {\n if (!isDefined(style)) return attributes;\n\n const declarations = style.split(\";\").flatMap((declaration): [string, string][] => {\n const [property = \"\", ...value] = declaration.split(\":\");\n const name = property.trim();\n const joined = value.join(\":\").trim();\n if (!isDefined(name) || !isDefined(joined)) return [];\n\n const key = name.startsWith(\"--\")\n ? name\n : name\n .replace(/^-ms-/u, \"ms-\")\n .replaceAll(/-(?<letter>[a-z])/gu, (_match, letter: string) => letter.toUpperCase());\n\n return [[key, joined]];\n });\n\n return { ...attributes, style: Object.fromEntries(declarations) };\n}\n\n/**\n * Draws one element of a stored drawing, with its children.\n *\n * @param child - The element, or text inside one.\n * @param index - Its position among its siblings.\n * @returns The element.\n */\nfunction renderChild(child: IconElement | string, index: number): ReactElement | string {\n if (typeof child === \"string\") return child;\n\n const [element, attributes, children] = child;\n\n return createElement(\n element,\n { ...toProps(attributes), key: String(index) },\n children?.map((nested, position) => renderChild(nested, position)),\n );\n}\n\nexport type DrawingProps = Omit<ComponentProps<\"svg\">, \"children\"> & { drawing: IconDrawing | undefined };\n\nexport function Drawing({ drawing, ...props }: DrawingProps) {\n if (!isDefined(drawing)) return null;\n\n // Stored roots only hold checked attribute names, but their values are text, not React's literal types.\n const root = toProps(drawing.root) as ComponentProps<\"svg\">;\n\n return (\n <svg {...iconSvgAttributes} {...root} aria-hidden=\"true\" {...props}>\n {drawing.node.map((child, index) => renderChild(child, index))}\n </svg>\n );\n}\n","import { iconRegistry } from \"@driftime/sanity-plugin-icon/sets\";\nimport { convertCase, isDefined } from \"@repo/lib/utils\";\n\nimport type { IconDrawing } from \"@/lib/nodes\";\nimport { getIconSetKey } from \"@/lib/registry\";\nimport { parseIconSet } from \"@/lib/sets\";\n\n/** Icon in the library, with the terms a search matches against. */\nexport interface LibraryIcon {\n /** Name of the icon in its library. */\n name: string;\n /** Readable form of the name. */\n label: string;\n /** Keywords describing the icon, as a comma-separated list. */\n tags: string;\n /** The icon's shapes and the SVG attributes they're drawn inside. */\n drawing: IconDrawing;\n /** Name and keywords, normalised for search. */\n terms: string;\n}\n\n/** Why a library's icons can't be shown, and what to do about it, with code marked by backticks. */\nexport interface LibraryProblem {\n /** What's wrong, in a few words. */\n title: string;\n /** What to do about it. */\n description: string;\n}\n\n/** Outcome of loading a library: its icons, or why they can't be shown. */\nexport type LibraryResult =\n | { icons: LibraryIcon[]; problem?: undefined }\n | { icons?: undefined; problem: LibraryProblem };\n\n/**\n * Normalises text for search, so hyphenated names and multi-word keywords match the same way.\n *\n * @param value - The text.\n * @returns The normalised text.\n */\nexport function normalizeTerms(value: string) {\n return value\n .toLowerCase()\n .replaceAll(/[\\s-]+/gu, \" \")\n .trim();\n}\n\n/**\n * Splits text into the parts a search matches and the parts it doesn't, matching the way search does: ignoring case,\n * and treating spaces and hyphens alike.\n *\n * @param text - The text to split.\n * @param query - The normalised search.\n * @returns The parts in order, each with where it starts in the text and whether it matches.\n */\nexport function splitMatches(text: string, query: string) {\n if (!isDefined(query)) return [{ text, start: 0, match: false }];\n\n const pattern = query\n .split(\" \")\n .map((word) => word.replaceAll(/[$()*+.?[\\\\\\]^{|}]/gu, String.raw`\\$&`))\n .join(String.raw`[\\s-]+`);\n\n const parts = text.split(new RegExp(`(${pattern})`, \"giu\"));\n\n return parts.map((part, index) => ({\n text: part,\n start: parts.slice(0, index).join(\"\").length,\n match: index % 2 === 1,\n }));\n}\n\n/**\n * Narrows the library to the named icons, in the order given. Unknown names are skipped, so a list keeps working\n * across library releases.\n *\n * @param library - Every icon in the library.\n * @param names - The icons to offer, or undefined for all of them.\n * @returns The icons to offer.\n */\nexport function selectIcons(library: LibraryIcon[], names: string[] | undefined) {\n if (!isDefined(names)) return library;\n\n const byName = new Map(library.map((icon) => [icon.name, icon]));\n\n return [...new Set(names)].flatMap((name) => {\n const icon = byName.get(name);\n\n return isDefined(icon) ? [icon] : [];\n });\n}\n\n/**\n * Lists identifiers as inline code, separated by commas.\n *\n * @param identifiers - The identifiers.\n * @returns The list.\n */\nfunction formatList(identifiers: string[]) {\n return identifiers.map((identifier) => `\\`${identifier}\\``).join(\", \");\n}\n\n/**\n * Describes why a library the project hasn't installed can't be shown, and what to add.\n *\n * @param label - Readable name of the library.\n * @param packageName - Package the library is read from, or an example of one for a family of packages.\n * @param family - Whether the library is a family of packages, one per style.\n * @param listed - Whether the project's `package.json` lists the package.\n * @param sitePackage - Another package of the library the project lists, or undefined when there's none.\n * @returns The problem.\n */\nfunction describeMissingLibrary(\n label: string,\n packageName: string,\n family: boolean,\n listed: boolean,\n sitePackage: string | undefined,\n): LibraryProblem {\n if (listed) {\n return {\n title: `${label} isn't installed yet`,\n description: `\\`${packageName}\\` is in \\`package.json\\` but not in \\`node_modules\\`. Reinstall the project's dependencies.`,\n };\n }\n\n if (isDefined(sitePackage)) {\n return {\n title: `${label} needs \\`${packageName}\\``,\n description: `The Studio reads ${label} from \\`${packageName}\\`, not \\`${sitePackage}\\`. Add it as a dev dependency.`,\n };\n }\n\n return {\n title: `${label} isn't installed`,\n description: family\n ? `Install a ${label} style package, such as \\`${packageName}\\`.`\n : `Install \\`${packageName}\\` in the project.`,\n };\n}\n\n/**\n * Loads one library style from the sets the build step converted.\n *\n * @param library - Identifier of the library, or undefined when none is set.\n * @param style - Identifier of the style, or undefined for the library's default.\n * @returns The icons, or why they can't be shown.\n */\nasync function readLibrary(library: string | undefined, style: string | undefined): Promise<LibraryResult> {\n if (!isDefined(library)) {\n return {\n problem: {\n title: \"No icon library set\",\n description: \"Set `library` in the icon plugin's configuration or in the field's options.\",\n },\n };\n }\n\n if (!iconRegistry.ready) {\n return {\n problem: {\n title: \"Icons aren't set up\",\n description: \"Add `withIcons()` to the Studio's build configuration, then restart the Studio.\",\n },\n };\n }\n\n const info = iconRegistry.libraries[library];\n if (!isDefined(info)) {\n return {\n problem: {\n title: \"Unknown icon library\",\n description: `There's no icon library called \\`${library}\\`. Use one of: ${formatList(Object.keys(iconRegistry.libraries))}.`,\n },\n };\n }\n\n const { label, packageName, packagePrefix, styles, listed, installed, sitePackage } = info;\n if (!installed) {\n return { problem: describeMissingLibrary(label, packageName, isDefined(packagePrefix), listed, sitePackage) };\n }\n\n const resolvedStyle = style ?? styles[0] ?? \"\";\n const loader = iconRegistry.sets[getIconSetKey(library, resolvedStyle)];\n if (!isDefined(loader)) {\n return {\n problem: isDefined(packagePrefix)\n ? {\n title: `${label} style \\`${resolvedStyle}\\` isn't installed`,\n description: `Install \\`${packagePrefix}${resolvedStyle}\\` in the project.`,\n }\n : {\n title: `Unknown ${label} style`,\n description: `${label} has no \\`${resolvedStyle}\\` style. Use one of: ${formatList(styles)}.`,\n },\n };\n }\n\n const module = await loader();\n const set = parseIconSet(module.default);\n if (!isDefined(set)) {\n return { problem: { title: `Couldn't load ${label}`, description: \"Restart the Studio and try again.\" } };\n }\n\n return {\n icons: set.icons.map(({ name, keywords, node, root }) => ({\n name,\n label: convertCase(name, \"title\"),\n tags: keywords.join(\", \"),\n drawing: { root: root ?? set.root, node },\n terms: normalizeTerms([name, ...keywords].join(\" \")),\n })),\n };\n}\n\n/** Library requests shared by every field in the session, keyed by library and style, since the data never changes. */\nconst libraryRequests = new Map<string, Promise<LibraryResult>>();\n\n/**\n * Loads a library style, reusing a request already in progress.\n *\n * @param library - Identifier of the library, or undefined when none is set.\n * @param style - Identifier of the style, or undefined for the library's default.\n * @returns The icons, or why they can't be shown.\n */\nexport async function requestLibrary(library: string | undefined, style: string | undefined) {\n const key = getIconSetKey(library ?? \"\", style ?? \"\");\n let request = libraryRequests.get(key);\n\n if (!isDefined(request)) {\n request = readLibrary(library, style);\n libraryRequests.set(key, request);\n }\n\n const result = await request;\n\n return result;\n}\n","import type { SanityIconNames } from \"@driftime/sanity-plugin-icon/names\";\n\nimport type { iconLibraryStyles } from \"@/lib/libraries\";\n\n/** Schema type name of the icon object. */\nexport const iconTypeName = \"icon\";\n\n/**\n * Stored icon: which library it came from, its name, and the shapes it's drawn from.\n *\n * @public\n */\nexport interface SanityIcon {\n _type: typeof iconTypeName;\n /** Identifier of the library the icon came from. */\n library?: string;\n /** Identifier of the library style the icon came from. */\n style?: string;\n /** Name of the icon in its library. */\n name?: string;\n /** Shapes the icon is drawn from, saved when it's chosen. */\n node?: string;\n}\n\n/** Styles of each supported library, from the plugin's own list. */\ntype IconLibraryStyles = typeof iconLibraryStyles;\n\n/**\n * Identifier of a library the plugin supports.\n *\n * @public\n */\nexport type SanityIconLibrary = keyof IconLibraryStyles;\n\n/**\n * Styles a library offers. The project's own icon folders have one style, `default`.\n *\n * @public\n */\nexport type SanityIconStyle<Library extends string> = Library extends SanityIconLibrary\n ? IconLibraryStyles[Library][number]\n : \"default\";\n\n/**\n * Names of a library's icons, once the build step has listed the installed version's, or any name before then.\n *\n * @public\n */\nexport type SanityIconName<Library extends string> = Library extends keyof SanityIconNames\n ? SanityIconNames[Library]\n : string;\n\n/** Libraries the build step has listed, or any identifier before it has, so the project's own folders can be named. */\nexport type ListedLibraryId = [keyof SanityIconNames] extends [never]\n ? string & NonNullable<unknown>\n : Extract<keyof SanityIconNames, string>;\n\n/** Libraries a field can name: the supported ones, plus the project's own folders. */\nexport type IconLibraryId = SanityIconLibrary | ListedLibraryId;\n"],"mappings":";;;;;;;;;;;AAgBA,SAASO,QAAQ,EAAEC,OAAO,GAAGC,cAAsC;CACjE,IAAI,CAACT,UAAUQ,KAAK,GAAG,OAAOC;CAE9B,IAAME,eAAeH,MAAMI,MAAM,GAAG,CAAC,CAACC,SAASC,gBAAoC;EACjF,IAAM,CAACC,WAAW,IAAI,GAAGC,SAASF,YAAYF,MAAM,GAAG,GACjDK,OAAOF,SAASG,KAAK,GACrBC,SAASH,MAAMI,KAA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E;EACAC,OAAOP,YAAYM,MAAM,OAAO;EAChCE,MAAMkE,SAASzC,KAAK,IAAI;EACxBxB,SAAS;GAAEmE,MAAMA,QAAQJ,IAAII;GAAMD;EAAK;EACxCjE,OAAOO,eAAe,CAACX,MAAM,GAAGoE,QAAQ,CAAC,CAACzC,KAAK,GAAG,CAAC;CACrD,EAAE,EACJ,IAXS,EAAEjB,SAAS;EAAEJ,OAAO,iBAAiBL;EAASM,aAAa;CAAoC,EAAE;AAY5G;;AAGA,MAAMgE,kCAAkB,IAAIjC,IAAoC;;;;;;;;AAShE,eAAsBkC,eAAerC,SAA6BiB,OAA2B;CAC3F,IAAMqB,MAAM5E,cAAcsC,WAAW,IAAIiB,SAAS,EAAE,GAChDsB,UAAUH,gBAAgB7B,IAAI+B,GAAG;CASrC,OAPK9E,UAAU+E,OAAO,MACpBA,UAAUvB,YAAYhB,SAASiB,KAAK,GACpCmB,gBAAgBL,IAAIO,KAAKC,OAAO,IAK3BC,MAFcD;AAGvB;;ACxOA,MAAaI,eAAe"}
|
package/dist/vite.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { n as pluginName, t as logger } from "./defaults-BEzCWZtH.js";
|
|
2
|
-
import {
|
|
3
|
-
import { r as isRegistryModule, t as
|
|
4
|
-
import { a as writeIconNames, i as loadIconSet, n as detectLibraries, r as listRegistryDependencies, t as describeReport } from "./sets-B2lHNI7c.js";
|
|
2
|
+
import { c as isDefined } from "./nodes-Bn7fLVZO.js";
|
|
3
|
+
import { a as writeIconNames, i as loadIconSet, n as detectLibraries, o as createRegistryModule, r as listRegistryDependencies, s as isRegistryModule, t as describeReport } from "./sets-B5arQvrZ.js";
|
|
5
4
|
import path from "node:path";
|
|
6
5
|
/** Prefix of the module each set is loaded from, followed by its library and style. */
|
|
7
6
|
const setPrefix = `virtual:${pluginName}/set/`;
|
package/dist/vite.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"vite.js","names":["path","isDefined","writeIconNames","createRegistryModule","isRegistryModule","DetectedLibrary","describeReport","detectLibraries","listRegistryDependencies","loadIconSet","logger","pluginName","SanityIconBuildOptions","custom","Record","SanityIconVitePlugin","name","config","optimizeDeps","exclude","configResolved","root","cacheDir","Promise","configureServer","server","watcher","add","paths","on","event","listener","file","moduleGraph","invalidateAll","ws","send","payload","type","buildStart","resolveId","id","load","this","addWatchFile","setPrefix","iconLibraries","options","process","cwd","undefined","libraries","folders","Object","values","map","folder","resolve","_event","some","startsWith","sep","names","Map","Set","loaded","all","flatMap","library","styles","style","set","adapter","libraryNames","get","icon","icons","files","key","libraryName","slice","length","split","find","report","info","label","JSON","stringify","withIcons","extendConfig","plugins","Config"],"sources":["../src/build/vite.ts"],"sourcesContent":["import path from \"node:path\";\n\nimport { isDefined } from \"@repo/lib/utils\";\n\nimport { writeIconNames } from \"@/build/names\";\nimport { createRegistryModule, isRegistryModule } from \"@/build/registry\";\nimport type { DetectedLibrary } from \"@/build/sets\";\nimport { describeReport, detectLibraries, listRegistryDependencies, loadIconSet } from \"@/build/sets\";\nimport { logger, pluginName } from \"@/config/defaults\";\n\n/**\n * Options for the build step that converts icon libraries for the Studio.\n *\n * @public\n */\nexport interface SanityIconBuildOptions {\n /** Folders of the project's own SVG icons, keyed by the identifier fields use, such as `{ acme: \"./icons\" }`. */\n custom?: Record<string, string>;\n}\n\n/**\n * A Vite plugin, limited to the hooks the build step uses, so the package doesn't depend on Vite's own types.\n *\n * @public\n */\nexport interface SanityIconVitePlugin {\n /** Name Vite reports the plugin under. */\n name: string;\n /**\n * Keeps the placeholder registry out of Vite's pre-bundling in development, which would fix it in place, while the\n * rest of the plugin and its dependencies are pre-bundled as usual.\n *\n * @returns The configuration to merge.\n */\n config: () => { optimizeDeps: { exclude: string[] } };\n /**\n * Reads the project folder and cache folder once Vite has resolved its configuration.\n *\n * @param config - Vite's resolved configuration.\n */\n configResolved: (config: { root: string; cacheDir: string }) => Promise<void>;\n /**\n * Watches the project's own icon folders in development, reloading the Studio when an icon is added, changed, or\n * removed.\n *\n * @param server - Vite's development server.\n */\n configureServer: (server: {\n watcher: {\n add: (paths: string[]) => void;\n on: (event: \"all\", listener: (event: string, file: string) => void) => void;\n };\n moduleGraph: { invalidateAll: () => void };\n ws: { send: (payload: { type: \"full-reload\" }) => void };\n }) => void;\n /** Lists the installed icon names in the plugin's types when a build or dev server starts. */\n buildStart: () => Promise<void>;\n /**\n * Claims the modules each set is loaded from.\n *\n * @param id - The module requested.\n * @returns The module's resolved id, or undefined when it isn't a set.\n */\n resolveId: (id: string) => string | undefined;\n /**\n * Generates the registry in place of the placeholder, and each set's module.\n *\n * @param this - Vite's plugin context, used to watch the files the registry depends on.\n * @param id - The resolved module id.\n * @returns The module's code, or undefined when it isn't the build step's.\n */\n load: (this: { addWatchFile?: (file: string) => void }, id: string) => Promise<string | undefined>;\n}\n\n/** Prefix of the module each set is loaded from, followed by its library and style. */\nconst setPrefix = `virtual:${pluginName}/set/`;\n\n/**\n * Creates the Vite plugin that converts the project's installed icon libraries when the Studio starts or builds.\n *\n * @param options - Options for the build step.\n * @returns The Vite plugin.\n * @public\n */\nexport function iconLibraries(options: SanityIconBuildOptions = {}): SanityIconVitePlugin {\n let root = process.cwd();\n let cacheDir: string | undefined = undefined;\n let libraries: DetectedLibrary[] = [];\n\n return {\n name: pluginName,\n config() {\n return { optimizeDeps: { exclude: [`${pluginName}/sets`] } };\n },\n async configResolved(config) {\n ({ root, cacheDir } = config);\n libraries = await detectLibraries(root, options.custom);\n },\n configureServer(server) {\n const folders = Object.values(options.custom ?? {}).map((folder) => path.resolve(root, folder));\n if (!isDefined(folders)) return;\n\n server.watcher.add(folders);\n server.watcher.on(\"all\", (_event, file) => {\n if (!folders.some((folder) => file.startsWith(`${folder}${path.sep}`))) return;\n\n server.moduleGraph.invalidateAll();\n server.ws.send({ type: \"full-reload\" });\n });\n },\n async buildStart() {\n const names = new Map<string, Set<string>>();\n const loaded = await Promise.all(\n libraries.flatMap((library) =>\n library.styles.map(async ({ style }) => {\n const { set } = await loadIconSet(library, style, { root, cacheDir });\n\n return { library: library.adapter.library, set };\n }),\n ),\n );\n\n for (const { library, set } of loaded) {\n const libraryNames = names.get(library) ?? new Set<string>();\n\n for (const icon of set.icons) libraryNames.add(icon.name);\n names.set(library, libraryNames);\n }\n\n await writeIconNames(names);\n },\n resolveId(id) {\n return id.startsWith(setPrefix) ? `\\0${id}` : undefined;\n },\n async load(id) {\n if (isRegistryModule(id)) {\n libraries = await detectLibraries(root, options.custom);\n\n // Vite treats watched files as imports in development, so folders are watched by the server instead.\n const { files } = listRegistryDependencies(root, libraries);\n for (const file of files) this.addWatchFile?.(file);\n\n return createRegistryModule(libraries, (key) => `${setPrefix}${key}`);\n }\n if (!id.startsWith(`\\0${setPrefix}`)) return undefined;\n\n const [libraryName, style] = id.slice(`\\0${setPrefix}`.length).split(\"/\");\n const library = libraries.find(({ adapter }) => adapter.library === libraryName);\n if (!isDefined(library) || !isDefined(style)) return undefined;\n\n const { set, report } = await loadIconSet(library, style, { root, cacheDir });\n logger.info(describeReport(library.adapter.label, style, report));\n\n return `export default JSON.parse(${JSON.stringify(JSON.stringify(set))});`;\n },\n };\n}\n\n/**\n * Adds the icon build step to a Vite configuration, for the `vite` option in `sanity.cli.ts` or a framework's own\n * Vite settings.\n *\n * @param options - Options for the build step.\n * @returns A function that extends the Vite configuration.\n * @public\n */\nexport function withIcons(options: SanityIconBuildOptions = {}) {\n return function extendConfig<Config extends { plugins?: unknown[] }>(config: Config): Config {\n return { ...config, plugins: [...(config.plugins ?? []), iconLibraries(options)] };\n };\n}\n"],"mappings":"
|
|
1
|
+
{"version":3,"file":"vite.js","names":["path","isDefined","writeIconNames","createRegistryModule","isRegistryModule","DetectedLibrary","describeReport","detectLibraries","listRegistryDependencies","loadIconSet","logger","pluginName","SanityIconBuildOptions","custom","Record","SanityIconVitePlugin","name","config","optimizeDeps","exclude","configResolved","root","cacheDir","Promise","configureServer","server","watcher","add","paths","on","event","listener","file","moduleGraph","invalidateAll","ws","send","payload","type","buildStart","resolveId","id","load","this","addWatchFile","setPrefix","iconLibraries","options","process","cwd","undefined","libraries","folders","Object","values","map","folder","resolve","_event","some","startsWith","sep","names","Map","Set","loaded","all","flatMap","library","styles","style","set","adapter","libraryNames","get","icon","icons","files","key","libraryName","slice","length","split","find","report","info","label","JSON","stringify","withIcons","extendConfig","plugins","Config"],"sources":["../src/build/vite.ts"],"sourcesContent":["import path from \"node:path\";\n\nimport { isDefined } from \"@repo/lib/utils\";\n\nimport { writeIconNames } from \"@/build/names\";\nimport { createRegistryModule, isRegistryModule } from \"@/build/registry\";\nimport type { DetectedLibrary } from \"@/build/sets\";\nimport { describeReport, detectLibraries, listRegistryDependencies, loadIconSet } from \"@/build/sets\";\nimport { logger, pluginName } from \"@/config/defaults\";\n\n/**\n * Options for the build step that converts icon libraries for the Studio.\n *\n * @public\n */\nexport interface SanityIconBuildOptions {\n /** Folders of the project's own SVG icons, keyed by the identifier fields use, such as `{ acme: \"./icons\" }`. */\n custom?: Record<string, string>;\n}\n\n/**\n * A Vite plugin, limited to the hooks the build step uses, so the package doesn't depend on Vite's own types.\n *\n * @public\n */\nexport interface SanityIconVitePlugin {\n /** Name Vite reports the plugin under. */\n name: string;\n /**\n * Keeps the placeholder registry out of Vite's pre-bundling in development, which would fix it in place, while the\n * rest of the plugin and its dependencies are pre-bundled as usual.\n *\n * @returns The configuration to merge.\n */\n config: () => { optimizeDeps: { exclude: string[] } };\n /**\n * Reads the project folder and cache folder once Vite has resolved its configuration.\n *\n * @param config - Vite's resolved configuration.\n */\n configResolved: (config: { root: string; cacheDir: string }) => Promise<void>;\n /**\n * Watches the project's own icon folders in development, reloading the Studio when an icon is added, changed, or\n * removed.\n *\n * @param server - Vite's development server.\n */\n configureServer: (server: {\n watcher: {\n add: (paths: string[]) => void;\n on: (event: \"all\", listener: (event: string, file: string) => void) => void;\n };\n moduleGraph: { invalidateAll: () => void };\n ws: { send: (payload: { type: \"full-reload\" }) => void };\n }) => void;\n /** Lists the installed icon names in the plugin's types when a build or dev server starts. */\n buildStart: () => Promise<void>;\n /**\n * Claims the modules each set is loaded from.\n *\n * @param id - The module requested.\n * @returns The module's resolved id, or undefined when it isn't a set.\n */\n resolveId: (id: string) => string | undefined;\n /**\n * Generates the registry in place of the placeholder, and each set's module.\n *\n * @param this - Vite's plugin context, used to watch the files the registry depends on.\n * @param id - The resolved module id.\n * @returns The module's code, or undefined when it isn't the build step's.\n */\n load: (this: { addWatchFile?: (file: string) => void }, id: string) => Promise<string | undefined>;\n}\n\n/** Prefix of the module each set is loaded from, followed by its library and style. */\nconst setPrefix = `virtual:${pluginName}/set/`;\n\n/**\n * Creates the Vite plugin that converts the project's installed icon libraries when the Studio starts or builds.\n *\n * @param options - Options for the build step.\n * @returns The Vite plugin.\n * @public\n */\nexport function iconLibraries(options: SanityIconBuildOptions = {}): SanityIconVitePlugin {\n let root = process.cwd();\n let cacheDir: string | undefined = undefined;\n let libraries: DetectedLibrary[] = [];\n\n return {\n name: pluginName,\n config() {\n return { optimizeDeps: { exclude: [`${pluginName}/sets`] } };\n },\n async configResolved(config) {\n ({ root, cacheDir } = config);\n libraries = await detectLibraries(root, options.custom);\n },\n configureServer(server) {\n const folders = Object.values(options.custom ?? {}).map((folder) => path.resolve(root, folder));\n if (!isDefined(folders)) return;\n\n server.watcher.add(folders);\n server.watcher.on(\"all\", (_event, file) => {\n if (!folders.some((folder) => file.startsWith(`${folder}${path.sep}`))) return;\n\n server.moduleGraph.invalidateAll();\n server.ws.send({ type: \"full-reload\" });\n });\n },\n async buildStart() {\n const names = new Map<string, Set<string>>();\n const loaded = await Promise.all(\n libraries.flatMap((library) =>\n library.styles.map(async ({ style }) => {\n const { set } = await loadIconSet(library, style, { root, cacheDir });\n\n return { library: library.adapter.library, set };\n }),\n ),\n );\n\n for (const { library, set } of loaded) {\n const libraryNames = names.get(library) ?? new Set<string>();\n\n for (const icon of set.icons) libraryNames.add(icon.name);\n names.set(library, libraryNames);\n }\n\n await writeIconNames(names);\n },\n resolveId(id) {\n return id.startsWith(setPrefix) ? `\\0${id}` : undefined;\n },\n async load(id) {\n if (isRegistryModule(id)) {\n libraries = await detectLibraries(root, options.custom);\n\n // Vite treats watched files as imports in development, so folders are watched by the server instead.\n const { files } = listRegistryDependencies(root, libraries);\n for (const file of files) this.addWatchFile?.(file);\n\n return createRegistryModule(libraries, (key) => `${setPrefix}${key}`);\n }\n if (!id.startsWith(`\\0${setPrefix}`)) return undefined;\n\n const [libraryName, style] = id.slice(`\\0${setPrefix}`.length).split(\"/\");\n const library = libraries.find(({ adapter }) => adapter.library === libraryName);\n if (!isDefined(library) || !isDefined(style)) return undefined;\n\n const { set, report } = await loadIconSet(library, style, { root, cacheDir });\n logger.info(describeReport(library.adapter.label, style, report));\n\n return `export default JSON.parse(${JSON.stringify(JSON.stringify(set))});`;\n },\n };\n}\n\n/**\n * Adds the icon build step to a Vite configuration, for the `vite` option in `sanity.cli.ts` or a framework's own\n * Vite settings.\n *\n * @param options - Options for the build step.\n * @returns A function that extends the Vite configuration.\n * @public\n */\nexport function withIcons(options: SanityIconBuildOptions = {}) {\n return function extendConfig<Config extends { plugins?: unknown[] }>(config: Config): Config {\n return { ...config, plugins: [...(config.plugins ?? []), iconLibraries(options)] };\n };\n}\n"],"mappings":";;;;;AA2EA,MAAM6C,YAAY,WAAWlC,WAAU;;;;;;;;AASvC,SAAgBmC,cAAcC,UAAkC,CAAC,GAAyB;CACxF,IAAI1B,OAAO2B,QAAQC,IAAI,GACnB3B,UACA6B,YAA+B,CAAA;CAEnC,OAAO;EACLnC,MAAML;EACNM,SAAS;GACP,OAAO,EAAEC,cAAc,EAAEC,SAAS,CAAC,GAAGR,WAAU,MAAO,EAAE,EAAE;EAC7D;EACA,MAAMS,eAAeH,QAAQ;GAE3BkC,CADC,CAAE9B,MAAMC,YAAaL,SACtBkC,YAAY,MAAM5C,gBAAgBc,MAAM0B,QAAQlC,MAAM;EACxD;EACAW,gBAAgBC,QAAQ;GACt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M,EAAEgE,UAAUrE,yBAAyBa,MAAM8B,SAAS;IAC1D,KAAK,IAAMnB,QAAQ6C,OAAO,KAAKjC,eAAeZ,IAAI;IAElD,OAAO7B,qBAAqBgD,YAAY2B,QAAQ,GAAGjC,YAAYiC,KAAK;GACtE;GACA,IAAI,CAACrC,GAAGmB,WAAW,KAAKf,WAAW,GAAG;GAEtC,IAAM,CAACkC,aAAaT,SAAS7B,GAAGuC,MAAM,KAAKnC,YAAYoC,MAAM,CAAC,CAACC,MAAM,GAAG,GAClEd,UAAUjB,UAAUgC,MAAM,EAAEX,cAAcA,QAAQJ,YAAYW,WAAW;GAC/E,IAAI,CAAC9E,UAAUmE,OAAO,KAAK,CAACnE,UAAUqE,KAAK,GAAG;GAE9C,IAAM,EAAEC,KAAKa,WAAW,MAAM3E,YAAY2D,SAASE,OAAO;IAAEjD;IAAMC;GAAS,CAAC;GAG5E,OAFAZ,OAAO2E,KAAK/E,eAAe8D,QAAQI,QAAQc,OAAOhB,OAAOc,MAAM,CAAC,GAEzD,6BAA6BG,KAAKC,UAAUD,KAAKC,UAAUjB,GAAG,CAAC,EAAC;EACzE;CACF;AACF;;;;;;;;;AAUA,SAAgBkB,UAAU1C,UAAkC,CAAC,GAAG;CAC9D,OAAO,SAAS2C,aAAqDzE,QAAwB;EAC3F,OAAO;GAAE,GAAGA;GAAQ0E,SAAS,CAAC,GAAI1E,OAAO0E,WAAW,CAAA,GAAK7C,cAAcC,OAAO,CAAC;EAAE;CACnF;AACF"}
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"nodes-DAzj56Xn.js","names":["isDefined","isRecord","stegaClean","IconElement","element","attributes","Record","children","IconNode","IconRoot","IconDrawing","root","node","iconElements","ReadonlySet","Set","linkAttributes","urlPattern","iconSvgAttributes","xmlns","width","height","const","isAttributes","value","Object","values","every","attribute","isIconElement","Array","isArray","length","parts","name","child","findAttributeProblem","entries","test","has","startsWith","includes","references","matchAll","outside","some","groups","trim","replace","split","undefined","findNodeProblem","problem","findDrawingProblem","parseIconNode","parseIconRoot","parseJson","JSON","parse","resolveIconDrawing","cleaned","stored","drawing","serializeIconDrawing","stringify","parts","\"reference\"","\"root\"","\"node\""],"sources":["../src/lib/nodes.ts"],"sourcesContent":["import { isDefined, isRecord } from \"@repo/lib/utils\";\nimport { stegaClean } from \"@sanity/client/stega\";\n\n/** One element in a drawing: its name, its attributes, and any children, which may include text. */\nexport type IconElement = [element: string, attributes: Record<string, string>, children?: (IconElement | string)[]];\n\n/** An icon's drawing, stored as a tree of elements rather than a component. */\nexport type IconNode = IconElement[];\n\n/** Attributes for the SVG around a drawing's elements. */\nexport type IconRoot = Record<string, string>;\n\n/** An icon's elements together with the SVG attributes they're drawn inside. */\nexport interface IconDrawing {\n /** Attributes for the SVG around the elements. */\n root: IconRoot;\n /** Elements the icon is drawn from. */\n node: IconNode;\n}\n\n/**\n * SVG elements a drawing may contain: everything that draws, paints, clips, masks, or filters. Anything that runs\n * code, embeds other content, links away, loads a file, animates, or styles the page around it is left out.\n */\nconst iconElements: ReadonlySet<string> = new Set([\n \"circle\",\n \"clipPath\",\n \"defs\",\n \"ellipse\",\n \"feBlend\",\n \"feColorMatrix\",\n \"feComponentTransfer\",\n \"feComposite\",\n \"feConvolveMatrix\",\n \"feDiffuseLighting\",\n \"feDisplacementMap\",\n \"feDistantLight\",\n \"feDropShadow\",\n \"feFlood\",\n \"feFuncA\",\n \"feFuncB\",\n \"feFuncG\",\n \"feFuncR\",\n \"feGaussianBlur\",\n \"feMerge\",\n \"feMergeNode\",\n \"feMorphology\",\n \"feOffset\",\n \"fePointLight\",\n \"feSpecularLighting\",\n \"feSpotLight\",\n \"feTile\",\n \"feTurbulence\",\n \"filter\",\n \"g\",\n \"line\",\n \"linearGradient\",\n \"marker\",\n \"mask\",\n \"path\",\n \"pattern\",\n \"polygon\",\n \"polyline\",\n \"radialGradient\",\n \"rect\",\n \"stop\",\n \"symbol\",\n \"text\",\n \"textPath\",\n \"tspan\",\n \"use\",\n]);\n\n/** Attributes that point at another element by URL, which must point inside the drawing. */\nconst linkAttributes = new Set([\"href\", \"xlinkHref\"]);\n\n/** A reference to another element in an attribute value, such as `url(#fade)`. */\nconst urlPattern = /url\\((?<reference>[^)]*)\\)/gu;\n\n/** Attributes every drawing's SVG carries, whichever library it came from. */\nexport const iconSvgAttributes = { xmlns: \"http://www.w3.org/2000/svg\", width: 24, height: 24 } as const;\n\n/**\n * Checks whether a value is a set of attributes, each with a text value.\n *\n * @param value - The value to check.\n * @returns True if the value is a set of attributes.\n */\nfunction isAttributes(value: unknown): value is Record<string, string> {\n return isRecord(value) && Object.values(value).every((attribute) => typeof attribute === \"string\");\n}\n\n/**\n * Checks whether a value is an element in a drawing, with text attributes and valid children.\n *\n * @param value - The value to check.\n * @returns True if the value is an element.\n */\nfunction isIconElement(value: unknown): value is IconElement {\n if (!Array.isArray(value) || value.length < 2 || value.length > 3) return false;\n\n const parts: unknown[] = value;\n const [name, attributes, children] = parts;\n if (typeof name !== \"string\" || !isAttributes(attributes)) return false;\n\n return (\n !isDefined(children) ||\n (Array.isArray(children) && children.every((child) => typeof child === \"string\" || isIconElement(child)))\n );\n}\n\n/**\n * Finds why an element's attributes can't be drawn safely.\n *\n * @param attributes - The attributes.\n * @returns The problem, or undefined when the attributes are safe.\n */\nfunction findAttributeProblem(attributes: Record<string, string>) {\n for (const [name, value] of Object.entries(attributes)) {\n if (/^on/iu.test(name)) return `has an event handler (\\`${name}\\`)`;\n if (!/^[a-zA-Z][a-zA-Z0-9]*$/u.test(name)) return `has an unknown attribute (\\`${name}\\`)`;\n if (/javascript:/iu.test(value)) return \"runs a script\";\n\n if (linkAttributes.has(name) && !value.startsWith(\"#\")) return \"links outside the icon\";\n\n if (value.includes(\"url(\")) {\n const references = [...value.matchAll(urlPattern)];\n const outside = references.some(\n ({ groups }) => !(groups?.[\"reference\"]?.trim().replace(/^[\"']/u, \"\").startsWith(\"#\") ?? false),\n );\n\n if (outside || value.split(\"url(\").length - 1 !== references.length) {\n return \"refers to something outside the icon\";\n }\n }\n }\n\n return undefined;\n}\n\n/**\n * Finds why part of a drawing can't be drawn safely.\n *\n * @param node - The elements to check.\n * @returns The problem, or undefined when every element is safe.\n */\nfunction findNodeProblem(node: (IconElement | string)[]): string | undefined {\n for (const child of node) {\n if (typeof child === \"string\") continue;\n\n const [name, attributes, children] = child;\n if (!iconElements.has(name)) return `uses the \\`<${name}>\\` element`;\n\n const problem = findAttributeProblem(attributes) ?? (isDefined(children) ? findNodeProblem(children) : undefined);\n if (isDefined(problem)) return problem;\n }\n\n return undefined;\n}\n\n/**\n * Finds why a drawing can't be drawn safely: an element or attribute that could run code, load something, or reach\n * outside the icon. The same check guards the build step's output and every stored value before it's drawn.\n *\n * @param drawing - The drawing to check.\n * @returns The problem, or undefined when the drawing is safe.\n */\nexport function findDrawingProblem({ root, node }: IconDrawing) {\n if (!isDefined(node)) return \"draws nothing\";\n\n return findAttributeProblem(root) ?? findNodeProblem(node);\n}\n\n/**\n * Reads a drawing's elements from an already parsed value, such as a converted set.\n *\n * @param value - The value to read.\n * @returns The elements, or undefined when the value isn't a list of them.\n */\nexport function parseIconNode(value: unknown) {\n return Array.isArray(value) && value.every((element) => isIconElement(element)) ? value : undefined;\n}\n\n/**\n * Reads an SVG root from an already parsed value.\n *\n * @param value - The value to read.\n * @returns The root, or undefined when the value isn't one.\n */\nexport function parseIconRoot(value: unknown) {\n return isAttributes(value) ? value : undefined;\n}\n\n/**\n * Parses stored JSON.\n *\n * @param value - The stored text.\n * @returns The parsed value, or undefined when the text isn't JSON.\n */\nfunction parseJson(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return undefined;\n }\n}\n\n/**\n * Reads a drawing back from its stored form, removing stega characters first.\n *\n * @param value - The stored drawing.\n * @returns The drawing, or undefined when nothing readable and safe was stored.\n */\nexport function resolveIconDrawing(value: string | undefined): IconDrawing | undefined {\n const cleaned = stegaClean(value);\n if (!isDefined(cleaned)) return undefined;\n\n const stored = parseJson(cleaned);\n if (!isRecord(stored)) return undefined;\n\n const root = parseIconRoot(stored[\"root\"]);\n const node = parseIconNode(stored[\"node\"]);\n if (!isDefined(root) || !isDefined(node)) return undefined;\n\n const drawing = { root, node };\n\n return isDefined(findDrawingProblem(drawing)) ? undefined : drawing;\n}\n\n/**\n * Converts a drawing to its stored form.\n *\n * @param drawing - The drawing.\n * @returns The drawing as a string.\n */\nexport function serializeIconDrawing(drawing: IconDrawing) {\n return JSON.stringify({ root: drawing.root, node: drawing.node });\n}\n"],"mappings":";;;;;;AAwBA,MAAMa,+BAAoC,IAAIE,IAAI,+dA8C3C,CACN,GAGKC,iCAAiB,IAAID,IAAI,CAAC,QAAQ,WAAW,CAAC,GAG9CE,aAAa,gCAGNC,oBAAoB;CAAEC,OAAO;CAA8BC,OAAO;CAAIC,QAAQ;AAAG;;;;;;;AAQ9F,SAASE,aAAaC,OAAiD;CACrE,OAAOvB,SAASuB,KAAK,KAAKC,OAAOC,OAAOF,KAAK,CAAC,CAACG,OAAOC,cAAc,OAAOA,aAAc,QAAQ;AACnG;;;;;;;AAQA,SAASC,cAAcL,OAAsC;CAC3D,IAAI,CAACM,MAAMC,QAAQP,KAAK,KAAKA,MAAMQ,SAAS,KAAKR,MAAMQ,SAAS,GAAG,OAAO;CAG1E,IAAM,CAACE,MAAM7B,YAAYE,YAAY0B;CAGrC,OAFI,OAAOC,QAAS,YAAY,CAACX,aAAalB,UAAU,IAAU,KAGhE,CAACL,UAAUO,QAAQ,KAClBuB,MAAMC,QAAQxB,QAAQ,KAAKA,SAASoB,OAAOQ,UAAU,OAAOA,SAAU,YAAYN,cAAcM,KAAK,CAAC;AAE3G;;;;;;;AAQA,SAASC,qBAAqB/B,YAAoC;CAChE,KAAK,IAAM,CAAC6B,MAAMV,UAAUC,OAAOY,QAAQhC,UAAU,GAAG;EACtD,IAAI,QAAQiC,KAAKJ,IAAI,GAAG,OAAO,2BAA2BA,KAAI;EAC9D,IAAI,CAAC,0BA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C,OAAOD,aAAaC,KAAK,IAAIA,QAAQ0B,KAAAA;AACvC;;;;;;;AAQA,SAASM,UAAUhC,OAAwB;CACzC,IAAI;EACF,OAAOiC,KAAKC,MAAMlC,KAAK;CACzB,QAAQ;EACN;CACF;AACF;;;;;;;AAQA,SAAgBmC,mBAAmBnC,OAAoD;CACrF,IAAMoC,UAAU1D,WAAWsB,KAAK;CAChC,IAAI,CAACxB,UAAU4D,OAAO,GAAG;CAEzB,IAAMC,SAASL,UAAUI,OAAO;CAChC,IAAI,CAAC3D,SAAS4D,MAAM,GAAG;CAEvB,IAAMlD,OAAO4C,cAAcM,OAAOM,IAAO,GACnCvD,OAAO0C,cAAcO,OAAOO,IAAO;CACzC,IAAI,CAACpE,UAAUW,IAAI,KAAK,CAACX,UAAUY,IAAI,GAAG;CAE1C,IAAMkD,UAAU;EAAEnD;EAAMC;CAAK;CAE7B,OAAOZ,UAAUqD,mBAAmBS,OAAO,CAAC,IAAIZ,KAAAA,IAAYY;AAC9D;;;;;;;AAQA,SAAgBC,qBAAqBD,SAAsB;CACzD,OAAOL,KAAKO,UAAU;EAAErD,MAAMmD,QAAQnD;EAAMC,MAAMkD,QAAQlD;CAAK,CAAC;AAClE"}
|
|
@@ -1,68 +0,0 @@
|
|
|
1
|
-
import { n as isDefined } from "./utils-COPacfAq.js";
|
|
2
|
-
import { t as getIconSetKey } from "./registry-BEEpqK3z.js";
|
|
3
|
-
import path from "node:path";
|
|
4
|
-
import { realpathSync } from "node:fs";
|
|
5
|
-
import { fileURLToPath } from "node:url";
|
|
6
|
-
/**
|
|
7
|
-
* Resolves symbolic links in a path, so a package linked into `node_modules` matches its real location.
|
|
8
|
-
*
|
|
9
|
-
* @param file - The path.
|
|
10
|
-
* @returns The real path, or the path unchanged when it doesn't exist.
|
|
11
|
-
*/
|
|
12
|
-
function resolveRealPath(file) {
|
|
13
|
-
try {
|
|
14
|
-
return realpathSync(file);
|
|
15
|
-
} catch {
|
|
16
|
-
return file;
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
|
-
/**
|
|
20
|
-
* Path of the placeholder registry module the Studio imports, which the build step replaces. The build step's own
|
|
21
|
-
* code is published next to it, so the path is found from this file's location.
|
|
22
|
-
*/
|
|
23
|
-
const registryModulePath = resolveRealPath(fileURLToPath(new URL("sets.js", import.meta.url)));
|
|
24
|
-
/**
|
|
25
|
-
* Checks whether a module the bundler is loading is the placeholder registry.
|
|
26
|
-
*
|
|
27
|
-
* @param id - The module's path, possibly followed by a query.
|
|
28
|
-
* @returns Whether it's the placeholder.
|
|
29
|
-
*/
|
|
30
|
-
function isRegistryModule(id) {
|
|
31
|
-
let [file] = id.split("?");
|
|
32
|
-
return isDefined(file) && resolveRealPath(file) === registryModulePath;
|
|
33
|
-
}
|
|
34
|
-
/**
|
|
35
|
-
* Works out the folder the Next.js build step writes converted sets to, inside the project's `node_modules`.
|
|
36
|
-
*
|
|
37
|
-
* @param root - The project's folder.
|
|
38
|
-
* @returns The folder's path.
|
|
39
|
-
*/
|
|
40
|
-
function getSetsFolder(root) {
|
|
41
|
-
return path.join(root, "node_modules", ".cache", "driftime-icon", "sets");
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Writes the module that replaces the placeholder registry, with a loader for each installed library style, so each
|
|
45
|
-
* set is only downloaded when a picker for it opens.
|
|
46
|
-
*
|
|
47
|
-
* @param libraries - Every library the build step knows.
|
|
48
|
-
* @param importFor - The specifier the bundler imports a set from, given its key.
|
|
49
|
-
* @returns The module's code.
|
|
50
|
-
*/
|
|
51
|
-
function createRegistryModule(libraries, importFor) {
|
|
52
|
-
let loaders = libraries.flatMap(({ adapter, styles }) => styles.map(({ style }) => {
|
|
53
|
-
let key = getIconSetKey(adapter.library, style);
|
|
54
|
-
return `${JSON.stringify(key)}: () => import(${JSON.stringify(importFor(key))})`;
|
|
55
|
-
})), info = Object.fromEntries(libraries.map(({ adapter, styles, listed, sitePackage }) => [adapter.library, {
|
|
56
|
-
label: adapter.label,
|
|
57
|
-
packageName: adapter.packageName ?? adapter.packageExample ?? adapter.library,
|
|
58
|
-
...isDefined(adapter.packagePrefix) && { packagePrefix: adapter.packagePrefix },
|
|
59
|
-
styles: isDefined(styles) ? styles.map(({ style }) => style) : adapter.styles,
|
|
60
|
-
listed,
|
|
61
|
-
installed: isDefined(styles),
|
|
62
|
-
...isDefined(sitePackage) && { sitePackage }
|
|
63
|
-
}]));
|
|
64
|
-
return [`const sets = {\n ${loaders.join(",\n ")}\n};`, `export const iconRegistry = { ready: true, sets, libraries: ${JSON.stringify(info)} };`].join("\n");
|
|
65
|
-
}
|
|
66
|
-
export { registryModulePath as i, getSetsFolder as n, isRegistryModule as r, createRegistryModule as t };
|
|
67
|
-
|
|
68
|
-
//# sourceMappingURL=registry-B0Dxiwhh.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"registry-B0Dxiwhh.js","names":["realpathSync","path","fileURLToPath","isDefined","DetectedLibrary","getIconSetKey","IconLibraryInfo","resolveRealPath","file","registryModulePath","URL","import","meta","url","isRegistryModule","id","split","getSetsFolder","root","join","createRegistryModule","libraries","importFor","key","loaders","flatMap","adapter","styles","map","style","library","JSON","stringify","info","Record","Object","fromEntries","listed","sitePackage","label","packageName","packageExample","packagePrefix","installed"],"sources":["../src/build/registry.ts"],"sourcesContent":["import { realpathSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { isDefined } from \"@repo/lib/utils\";\n\nimport type { DetectedLibrary } from \"@/build/sets\";\nimport { getIconSetKey } from \"@/lib/registry\";\nimport type { IconLibraryInfo } from \"@/lib/sets\";\n\n/**\n * Resolves symbolic links in a path, so a package linked into `node_modules` matches its real location.\n *\n * @param file - The path.\n * @returns The real path, or the path unchanged when it doesn't exist.\n */\nfunction resolveRealPath(file: string) {\n try {\n return realpathSync(file);\n } catch {\n return file;\n }\n}\n\n/**\n * Path of the placeholder registry module the Studio imports, which the build step replaces. The build step's own\n * code is published next to it, so the path is found from this file's location.\n */\nexport const registryModulePath = resolveRealPath(fileURLToPath(new URL(\"sets.js\", import.meta.url)));\n\n/**\n * Checks whether a module the bundler is loading is the placeholder registry.\n *\n * @param id - The module's path, possibly followed by a query.\n * @returns Whether it's the placeholder.\n */\nexport function isRegistryModule(id: string) {\n const [file] = id.split(\"?\");\n\n return isDefined(file) && resolveRealPath(file) === registryModulePath;\n}\n\n/**\n * Works out the folder the Next.js build step writes converted sets to, inside the project's `node_modules`.\n *\n * @param root - The project's folder.\n * @returns The folder's path.\n */\nexport function getSetsFolder(root: string) {\n return path.join(root, \"node_modules\", \".cache\", \"driftime-icon\", \"sets\");\n}\n\n/**\n * Writes the module that replaces the placeholder registry, with a loader for each installed library style, so each\n * set is only downloaded when a picker for it opens.\n *\n * @param libraries - Every library the build step knows.\n * @param importFor - The specifier the bundler imports a set from, given its key.\n * @returns The module's code.\n */\nexport function createRegistryModule(libraries: DetectedLibrary[], importFor: (key: string) => string) {\n const loaders = libraries.flatMap(({ adapter, styles }) =>\n styles.map(({ style }) => {\n const key = getIconSetKey(adapter.library, style);\n\n return `${JSON.stringify(key)}: () => import(${JSON.stringify(importFor(key))})`;\n }),\n );\n\n const info: Record<string, IconLibraryInfo> = Object.fromEntries(\n libraries.map(({ adapter, styles, listed, sitePackage }) => [\n adapter.library,\n {\n label: adapter.label,\n packageName: adapter.packageName ?? adapter.packageExample ?? adapter.library,\n ...(isDefined(adapter.packagePrefix) && { packagePrefix: adapter.packagePrefix }),\n styles: isDefined(styles) ? styles.map(({ style }) => style) : adapter.styles,\n listed,\n installed: isDefined(styles),\n ...(isDefined(sitePackage) && { sitePackage }),\n },\n ]),\n );\n\n return [\n `const sets = {\\n ${loaders.join(\",\\n \")}\\n};`,\n `export const iconRegistry = { ready: true, sets, libraries: ${JSON.stringify(info)} };`,\n ].join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;AAgBA,SAASO,gBAAgBC,MAAc;CACrC,IAAI;EACF,OAAOR,aAAaQ,IAAI;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AK,IAAI;AACb"}
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Builds the key a set is registered under.
|
|
3
|
-
*
|
|
4
|
-
* @param library - Identifier of the library.
|
|
5
|
-
* @param style - Identifier of the style.
|
|
6
|
-
* @returns The key.
|
|
7
|
-
*/
|
|
8
|
-
function getIconSetKey(library, style) {
|
|
9
|
-
return `${library}/${style}`;
|
|
10
|
-
}
|
|
11
|
-
export { getIconSetKey as t };
|
|
12
|
-
|
|
13
|
-
//# sourceMappingURL=registry-BEEpqK3z.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"registry-BEEpqK3z.js","names":["IconLibraryInfo","IconSetLoader","Promise","default","IconRegistry","ready","sets","Record","libraries","getIconSetKey","library","style"],"sources":["../src/lib/registry.ts"],"sourcesContent":["import type { IconLibraryInfo } from \"@/lib/sets\";\n\n/**\n * Loads one converted set, as a module whose default export is the set.\n *\n * @public\n */\nexport type IconSetLoader = () => Promise<{ default: unknown }>;\n\n/**\n * What the build step generates: a loader for every converted set, and every library it knows.\n *\n * @public\n */\nexport interface IconRegistry {\n /** Whether the build step generated the registry, rather than the placeholder being used. */\n ready: boolean;\n /** Loaders keyed by library and style, such as `phosphor/bold`. */\n sets: Record<string, IconSetLoader>;\n /** Libraries the build step knows, keyed by identifier. */\n libraries: Record<string, IconLibraryInfo>;\n}\n\n/**\n * Builds the key a set is registered under.\n *\n * @param library - Identifier of the library.\n * @param style - Identifier of the style.\n * @returns The key.\n */\nexport function getIconSetKey(library: string, style: string) {\n return `${library}/${style}`;\n}\n"],"mappings":";;;;;;;AA8BA,SAAgBS,cAAcC,SAAiBC,OAAe;CAC5D,OAAO,GAAGD,QAAO,GAAIC;AACvB"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sets-B2lHNI7c.js","names":["readFile","rename","writeFile","path","isDefined","registryModulePath","pluginName","namesFile","join","dirname","writeIconNames","names","Map","Set","entries","toSorted","first","second","localeCompare","map","library","icons","union","name","JSON","stringify","content","current","catch","temporary","process","pid","once","mkdir","writeFile","path","Worker","isDefined","isRecord","createCustomAdapter","iconAdapters","IconAdapter","SourceIcon","convertIcon","InstalledPackage","findPackage","readDeclaredPackages","readJson","readPluginBuild","IconSet","IconSetIcon","parseIconSet","IconSetReport","total","skipped","name","reason","duration","DetectedStyle","style","installed","DetectedLibrary","adapter","styles","listed","sitePackage","folder","IconSetContext","root","cacheDir","detectLibraries","custom","Record","Promise","declared","known","all","map","packageName","packagePrefix","packagePattern","names","filter","startsWith","toSorted","found","slice","length","flat","has","undefined","find","test","folders","Object","entries","library","directory","resolve","version","findCommonRoot","icons","NonNullable","counts","Map","count","key","JSON","stringify","set","get","common","values","first","second","isSourceIcon","value","keywords","svg","Array","isArray","every","keyword","readSources","candidate","worker","URL","import","meta","url","workerData","env","process","NODE_ENV","received","sources","source","terminate","convertIconSet","started","performance","now","report","converted","icon","problem","push","iconRoot","Math","round","parseReport","flatMap","entry","loadIconSet","context","cacheable","cacheFile","join","replaceAll","cached","dirname","recursive","listRegistryDependencies","libraries","files","describeReport","label","kept","toLocaleString","timing","summary","shown","hidden","more","\"total\"","\"skipped\"","\"name\"","\"reason\"","\"set\"","\"report\""],"sources":["../src/build/names.ts","../src/build/sets.ts"],"sourcesContent":["import { readFile, rename, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { isDefined } from \"@repo/lib/utils\";\n\nimport { registryModulePath } from \"@/build/registry\";\nimport { pluginName } from \"@/config/defaults\";\n\n/** Types file the plugin reads icon names from, published next to the placeholder registry. */\nconst namesFile = path.join(path.dirname(registryModulePath), \"names.d.ts\");\n\n/**\n * Writes the installed icon names into the plugin's own types, so options that list icons are checked against them.\n * The file is replaced rather than edited, because pnpm shares a package's files between projects.\n *\n * @param names - Icon names keyed by library.\n */\nexport async function writeIconNames(names: Map<string, Set<string>>) {\n const entries = [...names]\n .toSorted(([first], [second]) => first.localeCompare(second))\n .map(([library, icons]) => {\n const union = [...icons].toSorted().map((name) => JSON.stringify(name));\n\n return ` ${JSON.stringify(library)}: ${isDefined(union) ? union.join(\" | \") : \"never\"};`;\n });\n\n const content = [\n `// Written by ${pluginName}'s build step from the project's installed icon libraries.`,\n \"export type SanityIconNames = {\",\n ...entries,\n \"};\",\n \"\",\n ].join(\"\\n\");\n\n const current = await readFile(namesFile, \"utf8\").catch(() => \"\");\n if (current === content) return;\n\n const temporary = `${namesFile}.${process.pid}.tmp`;\n await writeFile(temporary, content);\n await rename(temporary, namesFile);\n}\n","import { once } from \"node:events\";\nimport { mkdir, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { Worker } from \"node:worker_threads\";\n\nimport { isDefined, isRecord } from \"@repo/lib/utils\";\n\nimport { createCustomAdapter } from \"@/build/adapters/custom\";\nimport { iconAdapters } from \"@/build/adapters/index\";\nimport type { IconAdapter } from \"@/build/adapters/types\";\nimport type { SourceIcon } from \"@/build/convert\";\nimport { convertIcon } from \"@/build/convert\";\nimport type { InstalledPackage } from \"@/build/packages\";\nimport { findPackage, readDeclaredPackages, readJson, readPluginBuild } from \"@/build/packages\";\nimport type { IconSet, IconSetIcon } from \"@/lib/sets\";\nimport { parseIconSet } from \"@/lib/sets\";\n\n/** What happened converting a set, for the build's log. */\nexport interface IconSetReport {\n /** Icons the library ships in the style. */\n total: number;\n /** Icons skipped, with why. */\n skipped: { name: string; reason: string }[];\n /** Time the conversion took, in milliseconds, or 0 when it came from the cache. */\n duration: number;\n}\n\n/** One installed style of a library, and the package it's read from. */\nexport interface DetectedStyle {\n /** Identifier of the style. */\n style: string;\n /** The package the style is read from. */\n installed: InstalledPackage;\n}\n\n/** A library found in the project, and where each of its styles is installed. */\nexport interface DetectedLibrary {\n /** How to read the library. */\n adapter: IconAdapter;\n /** The styles the project has installed, empty when it has none. */\n styles: DetectedStyle[];\n /** Whether the project's `package.json` lists the package the library is read from, installed or not. */\n listed: boolean;\n /**\n * Another package of the library the project lists, such as its React version, or undefined when there's none or the\n * library's own package is listed.\n */\n sitePackage?: string;\n /** Folder of the project's own icons, relative to the project, or undefined for a known library. */\n folder?: string;\n}\n\n/** Where the build step reads libraries from and caches conversions. */\nexport interface IconSetContext {\n /** The project folder. */\n root: string;\n /** Folder for cached conversions, or undefined to convert every time. */\n cacheDir: string | undefined;\n}\n\n/**\n * Finds every library the project can use: known libraries whose package it lists and has installed, and its own icon\n * folders. Only listed packages count, so a package that's only there because another one depends on it is ignored.\n *\n * @param root - The project folder.\n * @param custom - The project's own icon folders, keyed by identifier.\n * @returns Every library the build step knows, with where it's installed.\n */\nexport async function detectLibraries(root: string, custom: Record<string, string> = {}): Promise<DetectedLibrary[]> {\n const declared = await readDeclaredPackages(root);\n\n const known = await Promise.all(\n iconAdapters.map(async (adapter) => {\n const { packageName, packagePrefix, packagePattern } = adapter;\n\n if (isDefined(packagePrefix)) {\n const names = [...declared].filter((name) => name.startsWith(packagePrefix)).toSorted();\n const found = await Promise.all(\n names.map(async (name) => {\n const installed = await findPackage(root, name);\n\n return isDefined(installed) ? [{ style: name.slice(packagePrefix.length), installed }] : [];\n }),\n );\n\n return { adapter, styles: found.flat(), listed: isDefined(names) };\n }\n\n const listed = isDefined(packageName) && declared.has(packageName);\n const installed = listed ? await findPackage(root, packageName) : undefined;\n const styles = isDefined(installed) ? adapter.styles.map((style) => ({ style, installed })) : [];\n const sitePackage =\n listed || !isDefined(packagePattern)\n ? undefined\n : [...declared].toSorted().find((name) => packagePattern.test(name));\n\n return { adapter, styles, listed, ...(isDefined(sitePackage) && { sitePackage }) };\n }),\n );\n\n const folders = Object.entries(custom).map(([library, folder]) => ({\n adapter: createCustomAdapter(library, folder),\n listed: true,\n folder,\n styles: [\n { style: \"default\", installed: { name: library, directory: path.resolve(root, folder), version: \"custom\" } },\n ],\n }));\n\n return [...known, ...folders];\n}\n\n/**\n * Picks the root most icons in a set share, so only the others need their own.\n *\n * @param icons - The converted icons.\n * @returns The most common root.\n */\nfunction findCommonRoot(icons: (IconSetIcon & { root: NonNullable<IconSetIcon[\"root\"]> })[]) {\n const counts = new Map<string, { root: IconSet[\"root\"]; count: number }>();\n\n for (const { root } of icons) {\n const key = JSON.stringify(root);\n counts.set(key, { root, count: (counts.get(key)?.count ?? 0) + 1 });\n }\n\n const [common] = [...counts.values()].toSorted((first, second) => second.count - first.count);\n\n return common?.root ?? {};\n}\n\n/**\n * Checks whether a value is an icon as a worker read it from its library.\n *\n * @param value - The value to check.\n * @returns True if the value is a source icon.\n */\nfunction isSourceIcon(value: unknown): value is SourceIcon {\n if (!isRecord(value)) return false;\n\n const { name, keywords, svg } = value;\n\n return (\n typeof name === \"string\" &&\n Array.isArray(keywords) &&\n keywords.every((keyword) => typeof keyword === \"string\") &&\n typeof svg === \"string\"\n );\n}\n\n/**\n * Reads a library's icons in a fresh worker thread. A long-running bundler keeps every module it has imported, so an\n * icon package updated in place would otherwise be read from the old copy.\n *\n * @param library - The library and where it's installed.\n * @param style - The style to read.\n * @param root - The project folder.\n * @returns The icons as the library ships them.\n */\nasync function readSources(library: DetectedLibrary, style: string, root: string) {\n const { adapter, folder } = library;\n const installed = library.styles.find((candidate) => candidate.style === style)?.installed;\n if (!isDefined(installed)) return [];\n\n const worker = new Worker(new URL(\"read-worker.js\", import.meta.url), {\n workerData: { library: adapter.library, folder, style, root, directory: installed.directory },\n // Libraries' components render with React's production build, which writes the same markup without warnings.\n env: { ...process.env, NODE_ENV: \"production\" },\n });\n\n try {\n const received: unknown[] = await once(worker, \"message\");\n const [sources] = received;\n\n return Array.isArray(sources) ? sources.filter((source) => isSourceIcon(source)) : [];\n } finally {\n void worker.terminate();\n }\n}\n\n/**\n * Converts one style of a library into a set, reporting anything skipped.\n *\n * @param library - The library and where it's installed.\n * @param style - The style to convert.\n * @param root - The project folder.\n * @returns The set and its report.\n */\nasync function convertIconSet(library: DetectedLibrary, style: string, root: string) {\n const { adapter } = library;\n const started = performance.now();\n const sources = await readSources(library, style, root);\n\n const report: IconSetReport = { total: sources.length, skipped: [], duration: 0 };\n const converted: (IconSetIcon & { root: NonNullable<IconSetIcon[\"root\"]> })[] = [];\n\n for (const source of sources) {\n const { icon, problem } = convertIcon(source);\n\n if (isDefined(icon)) converted.push(icon);\n else if (isDefined(problem)) report.skipped.push({ name: source.name, reason: problem });\n }\n\n const common = findCommonRoot(converted);\n const set: IconSet = {\n library: adapter.library,\n style,\n root: common,\n icons: converted.map(({ root: iconRoot, ...icon }) =>\n JSON.stringify(iconRoot) === JSON.stringify(common) ? icon : { ...icon, root: iconRoot },\n ),\n };\n\n report.duration = Math.round(performance.now() - started);\n\n return { set, report };\n}\n\n/**\n * Reads a cached conversion's report.\n *\n * @param value - The cached report.\n * @returns The report, or undefined when the value isn't one.\n */\nfunction parseReport(value: unknown): IconSetReport | undefined {\n if (!isRecord(value) || typeof value[\"total\"] !== \"number\" || !Array.isArray(value[\"skipped\"])) return undefined;\n\n const skipped = value[\"skipped\"].flatMap((entry: unknown) =>\n isRecord(entry) && typeof entry[\"name\"] === \"string\" && typeof entry[\"reason\"] === \"string\"\n ? [{ name: entry[\"name\"], reason: entry[\"reason\"] }]\n : [],\n );\n\n return { total: value[\"total\"], skipped, duration: 0 };\n}\n\n/**\n * Loads a converted set, from the cache when the same package version was converted before.\n *\n * @param library - The library and where it's installed.\n * @param style - The style to load.\n * @param context - The project folder and cache folder.\n * @returns The set and its report.\n */\nexport async function loadIconSet(library: DetectedLibrary, style: string, context: IconSetContext) {\n const { adapter, folder } = library;\n const installed = library.styles.find((candidate) => candidate.style === style)?.installed;\n const cacheable = isDefined(context.cacheDir) && isDefined(installed) && !isDefined(folder);\n const cacheFile =\n cacheable && isDefined(context.cacheDir)\n ? path.join(\n context.cacheDir,\n \"driftime-icon\",\n `${adapter.library}-${style}-${installed.name.replaceAll(/[@/]/gu, \"_\")}-${installed.version}-${await readPluginBuild()}.json`,\n )\n : undefined;\n\n if (isDefined(cacheFile)) {\n const cached = await readJson(cacheFile);\n const set = isRecord(cached) ? parseIconSet(cached[\"set\"]) : undefined;\n const report = isRecord(cached) ? parseReport(cached[\"report\"]) : undefined;\n\n if (isDefined(set) && isDefined(report)) return { set, report };\n }\n\n const { set, report } = await convertIconSet(library, style, context.root);\n\n if (isDefined(cacheFile)) {\n await mkdir(path.dirname(cacheFile), { recursive: true });\n await writeFile(cacheFile, JSON.stringify({ set, report }));\n }\n\n return { set, report };\n}\n\n/**\n * Lists the files the registry is generated from, so the bundler regenerates it when a library is installed, removed,\n * or updated, instead of keeping a cached copy.\n *\n * @param root - The project folder.\n * @param libraries - Every library the build step knows.\n * @returns The files, and the folders of the project's own icons.\n */\nexport function listRegistryDependencies(root: string, libraries: DetectedLibrary[]) {\n const files = [path.join(root, \"package.json\")];\n const folders: string[] = [];\n\n for (const { styles, folder } of libraries) {\n for (const { installed } of styles) {\n if (isDefined(folder)) folders.push(installed.directory);\n else files.push(path.join(installed.directory, \"package.json\"));\n }\n }\n\n return { files, folders };\n}\n\n/**\n * Summarises a set's conversion for the build's log, listing the first few icons it skipped and why.\n *\n * @param label - Readable name of the library.\n * @param style - The style converted.\n * @param report - What happened.\n * @returns The summary, one line per skipped icon after the first.\n */\nexport function describeReport(label: string, style: string, report: IconSetReport) {\n const { total, skipped, duration } = report;\n const kept = total - skipped.length;\n const count = `${kept.toLocaleString(\"en-US\")} ${kept === 1 ? \"icon\" : \"icons\"}`;\n const timing = duration > 0 ? `converted in ${duration.toLocaleString(\"en-US\")} ms` : \"loaded from the cache\";\n const summary = `${label} (\\`${style}\\`): ${count} ${timing}`;\n if (!isDefined(skipped)) return `${summary}.`;\n\n const shown = skipped.slice(0, 5).map(({ name, reason }) => ` \\`${name}\\` ${reason}.`);\n const hidden = skipped.length - shown.length;\n const more = hidden > 0 ? [` …and ${hidden.toLocaleString(\"en-US\")} more.`] : [];\n\n return [`${summary}, ${skipped.length.toLocaleString(\"en-US\")} skipped:`, ...shown, ...more].join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;AASA,MAAMO,YAAYJ,KAAKK,KAAK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","IconNode","IconRoot","parseIconNode","parseIconRoot","IconSetIcon","name","keywords","node","root","IconSet","library","style","icons","IconLibraryInfo","label","packageName","packagePrefix","styles","listed","installed","sitePackage","parseIconSetIcon","value","undefined","parsedNode","parsedRoot","Array","isArray","filter","keyword","parseIconSet","flatMap","icon","parsed"],"sources":["../src/lib/sets.ts"],"sourcesContent":["import { isDefined, isRecord } from \"@repo/lib/utils\";\n\nimport type { IconNode, IconRoot } from \"@/lib/nodes\";\nimport { parseIconNode, parseIconRoot } from \"@/lib/nodes\";\n\n/** One icon in a converted set. */\nexport interface IconSetIcon {\n /** Name of the icon in its library. */\n name: string;\n /** Words describing the icon, from its library. */\n keywords: string[];\n /** Shapes the icon is drawn from. */\n node: IconNode;\n /** Root for this icon, or undefined when it uses the set's. */\n root?: IconRoot;\n}\n\n/** Icons of one library style, converted by the build step into the stored drawing format. */\nexport interface IconSet {\n /** Identifier of the library, such as `lucide`. */\n library: string;\n /** Identifier of the style, such as `bold`. */\n style: string;\n /** Root most icons in the set share. */\n root: IconRoot;\n /** Every icon in the set. */\n icons: IconSetIcon[];\n}\n\n/**\n * A library the build step knows how to convert, and whether the project has it installed.\n *\n * @public\n */\nexport interface IconLibraryInfo {\n /** Readable name of the library. */\n label: string;\n /** Package the library is read from, or an example of one for a family of packages. */\n packageName: string;\n /** Shared start of the package names of a family of packages, one per style, or undefined for a single package. */\n packagePrefix?: string;\n /** Styles the library offers, the first being the default. */\n styles: string[];\n /** Whether the project's `package.json` lists the package, installed or not. */\n listed: boolean;\n /** Whether the project has the package installed. */\n installed: boolean;\n /** Another package of the library the project lists, such as its React version, or undefined when there's none. */\n sitePackage?: string;\n}\n\n/**\n * Reads one icon of a converted set, skipping it when its data isn't usable.\n *\n * @param value - The value to read.\n * @returns The icon, or undefined when the value isn't one.\n */\nfunction parseIconSetIcon(value: unknown): IconSetIcon | undefined {\n if (!isRecord(value)) return undefined;\n\n const { name, keywords, node, root } = value;\n const parsedNode = parseIconNode(node);\n const parsedRoot = isDefined(root) ? parseIconRoot(root) : undefined;\n\n if (typeof name !== \"string\" || !Array.isArray(keywords) || !isDefined(parsedNode)) return undefined;\n if (isDefined(root) && !isDefined(parsedRoot)) return undefined;\n\n return {\n name,\n keywords: keywords.filter((keyword: unknown) => typeof keyword === \"string\"),\n node: parsedNode,\n ...(isDefined(parsedRoot) && { root: parsedRoot }),\n };\n}\n\n/**\n * Reads a converted set, keeping only the icons whose data is usable.\n *\n * @param value - The value to read.\n * @returns The set, or undefined when the value isn't one.\n */\nexport function parseIconSet(value: unknown): IconSet | undefined {\n if (!isRecord(value)) return undefined;\n\n const { library, style, root, icons } = value;\n const parsedRoot = parseIconRoot(root);\n\n if (typeof library !== \"string\" || typeof style !== \"string\" || !isDefined(parsedRoot) || !Array.isArray(icons)) {\n return undefined;\n }\n\n return {\n library,\n style,\n root: parsedRoot,\n icons: icons.flatMap((icon: unknown) => {\n const parsed = parseIconSetIcon(icon);\n\n return isDefined(parsed) ? [parsed] : [];\n }),\n };\n}\n"],"mappings":";;;;;;;;AAyDA,SAASuB,iBAAiBC,OAAyC;CACjE,IAAI,CAACvB,SAASuB,KAAK,GAAG;CAEtB,IAAM,EAAEjB,MAAMC,UAAUC,MAAMC,SAASc,OACjCE,aAAatB,cAAcK,IAAI,GAC/BkB,aAAa3B,UAAUU,IAAI,IAAIL,cAAcK,IAAI,IAAIe,KAAAA;CAE3D,IAAI,OAAOlB,QAAS,YAAaqB,MAAMC,QAAQrB,QAAQ,KAAMR,UAAU0B,UAAU,MAC7E1B,WAAUU,IAAI,KAAMV,UAAU2B,UAAU,IAE5C,OAAO;EACLpB;EACAC,UAAUA,SAASsB,QAAQC,YAAqB,OAAOA,WAAY,QAAQ;EAC3EtB,MAAMiB;EACN,GAAI1B,UAAU2B,UAAU,KAAK,EAAEjB,MAAMiB,WAAW;CAClD;AACF;;;;;;;AAQA,SAAgBK,aAAaR,OAAqC;CAChE,IAAI,CAACvB,SAASuB,KAAK,GAAG;CAEtB,IAAM,EAAEZ,SAASC,OAAOH,MAAMI,UAAUU,OAClCG,aAAatB,cAAcK,IAAI;CAErC,IAAI,OAAOE,WAAY,YAAY,OAAOC,SAAU,YAAab,UAAU2B,UAAU,KAAMC,MAAMC,QAAQf,KAAK,GAI9G,OAAO;EACLF;EACAC;EACAH,MAAMiB;EACNb,OAAOA,MAAMmB,SAASC,SAAkB;GACtC,IAAMC,SAASZ,iBAAiBW,IAAI;GAEpC,OAAOlC,UAAUmC,MAAM,IAAI,CAACA,MAAM,IAAI,CAAA;EACxC,CAAC;CACH;AACF"}
|
package/dist/utils-COPacfAq.js
DELETED
|
@@ -1,48 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Checks whether a value is present. `false`, blank strings, and empty plain objects count as absent,
|
|
3
|
-
* as does an array with no present elements.
|
|
4
|
-
*
|
|
5
|
-
* @param value - The value to check.
|
|
6
|
-
* @returns True if the value is present.
|
|
7
|
-
*/
|
|
8
|
-
function isDefined(value) {
|
|
9
|
-
if (value == null || value === !1) return !1;
|
|
10
|
-
if (typeof value == "string") return value.trim() !== "";
|
|
11
|
-
if (Array.isArray(value)) return value.some((element) => isDefined(element));
|
|
12
|
-
if (typeof value == "object") {
|
|
13
|
-
let prototype = Reflect.getPrototypeOf(value);
|
|
14
|
-
return prototype !== Object.prototype && prototype !== null || Object.keys(value).length > 0;
|
|
15
|
-
}
|
|
16
|
-
return !0;
|
|
17
|
-
}
|
|
18
|
-
/**
|
|
19
|
-
* Converts a string to another case.
|
|
20
|
-
*
|
|
21
|
-
* @param value - The string to convert.
|
|
22
|
-
* @param format - The case to convert to.
|
|
23
|
-
* @returns The converted string.
|
|
24
|
-
*/
|
|
25
|
-
function convertCase(value, format) {
|
|
26
|
-
let words = value.replaceAll(/(?<lower>[a-z0-9])(?<upper>[A-Z])/gu, "$<lower> $<upper>").replaceAll(/[-_\s]+/gu, " ").trim().toLowerCase();
|
|
27
|
-
switch (format) {
|
|
28
|
-
case "kebab": return words.replaceAll(/\s+/gu, "-");
|
|
29
|
-
case "snake": return words.replaceAll(/\s+/gu, "_");
|
|
30
|
-
case "camel": return words.replaceAll(/\s+(?<character>.)/gu, (_match, character) => character.toUpperCase());
|
|
31
|
-
case "pascal": return words.replaceAll(/(?:^|\s+)(?<character>.)/gu, (_match, character) => character.toUpperCase());
|
|
32
|
-
case "title": return words.replaceAll(/\b\w/gu, (character) => character.toUpperCase());
|
|
33
|
-
case "sentence": return words.replaceAll(/^(?<character>.)/gu, (character) => character.toUpperCase());
|
|
34
|
-
default: return value;
|
|
35
|
-
}
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Checks whether a value is an object whose keys can be read.
|
|
39
|
-
*
|
|
40
|
-
* @param value - The value to check.
|
|
41
|
-
* @returns True if the value is an object.
|
|
42
|
-
*/
|
|
43
|
-
function isRecord(value) {
|
|
44
|
-
return typeof value == "object" && !!value;
|
|
45
|
-
}
|
|
46
|
-
export { isDefined as n, isRecord as r, convertCase as t };
|
|
47
|
-
|
|
48
|
-
//# sourceMappingURL=utils-COPacfAq.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"utils-COPacfAq.js","names":["Nullable","T","isDefined","value","undefined","trim","Array","isArray","some","element","prototype","Reflect","getPrototypeOf","Object","keys","length","convertCase","format","words","replaceAll","toLowerCase","_match","character","toUpperCase","isRecord","Record","readPath","path","current","segment"],"sources":["../../@repo/lib/utils.ts"],"sourcesContent":["/** A value that may be null or undefined. */\ntype Nullable<T> = T | null | undefined;\n\n/**\n * Checks whether a value is present. `false`, blank strings, and empty plain objects count as absent,\n * as does an array with no present elements.\n *\n * @param value - The value to check.\n * @returns True if the value is present.\n */\nexport function isDefined<T>(value: Nullable<T> | false): value is T {\n if (value === undefined || value === null || value === false) return false;\n if (typeof value === \"string\") return value.trim() !== \"\";\n if (Array.isArray(value)) return value.some((element) => isDefined(element));\n\n if (typeof value === \"object\") {\n const prototype = Reflect.getPrototypeOf(value);\n if (prototype !== Object.prototype && prototype !== null) return true;\n\n return Object.keys(value).length > 0;\n }\n\n return true;\n}\n\n/**\n * Converts a string to another case.\n *\n * @param value - The string to convert.\n * @param format - The case to convert to.\n * @returns The converted string.\n */\nexport function convertCase(value: string, format: \"kebab\" | \"snake\" | \"camel\" | \"pascal\" | \"title\" | \"sentence\") {\n const words = value\n .replaceAll(/(?<lower>[a-z0-9])(?<upper>[A-Z])/gu, \"$<lower> $<upper>\")\n .replaceAll(/[-_\\s]+/gu, \" \")\n .trim()\n .toLowerCase();\n\n switch (format) {\n case \"kebab\": {\n return words.replaceAll(/\\s+/gu, \"-\");\n }\n case \"snake\": {\n return words.replaceAll(/\\s+/gu, \"_\");\n }\n case \"camel\": {\n return words.replaceAll(/\\s+(?<character>.)/gu, (_match, character: string) => character.toUpperCase());\n }\n case \"pascal\": {\n return words.replaceAll(/(?:^|\\s+)(?<character>.)/gu, (_match, character: string) => character.toUpperCase());\n }\n case \"title\": {\n return words.replaceAll(/\\b\\w/gu, (character) => character.toUpperCase());\n }\n case \"sentence\": {\n return words.replaceAll(/^(?<character>.)/gu, (character) => character.toUpperCase());\n }\n default: {\n return value;\n }\n }\n}\n\n/**\n * Checks whether a value is an object whose keys can be read.\n *\n * @param value - The value to check.\n * @returns True if the value is an object.\n */\nexport function isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null;\n}\n\n/**\n * Reads a nested value by following a path of keys.\n *\n * @param value - The object to read from.\n * @param path - The keys to follow.\n * @returns The value, or undefined when the path doesn't exist.\n */\nexport function readPath(value: unknown, path: string[]) {\n let current: unknown = value;\n\n for (const segment of path) {\n if (!isRecord(current)) return undefined;\n\n current = current[segment];\n }\n\n return current;\n}\n"],"mappings":";;;;;;;AAUA,SAAgBE,UAAaC,OAAwC;CACnE,IAAIA,SAAiC,QAAQA,UAAU,IAAO,OAAO;CACrE,IAAI,OAAOA,SAAU,UAAU,OAAOA,MAAME,KAAK,MAAM;CACvD,IAAIC,MAAMC,QAAQJ,KAAK,GAAG,OAAOA,MAAMK,MAAMC,YAAYP,UAAUO,OAAO,CAAC;CAE3E,IAAI,OAAON,SAAU,UAAU;EAC7B,IAAMO,YAAYC,QAAQC,eAAeT,KAAK;EAG9C,OAFIO,cAAcG,OAAOH,aAAaA,cAAc,QAE7CG,OAAOC,KAAKX,KAAK,CAAC,CAACY,SAAS;CACrC;CAEA,OAAO;AACT;;;;;;;;AASA,SAAgBC,YAAYb,OAAec,QAAuE;CAChH,IAAMC,QAAQf,MACXgB,WAAW,uCAAuC,mBAAmB,CAAC,CACtEA,WAAW,aAAa,GAAG,CAAC,CAC5Bd,KAAK,CAAC,CACNe,YAAY;CAEf,QAAQH,QAAR;EACE,KAAK,SACH,OAAOC,MAAMC,WAAW,SAAS,GAAG;EAEtC,KAAK,SACH,OAAOD,MAAMC,WAAW,SAAS,GAAG;EAEtC,KAAK,SACH,OAAOD,MAAMC,WAAW,yBAAyBE,QAAQC,cAAsBA,UAAUC,YAAY,CAAC;EAExG,KAAK,UACH,OAAOL,MAAMC,WAAW,+BAA+BE,QAAQC,cAAsBA,UAAUC,YAAY,CAAC;EAE9G,KAAK,SACH,OAAOL,MAAMC,WAAW,WAAWG,cAAcA,UAAUC,YAAY,CAAC;EAE1E,KAAK,YACH,OAAOL,MAAMC,WAAW,uBAAuBG,cAAcA,UAAUC,YAAY,CAAC;EAEtF,SACE,OAAOpB;CAEX;AACF;;;;;;;AAQA,SAAgBqB,SAASrB,OAAkD;CACzE,OAAO,OAAOA,SAAU,cAAYA;AACtC"}
|