@iconia/react 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- var v=new AbortController;process.on("SIGINT",()=>{v.abort(),process.stderr.write(`
3
- `),process.exit(130)});import{Command as Bo}from"commander";import{Command as jo}from"commander";import X from"fs";import Uo from"path";import S from"picocolors";var uo=`import type { IconiaConfig } from '@iconia/react';
2
+ var E=new AbortController;process.on("SIGINT",()=>{E.abort(),process.stderr.write(`
3
+ `),process.exit(130)});import{Command as Ho}from"commander";import{Command as Ro}from"commander";import N from"fs";import ho from"path";import v from"picocolors";var jo=`import type { IconiaConfig } from '@iconia/react';
4
4
 
5
5
  const config: IconiaConfig = {
6
6
  apiKey: process.env.ICONIA_API_KEY ?? '',
@@ -8,20 +8,20 @@ const config: IconiaConfig = {
8
8
  };
9
9
 
10
10
  export default config;
11
- `,l=new jo("init").description("Create an iconia.config.ts file in the current directory").action(()=>{let o=Uo.resolve(process.cwd(),"iconia.config.ts");if(X.existsSync(o)){console.log(S.yellow("iconia.config.ts already exists. Skipping."));return}X.writeFileSync(o,uo),console.log(S.green("✓ Created iconia.config.ts")),console.log(`
12
- Next steps:`),console.log(` 1. Set ${S.cyan("ICONIA_API_KEY")} in your environment`),console.log(` 2. Edit ${S.cyan("iconia.config.ts")} to add your collections`),console.log(` 3. Run ${S.cyan("npx iconia pull")} to fetch icons`),console.log(`
13
- Import icons: ${S.cyan("import { MyIcon } from '@iconia/react/my-collection'")}`)});import{Command as Oo}from"commander";import O from"picocolors";import So from"ora";import{z as Y}from"zod";import D from"path";var po=Y.object({apiKey:Y.string().min(1,"apiKey is required"),collections:Y.array(Y.string()).default([])}),Lo="https://api.iconia.io";async function u(){let o=D.resolve(process.cwd(),"iconia.config.ts"),r=D.resolve(process.cwd(),"iconia.config.js"),i;try{let f=await import(o);i=f.default??f}catch{try{let f=await import(r);i=f.default??f}catch{throw Error("Could not find iconia.config.ts or iconia.config.js\nRun `npx @iconia/react init` to create one.")}}let n=po.safeParse(i);if(!n.success){let f=n.error.issues.map((a)=>` - ${a.path.join(".")}: ${a.message}`).join(`
11
+ `,X=new Ro("init").description("Create an iconia.config.ts file in the current directory").action(()=>{let o=ho.resolve(process.cwd(),"iconia.config.ts");if(N.existsSync(o)){console.log(v.yellow("iconia.config.ts already exists. Skipping."));return}N.writeFileSync(o,jo),console.log(v.green("✓ Created iconia.config.ts")),console.log(`
12
+ Next steps:`),console.log(` 1. Set ${v.cyan("ICONIA_API_KEY")} in your environment`),console.log(` 2. Edit ${v.cyan("iconia.config.ts")} to add your collections`),console.log(` 3. Run ${v.cyan("npx iconia pull")} to fetch icons`),console.log(`
13
+ Import icons: ${v.cyan("import { MyIcon } from '@iconia/react/my-collection'")}`)});import{Command as bo}from"commander";import b from"picocolors";import vo from"ora";import{z as P}from"zod";import D from"path";var Fo=P.object({apiKey:P.string().min(1,"apiKey is required"),collections:P.array(P.string()).default([]),uploadBatchSize:P.number().int().min(1).max(100).default(50)}),Uo="https://api.iconia.io";async function j(){let o=D.resolve(process.cwd(),"iconia.config.ts"),r=D.resolve(process.cwd(),"iconia.config.js"),i;try{let a=await import(o);i=a.default??a}catch{try{let a=await import(r);i=a.default??a}catch{throw Error("Could not find iconia.config.ts or iconia.config.js\nRun `npx @iconia/react init` to create one.")}}let t=Fo.safeParse(i);if(!t.success){let a=t.error.issues.map((f)=>` - ${f.path.join(".")}: ${f.message}`).join(`
14
14
  `);throw Error(`Invalid iconia config:
15
- ${f}`)}let t=i.__internal?.endpoint??Lo;return{...n.data,apiUrl:t}}function Z(o){return{Authorization:`ApiKey ${o.apiKey}`,"Content-Type":"application/json"}}async function G(o,r=3){for(let i=0;i<=r;i++){let n=await o(v.signal);if(n.status!==429||i===r)return n;let c=parseInt(n.headers.get("Retry-After")??"60",10);process.stderr.write(`
15
+ ${a}`)}let n=i.__internal?.endpoint??Uo;return{...t.data,apiUrl:n}}function W(o){return{Authorization:`ApiKey ${o.apiKey}`,"Content-Type":"application/json"}}async function Z(o,r=3){for(let i=0;i<=r;i++){let t=await o(E.signal);if(t.status!==429||i===r)return t;let c=parseInt(t.headers.get("Retry-After")??"60",10);process.stderr.write(`
16
16
  ⏳ Rate limited — waiting ${c}s before retry ${i+1}/${r}...
17
- `),await new Promise((t)=>{let f=()=>{clearTimeout(a),process.exit(130)},a=setTimeout(()=>{process.removeListener("SIGINT",f),t()},c*1000);process.once("SIGINT",f),v.signal.addEventListener("abort",f,{once:!0})})}return o(v.signal)}async function x(o){let r=await G((n)=>fetch(new URL("/v1/collections",o.apiUrl).toString(),{headers:Z(o),signal:n}));if(!r.ok){let n={};try{n=await r.json()}catch{}throw Error(`API error ${r.status}: ${n.error??r.statusText}`)}return(await r.json()).collections}async function V(o,r){let i=new URL("/v1/collections/icons",o.apiUrl);i.searchParams.set("collections",r.join(","));let n=await G((t)=>fetch(i.toString(),{headers:Z(o),signal:t}));if(!n.ok){let t={};try{t=await n.json()}catch{}throw Error(`API error ${n.status}: ${t.error??n.statusText}`)}return(await n.json()).icons}async function g(o,r){let i=await G((n)=>fetch(new URL("/v1/icons",o.apiUrl).toString(),{method:"POST",headers:Z(o),body:JSON.stringify(r),signal:n}));if(!i.ok){let n={};try{n=await i.json()}catch{}throw Error(n.error??i.statusText)}return!0}import L from"fs";import K from"path";import{fileURLToPath as Eo}from"url";import bo from"picocolors";import{optimize as _o}from"svgo";function Co(o){return _o(o,{plugins:["removeDoctype","removeXMLProcInst","removeComments","removeMetadata","removeTitle","removeDesc"]}).data.replace(/<svg([^>]*)>/i,(i,n)=>`<svg${n.replace(/\s+(width|height)=['"][^'"]*['"]/gi,"")}>`)}function oo(o){let r={},i=/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,n;while((n=i.exec(o))!==null){let c=n[1].replace(/^xlink:/,"").replace(/-([a-z])/g,(t,f)=>f.toUpperCase());r[c]=n[2]??n[3]??""}return r}function ro(o){let r=[],i=0;while(i<o.length){let n=o.indexOf("<",i);if(n===-1)break;let c=o[n+1];if(c==="/"||c==="!"||c==="?"){let d=o.indexOf(">",n);i=d===-1?o.length:d+1;continue}let t=n+1,f=!1,a="";while(t<o.length){let d=o[t];if(f){if(d===a)f=!1}else if(d==='"'||d==="'")f=!0,a=d;else if(d===">")break;t++}if(t>=o.length)break;let w=o.slice(n+1,t),m=w.trimEnd().endsWith("/"),y=m?w.slice(0,w.lastIndexOf("/")).trim():w.trim(),e=y.search(/\s/),s=e===-1?y:y.slice(0,e);if(!s){i=t+1;continue}let j=e===-1?"":y.slice(e+1),E=oo(j);if(i=t+1,m)r.push([s,E]);else{let d=`<${s}`,b=`</${s}>`,F=1,R=i;while(F>0&&R<o.length){let U=o.indexOf(d,R),$=o.indexOf(b,R);if($===-1)break;if(U!==-1&&U<$)F++,R=U+d.length;else if(F--,F===0){let Fo=o.slice(i,$),N=ro(Fo),Ro=N.length>0?[s,E,N]:[s,E];r.push(Ro),i=$+b.length}else R=$+b.length}if(F>0)r.push([s,E])}}return r}function io(o){let r=Co(o),i=r.match(/<svg([^>]*)>/i),n=oo(i?.[1]??"");delete n.xmlns,delete n.xmlnsXlink;let{xmlns:c,xmlnsXlink:t,...f}=n,w=r.match(/<svg[^>]*>([\s\S]*)<\/svg>/i)?.[1]?.trim()??"";return{iconNode:ro(w),svgAttrs:f}}function A(o){return o.replace(/[-_\s]+(.)/g,(r,i)=>i.toUpperCase()).replace(/^(.)/,(r,i)=>i.toUpperCase())}function no(o){if(o.length===0)return"";let r=["import { forwardRef, createElement } from 'react';","","const _r = (n) => n.map(([t, a, c], i) => createElement(t, { key: i, ...a }, ...(c ? _r(c) : [])));",""];for(let{name:i,iconNode:n,svgAttrs:c}of o){let t=A(i),f={viewBox:"0 0 24 24",...c},a=JSON.stringify(n),w=JSON.stringify(f);r.push(`export const ${t} = /*#__PURE__*/forwardRef(({ children, ...props }, ref) =>`,` createElement('svg', { ref, xmlns: 'http://www.w3.org/2000/svg', ...${w}, ...props },`,` ..._r(${a}),`," children"," )",");",`${t}.displayName = '${t}';`,"")}return r.join(`
18
- `)}function to(o){let r=["import type { ForwardRefExoticComponent, SVGProps, RefAttributes } from 'react';","","type IconComponent = ForwardRefExoticComponent<SVGProps<SVGSVGElement> & RefAttributes<SVGSVGElement>>;",""];for(let i of o)r.push(`export declare const ${A(i)}: IconComponent;`);return r.push(""),r.join(`
19
- `)}function M(){return K.resolve(K.dirname(Eo(import.meta.url)),"..")}function P(o,r){let i=[];for(let c of r)try{let{iconNode:t,svgAttrs:f}=io(c.svgContent);i.push({name:c.name,iconNode:t,svgAttrs:f})}catch(t){console.warn(bo.yellow(` ⚠ Skipped ${c.name}: ${t.message}`))}if(i.length===0)return 0;let n=M();return L.writeFileSync(K.join(n,`${o}.js`),no(i),"utf-8"),L.writeFileSync(K.join(n,`${o}.d.ts`),to(i.map((c)=>c.name)),"utf-8"),i.length}function H(){let o=K.join(M(),"..","package.json");try{let r=JSON.parse(L.readFileSync(o,"utf-8")),i=r.exports??{};if(i["./*"]?.import?.startsWith("./dist/"))return;r.exports={".":i["."]??{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./*":{import:"./dist/*.js",types:"./dist/*.d.ts"}},L.writeFileSync(o,JSON.stringify(r,null,2)+`
20
- `,"utf-8")}catch{}}function co(o){let r=M(),i=K.join(r,`${o}.js`),n=K.join(r,`${o}.d.ts`);if(L.existsSync(i))L.unlinkSync(i);if(L.existsSync(n))L.unlinkSync(n)}import fo from"fs";import vo from"path";var Ko=".iconia-lock.json";function ao(){return vo.resolve(process.cwd(),Ko)}function _(){try{let o=fo.readFileSync(ao(),"utf-8");return JSON.parse(o)}catch{return{version:1,collections:{}}}}function C(o){fo.writeFileSync(ao(),JSON.stringify(o,null,2),"utf-8")}function z(o,r,i){return{...o,collections:{...o.collections,[r]:{icons:Object.fromEntries(i.map((n)=>[n.slug,n.fingerprint]))}}}}function mo(o,r){let{[r]:i,...n}=o.collections;return{...o,collections:n}}var eo=new Oo("pull").description("Fetch icons and regenerate all collection files (replaces existing)").option("-c, --collection <slug>","Pull only this collection").action(async(o)=>{let r=So("Loading config...").start(),i;try{i=await u()}catch(m){r.fail(O.red(m.message)),process.exit(1)}let n=o.collection?[o.collection]:i.collections;if(n.length===0){r.warn(O.yellow("No collections in config. Add one with `iconia add <slug>`."));return}if(o.collection&&!i.collections.includes(o.collection))r.fail(O.red(`Collection '${o.collection}' is not in your config.`)),process.exit(1);r.text=`Fetching icons for ${n.join(", ")}...`;let c;try{c=await V(i,n)}catch(m){r.fail(O.red(`Failed to fetch icons: ${m.message}`)),process.exit(1)}if(c.length===0){r.warn(O.yellow("No icons found."));return}r.text=`Generating ${c.length} icon${c.length!==1?"s":""}...`;let t=new Map;for(let m of c){let y=t.get(m.collectionSlug)??[];y.push(m),t.set(m.collectionSlug,y)}let f=_(),a=0,w=[];for(let[m,y]of t){let e=P(m,y);if(e===0)continue;a+=e,w.push(m),f=z(f,m,y.map((s)=>({slug:s.slug,fingerprint:s.fingerprint})))}if(C(f),H(),r.succeed(O.green(`Generated ${a} icon${a!==1?"s":""} across ${w.length} collection${w.length!==1?"s":""}`)),w.length>0){let m=w[0]??"",y=A(t.get(m)?.[0]?.name??"MyIcon");console.log(`
17
+ `),await new Promise((n)=>{let a=()=>{clearTimeout(f),process.exit(130)},f=setTimeout(()=>{process.removeListener("SIGINT",a),n()},c*1000);process.once("SIGINT",a),E.signal.addEventListener("abort",a,{once:!0})})}return o(E.signal)}async function x(o){let r=await Z((t)=>fetch(new URL("/v1/collections",o.apiUrl).toString(),{headers:W(o),signal:t}));if(!r.ok){let t={};try{t=await r.json()}catch{}throw Error(`API error ${r.status}: ${t.error??r.statusText}`)}return(await r.json()).collections}async function K(o,r){let i=new URL("/v1/collections/icons",o.apiUrl);i.searchParams.set("collections",r.join(","));let t=await Z((n)=>fetch(i.toString(),{headers:W(o),signal:n}));if(!t.ok){let n={};try{n=await t.json()}catch{}throw Error(`API error ${t.status}: ${n.error??t.statusText}`)}return(await t.json()).icons}async function g(o,r,i){let t=await Z((n)=>fetch(new URL("/v1/icons",o.apiUrl).toString(),{method:"POST",headers:W(o),body:JSON.stringify({collectionSlug:r,icons:i}),signal:n}));if(!t.ok){let n={};try{n=await t.json()}catch{}throw Error(`API error ${t.status}: ${n.error??t.statusText}`)}return(await t.json()).results}import U from"fs";import l from"path";import{fileURLToPath as Bo}from"url";import Co from"picocolors";import{optimize as Lo}from"svgo";function _o(o){return Lo(o,{plugins:["removeDoctype","removeXMLProcInst","removeComments","removeMetadata","removeTitle","removeDesc"]}).data.replace(/<svg([^>]*)>/i,(i,t)=>`<svg${t.replace(/\s+(width|height)=['"][^'"]*['"]/gi,"")}>`)}function oo(o){let r={},i=/([\w:-]+)\s*=\s*(?:"([^"]*)"|'([^']*)')/g,t;while((t=i.exec(o))!==null){let c=t[1].replace(/^xlink:/,"").replace(/-([a-z])/g,(n,a)=>a.toUpperCase());r[c]=t[2]??t[3]??""}return r}function ro(o){let r=[],i=0;while(i<o.length){let t=o.indexOf("<",i);if(t===-1)break;let c=o[t+1];if(c==="/"||c==="!"||c==="?"){let u=o.indexOf(">",t);i=u===-1?o.length:u+1;continue}let n=t+1,a=!1,f="";while(n<o.length){let u=o[n];if(a){if(u===f)a=!1}else if(u==='"'||u==="'")a=!0,f=u;else if(u===">")break;n++}if(n>=o.length)break;let y=o.slice(t+1,n),e=y.trimEnd().endsWith("/"),w=e?y.slice(0,y.lastIndexOf("/")).trim():y.trim(),m=w.search(/\s/),s=m===-1?w:w.slice(0,m);if(!s){i=n+1;continue}let d=m===-1?"":w.slice(m+1),B=oo(d);if(i=n+1,e)r.push([s,B]);else{let u=`<${s}`,C=`</${s}>`,I=1,R=i;while(I>0&&R<o.length){let h=o.indexOf(u,R),$=o.indexOf(C,R);if($===-1)break;if(h!==-1&&h<$)I++,R=h+u.length;else if(I--,I===0){let po=o.slice(i,$),k=ro(po),Io=k.length>0?[s,B,k]:[s,B];r.push(Io),i=$+C.length}else R=$+C.length}if(I>0)r.push([s,B])}}return r}function io(o){let r=_o(o),i=r.match(/<svg([^>]*)>/i),t=oo(i?.[1]??"");delete t.xmlns,delete t.xmlnsXlink;let{xmlns:c,xmlnsXlink:n,...a}=t,y=r.match(/<svg[^>]*>([\s\S]*)<\/svg>/i)?.[1]?.trim()??"";return{iconNode:ro(y),svgAttrs:a}}function z(o){return o.replace(/[-_\s]+(.)/g,(r,i)=>i.toUpperCase()).replace(/^(.)/,(r,i)=>i.toUpperCase())}function to(o){if(o.length===0)return"";let r=["import { forwardRef, createElement } from 'react';","","const _r = (n) => n.map(([t, a, c], i) => createElement(t, { key: i, ...a }, ...(c ? _r(c) : [])));",""];for(let{name:i,iconNode:t,svgAttrs:c}of o){let n=z(i),a={viewBox:"0 0 24 24",...c},f=JSON.stringify(t),y=JSON.stringify(a);r.push(`export const ${n} = /*#__PURE__*/forwardRef(({ children, ...props }, ref) =>`,` createElement('svg', { ref, xmlns: 'http://www.w3.org/2000/svg', ...${y}, ...props },`,` ..._r(${f}),`," children"," )",");",`${n}.displayName = '${n}';`,"")}return r.join(`
18
+ `)}function no(o){let r=["import type { ForwardRefExoticComponent, SVGProps, RefAttributes } from 'react';","","type IconComponent = ForwardRefExoticComponent<SVGProps<SVGSVGElement> & RefAttributes<SVGSVGElement>>;",""];for(let i of o)r.push(`export declare const ${z(i)}: IconComponent;`);return r.push(""),r.join(`
19
+ `)}function G(){return l.resolve(l.dirname(Bo(import.meta.url)),"..")}function O(o,r){let i=[];for(let c of r)try{let{iconNode:n,svgAttrs:a}=io(c.svgContent);i.push({name:c.name,iconNode:n,svgAttrs:a})}catch(n){console.warn(Co.yellow(` ⚠ Skipped ${c.name}: ${n.message}`))}if(i.length===0)return 0;let t=G();return U.writeFileSync(l.join(t,`${o}.js`),to(i),"utf-8"),U.writeFileSync(l.join(t,`${o}.d.ts`),no(i.map((c)=>c.name)),"utf-8"),i.length}function q(){let o=l.join(G(),"..","package.json");try{let r=JSON.parse(U.readFileSync(o,"utf-8")),i=r.exports??{};if(i["./*"]?.import?.startsWith("./dist/"))return;r.exports={".":i["."]??{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./*":{import:"./dist/*.js",types:"./dist/*.d.ts"}},U.writeFileSync(o,JSON.stringify(r,null,2)+`
20
+ `,"utf-8")}catch{}}function co(o){let r=G(),i=l.join(r,`${o}.js`),t=l.join(r,`${o}.d.ts`);if(U.existsSync(i))U.unlinkSync(i);if(U.existsSync(t))U.unlinkSync(t)}import ao from"fs";import Eo from"path";var lo=".iconia-lock.json";function fo(){return Eo.resolve(process.cwd(),lo)}function L(){try{let o=ao.readFileSync(fo(),"utf-8");return JSON.parse(o)}catch{return{version:1,collections:{}}}}function _(o){ao.writeFileSync(fo(),JSON.stringify(o,null,2),"utf-8")}function S(o,r,i){return{...o,collections:{...o.collections,[r]:{icons:Object.fromEntries(i.map((t)=>[t.slug,t.fingerprint]))}}}}function eo(o,r){let{[r]:i,...t}=o.collections;return{...o,collections:t}}var mo=new bo("pull").description("Fetch icons and regenerate all collection files (replaces existing)").option("-c, --collection <slug>","Pull only this collection").action(async(o)=>{let r=vo("Loading config...").start(),i;try{i=await j()}catch(e){r.fail(b.red(e.message)),process.exit(1)}let t=o.collection?[o.collection]:i.collections;if(t.length===0){r.warn(b.yellow("No collections in config. Add one with `iconia add <slug>`."));return}if(o.collection&&!i.collections.includes(o.collection))r.fail(b.red(`Collection '${o.collection}' is not in your config.`)),process.exit(1);r.text=`Fetching icons for ${t.join(", ")}...`;let c;try{c=await K(i,t)}catch(e){r.fail(b.red(`Failed to fetch icons: ${e.message}`)),process.exit(1)}if(c.length===0){r.warn(b.yellow("No icons found."));return}r.text=`Generating ${c.length} icon${c.length!==1?"s":""}...`;let n=new Map;for(let e of c){let w=n.get(e.collectionSlug)??[];w.push(e),n.set(e.collectionSlug,w)}let a=L(),f=0,y=[];for(let[e,w]of n){let m=O(e,w);if(m===0)continue;f+=m,y.push(e),a=S(a,e,w.map((s)=>({slug:s.slug,fingerprint:s.fingerprint})))}if(_(a),q(),r.succeed(b.green(`Generated ${f} icon${f!==1?"s":""} across ${y.length} collection${y.length!==1?"s":""}`)),y.length>0){let e=y[0]??"",w=z(n.get(e)?.[0]?.name??"MyIcon");console.log(`
21
21
  Import icons:
22
- ${O.cyan(`import { ${y} } from '@iconia/react/${m}'`)}`)}});import{Command as Vo}from"commander";import p from"picocolors";import Ao from"ora";import q from"fs";import yo from"path";function T(){let o=yo.resolve(process.cwd(),"iconia.config.ts"),r=yo.resolve(process.cwd(),"iconia.config.js");if(q.existsSync(o))return o;if(q.existsSync(r))return r;return null}function B(o){let n=q.readFileSync(o,"utf-8").match(/collections:\s*\[([\s\S]*?)\]/)?.[1];if(!n)return null;let c=[],t=/['"]([^'"]+)['"]/g,f;while((f=t.exec(n))!==null){let a=f[1];if(a)c.push(a)}return c}function Q(o,r){let i=q.readFileSync(o,"utf-8"),n=r.length===0?"[]":`[
23
- ${r.map((t)=>` '${t}'`).join(`,
22
+ ${b.cyan(`import { ${w} } from '@iconia/react/${e}'`)}`)}});import{Command as Ko}from"commander";import F from"picocolors";import zo from"ora";import V from"fs";import so from"path";function Y(){let o=so.resolve(process.cwd(),"iconia.config.ts"),r=so.resolve(process.cwd(),"iconia.config.js");if(V.existsSync(o))return o;if(V.existsSync(r))return r;return null}function H(o){let t=V.readFileSync(o,"utf-8").match(/collections:\s*\[([\s\S]*?)\]/)?.[1];if(!t)return null;let c=[],n=/['"]([^'"]+)['"]/g,a;while((a=n.exec(t))!==null){let f=a[1];if(f)c.push(f)}return c}function T(o,r){let i=V.readFileSync(o,"utf-8"),t=r.length===0?"[]":`[
23
+ ${r.map((n)=>` '${n}'`).join(`,
24
24
  `)},
25
- ]`,c=i.replace(/collections:\s*\[[\s\S]*?\]/,`collections: ${n}`);if(c===i)return!1;return q.writeFileSync(o,c,"utf-8"),!0}var wo=new Vo("add").description("Add a collection to your project (updates config and downloads icons)").argument("<slug>","Collection slug").action(async(o)=>{let r=Ao("Loading config...").start(),i;try{i=await u()}catch(a){r.fail(p.red(a.message)),process.exit(1)}if(i.collections.includes(o))r.info(p.yellow(`Collection '${o}' is already in your config. Running pull...`));else{r.text="Verifying collection...";let a;try{a=await x(i)}catch(j){r.fail(p.red(`Failed to fetch collections: ${j.message}`)),process.exit(1)}if(!a.find((j)=>j.slug===o))r.fail(p.red(`Collection '${o}' not found. Available: ${a.map((j)=>j.slug).join(", ")||"none"}`)),process.exit(1);let m=T();if(!m)r.fail(p.red("Config file not found. Run `npx @iconia/react init` first.")),process.exit(1);let e=[...B(m)??i.collections,o];if(!Q(m,e))r.warn(p.yellow(`Could not update config automatically. Add '${o}' to collections in iconia.config.ts manually.`));else r.text=`Added '${o}' to config. Fetching icons...`}r.text=`Fetching icons for '${o}'...`;let n;try{n=await V(i,[o])}catch(a){r.fail(p.red(`Failed to fetch icons: ${a.message}`)),process.exit(1)}if(n.length===0){r.warn(p.yellow(`No icons in collection '${o}'.`));return}r.text=`Generating ${n.length} icon${n.length!==1?"s":""}...`;let c=P(o,n),t=_();t=z(t,o,n.map((a)=>({slug:a.slug,fingerprint:a.fingerprint}))),C(t),r.succeed(p.green(`Added '${o}' — ${c} icon${c!==1?"s":""} generated`));let f=A(n[0]?.name??"Icon");console.log(`
25
+ ]`,c=i.replace(/collections:\s*\[[\s\S]*?\]/,`collections: ${t}`);if(c===i)return!1;return V.writeFileSync(o,c,"utf-8"),!0}var yo=new Ko("add").description("Add a collection to your project (updates config and downloads icons)").argument("<slug>","Collection slug").action(async(o)=>{let r=zo("Loading config...").start(),i;try{i=await j()}catch(f){r.fail(F.red(f.message)),process.exit(1)}if(i.collections.includes(o))r.info(F.yellow(`Collection '${o}' is already in your config. Running pull...`));else{r.text="Verifying collection...";let f;try{f=await x(i)}catch(d){r.fail(F.red(`Failed to fetch collections: ${d.message}`)),process.exit(1)}if(!f.find((d)=>d.slug===o))r.fail(F.red(`Collection '${o}' not found. Available: ${f.map((d)=>d.slug).join(", ")||"none"}`)),process.exit(1);let e=Y();if(!e)r.fail(F.red("Config file not found. Run `npx @iconia/react init` first.")),process.exit(1);let m=[...H(e)??i.collections,o];if(!T(e,m))r.warn(F.yellow(`Could not update config automatically. Add '${o}' to collections in iconia.config.ts manually.`));else r.text=`Added '${o}' to config. Fetching icons...`}r.text=`Fetching icons for '${o}'...`;let t;try{t=await K(i,[o])}catch(f){r.fail(F.red(`Failed to fetch icons: ${f.message}`)),process.exit(1)}if(t.length===0){r.warn(F.yellow(`No icons in collection '${o}'.`));return}r.text=`Generating ${t.length} icon${t.length!==1?"s":""}...`;let c=O(o,t),n=L();n=S(n,o,t.map((f)=>({slug:f.slug,fingerprint:f.fingerprint}))),_(n),r.succeed(F.green(`Added '${o}' — ${c} icon${c!==1?"s":""} generated`));let a=z(t[0]?.name??"Icon");console.log(`
26
26
  Import icons:
27
- ${p.cyan(`import { ${f} } from '@iconia/react/${o}'`)}`)});import{Command as Po}from"commander";import W from"picocolors";var so=new Po("remove").description("Remove a collection from your project (updates config and deletes generated files)").argument("<slug>","Collection slug").action(async(o)=>{let r;try{r=await u()}catch(n){console.error(W.red(n.message)),process.exit(1)}if(!r.collections.includes(o))console.warn(W.yellow(`Collection '${o}' is not in your config.`));else{let n=T();if(n){let t=(B(n)??r.collections).filter((a)=>a!==o);if(!Q(n,t))console.warn(W.yellow(`Could not update config automatically. Remove '${o}' from collections in iconia.config.ts manually.`))}}co(o);let i=_();i=mo(i,o),C(i),console.log(W.green(`✓ Removed collection '${o}'`))});import{Command as zo}from"commander";import I from"picocolors";import Jo from"ora";var $o=new zo("sync").description("Sync icons: add new, update changed, remove deleted — without full re-fetch").option("-c, --collection <slug>","Sync only this collection").action(async(o)=>{let r=Jo("Loading config...").start(),i;try{i=await u()}catch(e){r.fail(I.red(e.message)),process.exit(1)}let n=o.collection?[o.collection]:i.collections;if(n.length===0){r.warn(I.yellow("No collections in config. Add one with `iconia add <slug>`."));return}if(o.collection&&!i.collections.includes(o.collection))r.fail(I.red(`Collection '${o.collection}' is not in your config.`)),process.exit(1);r.text=`Fetching icons for ${n.join(", ")}...`;let c;try{c=await V(i,n)}catch(e){r.fail(I.red(`Failed to fetch icons: ${e.message}`)),process.exit(1)}let t=new Map;for(let e of c){let s=t.get(e.collectionSlug)??[];s.push(e),t.set(e.collectionSlug,s)}let f=_(),a=0,w=0,m=0,y=0;for(let e of n){let s=t.get(e)??[],j=f.collections[e]?.icons??{},E=new Map(s.map(($)=>[$.slug,$])),d=new Set(Object.keys(j)),b=new Set(E.keys()),F=[...b].filter(($)=>!d.has($)),R=[...d].filter(($)=>!b.has($)),U=[...b].filter(($)=>d.has($)&&j[$]!==E.get($).fingerprint);if(F.length===0&&R.length===0&&U.length===0){console.log(I.dim(` ${e}: up to date`));continue}if(F.length>0)console.log(I.green(` ${e}: +${F.length} added`)+I.dim(` (${F.slice(0,5).join(", ")}${F.length>5?"…":""})`));if(U.length>0)console.log(I.blue(` ${e}: ~${U.length} updated`)+I.dim(` (${U.slice(0,5).join(", ")}${U.length>5?"…":""})`));if(R.length>0)console.log(I.red(` ${e}: -${R.length} removed`)+I.dim(` (${R.slice(0,5).join(", ")}${R.length>5?"…":""})`));if(s.length>0)P(e,s);f=z(f,e,s.map(($)=>({slug:$.slug,fingerprint:$.fingerprint}))),a+=F.length,w+=U.length,m+=R.length,y++}if(C(f),y>0)H();if(y===0)r.succeed(I.green("Everything is up to date."));else r.succeed(I.green(`Sync complete: ${a} added, ${w} updated, ${m} removed across ${y} collection${y!==1?"s":""}`))});import{Command as ho}from"commander";import k from"fs";import h from"path";import J from"picocolors";import qo from"ora";function Yo(o){return h.basename(o,h.extname(o)).toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function Ho(o){return o.split("-").map((r)=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ")}function To(o){let r=k.statSync(o);if(r.isFile()){if(!o.endsWith(".svg"))throw Error(`File '${o}' is not an SVG.`);return[o]}if(r.isDirectory())return k.readdirSync(o).filter((i)=>i.endsWith(".svg")).map((i)=>h.join(o,i));throw Error(`'${o}' is not a file or directory.`)}var Io=new ho("upload").description("Upload SVG file(s) to an Iconia collection").argument("<path>","SVG file or directory of SVGs").requiredOption("-c, --collection <slug>","Target collection slug").option("--tags <tags>","Comma-separated tags to apply to all uploaded icons").action(async(o,r)=>{let i=qo({text:"Loading config...",discardStdin:!1}).start(),n;try{n=await u()}catch(m){i.fail(J.red(m.message)),process.exit(1)}let c;try{c=To(h.resolve(process.cwd(),o))}catch(m){i.fail(J.red(m.message)),process.exit(1)}if(c.length===0){i.warn(J.yellow("No SVG files found."));return}let t=r.tags?r.tags.split(",").map((m)=>m.trim()).filter(Boolean):[];i.text=`Uploading ${c.length} file${c.length!==1?"s":""} to '${r.collection}'...`;let f=0,a=0,w=[];for(let m of c){if(v.signal.aborted)break;let y=Yo(m);if(!y){w.push(`${h.basename(m)}: could not derive a valid slug`),a++;continue}let e=k.readFileSync(m,"utf-8");try{await g(n,{collectionSlug:r.collection,name:Ho(y),slug:y,svgContent:e,tags:t}),f++,i.text=`Uploading... (${f}/${c.length})`}catch(s){w.push(`${h.basename(m)}: ${s.message}`),a++}}if(a===0)i.succeed(J.green(`Uploaded ${f} icon${f!==1?"s":""} to '${r.collection}'`));else{i.warn(J.yellow(`Uploaded ${f}, failed ${a}`));for(let m of w)console.log(J.dim(` ✗ ${m}`))}});var Qo=new Bo("iconia").version("0.1.0").description("CLI for fetching and generating React icon components from Iconia").addCommand(l).addCommand(wo).addCommand(so).addCommand(eo).addCommand($o).addCommand(Io);Qo.parse(process.argv);
27
+ ${F.cyan(`import { ${a} } from '@iconia/react/${o}'`)}`)});import{Command as Oo}from"commander";import Q from"picocolors";var wo=new Oo("remove").description("Remove a collection from your project (updates config and deletes generated files)").argument("<slug>","Collection slug").action(async(o)=>{let r;try{r=await j()}catch(t){console.error(Q.red(t.message)),process.exit(1)}if(!r.collections.includes(o))console.warn(Q.yellow(`Collection '${o}' is not in your config.`));else{let t=Y();if(t){let n=(H(t)??r.collections).filter((f)=>f!==o);if(!T(t,n))console.warn(Q.yellow(`Could not update config automatically. Remove '${o}' from collections in iconia.config.ts manually.`))}}co(o);let i=L();i=eo(i,o),_(i),console.log(Q.green(`✓ Removed collection '${o}'`))});import{Command as So}from"commander";import p from"picocolors";import Ao from"ora";var $o=new So("sync").description("Sync icons: add new, update changed, remove deleted — without full re-fetch").option("-c, --collection <slug>","Sync only this collection").action(async(o)=>{let r=Ao("Loading config...").start(),i;try{i=await j()}catch(m){r.fail(p.red(m.message)),process.exit(1)}let t=o.collection?[o.collection]:i.collections;if(t.length===0){r.warn(p.yellow("No collections in config. Add one with `iconia add <slug>`."));return}if(o.collection&&!i.collections.includes(o.collection))r.fail(p.red(`Collection '${o.collection}' is not in your config.`)),process.exit(1);r.text=`Fetching icons for ${t.join(", ")}...`;let c;try{c=await K(i,t)}catch(m){r.fail(p.red(`Failed to fetch icons: ${m.message}`)),process.exit(1)}let n=new Map;for(let m of c){let s=n.get(m.collectionSlug)??[];s.push(m),n.set(m.collectionSlug,s)}let a=L(),f=0,y=0,e=0,w=0;for(let m of t){let s=n.get(m)??[],d=a.collections[m]?.icons??{},B=new Map(s.map(($)=>[$.slug,$])),u=new Set(Object.keys(d)),C=new Set(B.keys()),I=[...C].filter(($)=>!u.has($)),R=[...u].filter(($)=>!C.has($)),h=[...C].filter(($)=>u.has($)&&d[$]!==B.get($).fingerprint);if(I.length===0&&R.length===0&&h.length===0){console.log(p.dim(` ${m}: up to date`));continue}if(I.length>0)console.log(p.green(` ${m}: +${I.length} added`)+p.dim(` (${I.slice(0,5).join(", ")}${I.length>5?"…":""})`));if(h.length>0)console.log(p.blue(` ${m}: ~${h.length} updated`)+p.dim(` (${h.slice(0,5).join(", ")}${h.length>5?"…":""})`));if(R.length>0)console.log(p.red(` ${m}: -${R.length} removed`)+p.dim(` (${R.slice(0,5).join(", ")}${R.length>5?"…":""})`));if(s.length>0)O(m,s);a=S(a,m,s.map(($)=>({slug:$.slug,fingerprint:$.fingerprint}))),f+=I.length,y+=h.length,e+=R.length,w++}if(_(a),w>0)q();if(w===0)r.succeed(p.green("Everything is up to date."));else r.succeed(p.green(`Sync complete: ${f} added, ${y} updated, ${e} removed across ${w} collection${w!==1?"s":""}`))});import{Command as Po}from"commander";import M from"fs";import J from"path";import A from"picocolors";import Vo from"ora";function Jo(o){return J.basename(o,J.extname(o)).toLowerCase().replace(/\s+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-|-$/g,"")}function qo(o){return o.split("-").map((r)=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ")}function Yo(o){let r=M.statSync(o);if(r.isFile()){if(!o.endsWith(".svg"))throw Error(`File '${o}' is not an SVG.`);return[o]}if(r.isDirectory())return M.readdirSync(o).filter((i)=>i.endsWith(".svg")).map((i)=>J.join(o,i));throw Error(`'${o}' is not a file or directory.`)}var uo=new Po("upload").description("Upload SVG file(s) to an Iconia collection").argument("<path>","SVG file or directory of SVGs").requiredOption("-c, --collection <slug>","Target collection slug").option("--tags <tags>","Comma-separated tags to apply to all uploaded icons").action(async(o,r)=>{let i=Vo({text:"Loading config...",discardStdin:!1}).start(),t;try{t=await j()}catch(e){i.fail(A.red(e.message)),process.exit(1)}let c;try{c=Yo(J.resolve(process.cwd(),o))}catch(e){i.fail(A.red(e.message)),process.exit(1)}if(c.length===0){i.warn(A.yellow("No SVG files found."));return}let n=r.tags?r.tags.split(",").map((e)=>e.trim()).filter(Boolean):[];i.text=`Uploading ${c.length} file${c.length!==1?"s":""} to '${r.collection}'...`;let a=0,f=0,y=[];for(let e=0;e<c.length;e+=t.uploadBatchSize){if(E.signal.aborted)break;let w=c.slice(e,e+t.uploadBatchSize),m=[];for(let s of w){let d=Jo(s);if(!d){y.push(`${J.basename(s)}: could not derive a valid slug`),f++;continue}m.push({slug:d,name:qo(d),svgContent:M.readFileSync(s,"utf-8"),tags:n})}if(m.length===0)continue;try{let s=await g(t,r.collection,m);for(let d of s)if(d.status==="uploaded"||d.status==="duplicate")a++;else y.push(`${d.slug}: ${d.error??"upload failed"}`),f++}catch(s){for(let d of m)y.push(`${d.slug}: ${s.message}`),f++}i.text=`Uploading... (${a+f}/${c.length})`}if(f===0)i.succeed(A.green(`Uploaded ${a} icon${a!==1?"s":""} to '${r.collection}'`));else{i.warn(A.yellow(`Uploaded ${a}, failed ${f}`));for(let e of y)console.log(A.dim(` ✗ ${e}`))}});var To=new Ho("iconia").version("0.1.0").description("CLI for fetching and generating React icon components from Iconia").addCommand(X).addCommand(yo).addCommand(wo).addCommand(mo).addCommand($o).addCommand(uo);To.parse(process.argv);
package/dist/index.d.ts CHANGED
@@ -12,6 +12,7 @@ export type IconNode = IconNodeElement[];
12
12
  declare const configSchema: z.ZodObject<{
13
13
  apiKey: z.ZodString;
14
14
  collections: z.ZodDefault<z.ZodArray<z.ZodString>>;
15
+ uploadBatchSize: z.ZodDefault<z.ZodNumber>;
15
16
  }, z.core.$strip>;
16
17
  export type IconiaConfig = z.infer<typeof configSchema> & {
17
18
  apiUrl?: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@iconia/react",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "Fetch and generate React icon components from your Iconia collections",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",