@driftime/sanity-plugin-icon 0.3.0 → 0.4.1

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.
Files changed (55) hide show
  1. package/README.md +253 -61
  2. package/dist/adapters-Bx_MyEX_.js +633 -0
  3. package/dist/adapters-Bx_MyEX_.js.map +1 -0
  4. package/dist/drawing-ByrcBbWB.js +50 -0
  5. package/dist/drawing-ByrcBbWB.js.map +1 -0
  6. package/dist/index.d.ts +84 -32
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +545 -323
  9. package/dist/index.js.map +1 -1
  10. package/dist/names.d.ts +8 -0
  11. package/dist/names.d.ts.map +1 -0
  12. package/dist/names.js +0 -0
  13. package/dist/next-loader.d.ts +64 -0
  14. package/dist/next-loader.d.ts.map +1 -0
  15. package/dist/next-loader.js +103 -0
  16. package/dist/next-loader.js.map +1 -0
  17. package/dist/next.d.ts +43 -0
  18. package/dist/next.d.ts.map +1 -0
  19. package/dist/next.js +52 -0
  20. package/dist/next.js.map +1 -0
  21. package/dist/nodes-DAzj56Xn.js +139 -0
  22. package/dist/nodes-DAzj56Xn.js.map +1 -0
  23. package/dist/read-worker.d.ts +1 -0
  24. package/dist/read-worker.js +23 -0
  25. package/dist/read-worker.js.map +1 -0
  26. package/dist/registry-B0Dxiwhh.js +68 -0
  27. package/dist/registry-B0Dxiwhh.js.map +1 -0
  28. package/dist/registry-BEEpqK3z.js +13 -0
  29. package/dist/registry-BEEpqK3z.js.map +1 -0
  30. package/dist/render.d.ts +4 -5
  31. package/dist/render.d.ts.map +1 -1
  32. package/dist/render.js +5 -5
  33. package/dist/render.js.map +1 -1
  34. package/dist/sets-D5_YGFll.js +258 -0
  35. package/dist/sets-D5_YGFll.js.map +1 -0
  36. package/dist/sets-kepuObH8.js +90 -0
  37. package/dist/sets-kepuObH8.js.map +1 -0
  38. package/dist/sets.d.ts +50 -0
  39. package/dist/sets.d.ts.map +1 -0
  40. package/dist/sets.js +14 -0
  41. package/dist/sets.js.map +1 -0
  42. package/dist/types-qlHEYDoN.d.ts +20 -0
  43. package/dist/types-qlHEYDoN.d.ts.map +1 -0
  44. package/dist/utils-COPacfAq.js +48 -0
  45. package/dist/utils-COPacfAq.js.map +1 -0
  46. package/dist/vite-ifICG8y9.d.ts +98 -0
  47. package/dist/vite-ifICG8y9.d.ts.map +1 -0
  48. package/dist/vite.d.ts +2 -0
  49. package/dist/vite.js +88 -0
  50. package/dist/vite.js.map +1 -0
  51. package/package.json +42 -5
  52. package/dist/drawing-BThiR2bN.js +0 -129
  53. package/dist/drawing-BThiR2bN.js.map +0 -1
  54. package/dist/types-_D2jGm25.d.ts +0 -16
  55. package/dist/types-_D2jGm25.d.ts.map +0 -1
@@ -0,0 +1,258 @@
1
+ import { r as pluginName, t as parseIconSet } from "./sets-kepuObH8.js";
2
+ import { n as isDefined, r as isRecord } from "./utils-COPacfAq.js";
3
+ import { i as registryModulePath } from "./registry-B0Dxiwhh.js";
4
+ import { a as readDeclaredPackages, c as convertIcon, n as createCustomAdapter, o as readJson, r as findPackage, s as readPluginBuild, t as iconAdapters } from "./adapters-Bx_MyEX_.js";
5
+ import path from "node:path";
6
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
7
+ import { once } from "node:events";
8
+ import { Worker } from "node:worker_threads";
9
+ /** Types file the plugin reads icon names from, published next to the placeholder registry. */
10
+ const namesFile = path.join(path.dirname(registryModulePath), "names.d.ts");
11
+ /**
12
+ * Writes the installed icon names into the plugin's own types, so options that list icons are checked against them.
13
+ * The file is replaced rather than edited, because pnpm shares a package's files between projects.
14
+ *
15
+ * @param names - Icon names keyed by library.
16
+ */
17
+ async function writeIconNames(names) {
18
+ let entries = [...names].toSorted(([first], [second]) => first.localeCompare(second)).map(([library, icons]) => {
19
+ let union = [...icons].toSorted().map((name) => JSON.stringify(name));
20
+ return ` ${JSON.stringify(library)}: ${isDefined(union) ? union.join(" | ") : "never"};`;
21
+ }), content = [
22
+ `// Written by ${pluginName}'s build step from the project's installed icon libraries.`,
23
+ "export type SanityIconNames = {",
24
+ ...entries,
25
+ "};",
26
+ ""
27
+ ].join("\n");
28
+ if (await readFile(namesFile, "utf8").catch(() => "") === content) return;
29
+ let temporary = `${namesFile}.${process.pid}.tmp`;
30
+ await writeFile(temporary, content), await rename(temporary, namesFile);
31
+ }
32
+ /**
33
+ * Finds every library the project can use: known libraries whose package it lists and has installed, and its own icon
34
+ * folders. Only listed packages count, so a package that's only there because another one depends on it is ignored.
35
+ *
36
+ * @param root - The project folder.
37
+ * @param custom - The project's own icon folders, keyed by identifier.
38
+ * @returns Every library the build step knows, with where it's installed.
39
+ */
40
+ async function detectLibraries(root, custom = {}) {
41
+ let declared = await readDeclaredPackages(root), known = await Promise.all(iconAdapters.map(async (adapter) => {
42
+ let { packageName, packagePrefix, packagePattern } = adapter;
43
+ if (isDefined(packagePrefix)) {
44
+ let names = [...declared].filter((name) => name.startsWith(packagePrefix)).toSorted();
45
+ return {
46
+ adapter,
47
+ styles: (await Promise.all(names.map(async (name) => {
48
+ let installed = await findPackage(root, name);
49
+ return isDefined(installed) ? [{
50
+ style: name.slice(packagePrefix.length),
51
+ installed
52
+ }] : [];
53
+ }))).flat(),
54
+ listed: isDefined(names)
55
+ };
56
+ }
57
+ let listed = isDefined(packageName) && declared.has(packageName), installed = listed ? await findPackage(root, packageName) : void 0, styles = isDefined(installed) ? adapter.styles.map((style) => ({
58
+ style,
59
+ installed
60
+ })) : [], sitePackage = listed || !isDefined(packagePattern) ? void 0 : [...declared].toSorted().find((name) => packagePattern.test(name));
61
+ return {
62
+ adapter,
63
+ styles,
64
+ listed,
65
+ ...isDefined(sitePackage) && { sitePackage }
66
+ };
67
+ })), folders = Object.entries(custom).map(([library, folder]) => ({
68
+ adapter: createCustomAdapter(library, folder),
69
+ listed: !0,
70
+ folder,
71
+ styles: [{
72
+ style: "default",
73
+ installed: {
74
+ name: library,
75
+ directory: path.resolve(root, folder),
76
+ version: "custom"
77
+ }
78
+ }]
79
+ }));
80
+ return [...known, ...folders];
81
+ }
82
+ /**
83
+ * Picks the root most icons in a set share, so only the others need their own.
84
+ *
85
+ * @param icons - The converted icons.
86
+ * @returns The most common root.
87
+ */
88
+ function findCommonRoot(icons) {
89
+ let counts = /* @__PURE__ */ new Map();
90
+ for (let { root } of icons) {
91
+ let key = JSON.stringify(root);
92
+ counts.set(key, {
93
+ root,
94
+ count: (counts.get(key)?.count ?? 0) + 1
95
+ });
96
+ }
97
+ let [common] = [...counts.values()].toSorted((first, second) => second.count - first.count);
98
+ return common?.root ?? {};
99
+ }
100
+ /**
101
+ * Checks whether a value is an icon as a worker read it from its library.
102
+ *
103
+ * @param value - The value to check.
104
+ * @returns True if the value is a source icon.
105
+ */
106
+ function isSourceIcon(value) {
107
+ if (!isRecord(value)) return !1;
108
+ let { name, keywords, svg } = value;
109
+ return typeof name == "string" && Array.isArray(keywords) && keywords.every((keyword) => typeof keyword == "string") && typeof svg == "string";
110
+ }
111
+ /**
112
+ * Reads a library's icons in a fresh worker thread. A long-running bundler keeps every module it has imported, so an
113
+ * icon package updated in place would otherwise be read from the old copy.
114
+ *
115
+ * @param library - The library and where it's installed.
116
+ * @param style - The style to read.
117
+ * @param root - The project folder.
118
+ * @returns The icons as the library ships them.
119
+ */
120
+ async function readSources(library, style, root) {
121
+ let { adapter, folder } = library, installed = library.styles.find((candidate) => candidate.style === style)?.installed;
122
+ if (!isDefined(installed)) return [];
123
+ let worker = new Worker(new URL("read-worker.js", import.meta.url), {
124
+ workerData: {
125
+ library: adapter.library,
126
+ folder,
127
+ style,
128
+ root,
129
+ directory: installed.directory
130
+ },
131
+ env: {
132
+ ...process.env,
133
+ NODE_ENV: "production"
134
+ }
135
+ });
136
+ try {
137
+ let [sources] = await once(worker, "message");
138
+ return Array.isArray(sources) ? sources.filter((source) => isSourceIcon(source)) : [];
139
+ } finally {
140
+ worker.terminate();
141
+ }
142
+ }
143
+ /**
144
+ * Converts one style of a library into a set, reporting anything skipped.
145
+ *
146
+ * @param library - The library and where it's installed.
147
+ * @param style - The style to convert.
148
+ * @param root - The project folder.
149
+ * @returns The set and its report.
150
+ */
151
+ async function convertIconSet(library, style, root) {
152
+ let { adapter } = library, started = performance.now(), sources = await readSources(library, style, root), report = {
153
+ total: sources.length,
154
+ skipped: [],
155
+ duration: 0
156
+ }, converted = [];
157
+ for (let source of sources) {
158
+ let { icon, problem } = convertIcon(source);
159
+ isDefined(icon) ? converted.push(icon) : isDefined(problem) && report.skipped.push({
160
+ name: source.name,
161
+ reason: problem
162
+ });
163
+ }
164
+ let common = findCommonRoot(converted), set = {
165
+ library: adapter.library,
166
+ style,
167
+ root: common,
168
+ icons: converted.map(({ root: iconRoot, ...icon }) => JSON.stringify(iconRoot) === JSON.stringify(common) ? icon : {
169
+ ...icon,
170
+ root: iconRoot
171
+ })
172
+ };
173
+ return report.duration = Math.round(performance.now() - started), {
174
+ set,
175
+ report
176
+ };
177
+ }
178
+ /**
179
+ * Reads a cached conversion's report.
180
+ *
181
+ * @param value - The cached report.
182
+ * @returns The report, or undefined when the value isn't one.
183
+ */
184
+ function parseReport(value) {
185
+ if (!isRecord(value) || typeof value.total != "number" || !Array.isArray(value.skipped)) return;
186
+ let skipped = value.skipped.flatMap((entry) => isRecord(entry) && typeof entry.name == "string" && typeof entry.reason == "string" ? [{
187
+ name: entry.name,
188
+ reason: entry.reason
189
+ }] : []);
190
+ return {
191
+ total: value.total,
192
+ skipped,
193
+ duration: 0
194
+ };
195
+ }
196
+ /**
197
+ * Loads a converted set, from the cache when the same package version was converted before.
198
+ *
199
+ * @param library - The library and where it's installed.
200
+ * @param style - The style to load.
201
+ * @param context - The project folder and cache folder.
202
+ * @returns The set and its report.
203
+ */
204
+ async function loadIconSet(library, style, context) {
205
+ let { adapter, folder } = library, installed = library.styles.find((candidate) => candidate.style === style)?.installed, cacheFile = isDefined(context.cacheDir) && isDefined(installed) && !isDefined(folder) && isDefined(context.cacheDir) ? path.join(context.cacheDir, "driftime-icon", `${adapter.library}-${style}-${installed.name.replaceAll(/[@/]/gu, "_")}-${installed.version}-${await readPluginBuild()}.json`) : void 0;
206
+ if (isDefined(cacheFile)) {
207
+ let cached = await readJson(cacheFile), set = isRecord(cached) ? parseIconSet(cached.set) : void 0, report = isRecord(cached) ? parseReport(cached.report) : void 0;
208
+ if (isDefined(set) && isDefined(report)) return {
209
+ set,
210
+ report
211
+ };
212
+ }
213
+ let { set, report } = await convertIconSet(library, style, context.root);
214
+ return isDefined(cacheFile) && (await mkdir(path.dirname(cacheFile), { recursive: !0 }), await writeFile(cacheFile, JSON.stringify({
215
+ set,
216
+ report
217
+ }))), {
218
+ set,
219
+ report
220
+ };
221
+ }
222
+ /**
223
+ * Lists the files the registry is generated from, so the bundler regenerates it when a library is installed, removed,
224
+ * or updated, instead of keeping a cached copy.
225
+ *
226
+ * @param root - The project folder.
227
+ * @param libraries - Every library the build step knows.
228
+ * @returns The files, and the folders of the project's own icons.
229
+ */
230
+ function listRegistryDependencies(root, libraries) {
231
+ let files = [path.join(root, "package.json")], folders = [];
232
+ for (let { styles, folder } of libraries) for (let { installed } of styles) isDefined(folder) ? folders.push(installed.directory) : files.push(path.join(installed.directory, "package.json"));
233
+ return {
234
+ files,
235
+ folders
236
+ };
237
+ }
238
+ /**
239
+ * Summarises a set's conversion for the build's log, listing the first few icons it skipped and why.
240
+ *
241
+ * @param label - Readable name of the library.
242
+ * @param style - The style converted.
243
+ * @param report - What happened.
244
+ * @returns The summary, one line per skipped icon after the first.
245
+ */
246
+ function describeReport(label, style, report) {
247
+ let { total, skipped, duration } = report, kept = total - skipped.length, summary = `${label} (\`${style}\`): ${`${kept.toLocaleString("en-US")} ${kept === 1 ? "icon" : "icons"}`} ${duration > 0 ? `converted in ${duration.toLocaleString("en-US")} ms` : "loaded from the cache"}`;
248
+ if (!isDefined(skipped)) return `${summary}.`;
249
+ let shown = skipped.slice(0, 5).map(({ name, reason }) => ` \`${name}\` ${reason}.`), hidden = skipped.length - shown.length, more = hidden > 0 ? [` …and ${hidden.toLocaleString("en-US")} more.`] : [];
250
+ return [
251
+ `${summary}, ${skipped.length.toLocaleString("en-US")} skipped:`,
252
+ ...shown,
253
+ ...more
254
+ ].join("\n");
255
+ }
256
+ export { writeIconNames as a, loadIconSet as i, detectLibraries as n, listRegistryDependencies as r, describeReport as t };
257
+
258
+ //# sourceMappingURL=sets-D5_YGFll.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sets-D5_YGFll.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,KAAKL,KAAKM,QAAQJ,kBAAkB,GAAG,YAAY;;;;;;;AAQ1E,eAAsBK,eAAeC,OAAiC;CACpE,IAAMG,UAAU,CAAC,GAAGH,KAAK,CAAC,CACvBI,UAAU,CAACC,QAAQ,CAACC,YAAYD,MAAME,cAAcD,MAAM,CAAC,CAAC,CAC5DE,KAAK,CAACC,SAASC,WAAW;EACzB,IAAMC,QAAQ,CAAC,GAAGD,KAAK,CAAC,CAACN,SAAS,CAAC,CAACI,KAAKI,SAASC,KAAKC,UAAUF,IAAI,CAAC;EAEtE,OAAO,KAAKC,KAAKC,UAAUL,OAAO,EAAC,IAAKhB,UAAUkB,KAAK,IAAIA,MAAMd,KAAK,KAAK,IAAI,QAAO;CACxF,CAAC,GAEGkB,UAAU;EACd,iBAAiBpB,WAAU;EAC3B;EACA,GAAGQ;EACH;EACA;CAAE,CACH,CAACN,KAAK,IAAI;CAGX,IAAImB,MADkB3B,SAASO,WAAW,MAAM,CAAC,CAACqB,YAAY,EAAE,MAChDF,SAAS;CAEzB,IAAMG,YAAY,GAAGtB,UAAS,GAAIuB,QAAQC,IAAG;CAE7C,AADA,MAAM7B,UAAU2B,WAAWH,OAAO,GAClC,MAAMzB,OAAO4B,WAAWtB,SAAS;AACnC;;;;;;;;;AC4BA,eAAsB+D,gBAAgBF,MAAcG,SAAiC,CAAC,GAA+B;CACnH,IAAMG,WAAW,MAAM5B,qB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,KAAMC,OAAM,EAAG,GAChFoH,SAAStH,QAAQiC,SAASoF,MAAMpF,QAChCsF,OAAOD,SAAS,IAAI,CAAC,UAAUA,OAAOJ,eAAe,OAAO,EAAC,OAAQ,IAAI,CAAA;CAE/E,OAAO;EAAC,GAAGE,QAAO,IAAKpH,QAAQiC,OAAOiF,eAAe,OAAO,EAAC;EAAa,GAAGG;EAAO,GAAGE;CAAI,CAAC,CAAChB,KAAK,IAAI;AACxG"}
@@ -0,0 +1,90 @@
1
+ import { n as isDefined, r as isRecord } from "./utils-COPacfAq.js";
2
+ import { i as parseIconRoot, r as parseIconNode } from "./nodes-DAzj56Xn.js";
3
+ /** Whether this is a development build, the only kind in which the plugin logs. */
4
+ const isDevelopment = process.env.NODE_ENV === "development", prefixStyle = "color: #2276fc";
5
+ /**
6
+ * Creates a logger that prefixes messages with the plugin's name and only logs in development builds.
7
+ * Browser consoles show the prefix in blue.
8
+ *
9
+ * @param name - The package name to prefix messages with.
10
+ * @returns Functions that log progress, a warning, or an error, or format a message to throw.
11
+ */
12
+ function createLogger(name) {
13
+ let prefix = `[${name}]`;
14
+ /**
15
+ * Prefixes a message with the package name.
16
+ *
17
+ * @param message - The message.
18
+ * @returns The prefixed message.
19
+ */
20
+ function format(message) {
21
+ return `${prefix} ${message}`;
22
+ }
23
+ return {
24
+ /**
25
+ * Logs progress worth seeing, such as what a build step did, in development builds only.
26
+ *
27
+ * @param message - What happened.
28
+ */
29
+ info(message) {
30
+ isDevelopment && console.info(`%c${prefix}%c ${message}`, prefixStyle, "");
31
+ },
32
+ /**
33
+ * Logs a warning about something the plugin recovered from, in development builds only.
34
+ *
35
+ * @param message - What happened and what to do about it.
36
+ */
37
+ warn(message) {
38
+ isDevelopment && console.warn(`%c${prefix}%c ${message}`, prefixStyle, "");
39
+ },
40
+ /**
41
+ * Logs an error the plugin couldn't recover from, in development builds only.
42
+ *
43
+ * @param message - What went wrong and what to do about it.
44
+ */
45
+ error(message) {
46
+ isDevelopment && console.error(`%c${prefix}%c ${message}`, prefixStyle, "");
47
+ },
48
+ format
49
+ };
50
+ }
51
+ /** Package name, used as the prefix on every logged message. */
52
+ const pluginName = "@driftime/sanity-plugin-icon", logger = createLogger(pluginName);
53
+ /**
54
+ * Reads one icon of a converted set, skipping it when its data isn't usable.
55
+ *
56
+ * @param value - The value to read.
57
+ * @returns The icon, or undefined when the value isn't one.
58
+ */
59
+ function parseIconSetIcon(value) {
60
+ if (!isRecord(value)) return;
61
+ let { name, keywords, node, root } = value, parsedNode = parseIconNode(node), parsedRoot = isDefined(root) ? parseIconRoot(root) : void 0;
62
+ if (typeof name == "string" && Array.isArray(keywords) && isDefined(parsedNode) && (!isDefined(root) || isDefined(parsedRoot))) return {
63
+ name,
64
+ keywords: keywords.filter((keyword) => typeof keyword == "string"),
65
+ node: parsedNode,
66
+ ...isDefined(parsedRoot) && { root: parsedRoot }
67
+ };
68
+ }
69
+ /**
70
+ * Reads a converted set, keeping only the icons whose data is usable.
71
+ *
72
+ * @param value - The value to read.
73
+ * @returns The set, or undefined when the value isn't one.
74
+ */
75
+ function parseIconSet(value) {
76
+ if (!isRecord(value)) return;
77
+ let { library, style, root, icons } = value, parsedRoot = parseIconRoot(root);
78
+ if (typeof library == "string" && typeof style == "string" && isDefined(parsedRoot) && Array.isArray(icons)) return {
79
+ library,
80
+ style,
81
+ root: parsedRoot,
82
+ icons: icons.flatMap((icon) => {
83
+ let parsed = parseIconSetIcon(icon);
84
+ return isDefined(parsed) ? [parsed] : [];
85
+ })
86
+ };
87
+ }
88
+ export { logger as n, pluginName as r, parseIconSet as t };
89
+
90
+ //# sourceMappingURL=sets-kepuObH8.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sets-kepuObH8.js","names":["isDevelopment","process","env","isDevelopment","prefixStyle","createLogger","name","prefix","format","message","info","console","warn","error","createLogger","pluginName","logger","isDefined","isRecord","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","\"NODE_ENV\""],"sources":["../../@repo/lib/environment.ts","../../@repo/lib/logger.ts","../src/config/defaults.ts","../src/lib/sets.ts"],"sourcesContent":["/** Whether this is a development build, the only kind in which the plugin logs. */\nexport const isDevelopment = process.env[\"NODE_ENV\"] === \"development\";\n","import { isDevelopment } from \"./environment\";\n\n/** Console style for the prefix, in the blue the Studio uses for its own messages. */\nconst prefixStyle = \"color: #2276fc\";\n\n/**\n * Creates a logger that prefixes messages with the plugin's name and only logs in development builds.\n * Browser consoles show the prefix in blue.\n *\n * @param name - The package name to prefix messages with.\n * @returns Functions that log progress, a warning, or an error, or format a message to throw.\n */\nexport function createLogger(name: string) {\n const prefix = `[${name}]`;\n\n /**\n * Prefixes a message with the package name.\n *\n * @param message - The message.\n * @returns The prefixed message.\n */\n function format(message: string) {\n return `${prefix} ${message}`;\n }\n\n return {\n /**\n * Logs progress worth seeing, such as what a build step did, in development builds only.\n *\n * @param message - What happened.\n */\n info(message: string) {\n if (isDevelopment) console.info(`%c${prefix}%c ${message}`, prefixStyle, \"\");\n },\n /**\n * Logs a warning about something the plugin recovered from, in development builds only.\n *\n * @param message - What happened and what to do about it.\n */\n warn(message: string) {\n if (isDevelopment) console.warn(`%c${prefix}%c ${message}`, prefixStyle, \"\");\n },\n /**\n * Logs an error the plugin couldn't recover from, in development builds only.\n *\n * @param message - What went wrong and what to do about it.\n */\n error(message: string) {\n if (isDevelopment) console.error(`%c${prefix}%c ${message}`, prefixStyle, \"\");\n },\n format,\n };\n}\n","import { createLogger } from \"@repo/lib/logger\";\n\n/** Package name, used as the prefix on every logged message. */\nexport const pluginName = \"@driftime/sanity-plugin-icon\";\n\n/** The package's logger. */\nexport const logger = createLogger(pluginName);\n","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":";;;AACA,MAAaA,gBAAgBC,QAAQC,IAAImD,aAAgB,eCEnDjD,cAAc;;;;;;;;AASpB,SAAgBC,aAAaC,MAAc;CACzC,IAAMC,SAAS,IAAID,KAAI;;;;;;;CAQvB,SAASE,OAAOC,SAAiB;EAC/B,OAAO,GAAGF,OAAM,GAAIE;CACtB;CAEA,OAAO;;;;;;EAMLC,KAAKD,SAAiB;GACpB,AAAIN,iBAAeQ,QAAQD,KAAK,KAAKH,OAAM,KAAME,WAAWL,aAAa,EAAE;EAC7E;;;;;;EAMAQ,KAAKH,SAAiB;GACpB,AAAIN,iBAAeQ,QAAQC,KAAK,KAAKL,OAAM,KAAME,WAAWL,aAAa,EAAE;EAC7E;;;;;;EAMAS,MAAMJ,SAAiB;GACrB,AAAIN,iBAAeQ,QAAQE,MAAM,KAAKN,OAAM,KAAME,WAAWL,aAAa,EAAE;EAC9E;EACAI;CACF;AACF;;ACjDA,MAAaO,aAAa,gCAGbC,SAASF,aAAaC,UAAU;;;;;;;ACmD7C,SAASyB,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/sets.d.ts ADDED
@@ -0,0 +1,50 @@
1
+ /**
2
+ * A library the build step knows how to convert, and whether the project has it installed.
3
+ *
4
+ * @public
5
+ */
6
+ interface IconLibraryInfo {
7
+ /** Readable name of the library. */
8
+ label: string;
9
+ /** Package the library is read from, or an example of one for a family of packages. */
10
+ packageName: string;
11
+ /** Shared start of the package names of a family of packages, one per style, or undefined for a single package. */
12
+ packagePrefix?: string;
13
+ /** Styles the library offers, the first being the default. */
14
+ styles: string[];
15
+ /** Whether the project's `package.json` lists the package, installed or not. */
16
+ listed: boolean;
17
+ /** Whether the project has the package installed. */
18
+ installed: boolean;
19
+ /** Another package of the library the project lists, such as its React version, or undefined when there's none. */
20
+ sitePackage?: string;
21
+ }
22
+ /**
23
+ * Loads one converted set, as a module whose default export is the set.
24
+ *
25
+ * @public
26
+ */
27
+ type IconSetLoader = () => Promise<{
28
+ default: unknown;
29
+ }>;
30
+ /**
31
+ * What the build step generates: a loader for every converted set, and every library it knows.
32
+ *
33
+ * @public
34
+ */
35
+ interface IconRegistry {
36
+ /** Whether the build step generated the registry, rather than the placeholder being used. */
37
+ ready: boolean;
38
+ /** Loaders keyed by library and style, such as `phosphor/bold`. */
39
+ sets: Record<string, IconSetLoader>;
40
+ /** Libraries the build step knows, keyed by identifier. */
41
+ libraries: Record<string, IconLibraryInfo>;
42
+ }
43
+ /**
44
+ * Converted icon sets for the Studio. This is a placeholder: the build step replaces the module with the sets it
45
+ * converted from the project's installed libraries, so a Studio built without it finds no libraries.
46
+ *
47
+ * @public
48
+ */
49
+ export declare const iconRegistry: IconRegistry;
50
+ //# sourceMappingURL=sets.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sets.d.ts","names":["IconNode","IconRoot","IconSetIcon","IconSet","IconLibraryInfo","parseIconSet","IconLibraryInfo","IconSetLoader","Promise","IconRegistry","Record","getIconSetKey","IconRegistry","iconRegistry"],"sources":["../src/lib/sets.ts","../src/lib/registry.ts","../src/sets.ts"],"mappings":"AAkCA;;;;;UAAiBI;;EAEf;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;EAEA;;;;;;;KCzCUG,sBAAsBC;EAAU;;;;;;;UAO3BC;;EAEf;;EAEA,MAAMC,eAAeH;;EAErB,WAAWG,eAAeJ;;;;;;;;qBCZfO,cAAcD"}
package/dist/sets.js ADDED
@@ -0,0 +1,14 @@
1
+ /**
2
+ * Converted icon sets for the Studio. This is a placeholder: the build step replaces the module with the sets it
3
+ * converted from the project's installed libraries, so a Studio built without it finds no libraries.
4
+ *
5
+ * @public
6
+ */
7
+ const iconRegistry = {
8
+ ready: !1,
9
+ sets: {},
10
+ libraries: {}
11
+ };
12
+ export { iconRegistry };
13
+
14
+ //# sourceMappingURL=sets.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sets.js","names":["IconRegistry","iconRegistry","ready","sets","libraries"],"sources":["../src/sets.ts"],"sourcesContent":["import type { IconRegistry } from \"@/lib/registry\";\n\n/**\n * Converted icon sets for the Studio. This is a placeholder: the build step replaces the module with the sets it\n * converted from the project's installed libraries, so a Studio built without it finds no libraries.\n *\n * @public\n */\nexport const iconRegistry: IconRegistry = { ready: false, sets: {}, libraries: {} };\n"],"mappings":";;;;;;AAQA,MAAaC,eAA6B;CAAEC,OAAO;CAAOC,MAAM,CAAC;CAAGC,WAAW,CAAC;AAAE"}
@@ -0,0 +1,20 @@
1
+ /** Schema type name of the icon object. */
2
+ declare const iconTypeName = "icon";
3
+ /**
4
+ * Stored icon: which library it came from, its name, and the shapes it's drawn from.
5
+ *
6
+ * @public
7
+ */
8
+ interface SanityIcon {
9
+ _type: typeof iconTypeName;
10
+ /** Identifier of the library the icon came from. */
11
+ library?: string;
12
+ /** Identifier of the library style the icon came from. */
13
+ style?: string;
14
+ /** Name of the icon in its library. */
15
+ name?: string;
16
+ /** Shapes the icon is drawn from, saved when it's chosen. */
17
+ node?: string;
18
+ }
19
+ export { iconTypeName as n, SanityIcon as t };
20
+ //# sourceMappingURL=types-qlHEYDoN.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types-qlHEYDoN.d.ts","names":["iconTypeName","SanityIcon"],"sources":["../src/types.ts"],"mappings":"AACA;cAAaA;;;;;;UAOIC;EACf,cAAcD;;EAEd;;EAEA;;EAEA;;EAEA"}
@@ -0,0 +1,48 @@
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
@@ -0,0 +1 @@
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"}