@driftime/sanity-plugin-icon 0.4.3 → 0.5.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 (42) hide show
  1. package/README.md +2 -0
  2. package/dist/{adapters-Bx_MyEX_.js → adapters-JowAC3d_.js} +2 -3
  3. package/dist/{adapters-Bx_MyEX_.js.map → adapters-JowAC3d_.js.map} +1 -1
  4. package/dist/index.js +41 -41
  5. package/dist/index.js.map +1 -1
  6. package/dist/library-D07tGkaC.js +2 -0
  7. package/dist/{types-v7Qz7ogk.js → library-DRfdBS-O.js} +15 -54
  8. package/dist/library-DRfdBS-O.js.map +1 -0
  9. package/dist/loader-Mo7_FEBf.js +97 -0
  10. package/dist/loader-Mo7_FEBf.js.map +1 -0
  11. package/dist/next-loader.d.ts.map +1 -1
  12. package/dist/next-loader.js +3 -72
  13. package/dist/next-loader.js.map +1 -1
  14. package/dist/next.d.ts +3 -2
  15. package/dist/next.d.ts.map +1 -1
  16. package/dist/next.js +9 -8
  17. package/dist/next.js.map +1 -1
  18. package/dist/{nodes-DAzj56Xn.js → nodes-DdErxvpg.js} +54 -4
  19. package/dist/nodes-DdErxvpg.js.map +1 -0
  20. package/dist/read-worker.js +2 -2
  21. package/dist/render.d.ts.map +1 -1
  22. package/dist/render.js +3 -4
  23. package/dist/render.js.map +1 -1
  24. package/dist/{sets-BFcRq7dc.js → sets-BfqjcdEo.js} +13 -4
  25. package/dist/sets-BfqjcdEo.js.map +1 -0
  26. package/dist/{sets-B2lHNI7c.js → sets-FpS3h5A7.js} +58 -6
  27. package/dist/sets-FpS3h5A7.js.map +1 -0
  28. package/dist/types-Dl2HGUL5.js +51 -0
  29. package/dist/types-Dl2HGUL5.js.map +1 -0
  30. package/dist/vite.js +2 -3
  31. package/dist/vite.js.map +1 -1
  32. package/package.json +1 -1
  33. package/dist/nodes-DAzj56Xn.js.map +0 -1
  34. package/dist/registry-B0Dxiwhh.js +0 -68
  35. package/dist/registry-B0Dxiwhh.js.map +0 -1
  36. package/dist/registry-BEEpqK3z.js +0 -13
  37. package/dist/registry-BEEpqK3z.js.map +0 -1
  38. package/dist/sets-B2lHNI7c.js.map +0 -1
  39. package/dist/sets-BFcRq7dc.js.map +0 -1
  40. package/dist/types-v7Qz7ogk.js.map +0 -1
  41. package/dist/utils-COPacfAq.js +0 -48
  42. package/dist/utils-COPacfAq.js.map +0 -1
@@ -0,0 +1,97 @@
1
+ import { t as logger } from "./defaults-BEzCWZtH.js";
2
+ import { l as isRecord } from "./nodes-DdErxvpg.js";
3
+ import { n as getIconSetKey } from "./sets-BfqjcdEo.js";
4
+ import { a as writeIconNames, i as loadIconSet, n as detectLibraries, o as createRegistryModule, r as listRegistryDependencies, t as describeReport } from "./sets-FpS3h5A7.js";
5
+ import { i as listPluginFiles } from "./adapters-JowAC3d_.js";
6
+ import path from "node:path";
7
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
+ import { randomUUID } from "node:crypto";
9
+ /**
10
+ * Converts every installed library and writes each set to a file the bundler can split into its own chunk.
11
+ *
12
+ * @param root - The project folder.
13
+ * @param custom - Folders of the project's own icons, keyed by library identifier.
14
+ * @returns The libraries found, and each set with the file it was written to and what happened converting it.
15
+ */
16
+ async function writeIconSets(root, custom) {
17
+ let cacheDir = path.join(root, "node_modules", ".cache"), setsDir = path.join(cacheDir, "driftime-icon", "sets");
18
+ await mkdir(setsDir, { recursive: !0 });
19
+ let libraries = await detectLibraries(root, custom);
20
+ return {
21
+ libraries,
22
+ converted: await Promise.all(libraries.flatMap((library) => library.styles.map(async ({ style }) => {
23
+ let { adapter } = library, { set, report } = await loadIconSet(library, style, {
24
+ root,
25
+ cacheDir
26
+ }), file = path.join(setsDir, `${adapter.library}-${style}.json`), content = JSON.stringify(set);
27
+ if (await readFile(file, "utf8").catch(() => "") !== content) {
28
+ let temporary = `${file}.${randomUUID()}.tmp`;
29
+ await writeFile(temporary, content), await rename(temporary, file);
30
+ }
31
+ return {
32
+ adapter,
33
+ style,
34
+ set,
35
+ file,
36
+ report
37
+ };
38
+ })))
39
+ };
40
+ }
41
+ /**
42
+ * Converts every installed library, writes each set to a file the bundler can split into its own chunk, and returns
43
+ * the registry that replaces the placeholder.
44
+ *
45
+ * @param resourcePath - Path of the placeholder being replaced.
46
+ * @param options - The loader's options.
47
+ * @returns The registry's code, and the files and folders it was generated from.
48
+ */
49
+ async function generateRegistryOnce(resourcePath, options) {
50
+ let root = process.cwd(), custom = isRecord(options) && isRecord(options.custom) ? options.custom : {}, { libraries, converted } = await writeIconSets(root, Object.fromEntries(Object.entries(custom).flatMap(([name, folder]) => typeof folder == "string" ? [[name, folder]] : []))), files = /* @__PURE__ */ new Map(), names = /* @__PURE__ */ new Map();
51
+ for (let { adapter, style, set, file, report } of converted) {
52
+ let { label, library } = adapter;
53
+ logger.info(describeReport(label, style, report));
54
+ let libraryNames = names.get(library) ?? /* @__PURE__ */ new Set();
55
+ for (let icon of set.icons) libraryNames.add(icon.name);
56
+ names.set(library, libraryNames), files.set(getIconSetKey(library, style), file);
57
+ }
58
+ await writeIconNames(new Map([...names].filter(([, libraryNames]) => libraryNames.size > 0)));
59
+ let code = createRegistryModule(libraries, (key) => {
60
+ let file = files.get(key) ?? "", relative = path.relative(path.dirname(resourcePath), file).replaceAll("\\", "/");
61
+ return relative.startsWith(".") ? relative : `./${relative}`;
62
+ }), dependencies = listRegistryDependencies(root, libraries);
63
+ return {
64
+ code,
65
+ files: [...dependencies.files, ...await listPluginFiles()],
66
+ folders: dependencies.folders
67
+ };
68
+ }
69
+ /**
70
+ * Reads the project's `package.json` as text.
71
+ *
72
+ * @returns The contents, or an empty string when there's no file.
73
+ */
74
+ async function readManifest() {
75
+ try {
76
+ return await readFile(path.join(process.cwd(), "package.json"), "utf8");
77
+ } catch {
78
+ return "";
79
+ }
80
+ }
81
+ /**
82
+ * Generates the registry, running again when the project's `package.json` changes while it runs, so a package
83
+ * installed during a run isn't missed.
84
+ *
85
+ * @param resourcePath - Path of the placeholder being replaced.
86
+ * @param options - The loader's options.
87
+ * @param attempts - Runs allowed, including this one.
88
+ * @returns The registry's code, and the files and folders it was generated from.
89
+ * @public
90
+ */
91
+ async function generateRegistry(resourcePath, options, attempts = 3) {
92
+ let before = await readManifest(), result = await generateRegistryOnce(resourcePath, options);
93
+ return before === await readManifest() || attempts <= 1 ? result : generateRegistry(resourcePath, options, attempts - 1);
94
+ }
95
+ export { writeIconSets as n, generateRegistry as t };
96
+
97
+ //# sourceMappingURL=loader-Mo7_FEBf.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"loader-Mo7_FEBf.js","names":["randomUUID","mkdir","readFile","rename","writeFile","path","isRecord","writeIconNames","listPluginFiles","createRegistryModule","describeReport","detectLibraries","listRegistryDependencies","loadIconSet","logger","getIconSetKey","LoaderContext","resourcePath","getOptions","addDependency","file","addContextDependency","folder","writeIconSets","root","custom","Record","cacheDir","join","setsDir","recursive","libraries","converted","Promise","all","flatMap","library","styles","map","style","adapter","set","report","content","JSON","stringify","current","catch","temporary","generateRegistryOnce","options","process","cwd","folders","Object","fromEntries","entries","name","files","Map","names","Set","label","info","libraryNames","get","icon","icons","add","filter","size","code","key","relative","dirname","replaceAll","startsWith","dependencies","readManifest","generateRegistry","attempts","ReturnType","before","result","after","\"custom\""],"sources":["../src/build/loader.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { isRecord } from \"@repo/lib/utils\";\n\nimport { writeIconNames } from \"@/build/names\";\nimport { listPluginFiles } from \"@/build/packages\";\nimport { createRegistryModule } from \"@/build/registry\";\nimport { describeReport, detectLibraries, listRegistryDependencies, loadIconSet } from \"@/build/sets\";\nimport { logger } from \"@/config/defaults\";\nimport { getIconSetKey } from \"@/lib/registry\";\n\n/**\n * The parts of a webpack or Turbopack loader's context the build step uses.\n *\n * @public\n */\nexport interface LoaderContext {\n /** Path of the module being loaded. */\n resourcePath: string;\n /**\n * Reads the loader's options.\n *\n * @returns The options.\n */\n getOptions: () => unknown;\n /**\n * Tells the bundler to run the loader again when a file changes.\n *\n * @param file - The file.\n */\n addDependency?: (file: string) => void;\n /**\n * Tells the bundler to run the loader again when anything in a folder changes.\n *\n * @param folder - The folder.\n */\n addContextDependency?: (folder: string) => void;\n}\n\n/**\n * Converts every installed library and writes each set to a file the bundler can split into its own chunk.\n *\n * @param root - The project folder.\n * @param custom - Folders of the project's own icons, keyed by library identifier.\n * @returns The libraries found, and each set with the file it was written to and what happened converting it.\n */\nexport async function writeIconSets(root: string, custom: Record<string, string>) {\n const cacheDir = path.join(root, \"node_modules\", \".cache\");\n const setsDir = path.join(cacheDir, \"driftime-icon\", \"sets\");\n await mkdir(setsDir, { recursive: true });\n\n const libraries = await detectLibraries(root, custom);\n\n const converted = await Promise.all(\n libraries.flatMap((library) =>\n library.styles.map(async ({ style }) => {\n const { adapter } = library;\n const { set, report } = await loadIconSet(library, style, { root, cacheDir });\n const file = path.join(setsDir, `${adapter.library}-${style}.json`);\n const content = JSON.stringify(set);\n const current = await readFile(file, \"utf8\").catch(() => \"\");\n\n if (current !== content) {\n const temporary = `${file}.${randomUUID()}.tmp`;\n\n // The browser and server builds convert at once, even in one process, so each set is swapped in whole.\n await writeFile(temporary, content);\n await rename(temporary, file);\n }\n\n return { adapter, style, set, file, report };\n }),\n ),\n );\n\n return { libraries, converted };\n}\n\n/**\n * Converts every installed library, writes each set to a file the bundler can split into its own chunk, and returns\n * the registry that replaces the placeholder.\n *\n * @param resourcePath - Path of the placeholder being replaced.\n * @param options - The loader's options.\n * @returns The registry's code, and the files and folders it was generated from.\n */\nasync function generateRegistryOnce(resourcePath: string, options: unknown) {\n const root = process.cwd();\n const custom = isRecord(options) && isRecord(options[\"custom\"]) ? options[\"custom\"] : {};\n const folders = Object.fromEntries(\n Object.entries(custom).flatMap(([name, folder]) => (typeof folder === \"string\" ? [[name, folder]] : [])),\n );\n\n const { libraries, converted } = await writeIconSets(root, folders);\n const files = new Map<string, string>();\n const names = new Map<string, Set<string>>();\n\n for (const { adapter, style, set, file, report } of converted) {\n const { label, library } = adapter;\n logger.info(describeReport(label, style, report));\n\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 files.set(getIconSetKey(library, style), file);\n }\n\n await writeIconNames(new Map([...names].filter(([, libraryNames]) => libraryNames.size > 0)));\n\n const code = createRegistryModule(libraries, (key) => {\n const file = files.get(key) ?? \"\";\n const relative = path.relative(path.dirname(resourcePath), file).replaceAll(\"\\\\\", \"/\");\n\n return relative.startsWith(\".\") ? relative : `./${relative}`;\n });\n\n const dependencies = listRegistryDependencies(root, libraries);\n\n // The plugin's own files are included, so updating it runs the loader again even when `package.json` doesn't change.\n return { code, files: [...dependencies.files, ...(await listPluginFiles())], folders: dependencies.folders };\n}\n\n/**\n * Reads the project's `package.json` as text.\n *\n * @returns The contents, or an empty string when there's no file.\n */\nasync function readManifest() {\n try {\n return await readFile(path.join(process.cwd(), \"package.json\"), \"utf8\");\n } catch {\n return \"\";\n }\n}\n\n/**\n * Generates the registry, running again when the project's `package.json` changes while it runs, so a package\n * installed during a run isn't missed.\n *\n * @param resourcePath - Path of the placeholder being replaced.\n * @param options - The loader's options.\n * @param attempts - Runs allowed, including this one.\n * @returns The registry's code, and the files and folders it was generated from.\n * @public\n */\nexport async function generateRegistry(\n resourcePath: string,\n options: unknown,\n attempts = 3,\n): ReturnType<typeof generateRegistryOnce> {\n const before = await readManifest();\n const result = await generateRegistryOnce(resourcePath, options);\n const after = await readManifest();\n\n return before === after || attempts <= 1 ? result : generateRegistry(resourcePath, options, attempts - 1);\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgDA,eAAsBuB,cAAcC,MAAcC,QAAgC;CAChF,IAAME,WAAWtB,KAAKuB,KAAKJ,MAAM,gBAAgB,QAAQ,GACnDK,UAAUxB,KAAKuB,KAAKD,UAAU,iBAAiB,MAAM;CAC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qBhC,cAAciC,OAAO;CAG/D,OAAOgC,WAAWE,MAFEN,aAAa,KAENE,YAAY,IAAIG,SAASJ,iBAAiB9D,cAAciC,SAAS8B,WAAW,CAAC;AAC1G"}
@@ -1 +1 @@
1
- {"version":3,"file":"next-loader.d.ts","names":["LoaderContext","generateRegistryOnce","Promise","generateRegistry","ReturnType","LoaderContext","iconSetsLoader","Promise","default","generateRegistry"],"sources":["../src/build/loader.ts","../src/next-loader.ts"],"mappings":"AAiBA;;;;;UAAiBA;;EAEf;;;;;;EAMA;;;;;;EAMA,iBAAiB;;;;;;EAMjB,wBAAwB;;;;;;;;;;iBAWXC,qBAAqB,sBAAsB,mBAAgBC;;;;;;;;;;;;;;;wBA+EpDC,iBACpB,sBACA,kBACA,oBACCC,kBAAkBH;;;;;;;;;;;iBCnGNK,eAAe,MAAMD,gBAAaE"}
1
+ {"version":3,"file":"next-loader.d.ts","names":["_$__build_sets0","_$__adapters_types0","_$___lib_sets0","LoaderContext","writeIconSets","Record","DetectedLibrary","IconAdapter","IconSet","IconSetReport","Promise","generateRegistryOnce","generateRegistry","ReturnType","LoaderContext","iconSetsLoader","Promise","default","generateRegistry"],"sources":["../src/build/loader.ts","../src/next-loader.ts"],"mappings":"AAkBA;;;;;UAAiBG;;EAEf;;;;;;EAMA;;;;;;EAMA,iBAAiB;;;;;;EAMjB,wBAAwB;;;;;;;;;;iBAkDXQ,qBAAqB,sBAAsB,mBAAgBD;;;;;;;;;;;;;;;wBA4DpDE,iBACpB,sBACA,kBACA,oBACCC,kBAAkBF;;;;;;;;;;;iBCxHNI,eAAe,MAAMD,gBAAaE"}
@@ -1,76 +1,7 @@
1
1
  import { t as logger } from "./defaults-BEzCWZtH.js";
2
- import { r as isRecord } from "./utils-COPacfAq.js";
3
- import { n as getSetsFolder, t as createRegistryModule } from "./registry-B0Dxiwhh.js";
4
- import { a as writeIconNames, i as loadIconSet, n as detectLibraries, r as listRegistryDependencies, t as describeReport } from "./sets-B2lHNI7c.js";
5
- import { i as listPluginFiles, s as readPluginBuild } from "./adapters-Bx_MyEX_.js";
6
- import path from "node:path";
7
- import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
8
- import { randomUUID } from "node:crypto";
9
- /**
10
- * Converts every installed library, writes each set to a file the bundler can split into its own chunk, and returns
11
- * the registry that replaces the placeholder.
12
- *
13
- * @param resourcePath - Path of the placeholder being replaced.
14
- * @param options - The loader's options.
15
- * @returns The registry's code, and the files and folders it was generated from.
16
- */
17
- async function generateRegistryOnce(resourcePath, options) {
18
- let root = process.cwd(), custom = isRecord(options) && isRecord(options.custom) ? options.custom : {}, folders = Object.fromEntries(Object.entries(custom).flatMap(([name, folder]) => typeof folder == "string" ? [[name, folder]] : [])), cacheDir = path.join(root, "node_modules", ".cache"), setsDir = getSetsFolder(root);
19
- await mkdir(setsDir, { recursive: !0 });
20
- let libraries = await detectLibraries(root, folders), files = /* @__PURE__ */ new Map(), names = /* @__PURE__ */ new Map(), converted = await Promise.all(libraries.flatMap((library) => library.styles.map(async ({ style }) => {
21
- let { adapter } = library, { set, report } = await loadIconSet(library, style, {
22
- root,
23
- cacheDir
24
- }), file = path.join(setsDir, `${adapter.library}-${style}.json`), temporary = `${file}.${randomUUID()}.tmp`;
25
- return await writeFile(temporary, JSON.stringify(set)), await rename(temporary, file), logger.info(describeReport(adapter.label, style, report)), {
26
- library: adapter.library,
27
- style,
28
- set,
29
- file
30
- };
31
- })));
32
- for (let { library, style, set, file } of converted) {
33
- let libraryNames = names.get(library) ?? /* @__PURE__ */ new Set();
34
- for (let icon of set.icons) libraryNames.add(icon.name);
35
- names.set(library, libraryNames), files.set(`${library}/${style}`, file);
36
- }
37
- await writeIconNames(new Map([...names].filter(([, libraryNames]) => libraryNames.size > 0)));
38
- let code = createRegistryModule(libraries, (key) => {
39
- let file = files.get(key) ?? "", relative = path.relative(path.dirname(resourcePath), file).replaceAll("\\", "/");
40
- return relative.startsWith(".") ? relative : `./${relative}`;
41
- }), dependencies = listRegistryDependencies(root, libraries);
42
- return {
43
- code,
44
- files: [...dependencies.files, ...await listPluginFiles()],
45
- folders: dependencies.folders
46
- };
47
- }
48
- /**
49
- * Reads the project's `package.json` as text.
50
- *
51
- * @returns The contents, or an empty string when there's no file.
52
- */
53
- async function readManifest() {
54
- try {
55
- return await readFile(path.join(process.cwd(), "package.json"), "utf8");
56
- } catch {
57
- return "";
58
- }
59
- }
60
- /**
61
- * Generates the registry, running again when the project's `package.json` changes while it runs, so a package
62
- * installed during a run isn't missed.
63
- *
64
- * @param resourcePath - Path of the placeholder being replaced.
65
- * @param options - The loader's options.
66
- * @param attempts - Runs allowed, including this one.
67
- * @returns The registry's code, and the files and folders it was generated from.
68
- * @public
69
- */
70
- async function generateRegistry(resourcePath, options, attempts = 3) {
71
- let before = await readManifest(), result = await generateRegistryOnce(resourcePath, options);
72
- return before === await readManifest() || attempts <= 1 ? result : generateRegistry(resourcePath, options, attempts - 1);
73
- }
2
+ import { l as isRecord } from "./nodes-DdErxvpg.js";
3
+ import { s as readPluginBuild } from "./adapters-JowAC3d_.js";
4
+ import { t as generateRegistry } from "./loader-Mo7_FEBf.js";
74
5
  /**
75
6
  * Checks whether an imported module is a fresh copy of this one.
76
7
  *
@@ -1 +1 @@
1
- {"version":3,"file":"next-loader.js","names":["randomUUID","mkdir","readFile","rename","writeFile","path","isRecord","writeIconNames","listPluginFiles","createRegistryModule","getSetsFolder","describeReport","detectLibraries","listRegistryDependencies","loadIconSet","logger","LoaderContext","resourcePath","getOptions","addDependency","file","addContextDependency","folder","generateRegistryOnce","options","root","process","cwd","custom","folders","Object","fromEntries","entries","flatMap","name","cacheDir","join","setsDir","recursive","libraries","files","Map","names","Set","converted","Promise","all","library","styles","map","style","adapter","set","report","temporary","JSON","stringify","info","label","libraryNames","get","icon","icons","add","filter","size","code","key","relative","dirname","replaceAll","startsWith","dependencies","readManifest","generateRegistry","attempts","ReturnType","before","result","after","isRecord","LoaderContext","generateRegistry","readPluginBuild","logger","LoaderModule","isLoaderModule","value","iconSetsLoader","this","fresh","import","meta","url","Error","format","code","files","folders","resourcePath","getOptions","file","addDependency","folder","addContextDependency","\"custom\"","\"generateRegistry\""],"sources":["../src/build/loader.ts","../src/next-loader.ts"],"sourcesContent":["import { randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport path from \"node:path\";\n\nimport { isRecord } from \"@repo/lib/utils\";\n\nimport { writeIconNames } from \"@/build/names\";\nimport { listPluginFiles } from \"@/build/packages\";\nimport { createRegistryModule, getSetsFolder } from \"@/build/registry\";\nimport { describeReport, detectLibraries, listRegistryDependencies, loadIconSet } from \"@/build/sets\";\nimport { logger } from \"@/config/defaults\";\n\n/**\n * The parts of a webpack or Turbopack loader's context the build step uses.\n *\n * @public\n */\nexport interface LoaderContext {\n /** Path of the module being loaded. */\n resourcePath: string;\n /**\n * Reads the loader's options.\n *\n * @returns The options.\n */\n getOptions: () => unknown;\n /**\n * Tells the bundler to run the loader again when a file changes.\n *\n * @param file - The file.\n */\n addDependency?: (file: string) => void;\n /**\n * Tells the bundler to run the loader again when anything in a folder changes.\n *\n * @param folder - The folder.\n */\n addContextDependency?: (folder: string) => void;\n}\n\n/**\n * Converts every installed library, writes each set to a file the bundler can split into its own chunk, and returns\n * the registry that replaces the placeholder.\n *\n * @param resourcePath - Path of the placeholder being replaced.\n * @param options - The loader's options.\n * @returns The registry's code, and the files and folders it was generated from.\n */\nasync function generateRegistryOnce(resourcePath: string, options: unknown) {\n const root = process.cwd();\n const custom = isRecord(options) && isRecord(options[\"custom\"]) ? options[\"custom\"] : {};\n const folders = Object.fromEntries(\n Object.entries(custom).flatMap(([name, folder]) => (typeof folder === \"string\" ? [[name, folder]] : [])),\n );\n\n const cacheDir = path.join(root, \"node_modules\", \".cache\");\n const setsDir = getSetsFolder(root);\n await mkdir(setsDir, { recursive: true });\n\n const libraries = await detectLibraries(root, folders);\n const files = new Map<string, string>();\n const names = new Map<string, Set<string>>();\n\n const converted = await Promise.all(\n libraries.flatMap((library) =>\n library.styles.map(async ({ style }) => {\n const { adapter } = library;\n const { set, report } = await loadIconSet(library, style, { root, cacheDir });\n const file = path.join(setsDir, `${adapter.library}-${style}.json`);\n const temporary = `${file}.${randomUUID()}.tmp`;\n\n // The browser and server builds convert at once, even in one process, so each set is swapped in whole.\n await writeFile(temporary, JSON.stringify(set));\n await rename(temporary, file);\n logger.info(describeReport(adapter.label, style, report));\n\n return { library: adapter.library, style, set, file };\n }),\n ),\n );\n\n for (const { library, style, set, file } of converted) {\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 files.set(`${library}/${style}`, file);\n }\n\n await writeIconNames(new Map([...names].filter(([, libraryNames]) => libraryNames.size > 0)));\n\n const code = createRegistryModule(libraries, (key) => {\n const file = files.get(key) ?? \"\";\n const relative = path.relative(path.dirname(resourcePath), file).replaceAll(\"\\\\\", \"/\");\n\n return relative.startsWith(\".\") ? relative : `./${relative}`;\n });\n\n const dependencies = listRegistryDependencies(root, libraries);\n\n // The plugin's own files are included, so updating it runs the loader again even when `package.json` doesn't change.\n return { code, files: [...dependencies.files, ...(await listPluginFiles())], folders: dependencies.folders };\n}\n\n/**\n * Reads the project's `package.json` as text.\n *\n * @returns The contents, or an empty string when there's no file.\n */\nasync function readManifest() {\n try {\n return await readFile(path.join(process.cwd(), \"package.json\"), \"utf8\");\n } catch {\n return \"\";\n }\n}\n\n/**\n * Generates the registry, running again when the project's `package.json` changes while it runs, so a package\n * installed during a run isn't missed.\n *\n * @param resourcePath - Path of the placeholder being replaced.\n * @param options - The loader's options.\n * @param attempts - Runs allowed, including this one.\n * @returns The registry's code, and the files and folders it was generated from.\n * @public\n */\nexport async function generateRegistry(\n resourcePath: string,\n options: unknown,\n attempts = 3,\n): ReturnType<typeof generateRegistryOnce> {\n const before = await readManifest();\n const result = await generateRegistryOnce(resourcePath, options);\n const after = await readManifest();\n\n return before === after || attempts <= 1 ? result : generateRegistry(resourcePath, options, attempts - 1);\n}\n","import { isRecord } from \"@repo/lib/utils\";\n\nimport type { LoaderContext, generateRegistry } from \"@/build/loader\";\nimport { readPluginBuild } from \"@/build/packages\";\nimport { logger } from \"@/config/defaults\";\n\n/** This module as the loader imports it afresh on every run. */\ninterface LoaderModule {\n /** Generates the registry. */\n generateRegistry: typeof generateRegistry;\n}\n\n/**\n * Checks whether an imported module is a fresh copy of this one.\n *\n * @param value - The imported module.\n * @returns True if the module is this one.\n */\nfunction isLoaderModule(value: unknown): value is LoaderModule {\n return isRecord(value) && typeof value[\"generateRegistry\"] === \"function\";\n}\n\n/**\n * Webpack and Turbopack loader that replaces the placeholder registry with the project's converted icon sets. The\n * bundler keeps this module loaded, so it imports a fresh copy of itself, versioned by the plugin's code, and runs that\n * copy's build step, so updating the plugin takes effect without restarting the bundler.\n *\n * @param this - The loader context.\n * @returns The registry's code.\n * @throws When the plugin's build step can't be loaded.\n * @public\n */\nasync function iconSetsLoader(this: LoaderContext) {\n const fresh: unknown = await import(`${import.meta.url}?version=${await readPluginBuild()}`);\n if (!isLoaderModule(fresh)) throw new Error(logger.format(\"The build step couldn't be loaded.\"));\n\n const { code, files, folders } = await fresh.generateRegistry(this.resourcePath, this.getOptions());\n\n for (const file of files) this.addDependency?.(file);\n for (const folder of folders) this.addContextDependency?.(folder);\n\n return code;\n}\n\nexport default iconSetsLoader;\nexport { generateRegistry } from \"@/build/loader\";\n"],"mappings":";;;;;;;;;;;;;;;;AAgDA,eAAeuB,qBAAqBN,cAAsBO,SAAkB;CAC1E,IAAMC,OAAOC,QAAQC,IAAI,GACnBC,SAAStB,SAASkB,OAAO,KAAKlB,SAASkB,QAAQiF,MAAS,IAAIjF,QAAQiF,SAAY,CAAC,GACjF5E,UAAUC,OAAOC,YACrBD,OAAOE,QAAQJ,MAAM,CAAC,CAACK,SAAS,CAACC,MAAMZ,YAAa,OAAOA,UAAW,WAAW,CAAC,CAACY,MAAMZ,MAAM,CAAC,IAAI,CAAA,CAAG,CAC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AC;CAElG,KAAK,IAAMC,QAAQJ,OAAO,KAAKK,gBAAgBD,IAAI;CACnD,KAAK,IAAME,UAAUL,SAAS,KAAKM,uBAAuBD,MAAM;CAEhE,OAAOP;AACT"}
1
+ {"version":3,"file":"next-loader.js","names":["isRecord","LoaderContext","generateRegistry","readPluginBuild","logger","LoaderModule","isLoaderModule","value","iconSetsLoader","this","fresh","import","meta","url","Error","format","code","files","folders","resourcePath","getOptions","file","addDependency","folder","addContextDependency","\"generateRegistry\""],"sources":["../src/next-loader.ts"],"sourcesContent":["import { isRecord } from \"@repo/lib/utils\";\n\nimport type { LoaderContext, generateRegistry } from \"@/build/loader\";\nimport { readPluginBuild } from \"@/build/packages\";\nimport { logger } from \"@/config/defaults\";\n\n/** This module as the loader imports it afresh on every run. */\ninterface LoaderModule {\n /** Generates the registry. */\n generateRegistry: typeof generateRegistry;\n}\n\n/**\n * Checks whether an imported module is a fresh copy of this one.\n *\n * @param value - The imported module.\n * @returns True if the module is this one.\n */\nfunction isLoaderModule(value: unknown): value is LoaderModule {\n return isRecord(value) && typeof value[\"generateRegistry\"] === \"function\";\n}\n\n/**\n * Webpack and Turbopack loader that replaces the placeholder registry with the project's converted icon sets. The\n * bundler keeps this module loaded, so it imports a fresh copy of itself, versioned by the plugin's code, and runs that\n * copy's build step, so updating the plugin takes effect without restarting the bundler.\n *\n * @param this - The loader context.\n * @returns The registry's code.\n * @throws When the plugin's build step can't be loaded.\n * @public\n */\nasync function iconSetsLoader(this: LoaderContext) {\n const fresh: unknown = await import(`${import.meta.url}?version=${await readPluginBuild()}`);\n if (!isLoaderModule(fresh)) throw new Error(logger.format(\"The build step couldn't be loaded.\"));\n\n const { code, files, folders } = await fresh.generateRegistry(this.resourcePath, this.getOptions());\n\n for (const file of files) this.addDependency?.(file);\n for (const folder of folders) this.addContextDependency?.(folder);\n\n return code;\n}\n\nexport default iconSetsLoader;\nexport { generateRegistry } from \"@/build/loader\";\n"],"mappings":";;;;;;;;;;AAkBA,SAASM,eAAeC,OAAuC;CAC7D,OAAOP,SAASO,KAAK,KAAK,OAAOA,MAAMkB,oBAAwB;AACjE;;;;;;;;;;;AAYA,eAAejB,iBAAoC;CACjD,IAAME,QAAiB,MAAM,OAAO,GAAGC,YAAYE,IAAG,WAAY,MAAMV,gBAAgB;CACxF,IAAI,CAACG,eAAeI,KAAK,GAAG,MAAUI,MAAMV,OAAOW,OAAO,oCAAoC,CAAC;CAE/F,IAAM,EAAEC,MAAMC,OAAOC,YAAY,MAAMR,MAAMR,iBAAiB,KAAKiB,cAAc,KAAKC,WAAW,CAAC;CAElG,KAAK,IAAMC,QAAQJ,OAAO,KAAKK,gBAAgBD,IAAI;CACnD,KAAK,IAAME,UAAUL,SAAS,KAAKM,uBAAuBD,MAAM;CAEhE,OAAOP;AACT"}
package/dist/next.d.ts CHANGED
@@ -35,9 +35,10 @@ type SanityIconWebpackCustomizer = (config: SanityIconWebpackConfig, context: ne
35
35
  * Turbopack and webpack.
36
36
  *
37
37
  * @param options - Options for the build step.
38
- * @returns A function that extends the Next.js configuration.
38
+ * @returns A function that extends the Next.js configuration into an async configuration function, which converts the
39
+ * installed libraries before Next.js starts building.
39
40
  * @public
40
41
  */
41
- export declare function withIcons(options?: SanityIconBuildOptions): <Config extends SanityIconNextConfig>(config: Config) => Config;
42
+ export declare function withIcons(options?: SanityIconBuildOptions): <Config extends SanityIconNextConfig>(config: Config) => (phase: string) => Promise<Config>;
42
43
  export type { SanityIconNextConfig, SanityIconWebpackConfig, SanityIconWebpackCustomizer };
43
44
  //# sourceMappingURL=next.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"next.d.ts","names":["SanityIconBuildOptions","SanityIconWebpackConfig","SanityIconNextConfig","Record","SanityIconWebpackCustomizer","withIcons","Config"],"sources":["../src/build/next.ts"],"mappings":";;;;;;UAoBiBC;;EAEf;IAAW;;;;;;;;UAQIC;;EAEf;IAAc,QAAQC;;;EAEtB,UAAUC;;;;;;;;KASAA,+BAA+B,QAAQH,yBAAyB,mBAAmBA;;;;;;;;;wBAa/EI,UAAU,UAASL,0BAOJ,eAAeE,sBAAoB,QAAUI,WAASA"}
1
+ {"version":3,"file":"next.d.ts","names":["SanityIconBuildOptions","SanityIconWebpackConfig","SanityIconNextConfig","Record","SanityIconWebpackCustomizer","withIcons","Config","Promise"],"sources":["../src/build/next.ts"],"mappings":";;;;;;UAoBiBC;;EAEf;IAAW;;;;;;;;UAQIC;;EAEf;IAAc,QAAQC;;;EAEtB,UAAUC;;;;;;;;KASAA,+BAA+B,QAAQH,yBAAyB,mBAAmBA;;;;;;;;;;wBAc/EI,UAAU,UAASL,0BAKJ,eAAeE,sBAAoB,QAAUI,YAAM,kBAiBnDC,QAAAD"}
package/dist/next.js CHANGED
@@ -1,6 +1,6 @@
1
- import { i as registryModulePath, n as getSetsFolder, r as isRegistryModule } from "./registry-B0Dxiwhh.js";
1
+ import { c as registryModulePath, s as isRegistryModule } from "./sets-FpS3h5A7.js";
2
+ import { n as writeIconSets } from "./loader-Mo7_FEBf.js";
2
3
  import path from "node:path";
3
- import { mkdirSync } from "node:fs";
4
4
  import { fileURLToPath } from "node:url";
5
5
  /** Path of the loader, published next to this file. */
6
6
  const loaderPath = fileURLToPath(new URL("next-loader.js", import.meta.url));
@@ -9,17 +9,17 @@ const loaderPath = fileURLToPath(new URL("next-loader.js", import.meta.url));
9
9
  * Turbopack and webpack.
10
10
  *
11
11
  * @param options - Options for the build step.
12
- * @returns A function that extends the Next.js configuration.
12
+ * @returns A function that extends the Next.js configuration into an async configuration function, which converts the
13
+ * installed libraries before Next.js starts building.
13
14
  * @public
14
15
  */
15
16
  function withIcons(options = {}) {
16
- let loader = {
17
+ let custom = options.custom ?? {}, loader = {
17
18
  loader: loaderPath,
18
- options: { custom: options.custom ?? {} }
19
+ options: { custom }
19
20
  }, placeholder = path.basename(path.dirname(path.dirname(registryModulePath)));
20
- return mkdirSync(getSetsFolder(process.cwd()), { recursive: !0 }), function extendConfig(config) {
21
- let { turbopack, webpack } = config;
22
- return {
21
+ return function extendConfig(config) {
22
+ let { turbopack, webpack } = config, extendedConfig = {
23
23
  ...config,
24
24
  turbopack: {
25
25
  ...turbopack,
@@ -45,6 +45,7 @@ function withIcons(options = {}) {
45
45
  };
46
46
  }
47
47
  };
48
+ return async (phase) => ((phase === "phase-development-server" || phase === "phase-production-build") && await writeIconSets(process.cwd(), custom), extendedConfig);
48
49
  };
49
50
  }
50
51
  export { withIcons };
package/dist/next.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"next.js","names":["mkdirSync","path","fileURLToPath","getSetsFolder","isRegistryModule","registryModulePath","SanityIconBuildOptions","WebpackRule","test","resource","use","loader","options","custom","Record","SanityIconWebpackConfig","module","rules","SanityIconNextConfig","turbopack","webpack","SanityIconWebpackCustomizer","config","context","loaderPath","URL","import","meta","url","withIcons","placeholder","basename","dirname","process","cwd","recursive","extendConfig","Config","loaders","as","webpackConfig","resolved","rule"],"sources":["../src/build/next.ts"],"sourcesContent":["import { mkdirSync } from \"node:fs\";\nimport path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { getSetsFolder, isRegistryModule, registryModulePath } from \"@/build/registry\";\nimport type { SanityIconBuildOptions } from \"@/build/vite\";\n\n/** A webpack rule, limited to what the build step adds. */\ninterface WebpackRule {\n /** Matches the placeholder registry. */\n test: (resource: string) => boolean;\n /** The loader that replaces it, with the build step's options. */\n use: { loader: string; options: { custom: Record<string, string> } }[];\n}\n\n/**\n * The parts of a webpack configuration the build step extends.\n *\n * @public\n */\nexport interface SanityIconWebpackConfig {\n /** Module settings, whose rules the build step adds to. */\n module?: { rules?: unknown[] };\n}\n\n/**\n * The parts of a Next.js configuration the build step extends, so the package doesn't depend on Next.js's own types.\n *\n * @public\n */\nexport interface SanityIconNextConfig {\n /** Turbopack settings, whose rules the build step adds to. */\n turbopack?: { rules?: Record<string, unknown> };\n /** Customises webpack, for projects that build with it instead of Turbopack. */\n webpack?: SanityIconWebpackCustomizer | null;\n}\n\n/**\n * Customises webpack, as Next.js's `webpack` option does. The context is typed `never` because the build step only\n * passes Next.js's own context through, so any context type a project's function declares is accepted.\n *\n * @public\n */\nexport type SanityIconWebpackCustomizer = (config: SanityIconWebpackConfig, context: never) => SanityIconWebpackConfig;\n\n/** Path of the loader, published next to this file. */\nconst loaderPath = fileURLToPath(new URL(\"next-loader.js\", import.meta.url));\n\n/**\n * Adds the icon build step to a Next.js configuration, for Studios embedded in a Next.js app. It works with both\n * Turbopack and webpack.\n *\n * @param options - Options for the build step.\n * @returns A function that extends the Next.js configuration.\n * @public\n */\nexport function withIcons(options: SanityIconBuildOptions = {}) {\n const loader = { loader: loaderPath, options: { custom: options.custom ?? {} } };\n const placeholder = path.basename(path.dirname(path.dirname(registryModulePath)));\n\n // Turbopack never finds files in a folder that was missing when the build started, so it's made before then.\n mkdirSync(getSetsFolder(process.cwd()), { recursive: true });\n\n return function extendConfig<Config extends SanityIconNextConfig>(config: Config): Config {\n const { turbopack, webpack } = config;\n\n return {\n ...config,\n turbopack: {\n ...turbopack,\n rules: { ...turbopack?.rules, [`**/${placeholder}/dist/sets.js`]: { loaders: [loader], as: \"*.js\" } },\n },\n webpack(webpackConfig: SanityIconWebpackConfig, context: never) {\n const resolved = webpack?.(webpackConfig, context) ?? webpackConfig;\n const rule: WebpackRule = { test: isRegistryModule, use: [loader] };\n\n return { ...resolved, module: { ...resolved.module, rules: [...(resolved.module?.rules ?? []), rule] } };\n },\n };\n };\n}\n"],"mappings":";;;;;AA8CA,MAAMwB,aAAatB,cAAc,IAAIuB,IAAI,kBAAkBC,YAAYE,GAAG,CAAC;;;;;;;;;AAU3E,SAAgBC,UAAUjB,UAAkC,CAAC,GAAG;CAC9D,IAAMD,SAAS;EAAEA,QAAQa;EAAYZ,SAAS,EAAEC,QAAQD,QAAQC,UAAU,CAAC,EAAE;CAAE,GACzEiB,cAAc7B,KAAK8B,SAAS9B,KAAK+B,QAAQ/B,KAAK+B,QAAQ3B,kBAAkB,CAAC,CAAC;CAKhF,OAFAL,UAAUG,cAAc8B,QAAQC,IAAI,CAAC,GAAG,EAAEC,WAAW,GAAK,CAAC,GAEpD,SAASC,aAAkDd,QAAwB;EACxF,IAAM,EAAEH,WAAWC,YAAYE;EAE/B,OAAO;GACL,GAAGA;GACHH,WAAW;IACT,GAAGA;IACHF,OAAO;KAAE,GAAGE,WAAWF;MAAQ,MAAMa,YAAW,iBAAkB;MAAEQ,SAAS,CAAC3B,MAAM;MAAG4B,IAAI;KAAO;IAAE;GACtG;GACAnB,QAAQoB,eAAwCjB,SAAgB;IAC9D,IAAMkB,WAAWrB,UAAUoB,eAAejB,OAAO,KAAKiB,eAChDE,OAAoB;KAAElC,MAAMJ;KAAkBM,KAAK,CAACC,MAAM;IAAE;IAElE,OAAO;KAAE,GAAG8B;KAAUzB,QAAQ;MAAE,GAAGyB,SAASzB;MAAQC,OAAO,CAAC,GAAIwB,SAASzB,QAAQC,SAAS,CAAA,GAAKyB,IAAI;KAAE;IAAE;GACzG;EACF;CACF;AACF"}
1
+ {"version":3,"file":"next.js","names":["path","fileURLToPath","writeIconSets","isRegistryModule","registryModulePath","SanityIconBuildOptions","WebpackRule","test","resource","use","loader","options","custom","Record","SanityIconWebpackConfig","module","rules","SanityIconNextConfig","turbopack","webpack","SanityIconWebpackCustomizer","config","context","loaderPath","URL","import","meta","url","withIcons","placeholder","basename","dirname","extendConfig","Config","extendedConfig","loaders","as","webpackConfig","resolved","rule","phase","process","cwd"],"sources":["../src/build/next.ts"],"sourcesContent":["import path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\nimport { writeIconSets } from \"@/build/loader\";\nimport { isRegistryModule, registryModulePath } from \"@/build/registry\";\nimport type { SanityIconBuildOptions } from \"@/build/vite\";\n\n/** A webpack rule, limited to what the build step adds. */\ninterface WebpackRule {\n /** Matches the placeholder registry. */\n test: (resource: string) => boolean;\n /** The loader that replaces it, with the build step's options. */\n use: { loader: string; options: { custom: Record<string, string> } }[];\n}\n\n/**\n * The parts of a webpack configuration the build step extends.\n *\n * @public\n */\nexport interface SanityIconWebpackConfig {\n /** Module settings, whose rules the build step adds to. */\n module?: { rules?: unknown[] };\n}\n\n/**\n * The parts of a Next.js configuration the build step extends, so the package doesn't depend on Next.js's own types.\n *\n * @public\n */\nexport interface SanityIconNextConfig {\n /** Turbopack settings, whose rules the build step adds to. */\n turbopack?: { rules?: Record<string, unknown> };\n /** Customises webpack, for projects that build with it instead of Turbopack. */\n webpack?: SanityIconWebpackCustomizer | null;\n}\n\n/**\n * Customises webpack, as Next.js's `webpack` option does. The context is typed `never` because the build step only\n * passes Next.js's own context through, so any context type a project's function declares is accepted.\n *\n * @public\n */\nexport type SanityIconWebpackCustomizer = (config: SanityIconWebpackConfig, context: never) => SanityIconWebpackConfig;\n\n/** Path of the loader, published next to this file. */\nconst loaderPath = fileURLToPath(new URL(\"next-loader.js\", import.meta.url));\n\n/**\n * Adds the icon build step to a Next.js configuration, for Studios embedded in a Next.js app. It works with both\n * Turbopack and webpack.\n *\n * @param options - Options for the build step.\n * @returns A function that extends the Next.js configuration into an async configuration function, which converts the\n * installed libraries before Next.js starts building.\n * @public\n */\nexport function withIcons(options: SanityIconBuildOptions = {}) {\n const custom = options.custom ?? {};\n const loader = { loader: loaderPath, options: { custom } };\n const placeholder = path.basename(path.dirname(path.dirname(registryModulePath)));\n\n return function extendConfig<Config extends SanityIconNextConfig>(config: Config) {\n const { turbopack, webpack } = config;\n const extendedConfig: Config = {\n ...config,\n turbopack: {\n ...turbopack,\n rules: { ...turbopack?.rules, [`**/${placeholder}/dist/sets.js`]: { loaders: [loader], as: \"*.js\" } },\n },\n webpack(webpackConfig: SanityIconWebpackConfig, context: never) {\n const resolved = webpack?.(webpackConfig, context) ?? webpackConfig;\n const rule: WebpackRule = { test: isRegistryModule, use: [loader] };\n\n return { ...resolved, module: { ...resolved.module, rules: [...(resolved.module?.rules ?? []), rule] } };\n },\n };\n\n // Turbopack never finds a file that wasn't there when the build started, even with a cache from an earlier build.\n return async (phase: string) => {\n // `next start` also loads the configuration, where `node_modules` may be read-only and nothing is bundled.\n if (phase === \"phase-development-server\" || phase === \"phase-production-build\") {\n await writeIconSets(process.cwd(), custom);\n }\n\n return extendedConfig;\n };\n };\n}\n"],"mappings":";;;;;AA8CA,MAAMuB,aAAatB,cAAc,IAAIuB,IAAI,kBAAkBC,YAAYE,GAAG,CAAC;;;;;;;;;;AAW3E,SAAgBC,UAAUjB,UAAkC,CAAC,GAAG;CAC9D,IAAMC,SAASD,QAAQC,UAAU,CAAC,GAC5BF,SAAS;EAAEA,QAAQa;EAAYZ,SAAS,EAAEC,OAAO;CAAE,GACnDiB,cAAc7B,KAAK8B,SAAS9B,KAAK+B,QAAQ/B,KAAK+B,QAAQ3B,kBAAkB,CAAC,CAAC;CAEhF,OAAO,SAAS4B,aAAkDX,QAAgB;EAChF,IAAM,EAAEH,WAAWC,YAAYE,QACzBa,iBAAyB;GAC7B,GAAGb;GACHH,WAAW;IACT,GAAGA;IACHF,OAAO;KAAE,GAAGE,WAAWF;MAAQ,MAAMa,YAAW,iBAAkB;MAAEM,SAAS,CAACzB,MAAM;MAAG0B,IAAI;KAAO;IAAE;GACtG;GACAjB,QAAQkB,eAAwCf,SAAgB;IAC9D,IAAMgB,WAAWnB,UAAUkB,eAAef,OAAO,KAAKe,eAChDE,OAAoB;KAAEhC,MAAMJ;KAAkBM,KAAK,CAACC,MAAM;IAAE;IAElE,OAAO;KAAE,GAAG4B;KAAUvB,QAAQ;MAAE,GAAGuB,SAASvB;MAAQC,OAAO,CAAC,GAAIsB,SAASvB,QAAQC,SAAS,CAAA,GAAKuB,IAAI;KAAE;IAAE;GACzG;EACF;EAGA,OAAO,OAAOC,YAERA,UAAU,8BAA8BA,UAAU,6BACpD,MAAMtC,cAAcuC,QAAQC,IAAI,GAAG9B,MAAM,GAGpCsB;CAEX;AACF"}
@@ -1,10 +1,59 @@
1
- import { n as isDefined, r as isRecord } from "./utils-COPacfAq.js";
2
1
  import { stegaClean } from "@sanity/client/stega";
3
2
  /**
3
+ * Checks whether a value is present. `false`, blank strings, and empty plain objects count as absent,
4
+ * as does an array with no present elements.
5
+ *
6
+ * @param value - The value to check.
7
+ * @returns True if the value is present.
8
+ */
9
+ function isDefined(value) {
10
+ if (value == null || value === !1) return !1;
11
+ if (typeof value == "string") return value.trim() !== "";
12
+ if (Array.isArray(value)) return value.some((element) => isDefined(element));
13
+ if (typeof value == "object") {
14
+ let prototype = Reflect.getPrototypeOf(value);
15
+ return prototype !== Object.prototype && prototype !== null || Object.keys(value).length > 0;
16
+ }
17
+ return !0;
18
+ }
19
+ /**
20
+ * Converts a string to another case.
21
+ *
22
+ * @param value - The string to convert.
23
+ * @param format - The case to convert to.
24
+ * @returns The converted string.
25
+ */
26
+ function convertCase(value, format) {
27
+ let words = value.replaceAll(/(?<lower>[a-z0-9])(?<upper>[A-Z])/gu, "$<lower> $<upper>").replaceAll(/[-_\s]+/gu, " ").trim().toLowerCase();
28
+ switch (format) {
29
+ case "kebab": return words.replaceAll(/\s+/gu, "-");
30
+ case "snake": return words.replaceAll(/\s+/gu, "_");
31
+ case "camel": return words.replaceAll(/\s+(?<character>.)/gu, (_match, character) => character.toUpperCase());
32
+ case "pascal": return words.replaceAll(/(?:^|\s+)(?<character>.)/gu, (_match, character) => character.toUpperCase());
33
+ case "title": return words.replaceAll(/\b\w/gu, (character) => character.toUpperCase());
34
+ case "sentence": return words.replaceAll(/^(?<character>.)/gu, (character) => character.toUpperCase());
35
+ default: return value;
36
+ }
37
+ }
38
+ /**
39
+ * Checks whether a value is an object whose keys can be read.
40
+ *
41
+ * @param value - The value to check.
42
+ * @returns True if the value is an object.
43
+ */
44
+ function isRecord(value) {
45
+ return typeof value == "object" && !!value;
46
+ }
47
+ /**
4
48
  * SVG elements a drawing may contain: everything that draws, paints, clips, masks, or filters. Anything that runs
5
49
  * code, embeds other content, links away, loads a file, animates, or styles the page around it is left out.
6
50
  */
7
- const iconElements = /* @__PURE__ */ new Set(/* @__PURE__ */ "circle.clipPath.defs.ellipse.feBlend.feColorMatrix.feComponentTransfer.feComposite.feConvolveMatrix.feDiffuseLighting.feDisplacementMap.feDistantLight.feDropShadow.feFlood.feFuncA.feFuncB.feFuncG.feFuncR.feGaussianBlur.feMerge.feMergeNode.feMorphology.feOffset.fePointLight.feSpecularLighting.feSpotLight.feTile.feTurbulence.filter.g.line.linearGradient.marker.mask.path.pattern.polygon.polyline.radialGradient.rect.stop.symbol.text.textPath.tspan.use".split(".")), linkAttributes = /* @__PURE__ */ new Set(["href", "xlinkHref"]), urlPattern = /url\((?<reference>[^)]*)\)/gu, iconSvgAttributes = {
51
+ const iconElements = /* @__PURE__ */ new Set(/* @__PURE__ */ "circle.clipPath.defs.ellipse.feBlend.feColorMatrix.feComponentTransfer.feComposite.feConvolveMatrix.feDiffuseLighting.feDisplacementMap.feDistantLight.feDropShadow.feFlood.feFuncA.feFuncB.feFuncG.feFuncR.feGaussianBlur.feMerge.feMergeNode.feMorphology.feOffset.fePointLight.feSpecularLighting.feSpotLight.feTile.feTurbulence.filter.g.line.linearGradient.marker.mask.path.pattern.polygon.polyline.radialGradient.rect.stop.symbol.text.textPath.tspan.use".split(".")), linkAttributes = /* @__PURE__ */ new Set(["href", "xlinkHref"]), reactProps = /* @__PURE__ */ new Set([
52
+ "children",
53
+ "dangerouslySetInnerHTML",
54
+ "key",
55
+ "ref"
56
+ ]), urlPattern = /url\((?<reference>[^)]*)\)/gu, iconSvgAttributes = {
8
57
  xmlns: "http://www.w3.org/2000/svg",
9
58
  width: 24,
10
59
  height: 24
@@ -39,6 +88,7 @@ function findAttributeProblem(attributes) {
39
88
  for (let [name, value] of Object.entries(attributes)) {
40
89
  if (/^on/iu.test(name)) return `has an event handler (\`${name}\`)`;
41
90
  if (!/^[a-zA-Z][a-zA-Z0-9]*$/u.test(name)) return `has an unknown attribute (\`${name}\`)`;
91
+ if (reactProps.has(name)) return `has an attribute React reserves (\`${name}\`)`;
42
92
  if (/javascript:/iu.test(value)) return "runs a script";
43
93
  if (linkAttributes.has(name) && !value.startsWith("#")) return "links outside the icon";
44
94
  if (value.includes("url(")) {
@@ -134,6 +184,6 @@ function serializeIconDrawing(drawing) {
134
184
  node: drawing.node
135
185
  });
136
186
  }
137
- export { resolveIconDrawing as a, parseIconRoot as i, iconSvgAttributes as n, serializeIconDrawing as o, parseIconNode as r, findDrawingProblem as t };
187
+ export { resolveIconDrawing as a, isDefined as c, parseIconRoot as i, isRecord as l, iconSvgAttributes as n, serializeIconDrawing as o, parseIconNode as r, convertCase as s, findDrawingProblem as t };
138
188
 
139
- //# sourceMappingURL=nodes-DAzj56Xn.js.map
189
+ //# sourceMappingURL=nodes-DdErxvpg.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"nodes-DdErxvpg.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","isDefined","isRecord","stegaClean","IconElement","element","attributes","Record","children","IconNode","IconRoot","IconDrawing","root","node","iconElements","ReadonlySet","Set","linkAttributes","reactProps","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":["../../@repo/lib/utils.ts","../src/lib/nodes.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","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/** Props React treats specially rather than passing to the element, where a stored string would break rendering. */\nconst reactProps = new Set([\"children\", \"dangerouslySetInnerHTML\", \"key\", \"ref\"]);\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 (reactProps.has(name)) return `has an attribute React reserves (\\`${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":";;;;;;;;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,u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AAUhC,OAAwB;CACzC,IAAI;EACF,OAAOiC,KAAKC,MAAMlC,KAAK;CACzB,QAAQ;EACN;CACF;AACF;;;;;;;AAQA,SAAgBmC,mBAAmBnC,OAAoD;CACrF,IAAMoC,UAAU3D,WAAWuB,KAAK;CAChC,IAAI,CAACzB,UAAU6D,OAAO,GAAG;CAEzB,IAAMC,SAASL,UAAUI,OAAO;CAChC,IAAI,CAAC5D,SAAS6D,MAAM,GAAG;CAEvB,IAAMnD,OAAO6C,cAAcM,OAAOM,IAAO,GACnCxD,OAAO2C,cAAcO,OAAOO,IAAO;CACzC,IAAI,CAACrE,UAAUW,IAAI,KAAK,CAACX,UAAUY,IAAI,GAAG;CAE1C,IAAMmD,UAAU;EAAEpD;EAAMC;CAAK;CAE7B,OAAOZ,UAAUsD,mBAAmBS,OAAO,CAAC,IAAIZ,KAAAA,IAAYY;AAC9D;;;;;;;AAQA,SAAgBC,qBAAqBD,SAAsB;CACzD,OAAOL,KAAKO,UAAU;EAAEtD,MAAMoD,QAAQpD;EAAMC,MAAMmD,QAAQnD;CAAK,CAAC;AAClE"}
@@ -1,5 +1,5 @@
1
- import { n as isDefined, r as isRecord } from "./utils-COPacfAq.js";
2
- import { n as createCustomAdapter, t as iconAdapters } from "./adapters-Bx_MyEX_.js";
1
+ import { c as isDefined, l as isRecord } from "./nodes-DdErxvpg.js";
2
+ import { n as createCustomAdapter, t as iconAdapters } from "./adapters-JowAC3d_.js";
3
3
  import { parentPort, workerData } from "node:worker_threads";
4
4
  /**
5
5
  * Reads one library style in a worker thread, so every package is imported afresh, and posts the icons back.
@@ -1 +1 @@
1
- {"version":3,"file":"render.d.ts","names":["ComponentProps","SanityIcon","SanityIconProps","Omit","Icon","value","JSX","IconLibraryId","SanityIcon","SanityIconName","SanityIconStyle","SanityIconLookup","Library","getIcon","library","style","name","Promise"],"sources":["../src/components/icon.tsx","../src/lib/lookup.ts"],"mappings":";;;;;;;KAcYE,kBAAkBC,KAAKH;;EAEjC,OAAOC;;;;;;;;wBASOG,OAAOC,UAAU,SAASH,kCAAeI,IAAA;;;;;;KCb7CK,sBACT,WAAWJ;;EAEV,SAASK;;EAET,QAAQF,gBAAgBE;;EAExB,MAAMH,eAAeG;KAEvBL;;;;;;;;;wBAUoBM,UAAUC,SAASC,OAAOC,QAAQL,mBAAmBM,QAAQT"}
1
+ {"version":3,"file":"render.d.ts","names":["ComponentProps","SanityIcon","SanityIconProps","Omit","Icon","value","JSX","IconLibraryId","SanityIcon","SanityIconName","SanityIconStyle","SanityIconLookup","Library","getIcon","library","style","name","Promise"],"sources":["../src/components/icon.tsx","../src/lib/lookup.ts"],"mappings":";;;;;;;KAcYE,kBAAkBC,KAAKH;;EAEjC,OAAOC;;;;;;;;wBASOG,OAAOC,UAAU,SAASH,kCAAeI,IAAA;;;;;;KCd7CK,sBACT,WAAWJ;;EAEV,SAASK;;EAET,QAAQF,gBAAgBE;;EAExB,MAAMH,eAAeG;KAEvBL;;;;;;;;;wBAUoBM,UAAUC,SAASC,OAAOC,QAAQL,mBAAmBM,QAAQT"}
package/dist/render.js CHANGED
@@ -1,6 +1,5 @@
1
- import { n as isDefined } from "./utils-COPacfAq.js";
2
- import { a as resolveIconDrawing, o as serializeIconDrawing } from "./nodes-DAzj56Xn.js";
3
- import { o as Drawing, r as requestLibrary, t as iconTypeName } from "./types-v7Qz7ogk.js";
1
+ import { a as resolveIconDrawing, c as isDefined, o as serializeIconDrawing } from "./nodes-DdErxvpg.js";
2
+ import { n as Drawing, t as iconTypeName } from "./types-Dl2HGUL5.js";
4
3
  import { jsx } from "react/jsx-runtime";
5
4
  /**
6
5
  * Draws a stored icon from the shapes saved with it, without loading an icon library.
@@ -23,7 +22,7 @@ function Icon({ value, ...props }) {
23
22
  * @public
24
23
  */
25
24
  async function getIcon({ library, style, name }) {
26
- let { icons } = await requestLibrary(library, style), icon = icons?.find((candidate) => candidate.name === name);
25
+ let { requestLibrary } = await import("./library-D07tGkaC.js"), { icons } = await requestLibrary(library, style), icon = icons?.find((candidate) => candidate.name === name);
27
26
  if (isDefined(icon)) return {
28
27
  _type: iconTypeName,
29
28
  library,
@@ -1 +1 @@
1
- {"version":3,"file":"render.js","names":["ComponentProps","Drawing","resolveIconDrawing","SanityIcon","SanityIconProps","Omit","value","Icon","props","node","isDefined","requestLibrary","serializeIconDrawing","iconTypeName","IconLibraryId","SanityIcon","SanityIconName","SanityIconStyle","SanityIconLookup","library","Library","style","name","getIcon","Promise","icons","icon","find","candidate","undefined","_type","node","drawing"],"sources":["../src/components/icon.tsx","../src/lib/lookup.ts"],"sourcesContent":["// Consumers render this in server components, where the compiler's memo cache hook can't run.\n\"use no memo\";\n\nimport type { ComponentProps } from \"react\";\n\nimport { Drawing } from \"@/components/drawing\";\nimport { resolveIconDrawing } from \"@/lib/nodes\";\nimport type { SanityIcon } from \"@/types\";\n\n/**\n * Props for drawing a stored icon: an SVG element's props plus the stored value.\n *\n * @public\n */\nexport type SanityIconProps = Omit<ComponentProps<\"svg\">, \"children\"> & {\n /** Stored icon to draw. */\n value: SanityIcon | undefined;\n};\n\n/**\n * Draws a stored icon from the shapes saved with it, without loading an icon library.\n *\n * @returns The icon, or nothing when the value is missing or unreadable.\n * @public\n */\nexport function Icon({ value, ...props }: SanityIconProps) {\n return <Drawing drawing={resolveIconDrawing(value?.node)} {...props} />;\n}\n","import { isDefined } from \"@repo/lib/utils\";\n\nimport { requestLibrary } from \"@/lib/library\";\nimport { serializeIconDrawing } from \"@/lib/nodes\";\nimport { iconTypeName } from \"@/types\";\nimport type { IconLibraryId, SanityIcon, SanityIconName, SanityIconStyle } from \"@/types\";\n\n/**\n * An icon to look up by name, where the style and name are checked against the library.\n *\n * @public\n */\nexport type SanityIconLookup = {\n [Library in IconLibraryId]: {\n /** Identifier of the icon library, such as `phosphor`. */\n library: Library;\n /** Identifier of the library style, such as `bold`. Defaults to the library's first style. */\n style?: SanityIconStyle<Library>;\n /** Name of the icon in its library. */\n name: SanityIconName<Library>;\n };\n}[IconLibraryId];\n\n/**\n * Looks an icon up by name in an installed library, for an icon the site chooses rather than an author.\n *\n * @param lookup - The library, style, and name of the icon.\n * @returns The icon as the Studio stores it, or undefined when the build step hasn't run or the library, style, or\n * name isn't installed.\n * @public\n */\nexport async function getIcon({ library, style, name }: SanityIconLookup): Promise<SanityIcon | undefined> {\n const { icons } = await requestLibrary(library, style);\n const icon = icons?.find((candidate) => candidate.name === name);\n if (!isDefined(icon)) return undefined;\n\n return {\n _type: iconTypeName,\n library,\n ...(isDefined(style) && { style }),\n name,\n node: serializeIconDrawing(icon.drawing),\n };\n}\n"],"mappings":";;;;;;;;;;AAyBA,SAAgBO,KAAK,EAAED,OAAO,GAAGE,SAA0B;CACzD,OAAO,oBAAC,SAAD;EAAS,SAASN,mBAAmBI,OAAOG,IAAI;EAAG,GAAID;CAAM,CAAA;AACtE;;;;;;;;;ACIA,eAAsBe,QAAQ,EAAEJ,SAASE,OAAOC,QAA2D;CACzG,IAAM,EAAEG,UAAU,MAAMd,eAAeQ,SAASE,KAAK,GAC/CK,OAAOD,OAAOE,MAAMC,cAAcA,UAAUN,SAASA,IAAI;CAC/D,IAAKZ,UAAUgB,IAAI,GAEnB,OAAO;EACLI,OAAOjB;EACPM;EACA,GAAIT,UAAUW,KAAK,KAAK,EAAEA,MAAM;EAChCC;EACAS,MAAMnB,qBAAqBc,KAAKM,OAAO;CACzC;AACF"}
1
+ {"version":3,"file":"render.js","names":["ComponentProps","Drawing","resolveIconDrawing","SanityIcon","SanityIconProps","Omit","value","Icon","props","node","isDefined","serializeIconDrawing","iconTypeName","IconLibraryId","SanityIcon","SanityIconName","SanityIconStyle","SanityIconLookup","library","Library","style","name","getIcon","Promise","requestLibrary","icons","icon","find","candidate","undefined","_type","node","drawing"],"sources":["../src/components/icon.tsx","../src/lib/lookup.ts"],"sourcesContent":["// Consumers render this in server components, where the compiler's memo cache hook can't run.\n\"use no memo\";\n\nimport type { ComponentProps } from \"react\";\n\nimport { Drawing } from \"@/components/drawing\";\nimport { resolveIconDrawing } from \"@/lib/nodes\";\nimport type { SanityIcon } from \"@/types\";\n\n/**\n * Props for drawing a stored icon: an SVG element's props plus the stored value.\n *\n * @public\n */\nexport type SanityIconProps = Omit<ComponentProps<\"svg\">, \"children\"> & {\n /** Stored icon to draw. */\n value: SanityIcon | undefined;\n};\n\n/**\n * Draws a stored icon from the shapes saved with it, without loading an icon library.\n *\n * @returns The icon, or nothing when the value is missing or unreadable.\n * @public\n */\nexport function Icon({ value, ...props }: SanityIconProps) {\n return <Drawing drawing={resolveIconDrawing(value?.node)} {...props} />;\n}\n","import { isDefined } from \"@repo/lib/utils\";\n\nimport { serializeIconDrawing } from \"@/lib/nodes\";\nimport { iconTypeName } from \"@/types\";\nimport type { IconLibraryId, SanityIcon, SanityIconName, SanityIconStyle } from \"@/types\";\n\n/**\n * An icon to look up by name, where the style and name are checked against the library.\n *\n * @public\n */\nexport type SanityIconLookup = {\n [Library in IconLibraryId]: {\n /** Identifier of the icon library, such as `phosphor`. */\n library: Library;\n /** Identifier of the library style, such as `bold`. Defaults to the library's first style. */\n style?: SanityIconStyle<Library>;\n /** Name of the icon in its library. */\n name: SanityIconName<Library>;\n };\n}[IconLibraryId];\n\n/**\n * Looks an icon up by name in an installed library, for an icon the site chooses rather than an author.\n *\n * @param lookup - The library, style, and name of the icon.\n * @returns The icon as the Studio stores it, or undefined when the build step hasn't run or the library, style, or\n * name isn't installed.\n * @public\n */\nexport async function getIcon({ library, style, name }: SanityIconLookup): Promise<SanityIcon | undefined> {\n // Imported here, so a site that only draws icons never downloads the library loader and the set registry.\n const { requestLibrary } = await import(\"@/lib/library\");\n const { icons } = await requestLibrary(library, style);\n const icon = icons?.find((candidate) => candidate.name === name);\n if (!isDefined(icon)) return undefined;\n\n return {\n _type: iconTypeName,\n library,\n ...(isDefined(style) && { style }),\n name,\n node: serializeIconDrawing(icon.drawing),\n };\n}\n"],"mappings":";;;;;;;;;AAyBA,SAAgBO,KAAK,EAAED,OAAO,GAAGE,SAA0B;CACzD,OAAO,oBAAC,SAAD;EAAS,SAASN,mBAAmBI,OAAOG,IAAI;EAAG,GAAID;CAAM,CAAA;AACtE;;;;;;;;;ACGA,eAAsBc,QAAQ,EAAEJ,SAASE,OAAOC,QAA2D;CAEzG,IAAM,EAAEG,mBAAmB,MAAM,OAAO,0BAClC,EAAEC,UAAU,MAAMD,eAAeN,SAASE,KAAK,GAC/CM,OAAOD,OAAOE,MAAMC,cAAcA,UAAUP,SAASA,IAAI;CAC/D,IAAKX,UAAUgB,IAAI,GAEnB,OAAO;EACLI,OAAOlB;EACPM;EACA,GAAIR,UAAUU,KAAK,KAAK,EAAEA,MAAM;EAChCC;EACAU,MAAMpB,qBAAqBe,KAAKM,OAAO;CACzC;AACF"}
@@ -1,5 +1,14 @@
1
- import { n as isDefined, r as isRecord } from "./utils-COPacfAq.js";
2
- import { i as parseIconRoot, r as parseIconNode } from "./nodes-DAzj56Xn.js";
1
+ import { c as isDefined, i as parseIconRoot, l as isRecord, r as parseIconNode } from "./nodes-DdErxvpg.js";
2
+ /**
3
+ * Builds the key a set is registered under.
4
+ *
5
+ * @param library - Identifier of the library.
6
+ * @param style - Identifier of the style.
7
+ * @returns The key.
8
+ */
9
+ function getIconSetKey(library, style) {
10
+ return `${library}/${style}`;
11
+ }
3
12
  /**
4
13
  * Reads one icon of a converted set, skipping it when its data isn't usable.
5
14
  *
@@ -35,6 +44,6 @@ function parseIconSet(value) {
35
44
  })
36
45
  };
37
46
  }
38
- export { parseIconSet as t };
47
+ export { getIconSetKey as n, parseIconSet as t };
39
48
 
40
- //# sourceMappingURL=sets-BFcRq7dc.js.map
49
+ //# sourceMappingURL=sets-BfqjcdEo.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"sets-BfqjcdEo.js","names":["IconLibraryInfo","IconSetLoader","Promise","default","IconRegistry","ready","sets","Record","libraries","getIconSetKey","library","style","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"],"sources":["../src/lib/registry.ts","../src/lib/sets.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","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":";;;;;;;;AA8BA,SAAgBS,cAAcC,SAAiBC,OAAe;CAC5D,OAAO,GAAGD,QAAO,GAAIC;AACvB;;;;;;;ACyBA,SAASwB,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"}