@aurodesignsystem-dev/auro-cli 0.0.0-pr350.3 → 0.0.0-pr353.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -4
- package/dist/auro-cli.js +94 -92
- package/dist/auro-cli.js.map +4 -4
- package/package.json +1 -1
package/dist/auro-cli.js
CHANGED
|
@@ -1,37 +1,37 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{program as
|
|
2
|
+
import{program as yr}from"commander";import Di from"figlet";import{mind as Mi}from"gradient-string";var br=()=>Mi(Di.textSync("Auro CLI"));import wr from"node:fs";import vr from"node:path";import{fileURLToPath as Ni}from"node:url";function Je(e){process.env.DEBUG&&console.log(`[DEBUG] ${e}`)}function qt(){try{let e=Ni(import.meta.url),t=vr.dirname(e);Je(`Current module path: ${t}`);let n=vr.resolve(t,"..","package.json");return Je(`Checking package.json at: ${n}`),wr.existsSync(n)?(Je(`Found package.json at: ${n}`),JSON.parse(wr.readFileSync(n,"utf8")).version):(Je("Could not find package.json in the standard installed module location, using default version"),"0.0.0")}catch(e){return console.error("Error retrieving package version:",e),"0.0.0"}}import{program as ja}from"commander";import Yr from"ora";function ze(e){return e.option("-m, --module-paths [paths...]","Path(s) to node_modules folder").option("-w, --watch","Watches for changes").option("--skip-docs","Skip documentation generation",!1).option("-r, --readme-template <url>","URL to the README template file").option("--wca-input [files...]","Source file(s) to analyze for API documentation").option("--wca-output [files...]","Output file(s) for API documentation")}function Ve(e){return e.option("-s, --serve","Starts a server").option("-p, --port <number>","Port for the server").option("-o, --open","Open the browser after starting the server")}import Ma from"@rollup/plugin-terser";import{watch as Na}from"rollup";import{existsSync as Wr,readFileSync as ka,rmSync as $a,writeFileSync as Ea}from"node:fs";import{basename as Sa,dirname as Ca,join as Me,resolve as rt}from"node:path";import{pathToFileURL as Ur}from"node:url";import{glob as Aa}from"glob";import an from"ora";import{rollup as sn}from"rollup";import*as Hr from"sass";import Pe from"ora";import{spawn as Ii}from"node:child_process";import Oi from"ora";var _=(e,t)=>{let n=`${e} ${t?t.join(" "):""}`,r=Oi(),o=e,s=t||[];if(!t&&typeof e=="string"){let l=e.split(" ");o=l[0],s=l.slice(1)}let i=n.includes("--watch")||n.includes(" -w"),c=Ii(o,s,{stdio:i?"inherit":["inherit","pipe","pipe"],shell:!0});if(!i){let l=[];c.stdout?.on("data",m=>{let u=m.toString();l.push(u),process.stdout.write(u)}),c.stderr?.on("data",m=>{let u=m.toString();l.push(u),process.stderr.write(u)})}return new Promise((l,m)=>{c.on("close",u=>{u!==0?i?(r.info(`Watch mode terminated with code ${u}`),l()):(r.fail(`${n} failed (code ${u})`),m(new Error(`Command failed with exit code ${u}`))):(r.succeed(`${n} completed successfully`),l())})})};import Ke from"node:fs";import ji from"node:path";import{markdownTable as kr}from"markdown-table";var Ae=class e{static{this.manifest={schemaVersion:"1.0.0",readme:"",modules:[]}}static generate(t={}){let{outDir:n="./docs",outFile:r="api.md",manifestPath:o="./custom-elements.json"}=t,{getElements:s,renderAllElements:i}=e;if(o)try{let u=Ke.readFileSync(o,"utf8");e.manifest=JSON.parse(u)}catch(u){throw console.error(`Error reading manifest file at ${o}:`,u),u}let a=s(),c=n;Ke.existsSync(c)||Ke.mkdirSync(c,{recursive:!0});let l=i(a),m=ji.join(c,r);Ke.writeFileSync(m,l),console.log(`Generated combined API documentation at ${m}`)}static getElements(){let t=e.manifest.modules.filter(e.isWcaModule);return e.manifest.modules.reduce((n,r)=>n.concat(r.declarations?.filter(o=>"customElement"in o&&o.customElement===!0&&"tagName"in o&&(t.length>0?e.isWcaModule(r):!0))??[]),[])}static isWcaModule(t){let{path:n}=t;return n?n.startsWith("scripts/wca/auro-")&&n.endsWith(".js"):!1}static renderAllElements(t){return`${t.sort((n,r)=>(n.tagName||"").localeCompare(r.tagName||"")).map(n=>e.renderElement(n,!0)).join(`
|
|
3
3
|
|
|
4
|
-
`)}`}static renderElement(t,n=!0){let r=[],{renderTable:o,renderPropertiesAttributesTable:s,renderParameters:i,getType:a}=e;r.push(n?`# ${t.tagName}`:""),t.description&&r.push(t.description);let c=s(t);c&&r.push(c.trim());let l=o("Methods",["name","parameters","return","description"],(t.members||[]).filter(
|
|
4
|
+
`)}`}static renderElement(t,n=!0){let r=[],{renderTable:o,renderPropertiesAttributesTable:s,renderParameters:i,getType:a}=e;r.push(n?`# ${t.tagName}`:""),t.description&&r.push(t.description);let c=s(t);c&&r.push(c.trim());let l=o("Methods",["name","parameters","return","description"],(t.members||[]).filter(f=>f.kind==="method"&&("privacy"in f?f.privacy!=="private":!0)&&f.name[0]!=="_").map(f=>({...f,parameters:i("parameters"in f?f.parameters:void 0),return:"return"in f&&f.return?a(f.return):""})));l&&r.push(l.trim());let m=o("Events",["name","description"],t.events);m&&r.push(m.trim());let u=o("Slots",[["name","(default)"],"description"],t.slots);u&&r.push(u.trim());let p=o("CSS Shadow Parts",["name","description"],t.cssParts);p&&r.push(p.trim());let d=o("CSS Custom Properties",["name","description"],t.cssProperties);return d&&r.push(d.trim()),r.join(`
|
|
5
5
|
|
|
6
|
-
`)}static renderPropertiesAttributesTable(t){let{getType:n,escapeMarkdown:r}=e,o=t.members?.filter(u=>u.kind==="field"&&("privacy"in u?u.privacy!=="private":!0)&&u.name[0]!=="_")||[],s=t.attributes||[],i=[],a=new Set;if(o.forEach(u=>{if(u.description?.trim()){let p=n(u)||"",
|
|
6
|
+
`)}static renderPropertiesAttributesTable(t){let{getType:n,escapeMarkdown:r}=e,o=t.members?.filter(u=>u.kind==="field"&&("privacy"in u?u.privacy!=="private":!0)&&u.name[0]!=="_")||[],s=t.attributes||[],i=[],a=new Set;if(o.forEach(u=>{if(u.description?.trim()){let p=n(u)||"",f=("return"in u&&u.return?n(u.return):"")||p;i.push({name:u.name,properties:u.name,attributes:("attribute"in u?u.attribute:"")||"",modifiers:"readonly"in u&&u.readonly?"readonly":"",type:f,default:("default"in u?u.default:"")||"",description:u.description||""})}a.add(u.name),"attribute"in u&&u.attribute&&a.add(u.attribute)}),s.forEach(u=>{!a.has(u.name)&&u.description?.trim()&&i.push({name:u.name,properties:"",attributes:u.name,modifiers:"",type:n(u)||"",default:u.default||"",description:u.description||""})}),i.length===0)return"";let c=["Properties","Attributes","Modifiers","Type","Default","Description"],l=i.map(u=>{let g=(u.default||"").trim().replace(/^'([^']+)'$/,"$1").replace(/^"([^"]+)"$/,"$1"),h=g?g.startsWith("`")&&g.endsWith("`")?g:`\`${g}\``:"";return[r(u.properties),r(u.attributes),r(u.modifiers),r(u.type),r(h),r(u.description)]});return`### Properties & Attributes
|
|
7
7
|
|
|
8
|
-
${
|
|
9
|
-
`}static renderParameters(t){let{escapeMarkdown:n,getType:r}=e;return!t||t.length===0?"None":t.map(o=>{let s=r(o)||"any",i=o.description?` - ${o.description}`:"";return`\`${o.name}\` (${n(s)})${n(i)}`}).join("<br>")}static renderTable(t,n,r){let{escapeMarkdown:o,get:s,capitalize:i}=e;if(r===void 0||r.length===0)return"";let a=r.filter(u=>{let{description:p}=u;return typeof p=="string"&&p.trim()});if(a.length===0)return"";let c=n.map(u=>i((Array.isArray(u)?u[0]:u).split(".")[0])),l=a.map(u=>n.map(p=>{let
|
|
8
|
+
${kr([c,...l])}
|
|
9
|
+
`}static renderParameters(t){let{escapeMarkdown:n,getType:r}=e;return!t||t.length===0?"None":t.map(o=>{let s=r(o)||"any",i=o.description?` - ${o.description}`:"";return`\`${o.name}\` (${n(s)})${n(i)}`}).join("<br>")}static renderTable(t,n,r){let{escapeMarkdown:o,get:s,capitalize:i}=e;if(r===void 0||r.length===0)return"";let a=r.filter(u=>{let{description:p}=u;return typeof p=="string"&&p.trim()});if(a.length===0)return"";let c=n.map(u=>i((Array.isArray(u)?u[0]:u).split(".")[0])),l=a.map(u=>n.map(p=>{let d=s(u,p);return o(String(d||""))})),m=kr([c,...l]);return`### ${t}
|
|
10
10
|
|
|
11
11
|
${m}
|
|
12
|
-
`}static escapeMarkdown(t){return t.replace(/\\/g,"\\\\").replace(/\n/g,"<br>").replace(/\|/g,"\\|")}static getType(t){if(!t||!t.type)return"";let{type:n}=t,r=s=>s.replace(/\s*\|\s*/g," | ").replace(/'([^']+)'/g,"`$1`");if(typeof n=="string")return r(n);if(n.text)return r(n.text);if(Array.isArray(n))return n.map(s=>typeof s=="string"?s:s.text?s.text:s.name?s.name:String(s)).join(" \\| ");if(n.name)return r(n.name);if(n.references&&Array.isArray(n.references))return n.references.map(s=>s.name||String(s)).join(" \\| ");let o=String(n);return r(o)}static get(t,n){let r="",o=n;Array.isArray(n)&&([o,r]=n);let s=o.split("."),i=t;for(;i&&s.length;)i=i[s.shift()];return i==null||i===""?r:String(i)}static capitalize(t){return t.replace(/([A-Z])/g," $1").replace(/^./,n=>n.toUpperCase()).trim()}};import
|
|
12
|
+
`}static escapeMarkdown(t){return t.replace(/\\/g,"\\\\").replace(/\n/g,"<br>").replace(/\|/g,"\\|")}static getType(t){if(!t||!t.type)return"";let{type:n}=t,r=s=>s.replace(/\s*\|\s*/g," | ").replace(/'([^']+)'/g,"`$1`");if(typeof n=="string")return r(n);if(n.text)return r(n.text);if(Array.isArray(n))return n.map(s=>typeof s=="string"?s:s.text?s.text:s.name?s.name:String(s)).join(" \\| ");if(n.name)return r(n.name);if(n.references&&Array.isArray(n.references))return n.references.map(s=>s.name||String(s)).join(" \\| ");let o=String(n);return r(o)}static get(t,n){let r="",o=n;Array.isArray(n)&&([o,r]=n);let s=o.split("."),i=t;for(;i&&s.length;)i=i[s.shift()];return i==null||i===""?r:String(i)}static capitalize(t){return t.replace(/([A-Z])/g," $1").replace(/^./,n=>n.toUpperCase()).trim()}};import _i from"node:fs";import Fi from"node:os";import qe from"node:path";import Yt from"node:process";function Li(){let e=Fi.homedir()||Yt.env.HOME||Yt.env.USERPROFILE;if(!e)throw new Error("Unable to determine user home directory");return qe.join(e,".auro")}function Xt(...e){return qe.join(Li(),...e)}function Zt(...e){let t=_i.realpathSync(Yt.argv[1]),n=qe.dirname(t);return qe.resolve(n,...e)}var $r=e=>Zt("configs",e);import{copyFileSync as Gi,existsSync as Er,mkdirSync as Bi}from"node:fs";import{join as Wi,resolve as Qt}from"node:path";function Ye(){let e=process.cwd(),t=Qt(e,"README.md"),n=Wi(Qt(e,"demo"),"readme.md");if(!Er(t))return;let r=Qt(e,"demo");Er(r)||Bi(r,{recursive:!0}),Gi(t,n)}import Ui from"ora";var Cr=[];function xe(e){Cr.push(e)}var Sr=!1;function Xe(){Sr||(Sr=!0,process.on("SIGINT",()=>{let e=Ui("Wrapping up...").start();for(let t of Cr)t.close();e.succeed("All done! See you next time. \u2728"),process.exit(0)}))}import{Logger as Hi}from"@aurodesignsystem/auro-library/scripts/utils/logger.mjs";import{generateReadmeUrl as Ji,processContentForFile as zi,templateFiller as tn}from"@aurodesignsystem/auro-library/scripts/utils/sharedFileProcessorUtils.mjs";import F from"node:fs";import{readFileSync as nn,existsSync as en}from"node:fs";import W from"node:path";var Vi="/docs/pages",Tr={overwriteLocalCopies:!0,remoteReadmeVersion:"master",remoteReadmeVariant:"_updated_paths",monorepoName:void 0,extraVars:{}};function N(e){return`${process.cwd()}/${e}`}function Ki(e=process.cwd()){let t=e;for(;;){let n=W.join(t,"package.json");if(en(n))try{if(JSON.parse(nn(n,"utf8")).workspaces)return t}catch{}let r=W.dirname(t);if(r===t)break;t=r}return e}async function qi(e,t=!1){let n=[];if(!t){let o=e.localReadmePath?e.localReadmePath:{remoteUrl:e.remoteReadmeUrl||Ji(e.remoteReadmeVersion,e.remoteReadmeVariant),fileName:N("/docTemplates/README.md"),overwrite:e.overwriteLocalCopies};n.push({identifier:"README.md",input:o,output:N("/README.md")})}xr("/docs/partials/index.md")&&n.push({identifier:"index.md",input:N("/docs/partials/index.md"),output:N("/demo/index.md"),mdMagicConfig:{output:{directory:N("/demo")}}}),xr("/docs/partials/api.md")&&n.push({identifier:"api.md",input:N("/docs/partials/api.md"),output:N("/demo/api.md"),preProcessors:[tn.formatApiTable]});let r=N(Vi);if(F.existsSync(r)){let s=(await F.promises.readdir(r)).map(i=>({identifier:i,input:W.join(r,i),output:N(`/demo/${i}`)}));n.push(...s)}return n}async function Yi(e=Tr,t=!1){await tn.extractNames();let n=await qi(e,t),r=e.monorepoName;if(!r)try{let i=W.join(Ki(),"package.json");r=JSON.parse(nn(i,"utf8")).name?.replace(/^@[^/]+\//,"")}catch{}let o={...r?{monorepoName:r}:{},...e.extraVars||{}},s=[];for(let i of n)try{if(await zi({...i,extraVars:o,preProcessors:[...i.preProcessors??[],a=>Pr(a,o)]}),i.output.endsWith(".md")){await na(i.output,o);let a=ta(await F.promises.readFile(i.output,"utf8"));if(a.length>0)throw new Error(`Unreplaced template placeholders: ${a.join(", ")}`)}}catch(a){Hi.error(`Error processing ${i.identifier}: ${a.message}`),s.push(`${i.identifier}: ${a.message}`)}if(s.length>0)throw new Error(`Failed to generate ${s.length} docs file(s):
|
|
13
13
|
${s.map(i=>` - ${i}`).join(`
|
|
14
|
-
`)}`)}var
|
|
15
|
-
<!-- The below content is automatically added from ${
|
|
16
|
-
${
|
|
17
|
-
<!-- AURO-GENERATED-CONTENT:END -->`;else{let
|
|
18
|
-
</code></pre>`,t);
|
|
19
|
-
<!-- The below code snippet is automatically added from ${
|
|
20
|
-
${
|
|
21
|
-
<!-- AURO-GENERATED-CONTENT:END -->`}r=r.replace(
|
|
22
|
-
</code></pre>`});m!==r&&await F.promises.writeFile(e,m),r=await F.promises.readFile(e,"utf8"),r=r.replace(/(<pre[^>]*><code[^>]*>)([\s\S]*?)(<\/code><\/pre>)/g,(f,
|
|
23
|
-
`}`).join("");return
|
|
24
|
-
`),p=!1;for(let
|
|
25
|
-
`))}async function
|
|
26
|
-
`).start();try{let n={port:Number(e.port)||void 0,open:e.open?"/":void 0,watch:e.watch??Ce.watch,nodeResolve:e.nodeResolve??Ce.nodeResolve,basePath:e.basePath??Ce.basePath,rootDir:e.rootDir??Ce.rootDir,middleware:[function(s,i){return!s.url.endsWith("/")&&!s.url.includes(".")&&(s.url+=".html"),i()}],plugins:[zi(),qi(),Hi({include:e.hmrInclude??Ce.hmrInclude})]},r=await Wi({config:n,readCliArgs:!1,readFileConfig:!1});return t.stop(),r}catch(n){throw t.fail("Server snag! Couldn't start dev server."),console.error("Error starting development server:",n),new Error(`Development server failed to start: ${n.message}`)}}async function Ze(){let e=xe("Generating Custom Elements Manifest...").start();try{await _(`npx --package=@custom-elements-manifest/analyzer -y -- cem analyze --config '${ur("custom-elements-manifest.config.mjs")}'`),e.succeed("Custom Elements Manifest generated successfully!")}catch(t){let n=t instanceof Error?t.message:String(t);e.warn("CEM analyzer completed with warnings: "+n)}}async function Qe(){let e=xe("Generating API md file...").start();try{await $e.generate(),e.succeed("API md file generated successfully!")}catch(t){let n=t instanceof Error?t.message:String(t);throw e.fail("Failed to generate API md file: "+n),t}}async function kr(e={},{build:t=Ae,demo:n=Er}={}){let r=xe("Compiling documentation...").start(),o;try{await t(e),r.succeed("Documentation compiled successfully!")}catch(s){let i=s instanceof Error?s.message:String(s);r.fail("Failed to compile MD documentation: "+i),o=s}if(await n(e),o)throw o}async function Er(e={}){Ke(),await ee(),await Ar(e)}async function $r(e={}){await Xe(e)}async function Sr(e={}){let t=await import("chokidar"),n=["./src/**/*","./docs/**/*","./docTemplates/**/*","./apiExamples/**/*","./demo/**/*.scss"],r=["**/demo/*.min.js","**/demo/*.min.css","**/demo/*.md","**/demo/readme.md","**/docs/api.md","**/custom-elements.json","**/node_modules/**","**/dist/**","**/.git/**"],o=t.watch(n,{ignoreInitial:!0,ignored:r,awaitWriteFinish:{stabilityThreshold:1e3,pollInterval:100}}),s=xe("Waiting for changes...");s.spinner="bouncingBar",s.color="green",s.start();let i=null,a=!1,c=!1;async function l(m){if(a){c=!0;return}a=!0,o.unwatch(n);let u=xe(`Change detected: ${m}`).start();try{let p;try{await Ae(e)}catch(f){p=f}if(await Er(e),p)throw p;u.succeed("Docs rebuilt!")}catch(p){let f=p instanceof Error?p.message:String(p);u.fail("Rebuild failed: "+f)}finally{setTimeout(()=>{o.add(n),a=!1,c&&(c=!1,l("queued changes"))},1e3)}}o.on("all",(m,u)=>{a||(i&&clearTimeout(i),i=setTimeout(()=>{l(u)},1e3))}),Se(o),qe()}async function et(){await Ze(),await Qe()}import{basename as Zi,join as xr,resolve as Qi}from"node:path";import ea from"@rollup/plugin-commonjs";import{nodeResolve as ta}from"@rollup/plugin-node-resolve";import{glob as na}from"glob";import{litScss as ra}from"rollup-plugin-scss-lit";import Yi from"node:path";import{glob as Xi}from"glob";function Cr(e){return{name:"watch-globs",buildStart(){let t=Array.isArray(e)?e:[e];for(let n of t)try{for(let r of Xi.sync(Yi.resolve(n)))this.addWatchFile(r)}catch(r){this.error(`Error watching glob pattern "${n}": ${r.message}`)}}}}var Qt={moduleDirectories:["node_modules"],modulePaths:["../../node_modules","../node_modules","node_modules"],watchPatterns:["./apiExamples/**/*","./docs/**/*"]};function Tr(e=[],t={}){let{watchPatterns:n=Qt.watchPatterns,dedupe:r=["lit","lit-element","lit-html"],dev:o=!1}=t,s=[...Qt.modulePaths,...e],i=process.cwd(),a=J.map(c=>Qi(i,c));return[ta({dedupe:r,preferBuiltins:!1,moduleDirectories:Qt.moduleDirectories,modulePaths:a}),ea(),ra({minify:o?!1:{fast:!0},options:{loadPaths:[...s,xr(process.cwd(),"src","styles"),xr(process.cwd(),"src")]}}),Cr(n)]}function en(e={}){let{modulePaths:t=[],watch:n=!1,input:r=["./src/index.js","./src/registered.js"],outputDir:o="./dist",format:s="esm",dev:i=!1}=e;return{name:"Main",config:{input:r,output:{format:s,dir:o,entryFileNames:a=>i||["index","registered"].includes(a.name)?"[name].js":"[name]-[hash].js",chunkFileNames:i?"[name].js":"[name]-[hash].js",assetFileNames:i?"[name][extname]":"[name]-[hash][extname]"},external:oa(),plugins:Tr(t,{dev:i}),watch:Rr(n)}}}function Te(e={}){let{modulePaths:t=[],watch:n=!1,globPattern:r="./demo/*.js",ignorePattern:o=["./demo/*.min.js"],outputDir:s="./demo",dev:i=!1}=e,a=na.sync(r,{ignore:o}),c=Tr(t,{dev:i}),l=Rr(n);return{name:"Demo",configs:a.map(u=>({input:{[Zi(u,".js")]:u},output:{format:"esm",dir:s,entryFileNames:"[name].min.js",chunkFileNames:"[name].min.js",assetFileNames:i?"[name][extname]":"[name]-[hash][extname]",inlineDynamicImports:!0},plugins:c,onwarn(f,d){if(f.code==="UNRESOLVED_IMPORT")throw new Error(`Unresolved import "${f.exporter??f.source}" in ${f.id??u}. Make sure workspace dependencies are built before bundling demos.`);d(f)},watch:l}))}}function Rr(e){if(!e)return!1;let t=typeof e=="object"?e:{};return{clearScreen:t.clearScreen??!0,buildDelay:t.buildDelay??500,chokidar:{ignoreInitial:!0,ignored:t.ignored??["**/dist/**/*.d.ts","**/custom-elements.json","**/demo/*.md","**/demo/**/*.min.js","**/demo/**/*.min.css","**/docs/api.md","**/node_modules/**","**/.git/**"],awaitWriteFinish:t.awaitWriteFinish??{stabilityThreshold:1e3,pollInterval:100}},include:t.include??["./src/**/*.scss","./src/**/*.js","./src/**/*.ts","./demo/**/*.js","./apiExamples/**/*","./docs/**/*.md"],exclude:t.exclude??["./dist/**/*","./node_modules/**/*"]}}function oa(e=[]){return[...[/node_modules\/lit/,/node_modules\/lit-element/,/node_modules\/lit-html/,/node_modules\/@lit/],...e]}function Ir(){let e=Re("./dist"),t=nn("Cleaning dist folder...").start();try{return ia(e,{recursive:!0,force:!0}),t.succeed("All clean! Dist folder wiped."),!0}catch(n){return t.fail(`Oops! Couldn't clean dist/ folder: ${n.message}`),console.error(n),!1}}async function nt(e,t,n,r){let o=nn(e).start();try{let s=await t();return o.succeed(n),s}catch(s){throw o.fail(r),console.error(`Error: ${s.message}`),s}}async function Mr(e,t){return nt(`Bundling ${e.name||"main"} and demo...`,async()=>{let n=await tn(e);await n.write(e.output),await n.close();for(let r of t){let o=await tn(r);await o.write(r.output),await o.close()}},`Bundles ready! ${e.name||"Main"} and demo built.`,"Bundle hiccup! Build failed.")}async function rt(e){let{wcaInput:t,wcaOutput:n,skipDocs:r}=e;if(r){let o=nn("Skipping docs generation...").start();setTimeout(()=>{o.succeed("Docs generation skipped.")},0);return}return nt("Analyzing components and making docs...",async()=>{await et(t,n),await Ae(e),Ke()},"Docs ready! Looking good.","Doc troubles!")}function ma(){let e=process.cwd();function t(o){return[o,`${o}.scss`,`${o}.css`,Re(la(o),`_${ca(o)}.scss`),Re(o,"_index.scss"),Re(o,"index.scss")].find(i=>Pr(i))}function n(o){for(let i of J){let a=t(tt(e,i,o));if(a)return a}let s=r(o);return s||null}function r(o){let s,i;if(o.startsWith("@")){let a=o.split("/");if(a.length<3)return null;s=`${a[0]}/${a[1]}`,i=`./${a.slice(2).join("/")}`}else{let a=o.indexOf("/");if(a===-1)return null;s=o.slice(0,a),i=`./${o.slice(a+1)}`}for(let a of J){let c=tt(e,a,s,"package.json");if(Pr(c))try{let m=JSON.parse(sa(c,"utf-8")).exports;if(!m||typeof m!="object")continue;let u=m[i];if(!u)continue;let p=typeof u=="string"?u:u.default||u.import;if(!p)continue;let f=t(tt(e,a,s,p));if(f)return f}catch{continue}}return null}return{findFileUrl(o){if(o.includes("/node_modules/")){let s=o.lastIndexOf("/node_modules/"),i=o.slice(s+14),a=n(i);if(a)return Dr(a)}if(!o.startsWith(".")&&!o.startsWith("/")&&!o.startsWith("file:")){let s=n(o);if(s)return Dr(s)}return null}}}async function ee(e="./demo"){return nt("Compiling demo SCSS...",async()=>{let t=ua.sync(Re(e,"**/*.scss")),n=ma(),r=process.cwd(),o=J.map(s=>tt(r,s));for(let s of t){let i=Nr.compile(s,{importers:[n],loadPaths:o,silenceDeprecations:["import"],style:"compressed"}),a=s.replace(/\.scss$/,".min.css");aa(a,i.css)}return t.length},"Demo SCSS compiled.","SCSS compilation failed.")}async function Ar(e={}){let{configs:t}=Te(e);return nt("Bundling demo JS...",async()=>{for(let n of t){let r=await tn(n);await r.write(n.output),await r.close()}},"Demo JS bundled.","Demo JS bundling failed.")}import Or from"node:path";import te from"ora";import"rollup";var Pe=!1,pa={analyze:{active:!1,lastTime:0},docs:{active:!1,lastTime:0},scss:{active:!1,lastTime:0}},da=5e3,ot=new Set,fa=["/dist/index.d.ts","/custom-elements.json","/demo/api.md","/docs/api.md","/demo/index.min.js"];function ga(e){if(!e||typeof e!="string")return!1;try{let t=Or.normalize(e);return fa.some(n=>t.endsWith(n))||t.includes("/dist/")||t.endsWith(".min.js")||t.endsWith(".min.css")||t.endsWith(".d.ts")}catch(t){return console.error(`Error checking path (${typeof e}):`,t.message),!1}}async function rn(e,t){let n=pa[e];if(n.active||Date.now()-n.lastTime<da)return!1;try{return n.active=!0,n.lastTime=Date.now(),await t()}catch(r){return console.error(`Error in ${e} task:`,r),!1}finally{n.active=!1}}async function jr(e,t,n,{analyze:r=et,docs:o=rt,scss:s=ee}={}){let i=!0,a={analyze:!1,docs:!1,scss:!1},c=null,l,m=te("Activating watch mode...").start(),u={analyze:async()=>{let{wcaInput:d,wcaOutput:h,skipDocs:g}=t;if(g){let $=te("Skipping component analysis...").start();return setTimeout(()=>{$.succeed("Component analysis skipped.")},0),!0}let b=te("Detective work: analyzing components...").start();try{return await r(d,h),b.succeed("Component analysis complete! API generated."),!0}catch($){return b.fail("Analysis hiccup! Something went wrong."),console.error("Component analysis error:",$),!1}},docs:async()=>{if(Pe)return!1;if(t.skipDocs){let h=te("Skipping docs generation...").start();return setTimeout(()=>{h.succeed("Docs generation skipped.")},0),!0}let d=te("Refreshing docs...").start();try{await o(t),d.succeed("Documentation refreshed!")}catch(h){d.fail("Docs stumble! Couldn't refresh."),console.error("Documentation rebuild error:",h)}return!0},scss:async()=>{if(Pe)return!1;try{return await s(),!0}catch(d){return console.error("Demo SCSS compilation error:",d),!1}}},p=()=>{i&&a.analyze&&a.docs&&a.scss&&typeof n=="function"&&(i=!1,n())};function f(d=1e3){c&&clearTimeout(c),c=setTimeout(async()=>{setTimeout(async()=>{a.analyze=await rn("analyze",u.analyze),setTimeout(async()=>{a.docs=await rn("docs",u.docs),setTimeout(async()=>{a.scss=await rn("scss",u.scss),p()},500)},1e3)},1e3)},d)}e.on("event",async d=>{switch(d.code){case"START":m.succeed("Watch mode active! Eyes peeled.");break;case"BUNDLE_START":if(ot.clear(),d.input)try{let h=Array.isArray(d.input)?d.input:typeof d.input=="string"?[d.input]:typeof d.input=="object"&&d.input!==null?Object.values(d.input):[];for(let g of h)typeof g=="string"&&!ga(g)&&ot.add(Or.normalize(g))}catch(h){console.error("Error processing input paths:",h)}l=te("Weaving bundles...").start(),Pe=!0;break;case"BUNDLE_END":l&&l.succeed(`Bundle ${Array.isArray(d.input)?`of ${d.input.join("& ")} `:""}done in ${d.duration}ms! \u{1F680}`),Pe=!1,ot.size>0&&f();break;case"END":break;case"ERROR":Pe=!1,l?l.fail(`Oops! Bundle hit a snag: ${d.error.message}`):te().fail(`Watch mode hiccup: ${d.error.message}`),ot.clear();break}})}function _r(e,t){return Se(e),t&&Se(t),qe(),e}async function ba(e){let t=en(e),n=Te(e);e.dev||t.config.plugins.push(ha()),await rt(e),await ee(),await Mr(t.config,n.configs)}async function wa(e){let{dev:t}=e,n=en({...e,watch:!0}),r=Te({...e,watch:!0}),o=ya([n.config,...r.configs]);jr(o,e,t?async()=>Xe(e):void 0);let s=await import("chokidar"),i=!1,a=!1,c=null,l=s.watch("./demo/**/*.scss",{ignoreInitial:!0,ignored:["**/demo/**/*.min.css"],awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}});return l.on("all",()=>{c&&clearTimeout(c),c=setTimeout(async()=>{if(i){a=!0;return}i=!0;try{await ee()}catch(m){console.error("Demo SCSS watch compilation error:",m)}finally{i=!1,a&&(a=!1,l.emit("all"))}},500)}),_r(o,l),o}async function st(e={}){try{let{watch:t}=e;return Ir(),t?await wa(e):await ba(e)}catch(t){throw new Error(`Build failed: ${t.message}`)}}var De=va.command("dev").description("Runs development server for auro components");De=He(De);De=Je(De);var Zd=De.action(async e=>{try{let t=Fr("Initializing...");e.watch?(t.text="Waiting for changes...",t.spinner="bouncingBar",t.color="green"):t.text=e.docs===!1?"Building component (docs disabled)":"Building component",t.start(),e.watch||t.succeed("Build completed!"),await st({...e,dev:!0,watch:e.watch})}catch(t){Fr().fail(`Build failed: ${t.message}`),console.error(t),process.exit(1)}});import{program as ka}from"commander";import Lr from"ora";var on=ka.command("build").description("Builds auro components");on=He(on);var of=on.action(async e=>{try{let t=Lr("Initializing...");e.watch?(t.text="Waiting for changes...",t.spinner="bouncingBar",t.color="green"):t.text=e.docs===!1?"Building component (docs disabled)":"Building component",t.start(),await st(e),e.watch||t.succeed("Build completed!")}catch(t){Lr().fail(`Build failed: ${t.message}`),console.error(t),process.exit(1)}});import{exec as Ea}from"node:child_process";import Br from"node:path";import $a from"node:process";import{fileURLToPath as Sa}from"node:url";import Aa from"node:util";import{program as Ca}from"commander";import xa from"inquirer";var gf=Ca.command("migrate").description("Script runner to perform repetitive code change tasks").requiredOption("-i, --id <string>","Select the migration you would like to run by id").option("-m, --multi-gitter","Run the migration on all repositories in the multi-gitter config").action(async e=>{let t=Sa(import.meta.url),n=Br.dirname(t),r=Br.resolve(n,"migrations",e.id);if(e.multiGitter){let o=Aa.promisify(Ea);try{await o("command -v multi-gitter")}catch{console.error("multi-gitter is not installed."),$a.exit(1)}(await xa.prompt([{type:"confirm",name:"dryRun",message:"Run migration in dry-run mode? (no changes will be committed)",default:!0}])).dryRun?_(`multi-gitter run ${r}/script.sh --config "${r}/multi-gitter.yml" --dry-run`):_(`multi-gitter run ${r}/script.sh --config "${r}/multi-gitter.yml"`)}else _(`${r}/script.sh`)});import Jr from"node:process";import{program as Na}from"commander";import{readFile as Ia,writeFile as Ma}from"node:fs/promises";import{Logger as Ne}from"@aurodesignsystem/auro-library/scripts/utils/logger.mjs";import sn from"node:fs/promises";import an from"node:path";import{Octokit as Ta}from"@octokit/rest";import L from"ora";import{processContentForFile as Ra,templateFiller as Pa}from"@aurodesignsystem/auro-library/scripts/utils/sharedFileProcessorUtils.mjs";async function Gr(e,t){let n=new Ta({auth:process.env.GITHUB_TOKEN||""});try{let o=(await n.request("GET /repos/{owner}/{repo}/contents/{path}",{ref:t,owner:"AlaskaAirlines",repo:"auro-templates",path:e,headers:{"X-GitHub-Api-Version":"2022-11-28"}})).data;if(typeof o!="object"||!Array.isArray(o)){let s=`Unexpected response format: ${JSON.stringify(o)}`;throw L().start().fail(s),new Error("Failed to retrieve folder items")}return o}catch(r){let o=L().start();throw r.status===404?o.fail(`Template '${e.split("/")[1]}' not found`):o.fail(`Error accessing template: ${r.message}`),r}}async function Ur({folderItems:e,templatePathToReplace:t,rootDir:n,ref:r}){let o=[];for(let s of e){if(s.type=="dir"){let l=L(`Processing directory: ${s.path}`).start(),m=await Gr(s.path,r);l.succeed(`Found ${m.length} additional items in ${s.path}`);let u=await Ur({folderItems:m,templatePathToReplace:t,rootDir:n,ref:r});o.push(...u);continue}let i=s.path.replace(`${t}/`,""),a=`${n}/.github/${i}`,c={identifier:s.name,input:{remoteUrl:s.download_url||"",fileName:a,overwrite:!0},output:a};o.push(c)}return o}async function Da(e){try{await sn.rm(e,{recursive:!0,force:!0}),L().start().succeed(`Successfully removed directory: ${e}`)}catch(t){throw L().start().fail(`Error removing directory ${e}: ${t.message}`),t}}async function Wr(e,t="",n=!0){try{let r=await sn.stat(e),o=an.basename(e);if(!r.isDirectory())return`${t}${n?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${o}
|
|
14
|
+
`)}`)}var Xi=["name","Name","namespace","Namespace","Version","dtVersion","wcssVersion","monorepoName"],Zi=["capitalize","withAuroNamespace","packageName"],Qi=/^~?(?:[#/^!>&{*]|\s*else\b)/,Rr=/<pre\b[\s\S]*?<\/pre>|<code\b[\s\S]*?<\/code>|^[ \t]*(`{3,}|~{3,})[^\n]*\n[\s\S]*?^[ \t]*\1[ \t]*$|`[^`\n]*`/gim;function ea(e,t,n){if(Qi.test(e))return!n;let[r,...o]=e.replace(/^~?\s*|\s*~?$/g,"").split(/\s+/);return Zi.includes(r)?o.every(s=>t.has(s)||/^(["']).*\1$/.test(s)):o.length===0&&t.has(r)}function Pr(e,t={}){let n=new Set([...Xi,...Object.keys(t)]),r=(i,a)=>i.replace(/(?<![\\{])\{\{([\s\S]*?)\}\}/g,(c,l)=>ea(l,n,a)?c:`\\${c}`),o="",s=0;for(let i of e.matchAll(Rr))o+=r(e.slice(s,i.index),!1)+r(i[0],!0),s=i.index+i[0].length;return o+r(e.slice(s),!1)}function Ar(e,t){return tn.replaceTemplateValues(Pr(e,t),t)}function ta(e){return e.replace(Rr,"").match(/\{\{[\s\S]*?\}\}/g)??[]}async function na(e,t={}){let n=W.dirname(e),r=await F.promises.readFile(e,"utf8"),o=/^[ \t]*<!-- AURO-GENERATED-CONTENT:START \((FILE|CODE):src=([^)]+)\) -->\n[ \t]*<!-- AURO-GENERATED-CONTENT:END -->/gm,s,i=!1,a=N("demo"),c=[];for(;(s=o.exec(r))!==null;){let[d,f,g]=s,h=W.resolve(n,g),b=W.resolve(a,g),v=en(h)?h:en(b)?b:null;if(v){let j=nn(v,"utf8"),A;if(f==="FILE")A=`<!-- AURO-GENERATED-CONTENT:START (FILE:src=${g}) -->
|
|
15
|
+
<!-- The below content is automatically added from ${g} -->
|
|
16
|
+
${Ar(j,t).trimEnd()}
|
|
17
|
+
<!-- AURO-GENERATED-CONTENT:END -->`;else{let k=W.extname(g).slice(1)||"html",y=j.trimEnd().replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">"),w=Ar(`<pre class="language-${k}"><code class="language-${k}">${y}
|
|
18
|
+
</code></pre>`,t);A=`<!-- AURO-GENERATED-CONTENT:START (CODE:src=${g}) -->
|
|
19
|
+
<!-- The below code snippet is automatically added from ${g} -->
|
|
20
|
+
${w}
|
|
21
|
+
<!-- AURO-GENERATED-CONTENT:END -->`}r=r.replace(d,()=>A),o.lastIndex=0,i=!0}else c.includes(g)||c.push(g)}if(c.length>0)throw new Error(`Included file(s) not found: ${c.join(", ")}`);i&&await F.promises.writeFile(e,r),r=await F.promises.readFile(e,"utf8");let l=/^[ \t]*```(\w*)\n([\s\S]*?)^[ \t]*```[ \t]*$/gm,m=r.replace(l,(d,f,g)=>{let h=f||"html",b=g.trimEnd().replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">");return`<pre class="language-${h}"><code class="language-${h}">${b}
|
|
22
|
+
</code></pre>`});m!==r&&await F.promises.writeFile(e,m),r=await F.promises.readFile(e,"utf8"),r=r.replace(/(<pre[^>]*><code[^>]*>)([\s\S]*?)(<\/code><\/pre>)/g,(d,f,g,h)=>{let b=g.split(/\r?\n/),v=b.filter(y=>y.trim().length>0);if(v.length===0)return d;let j=Math.min(...v.map(y=>{let w=y.match(/^[ \t]*/);return w?w[0].length:0})),A=b.map(y=>j>0?y.substring(j):y);for(;A.length>0&&A[A.length-1].trim()==="";)A.pop();let k=A.map((y,w)=>w===A.length-1?y:`${y}${y.trim()===""?" ":`
|
|
23
|
+
`}`).join("");return f+k+h});let u=r.split(`
|
|
24
|
+
`),p=!1;for(let d=0;d<u.length;d++)/<pre[\s>]/i.test(u[d])&&(p=!0),p||(u[d]=u[d].replace(/^[ \t]+(?=<)/,"")),/<\/pre>/i.test(u[d])&&(p=!1);await F.promises.writeFile(e,u.join(`
|
|
25
|
+
`))}async function Te(e={}){let t=e.readmeTemplate,n=t&&!t.startsWith("http");await Yi({...Tr,...n?{localReadmePath:W.resolve(process.cwd(),t)}:{remoteReadmeUrl:t||"https://raw.githubusercontent.com/AlaskaAirlines/auro-templates/main/templates/default/README.md"}},e.skipReadme)}function xr(e){return F.existsSync(N(e))}import{existsSync as Dr,readFileSync as ra}from"node:fs";import{builtinModules as oa}from"node:module";import{resolve as Ze}from"node:path";import{startDevServer as sa}from"@web/dev-server";import{hmrPlugin as ia}from"@web/dev-server-hmr";import*as Mr from"esbuild";import aa from"ora";var z=["node_modules","../node_modules","../../node_modules","../../../node_modules"];var ca=/^\/__wds-outside-root__\/(\d+)\/(.+)$/;function la(){return{name:"node-modules-css",serve(e){if(!e.path.endsWith(".css")||!e.path.startsWith("/@")&&!/^\/[a-z]/i.test(e.path))return;let t=e.path.slice(1),n=process.cwd();for(let r of z){let o=Ze(n,r,t);if(Dr(o))return{body:ra(o,"utf-8"),type:"css"}}}}}function ua(e,t){let n=e.match(ca);return n?Ze(t,"../".repeat(Number.parseInt(n[1],10)),n[2]):Ze(t,`.${e}`)}function ma(){let e=/\b(require\s*\(|module\.exports\b|exports\.\w)/,t=new Map,n;return{name:"cjs-to-esm",async serverStart({config:r}){n=Ze(r.rootDir)},async transform(r){if(!r.path.includes("node_modules")||!r.path.endsWith(".js")&&!r.path.endsWith(".cjs")||typeof r.body!="string"||!e.test(r.body))return;let o=ua(r.path,n);if(t.has(o))return t.get(o);if(Dr(o))try{let i={body:(await Mr.build({entryPoints:[o],bundle:!0,format:"esm",platform:"browser",write:!1,logLevel:"silent",external:oa})).outputFiles[0].text};return t.set(o,i),i}catch(s){console.error(`CJS-to-ESM bundling failed for ${r.path}:`,s.message)}}}}var Re={watch:!0,nodeResolve:!0,basePath:"/",rootDir:"./demo",hmrInclude:["src/**/*","demo/**/*","apiExamples/**/*","docs/**/*"]};async function Qe(e={}){if(!e.serve)return;let t=aa(`Firing up dev server...
|
|
26
|
+
`).start();try{let n={port:Number(e.port)||void 0,open:e.open?"/":void 0,watch:e.watch??Re.watch,nodeResolve:e.nodeResolve??Re.nodeResolve,basePath:e.basePath??Re.basePath,rootDir:e.rootDir??Re.rootDir,middleware:[function(s,i){return!s.url.endsWith("/")&&!s.url.includes(".")&&(s.url+=".html"),i()}],plugins:[la(),ma(),ia({include:e.hmrInclude??Re.hmrInclude})]},r=await sa({config:n,readCliArgs:!1,readFileConfig:!1});return t.stop(),r}catch(n){throw t.fail("Server snag! Couldn't start dev server."),console.error("Error starting development server:",n),new Error(`Development server failed to start: ${n.message}`)}}async function et(){let e=Pe("Generating Custom Elements Manifest...").start();try{await _(`npx --package=@custom-elements-manifest/analyzer -y -- cem analyze --config '${$r("custom-elements-manifest.config.mjs")}'`),e.succeed("Custom Elements Manifest generated successfully!")}catch(t){let n=t instanceof Error?t.message:String(t);e.warn("CEM analyzer completed with warnings: "+n)}}async function tt(){let e=Pe("Generating API md file...").start();try{await Ae.generate(),e.succeed("API md file generated successfully!")}catch(t){let n=t instanceof Error?t.message:String(t);throw e.fail("Failed to generate API md file: "+n),t}}async function Nr(e={},{build:t=Te,demo:n=Ir}={}){let r=Pe("Compiling documentation...").start(),o;try{await t(e),r.succeed("Documentation compiled successfully!")}catch(s){let i=s instanceof Error?s.message:String(s);r.fail("Failed to compile MD documentation: "+i),o=s}if(await n(e),o)throw o}async function Ir(e={}){Ye(),await re(),await _r(e)}async function Or(e={}){await Qe(e)}async function jr(e={}){let t=await import("chokidar"),n=["./src/**/*","./docs/**/*","./docTemplates/**/*","./apiExamples/**/*","./demo/**/*.scss"],r=["**/demo/*.min.js","**/demo/*.min.css","**/demo/*.md","**/demo/readme.md","**/docs/api.md","**/custom-elements.json","**/node_modules/**","**/dist/**","**/.git/**"],o=t.watch(n,{ignoreInitial:!0,ignored:r,awaitWriteFinish:{stabilityThreshold:1e3,pollInterval:100}}),s=Pe("Waiting for changes...");s.spinner="bouncingBar",s.color="green",s.start();let i=null,a=!1,c=!1;async function l(m){if(a){c=!0;return}a=!0,o.unwatch(n);let u=Pe(`Change detected: ${m}`).start();try{let p;try{await Te(e)}catch(d){p=d}if(await Ir(e),p)throw p;u.succeed("Docs rebuilt!")}catch(p){let d=p instanceof Error?p.message:String(p);u.fail("Rebuild failed: "+d)}finally{setTimeout(()=>{o.add(n),a=!1,c&&(c=!1,l("queued changes"))},1e3)}}o.on("all",(m,u)=>{a||(i&&clearTimeout(i),i=setTimeout(()=>{l(u)},1e3))}),xe(o),Xe()}async function nt(){await et(),await tt()}import{basename as fa,join as Lr,resolve as ga}from"node:path";import ha from"@rollup/plugin-commonjs";import{nodeResolve as ya}from"@rollup/plugin-node-resolve";import{glob as ba}from"glob";import{litScss as wa}from"rollup-plugin-scss-lit";import pa from"node:path";import{glob as da}from"glob";function Fr(e){return{name:"watch-globs",buildStart(){let t=Array.isArray(e)?e:[e];for(let n of t)try{for(let r of da.sync(pa.resolve(n)))this.addWatchFile(r)}catch(r){this.error(`Error watching glob pattern "${n}": ${r.message}`)}}}}var rn={moduleDirectories:["node_modules"],modulePaths:["../../node_modules","../node_modules","node_modules"],watchPatterns:["./apiExamples/**/*","./docs/**/*"]};function Gr(e=[],t={}){let{watchPatterns:n=rn.watchPatterns,dedupe:r=["lit","lit-element","lit-html"],dev:o=!1}=t,s=[...rn.modulePaths,...e],i=process.cwd(),a=z.map(c=>ga(i,c));return[ya({dedupe:r,preferBuiltins:!1,moduleDirectories:rn.moduleDirectories,modulePaths:a}),ha(),wa({minify:o?!1:{fast:!0},options:{loadPaths:[...s,Lr(process.cwd(),"src","styles"),Lr(process.cwd(),"src")]}}),Fr(n)]}function on(e={}){let{modulePaths:t=[],watch:n=!1,input:r=["./src/index.js","./src/registered.js"],outputDir:o="./dist",format:s="esm",dev:i=!1}=e;return{name:"Main",config:{input:r,output:{format:s,dir:o,entryFileNames:a=>i||["index","registered"].includes(a.name)?"[name].js":"[name]-[hash].js",chunkFileNames:i?"[name].js":"[name]-[hash].js",assetFileNames:i?"[name][extname]":"[name]-[hash][extname]"},external:va(),plugins:Gr(t,{dev:i}),watch:Br(n)}}}function De(e={}){let{modulePaths:t=[],watch:n=!1,globPattern:r="./demo/*.js",ignorePattern:o=["./demo/*.min.js"],outputDir:s="./demo",dev:i=!1}=e,a=ba.sync(r,{ignore:o}),c=Gr(t,{dev:i}),l=Br(n);return{name:"Demo",configs:a.map(u=>({input:{[fa(u,".js")]:u},output:{format:"esm",dir:s,entryFileNames:"[name].min.js",chunkFileNames:"[name].min.js",assetFileNames:i?"[name][extname]":"[name]-[hash][extname]",inlineDynamicImports:!0},plugins:c,onwarn(d,f){if(d.code==="UNRESOLVED_IMPORT")throw new Error(`Unresolved import "${d.exporter??d.source}" in ${d.id??u}. Make sure workspace dependencies are built before bundling demos.`);f(d)},watch:l}))}}function Br(e){if(!e)return!1;let t=typeof e=="object"?e:{};return{clearScreen:t.clearScreen??!0,buildDelay:t.buildDelay??500,chokidar:{ignoreInitial:!0,ignored:t.ignored??["**/dist/**/*.d.ts","**/custom-elements.json","**/demo/*.md","**/demo/**/*.min.js","**/demo/**/*.min.css","**/docs/api.md","**/node_modules/**","**/.git/**"],awaitWriteFinish:t.awaitWriteFinish??{stabilityThreshold:1e3,pollInterval:100}},include:t.include??["./src/**/*.scss","./src/**/*.js","./src/**/*.ts","./demo/**/*.js","./apiExamples/**/*","./docs/**/*.md"],exclude:t.exclude??["./dist/**/*","./node_modules/**/*"]}}function va(e=[]){return[...[/node_modules\/lit/,/node_modules\/lit-element/,/node_modules\/lit-html/,/node_modules\/@lit/],...e]}function Jr(){let e=Me("./dist"),t=an("Cleaning dist folder...").start();try{return $a(e,{recursive:!0,force:!0}),t.succeed("All clean! Dist folder wiped."),!0}catch(n){return t.fail(`Oops! Couldn't clean dist/ folder: ${n.message}`),console.error(n),!1}}async function ot(e,t,n,r){let o=an(e).start();try{let s=await t();return o.succeed(n),s}catch(s){throw o.fail(r),console.error(`Error: ${s.message}`),s}}async function zr(e,t){return ot(`Bundling ${e.name||"main"} and demo...`,async()=>{let n=await sn(e);await n.write(e.output),await n.close();for(let r of t){let o=await sn(r);await o.write(r.output),await o.close()}},`Bundles ready! ${e.name||"Main"} and demo built.`,"Bundle hiccup! Build failed.")}async function st(e){let{wcaInput:t,wcaOutput:n,skipDocs:r}=e;if(r){let o=an("Skipping docs generation...").start();setTimeout(()=>{o.succeed("Docs generation skipped.")},0);return}return ot("Analyzing components and making docs...",async()=>{await nt(t,n),await Te(e),Ye()},"Docs ready! Looking good.","Doc troubles!")}function xa(){let e=process.cwd();function t(o){return[o,`${o}.scss`,`${o}.css`,Me(Ca(o),`_${Sa(o)}.scss`),Me(o,"_index.scss"),Me(o,"index.scss")].find(i=>Wr(i))}function n(o){for(let i of z){let a=t(rt(e,i,o));if(a)return a}let s=r(o);return s||null}function r(o){let s,i;if(o.startsWith("@")){let a=o.split("/");if(a.length<3)return null;s=`${a[0]}/${a[1]}`,i=`./${a.slice(2).join("/")}`}else{let a=o.indexOf("/");if(a===-1)return null;s=o.slice(0,a),i=`./${o.slice(a+1)}`}for(let a of z){let c=rt(e,a,s,"package.json");if(Wr(c))try{let m=JSON.parse(ka(c,"utf-8")).exports;if(!m||typeof m!="object")continue;let u=m[i];if(!u)continue;let p=typeof u=="string"?u:u.default||u.import;if(!p)continue;let d=t(rt(e,a,s,p));if(d)return d}catch{continue}}return null}return{findFileUrl(o){if(o.includes("/node_modules/")){let s=o.lastIndexOf("/node_modules/"),i=o.slice(s+14),a=n(i);if(a)return Ur(a)}if(!o.startsWith(".")&&!o.startsWith("/")&&!o.startsWith("file:")){let s=n(o);if(s)return Ur(s)}return null}}}async function re(e="./demo"){return ot("Compiling demo SCSS...",async()=>{let t=Aa.sync(Me(e,"**/*.scss")),n=xa(),r=process.cwd(),o=z.map(s=>rt(r,s));for(let s of t){let i=Hr.compile(s,{importers:[n],loadPaths:o,silenceDeprecations:["import"],style:"compressed"}),a=s.replace(/\.scss$/,".min.css");Ea(a,i.css)}return t.length},"Demo SCSS compiled.","SCSS compilation failed.")}async function _r(e={}){let{configs:t}=De(e);return ot("Bundling demo JS...",async()=>{for(let n of t){let r=await sn(n);await r.write(n.output),await r.close()}},"Demo JS bundled.","Demo JS bundling failed.")}import Vr from"node:path";import oe from"ora";import"rollup";var Ne=!1,Ta={analyze:{active:!1,lastTime:0},docs:{active:!1,lastTime:0},scss:{active:!1,lastTime:0}},Ra=5e3,it=new Set,Pa=["/dist/index.d.ts","/custom-elements.json","/demo/api.md","/docs/api.md","/demo/index.min.js"];function Da(e){if(!e||typeof e!="string")return!1;try{let t=Vr.normalize(e);return Pa.some(n=>t.endsWith(n))||t.includes("/dist/")||t.endsWith(".min.js")||t.endsWith(".min.css")||t.endsWith(".d.ts")}catch(t){return console.error(`Error checking path (${typeof e}):`,t.message),!1}}async function cn(e,t){let n=Ta[e];if(n.active||Date.now()-n.lastTime<Ra)return!1;try{return n.active=!0,n.lastTime=Date.now(),await t()}catch(r){return console.error(`Error in ${e} task:`,r),!1}finally{n.active=!1}}async function Kr(e,t,n,{analyze:r=nt,docs:o=st,scss:s=re}={}){let i=!0,a={analyze:!1,docs:!1,scss:!1},c=null,l,m=oe("Activating watch mode...").start(),u={analyze:async()=>{let{wcaInput:f,wcaOutput:g,skipDocs:h}=t;if(h){let v=oe("Skipping component analysis...").start();return setTimeout(()=>{v.succeed("Component analysis skipped.")},0),!0}let b=oe("Detective work: analyzing components...").start();try{return await r(f,g),b.succeed("Component analysis complete! API generated."),!0}catch(v){return b.fail("Analysis hiccup! Something went wrong."),console.error("Component analysis error:",v),!1}},docs:async()=>{if(Ne)return!1;if(t.skipDocs){let g=oe("Skipping docs generation...").start();return setTimeout(()=>{g.succeed("Docs generation skipped.")},0),!0}let f=oe("Refreshing docs...").start();try{await o(t),f.succeed("Documentation refreshed!")}catch(g){f.fail("Docs stumble! Couldn't refresh."),console.error("Documentation rebuild error:",g)}return!0},scss:async()=>{if(Ne)return!1;try{return await s(),!0}catch(f){return console.error("Demo SCSS compilation error:",f),!1}}},p=()=>{i&&a.analyze&&a.docs&&a.scss&&typeof n=="function"&&(i=!1,n())};function d(f=1e3){c&&clearTimeout(c),c=setTimeout(async()=>{setTimeout(async()=>{a.analyze=await cn("analyze",u.analyze),setTimeout(async()=>{a.docs=await cn("docs",u.docs),setTimeout(async()=>{a.scss=await cn("scss",u.scss),p()},500)},1e3)},1e3)},f)}e.on("event",async f=>{switch(f.code){case"START":m.succeed("Watch mode active! Eyes peeled.");break;case"BUNDLE_START":if(it.clear(),f.input)try{let g=Array.isArray(f.input)?f.input:typeof f.input=="string"?[f.input]:typeof f.input=="object"&&f.input!==null?Object.values(f.input):[];for(let h of g)typeof h=="string"&&!Da(h)&&it.add(Vr.normalize(h))}catch(g){console.error("Error processing input paths:",g)}l=oe("Weaving bundles...").start(),Ne=!0;break;case"BUNDLE_END":l&&l.succeed(`Bundle ${Array.isArray(f.input)?`of ${f.input.join("& ")} `:""}done in ${f.duration}ms! \u{1F680}`),Ne=!1,it.size>0&&d();break;case"END":break;case"ERROR":Ne=!1,l?l.fail(`Oops! Bundle hit a snag: ${f.error.message}`):oe().fail(`Watch mode hiccup: ${f.error.message}`),it.clear();break}})}function qr(e,t){return xe(e),t&&xe(t),Xe(),e}async function Ia(e){let t=on(e),n=De(e);e.dev||t.config.plugins.push(Ma()),await st(e),await re(),await zr(t.config,n.configs)}async function Oa(e){let{dev:t}=e,n=on({...e,watch:!0}),r=De({...e,watch:!0}),o=Na([n.config,...r.configs]);Kr(o,e,t?async()=>Qe(e):void 0);let s=await import("chokidar"),i=!1,a=!1,c=null,l=s.watch("./demo/**/*.scss",{ignoreInitial:!0,ignored:["**/demo/**/*.min.css"],awaitWriteFinish:{stabilityThreshold:500,pollInterval:100}});return l.on("all",()=>{c&&clearTimeout(c),c=setTimeout(async()=>{if(i){a=!0;return}i=!0;try{await re()}catch(m){console.error("Demo SCSS watch compilation error:",m)}finally{i=!1,a&&(a=!1,l.emit("all"))}},500)}),qr(o,l),o}async function at(e={}){try{let{watch:t}=e;return Jr(),t?await Oa(e):await Ia(e)}catch(t){throw new Error(`Build failed: ${t.message}`)}}var Ie=ja.command("dev").description("Runs development server for auro components");Ie=ze(Ie);Ie=Ve(Ie);var Of=Ie.action(async e=>{try{let t=Yr("Initializing...");e.watch?(t.text="Waiting for changes...",t.spinner="bouncingBar",t.color="green"):t.text=e.docs===!1?"Building component (docs disabled)":"Building component",t.start(),e.watch||t.succeed("Build completed!"),await at({...e,dev:!0,watch:e.watch})}catch(t){Yr().fail(`Build failed: ${t.message}`),console.error(t),process.exit(1)}});import{program as _a}from"commander";import Xr from"ora";var ln=_a.command("build").description("Builds auro components");ln=ze(ln);var Bf=ln.action(async e=>{try{let t=Xr("Initializing...");e.watch?(t.text="Waiting for changes...",t.spinner="bouncingBar",t.color="green"):t.text=e.docs===!1?"Building component (docs disabled)":"Building component",t.start(),await at(e),e.watch||t.succeed("Build completed!")}catch(t){Xr().fail(`Build failed: ${t.message}`),console.error(t),process.exit(1)}});import{exec as Fa}from"node:child_process";import Zr from"node:path";import La from"node:process";import{fileURLToPath as Ga}from"node:url";import Ba from"node:util";import{program as Wa}from"commander";import Ua from"inquirer";var Xf=Wa.command("migrate").description("Script runner to perform repetitive code change tasks").requiredOption("-i, --id <string>","Select the migration you would like to run by id").option("-m, --multi-gitter","Run the migration on all repositories in the multi-gitter config").action(async e=>{let t=Ga(import.meta.url),n=Zr.dirname(t),r=Zr.resolve(n,"migrations",e.id);if(e.multiGitter){let o=Ba.promisify(Fa);try{await o("command -v multi-gitter")}catch{console.error("multi-gitter is not installed."),La.exit(1)}(await Ua.prompt([{type:"confirm",name:"dryRun",message:"Run migration in dry-run mode? (no changes will be committed)",default:!0}])).dryRun?_(`multi-gitter run ${r}/script.sh --config "${r}/multi-gitter.yml" --dry-run`):_(`multi-gitter run ${r}/script.sh --config "${r}/multi-gitter.yml"`)}else _(`${r}/script.sh`)});import ro from"node:process";import{program as Ka}from"commander";import{readFile as qa,writeFile as Ya}from"node:fs/promises";import{Logger as Oe}from"@aurodesignsystem/auro-library/scripts/utils/logger.mjs";import un from"node:fs/promises";import mn from"node:path";import{Octokit as Ha}from"@octokit/rest";import L from"ora";import{processContentForFile as Ja,templateFiller as za}from"@aurodesignsystem/auro-library/scripts/utils/sharedFileProcessorUtils.mjs";async function Qr(e,t){let n=new Ha({auth:process.env.GITHUB_TOKEN||""});try{let o=(await n.request("GET /repos/{owner}/{repo}/contents/{path}",{ref:t,owner:"AlaskaAirlines",repo:"auro-templates",path:e,headers:{"X-GitHub-Api-Version":"2022-11-28"}})).data;if(typeof o!="object"||!Array.isArray(o)){let s=`Unexpected response format: ${JSON.stringify(o)}`;throw L().start().fail(s),new Error("Failed to retrieve folder items")}return o}catch(r){let o=L().start();throw r.status===404?o.fail(`Template '${e.split("/")[1]}' not found`):o.fail(`Error accessing template: ${r.message}`),r}}async function eo({folderItems:e,templatePathToReplace:t,rootDir:n,ref:r}){let o=[];for(let s of e){if(s.type=="dir"){let l=L(`Processing directory: ${s.path}`).start(),m=await Qr(s.path,r);l.succeed(`Found ${m.length} additional items in ${s.path}`);let u=await eo({folderItems:m,templatePathToReplace:t,rootDir:n,ref:r});o.push(...u);continue}let i=s.path.replace(`${t}/`,""),a=`${n}/.github/${i}`,c={identifier:s.name,input:{remoteUrl:s.download_url||"",fileName:a,overwrite:!0},output:a};o.push(c)}return o}async function Va(e){try{await un.rm(e,{recursive:!0,force:!0}),L().start().succeed(`Successfully removed directory: ${e}`)}catch(t){throw L().start().fail(`Error removing directory ${e}: ${t.message}`),t}}async function to(e,t="",n=!0){try{let r=await un.stat(e),o=mn.basename(e);if(!r.isDirectory())return`${t}${n?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${o}
|
|
27
27
|
`;let s=`${t}${n?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}${o}/
|
|
28
|
-
`;try{let a=(await
|
|
28
|
+
`;try{let a=(await un.readdir(e)).sort();for(let c=0;c<a.length;c++){let l=a[c],m=mn.join(e,l),u=c===a.length-1,p=t+(n?" ":"\u2502 ");s+=await to(m,p,u)}}catch{s+=`${t}${n?" ":"\u2502 "}\u2514\u2500\u2500 [Permission denied or error reading directory]
|
|
29
29
|
`}return s}catch(r){return`${t}${n?"\u2514\u2500\u2500 ":"\u251C\u2500\u2500 "}[Error: ${r}]
|
|
30
|
-
`}}async function
|
|
30
|
+
`}}async function no(e,t="main",n="default"){if(!e)throw L().start().fail("Root directory must be specified"),new Error("Root directory must be specified");if(await za.extractNames(),!process.env.GITHUB_TOKEN)throw L().start().fail("GITHUB_TOKEN environment variable is not set."),new Error("GITHUB_TOKEN environment variable is not set");let r=`templates/${n}/.github`,o=await Qr(r,t),s=".github",i=L("Removing existing .github directory...").start();try{await Va(s),i.succeed(".github directory removed successfully")}catch(l){throw i.fail(`Error removing .github directory: ${l.message}`),new Error(`Failed to remove .github directory: ${l.message}`)}let a=await eo({folderItems:o,templatePathToReplace:r,rootDir:e,ref:t}),c=L("Processing all files...").start();try{await Promise.all(a.map(m=>Ja(m))),c.succeed("All files processed.");let l=L("Generating directory tree...").start();try{let m=mn.join(e,".github"),u=await to(m);l.succeed("Synced .github directory structure:"),console.log(u)}catch(m){l.fail(`Error generating directory tree: ${m.message}`)}}catch(l){throw c.fail(`Error processing files: ${l.message}`),new Error(`Failed to process files: ${l.message}`)}}var ug=Ka.command("sync").option("-r, --ref <branch/tag/commit>","Git reference (branch/tag/commit) to use","main").option("-t, --template <name>","Template based on which to sync","default").description("Script runner to synchronize local repository configuration files").action(async e=>{Oe.info("Synchronizing repository configuration files..."),Oe.warn("Note: sync does not create a new git branch. Changes are added to the current branch.");let t=ro.cwd();try{await no(t,e.ref,e.template);try{let n=`${t}/.github/CODEOWNERS`,o=(await qa(n,{encoding:"utf-8"})).replace(/\r\n/gu,`
|
|
31
31
|
`).replace(/\n\n/gu,`
|
|
32
|
-
`);await
|
|
32
|
+
`);await Ya(n,o,{encoding:"utf-8"}),(o.includes("\r")||o.includes(`
|
|
33
33
|
|
|
34
|
-
`))&&
|
|
34
|
+
`))&&Oe.error("CODEOWNERS file still has Windows line endings.")}catch(n){throw Oe.error(`Error processing CODEOWNERS file: ${n.message}`),n}}catch(n){Oe.error(`Sync operation failed: ${n.message}`),ro.exit(1)}});import ct from"node:fs";import je from"node:path";import{Logger as so}from"@aurodesignsystem/auro-library/scripts/utils/logger.mjs";import{program as Xa}from"commander";import{glob as Za}from"glob";var oo=(e,t)=>{let n=(e.match(/static register\(name \= (.+)\)/)||e.match(/customElements.get\((.+?)\)/))[1],r=e.match(/export class (.+) extends/)?.[1],o=e.match(/\/\*\*((.|\n)*?)(\*\n|\*\/|[@])/)?.[1]||"";return!n||!r?e:`
|
|
35
35
|
import { ${r} } from '${t}';
|
|
36
36
|
|
|
37
37
|
/**${o}*/
|
|
@@ -40,33 +40,33 @@ class ${r}WCA extends ${r} {}
|
|
|
40
40
|
if (!customElements.get(${n})) {
|
|
41
41
|
customElements.define(${n}, ${r}WCA);
|
|
42
42
|
}
|
|
43
|
-
`};var
|
|
43
|
+
`};var lt=je.resolve(process.cwd(),"./scripts/wca");async function Qa(e){try{return(await Promise.all(e.map(n=>Za(n)))).flat()}catch(t){throw console.error("Error processing glob patterns:",t),t}}async function ec(e){ct.existsSync(lt)||await ct.promises.mkdir(lt,{recursive:!0});for(let t of e){let n=je.resolve(process.cwd(),t),r=await ct.promises.readFile(n,"utf-8"),o=je.resolve(lt,`${je.basename(t)}`),s=oo(r,je.relative(lt,t));await ct.promises.writeFile(o,s)}}async function tc(){let e=await Qa(["./src/auro-*.js"]);await ec(e)}var wg=Xa.command("wca-setup").description("Set up WCA (Web Component Analyzer) for the project").action(()=>{tc().then(()=>{so.success("WCA setup completed successfully.")}).catch(e=>{so.error(`WCA setup failed: ${e.message}`)})});import{program as mc}from"commander";import lo from"chalk";import uo from"ora";import{appendFile as nc,readFile as rc}from"node:fs/promises";import{Logger as $}from"@aurodesignsystem/auro-library/scripts/utils/logger.mjs";import{simpleGit as oc}from"simple-git";var E;try{E=oc({baseDir:process.cwd(),binary:"git",maxConcurrentProcesses:1})}catch(e){$.error(`Failed to initialize git: ${e}`),E={}}var V=class e{static async checkGitignore(t){if(t==="")return!1;try{return(await rc(".gitignore","utf-8")).includes(t)}catch(n){return $.error(`Error reading file: ${n}`),!1}}static async getCommitMessages(t=""){try{let n=t;n||(n=(await E.branchLocal()).current);let r="main",o="";if(!!process.env.GITHUB_ACTIONS){r=process.env.GITHUB_BASE_REF||"main";try{if(await E.fetch("origin",r),n!=="HEAD")try{await E.raw(["rev-parse","--verify",`origin/${n}`])}catch{await E.fetch("origin",n)}let i=n==="HEAD"?"HEAD":`origin/${n}`;o=`${(await E.raw(["merge-base",`origin/${r}`,i])).trim()}..${i}`}catch(i){$.warn(`Error setting up commit range in CI: ${i}`);let a=n==="HEAD"?"HEAD":`origin/${n}`;o=`origin/${r}..${a}`}}else try{try{await E.raw(["rev-parse","--verify",`origin/${r}`])}catch{$.info(`Fetching ${r} from origin`),await E.fetch("origin",r)}if(n!=="HEAD")try{await E.raw(["rev-parse","--verify",n])}catch{await E.fetch("origin",n)}o=`${(await E.raw(["merge-base",`origin/${r}`,n])).trim()}..${n}`}catch(i){$.warn(`Error determining commits locally: ${i}`),o=`${n}~10..${n}`}return await e.getFormattedCommits(o)}catch(n){return $.error(`Error getting commit messages: ${n}`),[]}}static async getRepoOwnerAndName(){try{let t=await E.getRemotes(!0);if(t.length===0)return $.warn("No remotes found"),null;let n=t.find(o=>o.name==="origin")||t[0],r=n.refs.fetch||n.refs.push;return e.parseGitUrl(r)}catch(t){return $.error(`Error getting repo owner and name: ${t}`),null}}static async getCurrentBranchName(){try{return(await E.branchLocal()).current||null}catch(t){return $.error(`Error getting current branch name: ${t}`),null}}static parseGitUrl(t){let n;return t.includes("@")&&t.includes(":")&&(n=t.match(/@([^:]+):([^/]+)\/(.+?)(?:\.git)?$/),n)?{owner:n[2],repo:n[3]}:(n=t.match(/https?:\/\/(?:[^@]+@)?[^/]+\/([^/]+)\/(.+?)(?:\.git)?$/),n?{owner:n[1],repo:n[2]}:($.warn(`Could not parse git URL: ${t}`),null))}static async getFormattedCommits(t){let r=(await E.raw(["log","--pretty=format:COMMIT_START%n%H%n%ad%n%an%n%s%n%b%nCOMMIT_END","--date=short",t])).split(`COMMIT_START
|
|
44
44
|
`).filter(s=>s.trim()!==""),o=[];for(let s of r){let i=s.split(`
|
|
45
|
-
`);if(i.length>=4){let a=i[0],c=i[1],l=i[2],m=i[3],u=i.slice(4).filter(
|
|
45
|
+
`);if(i.length>=4){let a=i[0],c=i[1],l=i[2],m=i[3],u=i.slice(4).filter(h=>h!=="COMMIT_END"),p=u.length>0?u.join(""):"",d=a.substring(0,7),f=m.match(/^(feat|fix|docs|style|refactor|perf|test|build|ci|chore)(\(.+\))?:/),g=f?f[1]:"unknown";p.includes("BREAKING CHANGE")&&(g="breaking"),o.push({type:g,hash:d,date:c,subject:m,body:p,message:`${m}${p?`
|
|
46
46
|
|
|
47
|
-
${p}`:""}`,author_name:l})}}return o}static async addToGitignore(t,n=!0){await e.checkGitignore(t).then(async r=>{if(r)
|
|
48
|
-
${t}`),n
|
|
49
|
-
`,o=""),o=`${o}${s} `;return o.length>0&&(r+=o.trim()),r}function
|
|
50
|
-
`)}import*as
|
|
47
|
+
${p}`:""}`,author_name:l})}}return o}static async addToGitignore(t,n=!0){await e.checkGitignore(t).then(async r=>{if(r)$.warn(`${t} already exists`);else try{await nc(".gitignore",`
|
|
48
|
+
${t}`),n&&$.success(`${t} added to .gitignore`)}catch(o){$.error(o)}})}static async removeFromGitCache(t){try{await E.rmKeepLocal(t),$.success(`${t.join(", ")} are removed from git cache`)}catch(n){$.error(n)}}static async createBranch(t){try{await E.checkoutLocalBranch(t),$.success(`Created and switched to ${t} branch`)}catch(n){$.error(n)}}static async commitStagedFiles(t){try{await E.add("."),await E.commit(t),$.success(`Committed with message: ${t}`)}catch(n){$.error(n)}}};import C from"chalk";var sc=60,ic=100;function _e(e){switch(e){case"breaking":return C.bold.red(e);case"feat":return C.bold.green(e);case"fix":return C.bold.green(e);case"perf":return C.bold.green(e);case"docs":return C.bold.cyan(e);case"style":return C.bold.cyan(e);case"refactor":return C.bold.cyan(e);case"test":return C.bold.cyan(e);case"build":return C.bold.cyan(e);case"ci":return C.bold.cyan(e);case"chore":return C.bold.cyan(e);default:return C.bold.white(e)}}function io(e,t){if(!e)return"";if(e.length<=t)return e;let n=e.split(" "),r="",o="";for(let s of n)(o+s).length>t&&o.length>0&&(r+=`${o.trim()}
|
|
49
|
+
`,o=""),o=`${o}${s} `;return o.length>0&&(r+=o.trim()),r}function ao(e){for(let t of e){console.log("\u2500".repeat(60));let n=io(t.subject,sc),r=io(t.body,ic);console.log(C.bold(`${_e(t.type)}`)),console.log(C.dim(`${t.hash} | ${t.date} | ${t.author_name}`)),console.log(C.bold(`${C.white(n)}`)),t.body&&console.log(C.dim(r))}console.log("\u2500".repeat(60)),console.log(`
|
|
50
|
+
`)}import*as Fe from"@actions/github";async function pn(){try{let e=process.env.GITHUB_TOKEN;if(!e)throw new Error("GITHUB_TOKEN environment variable is not set");if(!process.env.GITHUB_REPOSITORY||!process.env.GITHUB_EVENT_PATH)throw new Error("This function can only be used in a GitHub Actions environment");let t=Fe.getOctokit(e),{context:n}=Fe;if(!n.payload.pull_request)throw new Error("No pull request found in the GitHub context");let[r,o]=process.env.GITHUB_REPOSITORY.split("/"),s=n.payload.pull_request.number,{data:i}=await t.rest.issues.listLabelsOnIssue({owner:r,repo:o,issue_number:s});return i.map(a=>a.name)}catch(e){throw e instanceof Error?new Error(`Failed to get existing labels: ${e.message}`):e}}async function co(e){try{let t=process.env.GITHUB_TOKEN;if(!t)throw new Error("GITHUB_TOKEN environment variable is not set");if(!process.env.GITHUB_REPOSITORY||!process.env.GITHUB_EVENT_PATH)throw new Error("This function can only be used in a GitHub Actions environment");let n=Fe.getOctokit(t),{context:r}=Fe;if(!r.payload.pull_request)throw new Error("No pull request found in the GitHub context");let[o,s]=process.env.GITHUB_REPOSITORY.split("/"),i=r.payload.pull_request.number,a=`semantic-status: ${e}`,c=await pn();if(c.includes(a))return;let l=c.filter(m=>m.startsWith("semantic-status:")&&m!==a);for(let m of l)await n.rest.issues.removeLabel({owner:o,repo:s,issue_number:i,name:m});await n.rest.issues.addLabels({owner:o,repo:s,issue_number:i,labels:[a]});return}catch(t){throw t instanceof Error?new Error(`Failed to apply label: ${t.message}`):t}}var ac=["feat","fix","breaking","perf"];function cc(e,t=!0){let n=`### In this release
|
|
51
51
|
`;for(let r of e)if(n+=`- ${r.hash} ${r.subject}
|
|
52
|
-
`,r.body?.trim()){let s=r.body.trim().split(/\n+/).map(i=>i.trim()).filter(i=>i.length>0);for(let i of s){let a=i;a=a.replace(/([^\s])(AlaskaAirlines\/[a-zA-Z0-9-]+#\d+)/g,"$1 $2"),a=a.replace(/(AlaskaAirlines\/[a-zA-Z0-9-]+#\d+)([^\s])/g,"$1 $2"),n+=` - ${a}`}}return e.length===0?"":(t&&console.log(
|
|
53
|
-
`),r}async function
|
|
54
|
-
`).start();try{let o=await V.getCommitMessages();if(n){r.succeed(`Total commits analyzed: ${o.length}`);let s=
|
|
52
|
+
`,r.body?.trim()){let s=r.body.trim().split(/\n+/).map(i=>i.trim()).filter(i=>i.length>0);for(let i of s){let a=i;a=a.replace(/([^\s])(AlaskaAirlines\/[a-zA-Z0-9-]+#\d+)/g,"$1 $2"),a=a.replace(/(AlaskaAirlines\/[a-zA-Z0-9-]+#\d+)([^\s])/g,"$1 $2"),n+=` - ${a}`}}return e.length===0?"":(t&&console.log(lo.green(`\u2713 Generating release notes for ${e.length} commits`)),n)}function lc(e,t=!0){let n=e.filter(o=>ac.includes(o.type)),r;return t?r=n.length>0?n:e:r=n,r.length===0&&console.log(`No commits found to include in release notes.
|
|
53
|
+
`),r}async function mo(e=!1,t=!1,n=!1){let r=uo(`Checking commits...
|
|
54
|
+
`).start();try{let o=await V.getCommitMessages();if(n){r.succeed(`Total commits analyzed: ${o.length}`);let s=lc(o);console.log(cc(s));return}if(e&&ao(o),r.succeed(`Total commits analyzed: ${o.length}`),o.length!==0){let s=o.map(c=>c.type),a=Array.from(new Set(s)).map(c=>_e(c)).join(", ");r.succeed(`Found commit types: ${a}`)}else r.info(`The list of commits is created by comparing the current branch
|
|
55
55
|
with the main branch. If you are on a new branch, please
|
|
56
|
-
make sure to commit some changes before running this command.`);t&&await
|
|
57
|
-
`,"utf8"),r.succeed(`Package.json updated to use ${
|
|
56
|
+
make sure to commit some changes before running this command.`);t&&await uc(o,r)}catch(o){r.fail("Error getting commit messages"),console.error(o)}}async function uc(e,t){let n=["breaking","feat","fix","perf","docs","style","refactor","test","build","ci","chore"],r=e.map(i=>i.type).filter(i=>n.includes(i)),o=null,s=Number.POSITIVE_INFINITY;for(let i of r){let a=n.indexOf(i);a<s&&(s=a,o=i)}if(o){let i=uo("Checking existing labels on pull request...").start();try{if((await pn()).includes(`semantic-status: ${o}`)){i.info(`Label "semantic-status: ${_e(o)}" already exists on the pull request.`);return}i.text="Applying label to pull request...",await co(o),i.succeed(`Label "semantic-status: ${_e(o)}" applied to the pull request.`)}catch(a){let c=a instanceof Error?a.message:String(a);i.fail(c)}}else t.warn(lo.yellow("No semantic commit type found to apply as label."))}var jg=mc.command("check-commits").alias("cc").option("-l, --set-label","Set label on the pull request based on the commit message type").option("-d, --debug","Display detailed commit information for debugging").option("-r, --release-notes","Generate release notes based on commit messages").description("Check commits in the local repository for the types of semantic commit messages made and return the results.").action(async e=>{await mo(e.debug,e.setLabel,e.releaseNotes)});import po from"node:fs";import{get as fo}from"node:https";import se from"chalk";import{program as pc}from"commander";import dc from"ora";var Ug=pc.command("pr-release").option("-n, --namespace <package-namespace>","Set namespace of the package release","@aurodesignsystem-dev").option("-p, --pr-number <number>","Set pull request number for the release","0").description("Generate the package version based off of PR number then update the package.json file. Note: this does not publish the package.").action(async e=>{await fc(e)}),fc=async e=>{let{namespace:t,prNumber:n}=e,r=dc("Updating package.json").start();try{let o="package.json",s=JSON.parse(po.readFileSync(o,"utf8"));r.text="Checking npm registry for version information...";let i=`0.0.0-pr${n}`,a=s.name.split("/")[1],c=`${t}/${a}`,l=await gc(i,c,r),m=`${i}.${l}`;s.name=c,s.version=m,r.text="Writing updated package.json...",po.writeFileSync(o,`${JSON.stringify(s,null,2)}
|
|
57
|
+
`,"utf8"),r.succeed(`Package.json updated to use ${se.green(m)} and ${se.green(c)}`),process.exit(0)}catch(o){r.fail(`Failed to update package.json: ${o}`),process.exit(1)}},gc=(e,t,n)=>new Promise(r=>{try{let a=function(c){if(c.statusCode!==200){n.info(`Package not found. Status code: ${se.red(c.statusCode)}, defaulting to version 0`),r(0);return}n.text="Processing version information...";let l="";c.on("data",m=>{l+=m}),c.on("end",()=>{try{let m=JSON.parse(l),u=m.versions?Object.keys(m.versions):[];n.text="Calculating next version number...";let p=-1,d=new RegExp(`^${e}\\.(\\d+)$`);for(let f of u){let g=f.match(d);if(g){let h=Number.parseInt(g[1],10);p=Math.max(p,h)}}p>=0?n.info(`Found existing version ${se.green(`${e}.${p}`)}. Incrementing to ${se.green(`${e}.${p+1}`)}`):n.info(`No existing version found for ${se.green(e)}. Starting with ${se.green(`${e}.0`)}`),r(p+1)}catch(m){n.warn(`Failed to parse NPM registry response: ${m instanceof Error?m.message:"Unknown error"}, defaulting to version 0`),r(0)}})};var o=a;let s=`https://registry.npmjs.org/${t}`,i=fo(s,{headers:{Accept:"application/json"}},c=>{if((c.statusCode===301||c.statusCode===302)&&c.headers.location){n.info(`Following redirect to ${c.headers.location}...`);try{fo(c.headers.location,{headers:{Accept:"application/json"}},a).on("error",l=>{n.warn(`Error following redirect: ${l.message}, defaulting to version 0`),r(0)}).end()}catch(l){n.warn(`Redirect request failed: ${l instanceof Error?l.message:"Unknown error"}, defaulting to version 0`),r(0)}return}a(c)});i.on("error",c=>{n.warn(`Request error: ${c.message}, defaulting to version 0`),r(0)}),i.end()}catch{n.warn("Error checking version in npm registry, defaulting to version 0"),r(0)}});import dn from"node:path";import{fileURLToPath as hc}from"node:url";import{program as yc}from"commander";import bc from"open";var wc=hc(import.meta.url),vc=dn.resolve(dn.dirname(wc),".."),Yg=yc.command("test").option("-w, --watch","Set watch number for the test").option("-c, --coverage-report","Generate coverage report").option("-o, --open","Open the coverage report in the browser").option("-f, --files <String|String[]>","Test files glob pattern").description("Run the web test runner to test the component library").action(async e=>{let n=`npx wtr --config "${dn.join(vc,"dist","configs","web-test-runner.config.mjs")}"`,r=`${process.cwd()}/coverage/index.html`;if(e.coverageReport&&(n+=" --coverage"),e.watch&&(n+=" --watch"),e.files){let o=Array.isArray(e.files)?e.files.join(" "):e.files;n+=` --files "${o}"`}_(n),e.open&&await bc(r)});import yn from"node:fs/promises";import bo from"node:path";import{program as xc}from"commander";import Tc from"inquirer";import bn from"ora";import kc from"node:fs/promises";import $c from"node:path";import Ec from"ora";var Sc={"auth-type":"workspace-token","author-email":null,"author-name":null,"base-branch":"main","base-url":null,"clone-dir":".gitter-temp","code-search":null,concurrent:4,"conflict-strategy":"replace",draft:!1,"dry-run":!0,"fetch-depth":1,fork:!1,"fork-owner":null,"git-type":"go",group:null,"include-subgroups":!1,insecure:!1,interactive:!1,labels:null,"log-file":"'-'","log-format":"'text'","log-level":"'error'","max-reviewers":0,"max-team-reviewers":0,org:null,output:"'-'","plain-output":!1,platform:"github",project:null,"push-only":!1,repo:["AlaskaAirlines/auro-accordion","AlaskaAirlines/auro-alert","AlaskaAirlines/auro-avatar","AlaskaAirlines/auro-background","AlaskaAirlines/auro-backtotop","AlaskaAirlines/auro-button","AlaskaAirlines/auro-badge","AlaskaAirlines/auro-banner","AlaskaAirlines/auro-card","AlaskaAirlines/auro-carousel","AlaskaAirlines/auro-datetime","AlaskaAirlines/auro-dialog","AlaskaAirlines/auro-drawer","AlaskaAirlines/auro-flight","AlaskaAirlines/auro-flightline","AlaskaAirlines/auro-header","AlaskaAirlines/auro-hyperlink","AlaskaAirlines/auro-icon","AlaskaAirlines/auro-loader","AlaskaAirlines/auro-lockup","AlaskaAirlines/auro-nav","AlaskaAirlines/auro-pane","AlaskaAirlines/auro-popover","AlaskaAirlines/auro-sidenav","AlaskaAirlines/auro-skeleton","AlaskaAirlines/auro-slideshow","AlaskaAirlines/auro-table","AlaskaAirlines/auro-tabs","AlaskaAirlines/auro-toast"],"repo-exclude":null,"repo-include":null,"repo-search":null,reviewers:null,"skip-forks":!1,"skip-pr":!1,"skip-repo":null,"ssh-auth":!1,"team-reviewers":null};function Cc(e){return Object.entries(e).map(([t,n])=>Array.isArray(n)?`${t}:
|
|
58
58
|
- ${n.join(`
|
|
59
59
|
- `)}`:typeof n=="object"&&n!==null?`${t}:
|
|
60
60
|
${Object.entries(n).map(([r,o])=>` ${r}: ${o}`).join(`
|
|
61
61
|
`)}`:`${t}: ${n}`).join(`
|
|
62
|
-
`)}async function
|
|
62
|
+
`)}async function go(e){let t=Ec("Writing multi-gitter configuration...").start(),n=Cc(Sc),r=$c.join(e,"multi-gitter_DEPENDENCY_TREE.yml");try{await kc.writeFile(r,n,"utf8"),t.succeed(`Multi-gitter configuration written to ${r}`)}catch(o){t.fail("Error writing multi-gitter configuration:"),console.error(o)}}import fn from"node:fs";function ho(e){let t={},n=[],r=[],o=[];for(let s in e)t[s]=e[s].dependsOn.length;for(let s in t)t[s]===0&&o.push(s);for(;o.length>0;){r=[];let s=o.length;for(let i=0;i<s;i++){let a=o.shift();r.push(a);for(let c of e[a].dependentPackages)t[c]--,t[c]===0&&o.push(c)}n.push(r)}if(n.flat().length!==Object.keys(e).length)throw new Error("Circular dependency detected!");return n}function Ac(e){return fn.readdirSync(e).filter(t=>t.endsWith(".json"))}async function yo(e,t=[]){console.log(t);let n={},r=Ac(e);for(let o of r){if(o==="dependencyTree.json")continue;let s=fn.readFileSync(`${e}/${o}`,"utf-8"),i=JSON.parse(s),a=i.name,c=Object.keys(i.peerDependencies),l=Object.keys(i.devDependencies),m=Object.keys(i.dependencies);n[a]||(n[a]={dependsOn:[],dependentPackages:[]});let u=[...c,...l,...m];n[a].dependsOn=[...new Set(u)];for(let p of u)n[p]||(n[p]={dependsOn:[],dependentPackages:[]}),n[p].dependentPackages.includes(a)||n[p].dependentPackages.push(a)}if(t.length){let o=new Set;for(let[i,a]of Object.entries(n))a.dependsOn.some(c=>t.includes(c))&&o.add(i);for(let i of t)n[i]&&o.add(i);let s={};for(let i of o)s[i]={dependsOn:n[i].dependsOn.filter(a=>o.has(a)),dependentPackages:n[i].dependentPackages.filter(a=>o.has(a))};n=s}else console.log("No target dependencies provided - using all packages.");return fn.writeFileSync(`${e}/dependencyTree.json`,JSON.stringify(n,null,2)),n}var I=["@aurodesignsystem/auro-accordion","@aurodesignsystem/auro-alert","@aurodesignsystem/auro-avatar","@aurodesignsystem/auro-background","@aurodesignsystem/auro-backtotop","@aurodesignsystem/auro-badge","@aurodesignsystem/auro-banner","@aurodesignsystem/auro-button","@aurodesignsystem/auro-card","@aurodesignsystem/auro-carousel","@aurodesignsystem/auro-checkbox","@aurodesignsystem/auro-combobox","@aurodesignsystem/auro-datepicker","@aurodesignsystem/auro-datetime","@aurodesignsystem/auro-dialog","@aurodesignsystem/auro-drawer","@aurodesignsystem/auro-dropdown","@aurodesignsystem/auro-flight","@aurodesignsystem/auro-flightline","@aurodesignsystem/auro-form","@aurodesignsystem/auro-formkit","@aurodesignsystem/auro-header","@aurodesignsystem/auro-hyperlink","@aurodesignsystem/auro-icon","@aurodesignsystem/auro-input","@aurodesignsystem/auro-loader","@aurodesignsystem/auro-lockup","@aurodesignsystem/auro-menu","@aurodesignsystem/auro-nav","@aurodesignsystem/auro-pane","@aurodesignsystem/auro-popover","@aurodesignsystem/auro-radio","@aurodesignsystem/auro-select","@aurodesignsystem/auro-sidenav","@aurodesignsystem/auro-skeleton","@aurodesignsystem/auro-slideshow","@aurodesignsystem/auro-table","@aurodesignsystem/auro-tabs","@aurodesignsystem/auro-tail","@aurodesignsystem/auro-toast","@aurodesignsystem/auro-tokenlist"];var gn=Xt("run-migrations","config"),hn=Xt("run-migrations","outputs");var gh=[...I,"@aurodesignsystem/auro-library","@aurodesignsystem/WebCoreStyleSheets","@aurodesignsystem/AuroDesignTokens","@aurodesignsystem/auro-cli","@alaskaairux/icons"];async function Rc(e){try{await yn.mkdir(hn,{recursive:!0}),await yn.mkdir(gn,{recursive:!0})}catch(o){console.error("Failed to create output or config directories:",o),process.exit(1)}let t=bn("Creating dependency tree...").start();t.text="Creating multi-gitter dependency tree configuration...",await go(gn),t.text="Scraping dependencies from Auro packages...";let r=`multi-gitter run "node ${Zt("static","getAuroDeps.js")}" --config ${bo.join(gn,"multi-gitter_DEPENDENCY_TREE.yml")}`;try{await _(r)}catch(o){t.fail("Failed to generate dependency tree:"),console.error(o),process.exit(1)}return t.text="Generating dependency tree JSON file using packages...",await yo(hn,e),t.succeed("Dependency tree generated successfully."),bo.join(hn,"dependencyTree.json")}var Pc=async e=>{let t=bn("Loading dependency tree...").start(),n=JSON.parse(await yn.readFile(e,"utf-8"));t.text="Processing dependency tree...";let r=ho(n);return t.succeed("Dependency batches created successfully."),r},hh=xc.command("agent").action(async e=>{let t=await Tc.prompt([{type:"select",name:"agentAction",message:"What agent action do you want to perform?",choices:[{name:"Run a migration on auro components",value:"run-migration"}],default:["run-migration"]},{type:"input",name:"migrationId",message:"What migration id do you want to run?",when:n=>n.agentAction==="run-migration",validate:n=>n.trim()!==""||"Migration id cannot be empty."},{type:"confirm",name:"useExisting",message:"Would you like to specify starting packages?",default:!0,transformer:n=>n?"Yes = Packages related to selections":"No = All packages",when:n=>n.agentAction==="run-migration"},{type:"checkbox",name:"startWithComponents",message:"Enter the components to start with (comma-separated, blank for all):",choices:I.map(n=>({name:n.replace("@aurodesignsystem/",""),value:n})),when:n=>n.agentAction==="run-migration"&&n.useExisting}]);switch(t.agentAction){case"run-migration":{let n=bn("Running migration...").start(),r=await Rc(t.startWithComponents);n.text="Getting dependency batches from tree...";let s=(await Pc(r)).map((i,a)=>`Batch ${a+1}
|
|
63
63
|
${i.map(c=>` - ${c.replace("@aurodesignsystem","AlaskaAirlines").replace("@alaskaairux/icons","AlaskaAirlines/Icons")}`).join(`
|
|
64
64
|
`)}`).join(`
|
|
65
65
|
|
|
66
|
-
`);console.log(s),n.text="Running migrations on dependency batches...",new Promise(i=>setTimeout(i,2e3)),n.succeed("Migration process completed successfully.");break}default:console.error("Unknown action selected.")}});import{writeFile as
|
|
67
|
-
`,"utf-8")}catch(a){let c=a instanceof Error?a.message:String(a);t.fail(`Failed to write ${e.output}: ${c}`),
|
|
66
|
+
`);console.log(s),n.text="Running migrations on dependency batches...",new Promise(i=>setTimeout(i,2e3)),n.succeed("Migration process completed successfully.");break}default:console.error("Unknown action selected.")}});import{writeFile as _c}from"node:fs/promises";import Fc from"node:path";import ut from"node:process";import{Logger as Co}from"@aurodesignsystem/auro-library/scripts/utils/logger.mjs";import{program as Lc}from"commander";import Gc from"ora";import{readFile as wo}from"node:fs/promises";import ie from"node:path";import Dc from"node:process";var Mc="https://unpkg.com",Nc="https://registry.npmjs.org",wn=1e4;function Ic(e){let t=e.lastIndexOf("@");return t>0?{pkg:e.slice(0,t),ref:e.slice(t+1)}:{pkg:e}}function vo(e,t){let n=ie.relative(e,t);return n===""||!n.startsWith("..")&&!ie.isAbsolute(n)}async function Oc(e){let t=ie.join(Dc.cwd(),"node_modules"),n=ie.join(t,...e.split("/"));if(!vo(t,n))return null;let r,o="custom-elements.json";try{let s=JSON.parse(await wo(ie.join(n,"package.json"),"utf-8"));typeof s.version=="string"&&(r=s.version),typeof s.customElements=="string"&&vo(n,ie.resolve(n,s.customElements))&&(o=s.customElements)}catch{return null}try{let s=JSON.parse(await wo(ie.join(n,o),"utf-8"));return{target:e,manifest:s,source:"local",version:r}}catch{return null}}async function O(e,t={}){let{preferLocal:n=!0,allowNetwork:r=!0}=t,{ref:o}=Ic(e);if(n&&!o){let a=await Oc(e);if(a)return{...a,target:e}}if(!r)return{target:e,manifest:null,reason:"not installed locally and network fetching is disabled"};let s=`${Mc}/${e}/custom-elements.json`,i;try{i=await fetch(s,{signal:AbortSignal.timeout(wn)})}catch(a){let l=a instanceof DOMException&&a.name==="TimeoutError"?`timed out after ${wn/1e3}s`:a instanceof Error?a.message:String(a);return{target:e,manifest:null,reason:`request failed (${l})`,transient:!0}}if(i.status===404)return{target:e,manifest:null,reason:"no custom-elements.json published"};if(!i.ok)return{target:e,manifest:null,reason:`HTTP ${i.status}`,transient:!0};try{return{target:e,manifest:await i.json(),source:"unpkg"}}catch{return{target:e,manifest:null,reason:"custom-elements.json is not valid JSON",transient:!0}}}function ko(e){let t=e.filter(n=>!n.manifest);return{skipped:t,transientFailures:t.filter(n=>n.transient)}}async function $o(e){try{let t=await fetch(`${Nc}/${e}/latest`,{signal:AbortSignal.timeout(wn)});if(!t.ok)return null;let n=await t.json();return typeof n.version=="string"?n.version:null}catch{return null}}import{Logger as jc}from"@aurodesignsystem/auro-library/scripts/utils/logger.mjs";function vn(e,t){if(Array.isArray(e))return e.map(n=>vn(n,t));if(e&&typeof e=="object"){let n=e,r={};for(let[o,s]of Object.entries(n))o==="module"&&typeof s=="string"&&n.package==null?r[o]=`${t}/${s}`:r[o]=vn(s,t);return r}return e}function Eo(e,t=jc.warn){let n=[];for(let{pkg:o,manifest:s}of e)for(let i of s.modules??[]){let a=vn(i,o);typeof i.path=="string"&&(a.path=`${o}/${i.path}`),n.push(a)}let r=new Set(e.map(o=>o.manifest.schemaVersion).filter(Boolean));return r.size>1&&t(`Merging mixed CEM schema versions: ${[...r].join(", ")}`),{schemaVersion:e[0]?.manifest.schemaVersion??"1.0.0",modules:n}}async function So(e,t={}){let n=await Promise.all(e.map(i=>O(i,t))),r=[];for(let i of n)i.manifest&&r.push({pkg:i.target,manifest:i.manifest});let{skipped:o,transientFailures:s}=ko(n);return{manifest:Eo(r),sources:r,skipped:o,transientFailures:s}}async function Bc(e){let t=Gc(`Fetching manifests for ${I.length} components...`).start(),{manifest:n,sources:r,skipped:o,transientFailures:s}=await So(I,{preferLocal:!1});r.length===0&&(t.fail("No component manifests could be fetched."),ut.exit(1));let i=Fc.resolve(ut.cwd(),e.output);try{await _c(i,`${JSON.stringify(n,null,2)}
|
|
67
|
+
`,"utf-8")}catch(a){let c=a instanceof Error?a.message:String(a);t.fail(`Failed to write ${e.output}: ${c}`),ut.exit(1)}t.succeed(`Aggregated ${r.length}/${I.length} component manifests (${n.modules?.length??0} modules) to ${e.output}`);for(let a of o)a.transient||Co.info(`Skipped ${a.target}: ${a.reason}`);s.length>0&&(Co.error(`${s.length} component(s) failed to fetch transiently; the aggregate may be incomplete. Re-run to retry.`),ut.exit(1))}var Oh=Lc.command("cem").description("Fetch every published Auro component's custom-elements.json and merge them into a single aggregated manifest").option("-o, --output <file>","Path to write the aggregated manifest","custom-elements.aggregate.json").action(Bc);import{readFileSync as Uo}from"node:fs";import{dirname as Ho,join as zl,resolve as In}from"node:path";import bt from"node:process";import{program as Vl}from"commander";import Kl from"ora";import{mkdtempSync as Wc,rmSync as Uc}from"node:fs";import{tmpdir as Hc}from"node:os";import{join as Jc}from"node:path";function $n(e){return e.replace(/(['"`])(?:\\.|(?!\1)[\s\S])*\1/gu," ")}function En(e){let t={")":"(","]":"[","}":"{",">":"<"},n=[],r="";for(let o of $n(e)){if(o===">"&&r==="="){r=o;continue}if(o==="("||o==="["||o==="{"||o==="<")n.push(o);else if((o===")"||o==="]"||o==="}"||o===">")&&n.pop()!==t[o])return!1;r=o}return n.length===0}function kn(e){let t=e.type?.text;if(typeof t=="string"&&t!==""&&!En(t)){let{type:n,...r}=e;return r}return e}function Sn(e,t){let{fieldName:n,description:r}=e;if(typeof n!="string"||n===""||typeof r=="string"&&r!=="")return!1;if(!t.has(n))return!0;let o=t.get(n);return o==="private"||o==="protected"}function zc(e){let t=o=>typeof o.name=="string",n=e.members?.filter(t).map(kn),r=new Map((n??[]).map(o=>[o.name,o.privacy]));return{...e,...n&&{members:n},...e.attributes&&{attributes:e.attributes.filter(t).filter(o=>!Sn(o,r)).map(kn)},...e.slots&&{slots:e.slots.filter(t)},...e.events&&{events:e.events.filter(t).map(kn)},...e.cssParts&&{cssParts:e.cssParts.filter(t)},...e.cssProperties&&{cssProperties:e.cssProperties.filter(t)}}}function Cn(e,t){return t.get(e.tagName)??e.tagName}function xo(e){return new Map(e.map(t=>[t.declaration.name,t.importPath]))}function ge(e,t){return{schemaVersion:"1.0.0",modules:e.map(n=>{let r=zc({...n.declaration,tagName:t?Cn(n,t):n.tagName});return{kind:"javascript-module",path:n.importPath,declarations:[r],exports:[{kind:"js",name:r.name,declaration:{name:r.name,module:n.importPath}}]}})}}function K(e){let t=Wc(Jc(Hc(),"auro-editors-"));try{return e(t)}finally{try{Uc(t,{recursive:!0,force:!0,maxRetries:10,retryDelay:100})}catch{}}}function q(e){return e.endsWith(`
|
|
68
68
|
`)?e:`${e}
|
|
69
|
-
`}var
|
|
69
|
+
`}var Vc=` /** Identifies the currently active descendant of a composite widget. */
|
|
70
70
|
"aria-activedescendant"?: string;
|
|
71
71
|
/** Whether assistive technologies present all, or only parts of, changed regions. */
|
|
72
72
|
"aria-atomic"?: boolean | "true" | "false";
|
|
@@ -174,19 +174,19 @@ ${i.map(c=>` - ${c.replace("@aurodesignsystem","AlaskaAirlines").replace("@alas
|
|
|
174
174
|
"aria-valuetext"?: string;
|
|
175
175
|
/** Custom data-* attributes for the element. */
|
|
176
176
|
[key: \`data-\${string}\`]: string | number | boolean | null | undefined;
|
|
177
|
-
`,
|
|
177
|
+
`,Ao=/(type BaseProps(?:<[^>]*>)? = \{\n)/,Kc=` /** Defines the element's semantic role for accessibility APIs. */
|
|
178
178
|
role?: string;
|
|
179
179
|
/** The position of the element in the sequential keyboard navigation order. */
|
|
180
180
|
tabindex?: number;
|
|
181
|
-
`;function
|
|
181
|
+
`;function mt(e,{svelteGlobals:t}){if(!Ao.test(e))throw new Error("the JSX/Svelte generator no longer emits a recognizable `type BaseProps = {` block; the global-attribute injection in manifest.ts must be updated to match.");let n=`${t?Kc:""}${Vc}`;return e.replace(Ao,`$1${n}`)}function An(e){let t=[];for(let n of e)n.source==="local"&&n.manifest&&n.version&&t.push({pkg:n.target,version:n.version,manifest:n.manifest});return t}async function To(e=I){let t=await Promise.all(e.map(n=>O(n,{allowNetwork:!1})));return An(t)}function xn(e){return(e.modules??[]).flatMap(t=>t.declarations??[]).filter(t=>t.customElement&&t.tagName)}function Tn(e){let t=[],n=new Map,r=new Set;for(let{pkg:s,version:i,manifest:a}of e){let c=xn(a),l=c.length>1;for(let m of c){let u=m.tagName,p=n.get(u);p?p.includes(s)||p.push(s):n.set(u,[s]),!r.has(u)&&(r.add(u),t.push({pkg:s,version:i,tagName:u,declaration:m,importPath:l?`${s}/${u}`:s,isMonorepo:l}))}}let o=[];for(let[s,i]of n)i.length>1&&o.push({tagName:s,packages:i});return{components:t,duplicates:o}}async function Ro(e){let t=await To(e);return Tn(t)}var qc=new Set(["variant","shape","size","type","appearance"]),Yc=new Set(["string","String","any"]),Xc=new Map([["array","use `unknown[]`, `T[]`, or `Array<T>`"],["function","use `Function` or an explicit call signature `(\u2026) => \u2026`"]]),Zc=new Map([["Array","Array<T>"],["ReadonlyArray","ReadonlyArray<T>"],["Promise","Promise<T>"],["Map","Map<K, V>"],["WeakMap","WeakMap<K, V>"],["Set","Set<T>"],["WeakSet","WeakSet<T>"],["Record","Record<K, V>"]]),Qc=new Set(["object","Object"]),el=[...Xc].map(([e,t])=>({token:e,fix:t,re:new RegExp(`\\b${e}\\b(?!\\s*:)`,"u")})),tl=[...Zc].map(([e,t])=>({token:e,fix:t,re:new RegExp(`\\b${e}\\b(?!\\s*[<:])`,"u")}));function Po(e,t){return e===t?`\`type.text\` is \`${t}\``:`\`type.text\` (${JSON.stringify(e)}) uses \`${t}\``}var nl=[/^[\s>*_~([-]*@?deprecated\b/iu,/[([]\s*deprecated\b/iu,/\*\*\s*deprecated\b/iu,/@deprecated\b/iu];function Io(...e){return e.some(t=>typeof t=="string"&&nl.some(n=>n.test(t.trim())))}function Oo(e){return e===!0||Le(e)}function Do(e,t,n,r){!Oo(r.deprecated)&&Io(r.description,r.summary)&&e.push({rule:"deprecated-prose-unflagged",severity:"warn",element:t,path:n,message:"described as deprecated but missing the `deprecated` field \u2014 add an `@deprecated` JSDoc tag so the generated JSX/Svelte types surface it with a strikethrough. (VS Code HTML custom-data has no deprecation field, so vanilla-HTML editors won't show it.)"})}function Mo(e,t,n,r,o){!Oo(o.deprecated)&&Io(o.description,o.summary)&&e.push({rule:"deprecated-prose-unsupported",severity:"warn",element:t,path:r,message:`this ${n} reads as deprecated in prose, but the analyzer (v0.11.0) does not emit a \`deprecated\` field for inline \`@${n}\` tags \u2014 editors cannot surface it. Track upstream or a mapping plugin; suppress this warning if the prose is intentional.`})}function pt(e,t,n,r){r.deprecated===!0&&e.push({rule:"deprecated-no-detail",severity:"warn",element:t,path:n,message:"`deprecated` is set but carries no message \u2014 editors show a strikethrough with no migration target. Prefer `@deprecated <what to use instead>`."})}function Le(e){return typeof e=="string"&&e!==""}function he(e,t,n,r){r?.forEach((o,s)=>{typeof o.name!="string"&&e.push({rule:"name-required",severity:"error",element:t,path:`${n}[${s}].name`,message:`${n}[${s}] has no string \`name\` \u2014 community generators call \`.name.startsWith(\u2026)\` and throw mid-generation.`})})}function Rn(e,t,n,r){let o=r.type?.text;typeof o=="string"&&o!==""&&!En(o)&&e.push({rule:"type-parseable",severity:"error",element:t,path:`${n}.type.text`,message:`\`type.text\` has unbalanced delimiters: ${JSON.stringify(o)} \u2014 the generated \`.d.ts\` would not parse.`})}function Pn(e,t,n,r){let o=r.type?.text;if(typeof o!="string")return;let s=o.trim();if(s==="")return;let i=$n(s);for(let{token:a,re:c,fix:l}of el)if(c.test(i)){e.push({rule:"type-not-typescript",severity:"error",element:t,path:`${n}.type.text`,message:`${Po(s,a)}, which is not a TypeScript type \u2014 ${l}. The generated \`.d.ts\` would not compile.`});return}for(let{token:a,re:c,fix:l}of tl)if(c.test(i)){e.push({rule:"type-not-typescript",severity:"error",element:t,path:`${n}.type.text`,message:`${Po(s,a)}, a generic that requires a type argument \u2014 write \`${l}\`. The generated \`.d.ts\` would not compile.`});return}Qc.has(s)&&e.push({rule:"type-imprecise",severity:"warn",element:t,path:`${n}.type.text`,message:`\`type.text\` is \`${s}\` \u2014 a valid type, but it exposes no properties so nothing completes. Prefer an explicit shape (e.g. \`{ id: string }\`).`})}function rl(e,t){let n=0;for(let r=t-1;r>=0&&e[r]==="\\";r--)n++;return n%2===1}function ol(e){let t=[],n=0,r=null,o=0;for(let s=0;s<e.length;s++){let i=e[s];r!==null?i===r&&!rl(e,s)&&(r=null):i==='"'||i==="'"||i==="`"?r=i:i==="("||i==="["||i==="{"||i==="<"?n++:i===")"||i==="]"||i==="}"?n--:i===">"?s>0&&e[s-1]!=="="&&n--:i==="|"&&n===0&&(t.push(e.slice(o,s).trim()),o=s+1)}return t.push(e.slice(o).trim()),t.filter(s=>s!=="")}function sl(e){return/^(['"`]).*\1$/u.test(e)}function il(e,t,n,r){let o=r.type?.text?.trim();if(typeof o!="string"||!o.includes("|"))return;let s=ol(o),i=s.some(sl),a=s.some(c=>c==="string"||c==="String");i&&a&&e.push({rule:"union-widened-by-string",severity:"warn",element:t,path:`${n}.type.text`,message:`\`type.text\` (${JSON.stringify(o)}) unions string literals with a bare \`string\`, which widens the whole type back to \`string\` \u2014 drop the \`string\` member so the literals validate and complete.`})}function No(e){return typeof e!="string"||e.trim()===""}function Dn(e,t,n,r,o){No(o.description)&&No(o.summary)&&e.push({rule:"missing-description",severity:"warn",element:t,...r===void 0?{}:{path:r},message:`${n} has no description or summary \u2014 editors show no hover documentation for it. Add a JSDoc description.`})}function al(e,t){let n=Le(t.tagName)?t.tagName:"<unknown>";typeof t.name!="string"&&e.push({rule:"name-required",severity:"error",element:n,path:"name",message:"registered element has no string `name` \u2014 its generated import/export identity is undefined."}),Dn(e,n,"this component",void 0,t);let r=t.members??[],o=t.attributes??[],s=t.events??[],i=t.slots??[];he(e,n,"members",r),he(e,n,"attributes",o),he(e,n,"slots",t.slots),he(e,n,"events",s),he(e,n,"cssParts",t.cssParts),he(e,n,"cssProperties",t.cssProperties),r.forEach((c,l)=>{Rn(e,n,`members[${l}]`,c),Pn(e,n,`members[${l}]`,c),Do(e,n,`members[${l}]`,c),pt(e,n,`members[${l}]`,c)}),o.forEach((c,l)=>{Rn(e,n,`attributes[${l}]`,c),Pn(e,n,`attributes[${l}]`,c),il(e,n,`attributes[${l}]`,c),Dn(e,n,"attribute",`attributes[${l}]`,c),Do(e,n,`attributes[${l}]`,c),pt(e,n,`attributes[${l}]`,c)}),s.forEach((c,l)=>{Rn(e,n,`events[${l}]`,c),Pn(e,n,`events[${l}]`,c),Dn(e,n,"event",`events[${l}]`,c),Mo(e,n,"event",`events[${l}]`,c),pt(e,n,`events[${l}]`,c)}),i.forEach((c,l)=>{Mo(e,n,"slot",`slots[${l}]`,c),pt(e,n,`slots[${l}]`,c)});let a=new Map(r.filter(c=>typeof c.name=="string").map(c=>[c.name,c.privacy]));o.forEach((c,l)=>{Le(c.name)&&/[A-Z]/u.test(c.name)&&e.push({rule:"attribute-name-not-lowercase",severity:"warn",element:n,path:`attributes[${l}].name`,message:`attribute \`${c.name}\` has uppercase letters \u2014 HTML lowercases attribute names, so it never binds as written. Use \`${c.name.toLowerCase()}\` (the camelCase property name belongs in \`fieldName\`).`}),Le(c.name)&&qc.has(c.name)&&Yc.has(c.type?.text?.trim()??"")&&e.push({rule:"enumerated-union",severity:"warn",element:n,path:`attributes[${l}].type.text`,message:`\`${c.name}\` is typed as bare \`${JSON.stringify(c.type?.text??"")}\` \u2014 an enumerated attribute should carry a string-literal union (e.g. \`"primary" | "secondary"\`) so values validate and complete.`}),Sn(c,a)&&e.push({rule:"private-reflection",severity:"warn",element:n,path:`attributes[${l}]`,message:`\`${c.name??"<unnamed>"}\` reflects a private/omitted member and has no description \u2014 it leaks into editor autocomplete as a settable attribute (add a description if it is genuinely public).`})})}function jo(e){let t=[];Le(e.schemaVersion)||t.push({rule:"schema-version",severity:"warn",message:"manifest has no `schemaVersion` \u2014 declare the CEM schema version it targets."});for(let n of xn(e))al(t,n);return t}import{execFileSync as Sl}from"node:child_process";import{mkdirSync as Nn,writeFileSync as yt}from"node:fs";import{createRequire as Cl}from"node:module";import{dirname as Al,join as ye}from"node:path";import xl from"node:process";import{generateJsxTypes as ll}from"@wc-toolkit/jsx-types";var x=".vscode",ae="settings.json",_o="auro.html-custom-data.json",P="html.customData",U=`./${x}/${_o}`,ce=`${x}/${_o}`,cl="auro.code-snippets",dt=`${x}/${cl}`,Ge="auro-types",Mn="auro-jsx.d.ts",ft="auro-svelte.d.ts",le=`${Ge}/${Mn}`,ue=`${Ge}/${ft}`,D="include",H=Ge;function gt(e,t){let n=ge(e),r=xo(e),o=K(s=>ll(n,{outdir:s,fileName:Mn,tagFormatter:i=>t.get(i)??i,componentTypePath:i=>r.get(i)??i,useCemTypes:!0,includeDefaultDOMEvents:!0}));if(typeof o!="string")throw new Error("JSX type generation returned no output for the resolved components.");return{filename:le,contents:q(mt(o,{svelteGlobals:!1}))}}import{readFileSync as ul}from"node:fs";import{join as ml}from"node:path";import{generateSvelteTypes as pl}from"custom-element-svelte-integration";var Fo=`declare namespace svelteHTML {
|
|
182
182
|
// eslint-disable-next-line @typescript-eslint/no-empty-interface
|
|
183
183
|
interface IntrinsicElements extends CustomElements {}
|
|
184
|
-
}`,
|
|
184
|
+
}`,dl=`declare global {
|
|
185
185
|
namespace svelteHTML {
|
|
186
186
|
// eslint-disable-next-line @typescript-eslint/no-empty-interface
|
|
187
187
|
interface IntrinsicElements extends CustomElements {}
|
|
188
188
|
}
|
|
189
|
-
}`,
|
|
189
|
+
}`,fl=`
|
|
190
190
|
// Mouse events
|
|
191
191
|
"on:click"?: (e: MouseEvent) => void;
|
|
192
192
|
"on:contextmenu"?: (e: MouseEvent) => void;
|
|
@@ -234,30 +234,32 @@ ${i.map(c=>` - ${c.replace("@aurodesignsystem","AlaskaAirlines").replace("@alas
|
|
|
234
234
|
"on:copy"?: (e: ClipboardEvent) => void;
|
|
235
235
|
"on:cut"?: (e: ClipboardEvent) => void;
|
|
236
236
|
"on:paste"?: (e: ClipboardEvent) => void;
|
|
237
|
-
`,
|
|
238
|
-
${n}"on${r}"${o}`)}var
|
|
237
|
+
`,gl=/^([ \t]*)"on:([^"]+)"(\?:.*=> void;)$/gmu;function hl(e){return e.replace(gl,(t,n,r,o)=>`${n}"on:${r}"${o}
|
|
238
|
+
${n}"on${r}"${o}`)}var yl=/^(\s*"[^"]+": Partial<)(\w+)Props & BaseProps & BaseEvents(>;)$/gm;function bl(e){let t=!1,n=e.replace(yl,(r,o,s,i)=>(t=!0,`${o}Omit<${s}Props, keyof BaseProps> & BaseProps & Omit<BaseEvents, keyof ${s}Props>${i}`));if(!t)throw new Error("custom-element-svelte-integration no longer emits the expected `Partial<<Name>Props & BaseProps & BaseEvents>` element mapping; the base-member collision rewrite in svelteTypes.ts must be updated to match the new output.");return n}var wl=/^type (\w+)Props = \{\n([\s\S]*?)\n\};$/gm,vl=/\/\*\* /g;function kl(e,t){return e.replace(wl,(n,r,o)=>{let s=t.get(r);if(s===void 0)return n;let i=o.replace(vl,`/** \u3010${s}\u3011 `);return`type ${r}Props = {
|
|
239
239
|
${i}
|
|
240
|
-
};`})}function
|
|
240
|
+
};`})}function $l(e,t){return new Map(e.map(n=>{let r=n.tagName,o=t.get(r)??r,s=o===r?n.declaration.name:o;return[n.declaration.name,s]}))}function El(e){if(!e.includes(Fo))throw new Error("custom-element-svelte-integration no longer emits the expected `declare namespace svelteHTML` block; the global-augmentation rewrite in svelteTypes.ts must be updated to match the new output.");return e.replace(Fo,dl)}function ht(e,t){let n=ge(e,t),r=$l(e,t),o=K(s=>(pl(n,{outdir:s,fileName:ft,hideLogs:!0,globalEvents:fl}),ul(ml(s,ft),"utf-8")));return{filename:ue,contents:q(El(bl(mt(hl(kl(o,r)),{svelteGlobals:!0}))))}}var Tl=Cl(import.meta.url),Rl=Tl.resolve("typescript/bin/tsc"),Pl=`declare namespace JSX {
|
|
241
241
|
type Element = unknown;
|
|
242
242
|
interface CSSProperties {}
|
|
243
243
|
}
|
|
244
|
-
`;function
|
|
245
|
-
${i.trim()}`}}})}function
|
|
244
|
+
`;function Dl(e){return`${e.replace(/[^a-zA-Z0-9]+/gu,"_")}.d.ts`}function Ml(e){let t=new Map,n=/^[ \t]*import\s+(?:type\s+)?\{([^}]*)\}\s*from\s*["']([^"']+)["']/gmu;for(let r of e.matchAll(n)){let o=r[1].split(",").map(i=>i.trim().split(/\s+as\s+/u)[0].trim()).filter(Boolean);if(o.length===0)continue;let s=t.get(r[2])??new Set;for(let i of o)s.add(i);t.set(r[2],s)}return t}function Lo(e,t,n){yt(ye(e,"tsconfig.json"),JSON.stringify({compilerOptions:{noEmit:!0,skipLibCheck:!1,strict:!1,strictFunctionTypes:!0,target:"ES2020",module:"ESNext",moduleResolution:"bundler",...n&&{baseUrl:".",paths:n},lib:["ES2020","DOM"],types:[]},include:t},null,2),"utf-8")}function Nl(e,t){let n=ye(e,t.filename);Nn(Al(n),{recursive:!0}),yt(n,t.contents,"utf-8")}function Go(e,t,n){return K(r=>{Nl(r,t),n(r);try{return Sl(xl.execPath,[Rl,"-p","tsconfig.json"],{cwd:r,stdio:"pipe"}),null}catch(o){let s=o,i=`${s.stdout?.toString()??""}${s.stderr?.toString()??""}`;return{rule:"generation-smoke",severity:"error",element:e,message:`the generated ${e} \`.d.ts\` does not type-check \u2014 this CEM breaks the editor tooling:
|
|
245
|
+
${i.trim()}`}}})}function Bo(e){if(e.length===0)return[];let t=new Map(e.map(r=>[r.tagName,r.tagName])),n=[];try{let r=gt(e,t),o=Ml(r.contents),s=Go("JSX",r,i=>{Nn(ye(i,"stubs"),{recursive:!0});let a={},c=[r.filename];for(let[l,m]of o){let u=Dl(l);yt(ye(i,"stubs",u),`${[...m].map(p=>`export declare class ${p} extends HTMLElement {}`).join(`
|
|
246
246
|
`)}
|
|
247
|
-
`,"utf-8"),a[l]=[`./stubs/${u}`],c.push(`stubs/${u}`)}
|
|
248
|
-
`)
|
|
249
|
-
`)
|
|
250
|
-
`)
|
|
247
|
+
`,"utf-8"),a[l]=[`./stubs/${u}`],c.push(`stubs/${u}`)}Lo(i,c,a)});s&&n.push(s)}catch(r){n.push({rule:"generation-build",severity:"error",element:"JSX",message:`JSX type generation threw for this CEM: ${r.message}`})}try{let r=ht(e,t),o=Go("Svelte",r,s=>{Nn(ye(s,"stubs"),{recursive:!0}),yt(ye(s,"stubs","jsx-shim.d.ts"),Pl,"utf-8"),Lo(s,[r.filename,"stubs/jsx-shim.d.ts"])});o&&n.push(o)}catch(r){n.push({rule:"generation-build",severity:"error",element:"Svelte",message:`Svelte type generation threw for this CEM: ${r.message}`})}return n}import{readFileSync as Il}from"node:fs";import{resolve as Ol}from"node:path";var jl=/\/\*\*(?!\/)([\s\S]*?)\*\//gu,_l=/\.[cm]?[jt]s$/u,Fl=400;function Ll(e,t){let n=1;for(let r=0;r<t;r++)e.charCodeAt(r)===10&&n++;return n}function Gl(e){let t=[...e.matchAll(jl)];return t.map((n,r)=>{let o=n.index??0,s=o+n[0].length,i=t[r+1]?.index??e.length;return{line:Ll(e,o),lines:(n[1]??"").split(`
|
|
248
|
+
`).map(a=>a.replace(/^\s*\*?\s?/u,"").trimEnd()),following:e.slice(s,Math.min(i,s+Fl))}})}var Bl=/^@default\s+false$/u,Wl=/^@type\s+\{\s*boolean\s*\}/iu,Ul=[/^\s*[\w$]+\s*:\s*\{[^}]*?\btype\s*:\s*Boolean\b/u,/^\s*@property\(\s*\{[^}]*?\btype\s*:\s*Boolean\b/u];function Hl(e){return e.lines.some(t=>Wl.test(t))||Ul.some(t=>t.test(e.following))}function Jl(e,t,n){let r=n.lines.findIndex(o=>Bl.test(o.trim()));r===-1||!Hl(n)||e.push({rule:"redundant-boolean-default",severity:"warn",path:`${t}:${n.line+r}`,message:"`@default false` on a boolean property is redundant \u2014 a boolean that isn't set is already off, and the manifest picks up a constructor's `false` on its own. Remove the tag (content guidelines \u203A Defaults)."})}function Wo(e,t){let n=[],r=new Set;for(let o of e.modules??[]){let s=o.path;if(typeof s!="string"||!_l.test(s)||r.has(s))continue;r.add(s);let i;try{i=Il(Ol(t,s),"utf-8")}catch{continue}for(let a of Gl(i))Jl(n,s,a)}return n}function ql(e){try{let t=Uo(zl(Ho(In(e)),"package.json"),"utf-8"),n=JSON.parse(t);return{pkg:typeof n.name=="string"?n.name:"cem-check-subject",version:typeof n.version=="string"?n.version:"0.0.0"}}catch{return{pkg:"cem-check-subject",version:"0.0.0"}}}function Yl(e){let t=e.severity==="error"?"\u2716":"\u26A0",n=[e.element,e.path].filter(Boolean).join(" "),r=n?` ${n}`:"";return`${t} [${e.rule}]${r}: ${e.message}`}var Xl="custom-elements.json";async function Zl(e=Xl,t={}){let n=t.json?null:Kl(`Checking ${e} against the CEM contract...`).start(),r=g=>{n?n.fail(g):console.error(g),bt.exit(1)},o;try{o=JSON.parse(Uo(In(e),"utf-8"))}catch(g){r(`Could not read or parse ${e}: ${g.message}`)}(typeof o!="object"||o===null||Array.isArray(o))&&r(`Could not read or parse ${e}: not a CEM object.`);let s=o,{pkg:i,version:a}=ql(e),c=[{pkg:i,version:a,manifest:s}],{components:l}=Tn(c),m=[...jo(s),...Bo(l),...Wo(s,Ho(In(e)))],u=m.filter(g=>g.severity==="error"),p=m.filter(g=>g.severity==="warn"),d=u.length>0||!!t.strict&&p.length>0;if(t.json){bt.stdout.write(`${JSON.stringify(m,null,2)}
|
|
249
|
+
`),d&&bt.exit(1);return}let f=`${u.length} error${u.length===1?"":"s"}, ${p.length} warning${p.length===1?"":"s"}`;d?n?.fail(`CEM contract failed \u2014 ${f}.`):p.length>0?n?.warn(`CEM contract passed with warnings \u2014 ${f}.`):n?.succeed("CEM contract clean \u2014 no violations.");for(let g of[...u,...p])console.error(Yl(g));d&&bt.exit(1)}var xy=Vl.command("cem-check [path]").description("Validate a custom-elements.json against the CEM contract (structural + parseability rules, an end-to-end generation smoke, and documentation rules on the JSDoc in the source files it lists). Defaults to ./custom-elements.json.").option("--json","Output the findings as a JSON array on stdout",!1).option("--strict","Treat warnings as errors (any finding fails)",!1).action(Zl);import qn from"node:process";import{program as Gu}from"commander";import Bu from"ora";var be={none:0,patch:1,minor:2,major:3};function Jo(e){let t="none";for(let n of e)be[n]>be[t]&&(t=n);return t}function zo(e,t){return be[e]<be[t]?"fail":t==="none"&&e!=="none"?"warn":"pass"}function Vo(e){let t=new Set;return e.map((n,r)=>({change:n,index:r})).sort((n,r)=>be[r.change.bump]-be[n.change.bump]||n.index-r.index).map(({change:n})=>n).filter(n=>t.has(n.message)?!1:(t.add(n.message),!0))}import{existsSync as Ql,readFileSync as jn}from"node:fs";import{createRequire as Yo}from"node:module";import{join as wt}from"node:path";import{pathToFileURL as eu}from"node:url";var vt="@semantic-release/commit-analyzer",On={preset:"conventionalcommits",releaseRules:[{type:"docs",scope:"README",release:"patch"},{type:"refactor",release:"patch"},{type:"style",release:"patch"}]};function tu(e){for(let t of[".releaserc",".releaserc.json"]){let n=wt(e,t);if(Ql(n))try{return{config:JSON.parse(jn(n,"utf-8")),file:t}}catch{}}try{let t=JSON.parse(jn(wt(e,"package.json"),"utf-8"));if(t.release&&typeof t.release=="object")return{config:t.release,file:"package.json#release"}}catch{}return null}function Ko(e){for(let t of e??[]){if(t===vt)return{};if(Array.isArray(t)&&t[0]===vt)return t[1]??{}}return null}function Xo(e){let t=tu(e);if(!t)return{options:On,source:"default"};let n=Ko(t.config.plugins);if(n)return{options:n,source:t.file};if(t.config.plugins)return{options:On,source:"default"};let r=Yo(wt(e,"package.json")),o=[t.config.extends??[]].flat().reverse();for(let s of o)try{let i=r.resolve(s),a=JSON.parse(jn(i,"utf-8")),c=Ko(a.plugins);if(c)return{options:c,source:s}}catch{}return{options:On,source:"default"}}async function nu(e){let t;try{t=Yo(wt(e,"package.json")).resolve(vt)}catch{throw new Error(`${vt} isn't installed in ${e}. The declared bump is read with the repo's own analyzer, so the check matches the release; run \`npm ci\` first.`)}return(await import(eu(t).href)).analyzeCommits}var ru={log:()=>{}};function qo(e){return e==="major"||e==="minor"||e==="patch"?e:"none"}function ou(e){let t=/^(\w+)(?:\([^)]*\))?(!?):/u.exec(e);return t?`${t[1]}${t[2]}`:null}async function Zo(e,t,n){if(e.length===0)return{bump:"none",commits:[]};let r=await nu(n),o={cwd:n,logger:ru},s=qo(await r(t.options,{...o,commits:e})),i=[];for(let a of[...e].reverse()){let c=a.message.split(`
|
|
250
|
+
`)[0].trim();i.push({hash:a.hash,subject:c,type:ou(c),bump:qo(await r(t.options,{...o,commits:[a]}))})}return{bump:s,commits:i}}import{execFile as su,execFileSync as iu,spawn as au}from"node:child_process";import{existsSync as es,rmSync as cu}from"node:fs";import{mkdtemp as lu,readFile as Ln,rm as uu}from"node:fs/promises";import{constants as mu,tmpdir as pu}from"node:os";import{join as J}from"node:path";import{promisify as du}from"node:util";var fu=du(su);async function me(e,t){let{stdout:n}=await fu("git",t,{cwd:e,maxBuffer:67108864});return n.trim()}function Gn(e,t){return me(e,["rev-parse","--verify",`${t}^{commit}`])}function ts(e,t,n){return me(e,["merge-base",t,n])}async function $t(e,t,n){try{return await me(e,["show",`${t}:${n}`])}catch{return null}}async function ns(e,t,n){let r=await me(e,["diff","--name-only","--no-renames",t,n]);return r?r.split(`
|
|
251
|
+
`):[]}var gu=/^Merge (pull request|branch|remote-tracking branch) /u;async function rs(e,t,n){return(await me(e,["log","--no-merges","--format=%H%x1f%B%x1e",`${t}..${n}`])).split("").map(o=>o.trim()).filter(Boolean).map(o=>{let[s,i=""]=o.split("");return{hash:s.trim(),message:i.trim()}}).filter(o=>!gu.test(o.message))}var Be=new Map,kt=new Set,os=["SIGINT","SIGTERM"];function ss(e){for(let t of kt)hu(t);for(let[t,n]of Be){try{iu("git",["worktree","remove","--force",t],{cwd:n,stdio:"ignore"})}catch{}cu(t,{recursive:!0,force:!0})}process.exit(128+(mu.signals[e]??0))}var is=process.platform!=="win32";function hu(e){try{is&&e.pid?process.kill(-e.pid,"SIGKILL"):e.kill("SIGKILL")}catch{}}function yu(e,t){if(Be.size===0)for(let n of os)process.on(n,ss);Be.set(e,t)}function bu(e){if(Be.delete(e),Be.size===0)for(let t of os)process.off(t,ss)}function _n(e,t){return new Promise((n,r)=>{let o=au(e,{cwd:t,shell:!0,detached:is,stdio:["ignore","pipe","pipe"],env:{...process.env,HUSKY:"0"}});kt.add(o);let s=[];o.stdout?.on("data",i=>s.push(String(i))),o.stderr?.on("data",i=>s.push(String(i))),o.on("error",i=>{kt.delete(o),r(i)}),o.on("close",i=>{if(kt.delete(o),i===0){n();return}let a=s.join("").trim().split(`
|
|
251
252
|
`).slice(-20).join(`
|
|
252
253
|
`);r(new Error(`\`${e}\` exited with ${i}
|
|
253
|
-
${a}`))})})}async function In(e,t,n,r){let o=await jl(Bo(Bl(),"auro-api-diff-"));Jl(o,e);try{return await ce(e,["worktree","add","--detach","--force",o,t]),await Go(r.install,o),await Go(r.build,o),JSON.parse(await _l(Bo(o,n),"utf-8"))}finally{await ce(e,["worktree","remove","--force",o]).catch(()=>{}),await Fl(o,{recursive:!0,force:!0}).catch(()=>{}),Vl(o)}}function Ko(e){let t=new Map;for(let n of e.modules??[])for(let r of n.declarations??[]){let{tagName:o}=r;o&&!t.has(o)&&t.set(o,{tagName:o,className:r.name,declaration:r})}return t}function ge(e){return e.privacy===void 0||e.privacy==="public"}function zl(e){return e.static?`static ${e.name}`:e.name}function Mn(e){let t=e.kind==="field"?"property":e.kind;return e.static?`static ${t}`:t}function Le(e){return e.replace(/['`]/gu,'"').replace(/\s+/gu," ").trim()}function qo(e){let t=[],n=0,r=null,o="";for(let s of e){if(r)s===r&&(r=null);else if(s==='"'||s==="'"||s==="`")r=s;else if("([{<".includes(s))n++;else if(")]}>".includes(s)&&!(s===">"&&o.endsWith("=")))n--;else if(s==="|"&&n===0){t.push(o),o="";continue}o+=s}return t.push(o),t.map(Le).filter(s=>s.length>0)}function Zo(e,t,n){if(t===void 0||n===void 0)return null;let r=qo(t),o=qo(n),s=r.filter(c=>!o.includes(c)),i=o.filter(c=>!r.includes(c));if(s.length===0&&i.length===0)return null;let a=c=>c.map(l=>`\`${l}\``).join(", ");return s.length>0&&i.length>0?{bump:"major",source:"manifest",message:`Changed type of ${e} from \`${Le(t)}\` to \`${Le(n)}\``}:s.length>0?{bump:"major",source:"manifest",message:`Narrowed type of ${e} (removed ${a(s)})`}:{bump:"minor",source:"manifest",message:`Widened type of ${e} (added ${a(i)})`}}function Qo(e,t,n){let r=t===void 0?void 0:Le(t),o=n===void 0?void 0:Le(n);if(r===o)return null;let s;return r===void 0?s=`Added default \`${o}\` to ${e}`:o===void 0?s=`Removed default \`${r}\` from ${e}`:s=`Changed default of ${e} from \`${r}\` to \`${o}\``,{bump:"major",source:"manifest",message:s}}function Yo(e){let t=new Map;for(let n of e.members??[])t.set(zl(n),n);return t}function Xo(e,t){let n=new Map;for(let r of e.attributes??[]){let o=r.fieldName?t.get(r.fieldName):void 0;r.internal||o&&!ge(o)||n.set(r.name,r)}return n}function Kl(e,t,n){let r=[],o=`\`<${e}>\``;for(let[s,i]of t){if(!ge(i))continue;let a=n.get(s),c=Mn(i);if(!a){r.push({bump:"major",source:"manifest",message:`Removed ${c} \`${i.name}\` from ${o}`});continue}if(!ge(a)){r.push({bump:"major",source:"manifest",message:`Made ${c} \`${i.name}\` on ${o} ${a.privacy}`});continue}if(a.kind!==i.kind){r.push({bump:"major",source:"manifest",message:`Changed \`${i.name}\` on ${o} from a ${c} to a ${Mn(a)}`});continue}if(i.kind!=="field")continue;let l=`${c} \`${i.name}\` on ${o}`;i.reflects&&!a.reflects&&r.push({bump:"major",source:"manifest",message:`Attribute \`${i.attribute??i.name}\` on ${o} no longer reflects`});for(let m of[Zo(l,i.type?.text,a.type?.text),Qo(l,i.default,a.default)])m&&r.push(m)}for(let[s,i]of n){if(!ge(i))continue;let a=t.get(s),c=Mn(i);a?ge(a)||r.push({bump:"minor",source:"manifest",message:`Made ${a.privacy} ${c} \`${i.name}\` on ${o} public`}):r.push({bump:"minor",source:"manifest",message:`Added ${c} \`${i.name}\` to ${o}`})}return r}function ql(e,t,n,r,o){let s=[],i=`\`<${e}>\``,a=Xo(t,r),c=Xo(n,o),l=new Set((n.attributes??[]).map(p=>p.name)),m=new Set((t.attributes??[]).map(p=>p.name)),u=(p,f)=>{let d=p.fieldName?f.get(p.fieldName):void 0;return d!==void 0&&ge(d)};for(let[p,f]of a){let d=c.get(p);if(!d){s.push({bump:"major",source:"manifest",message:l.has(p)?`Made attribute \`${p}\` on ${i} private`:`Removed attribute \`${p}\` from ${i}`});continue}if(u(f,r)||u(d,o))continue;let h=`attribute \`${p}\` on ${i}`;for(let g of[Zo(h,f.type?.text,d.type?.text),Qo(h,f.default,d.default)])g&&s.push(g)}for(let p of c.keys())a.has(p)||s.push({bump:"minor",source:"manifest",message:m.has(p)?`Made private attribute \`${p}\` on ${i} public`:`Added attribute \`${p}\` to ${i}`});return s}function kt(e,t,n,r){let o=l=>t==="slot"&&l===""?"default slot":`${t} \`${l}\``,s=`\`<${e}>\``,i=new Set((n??[]).map(l=>l.name)),a=new Set((r??[]).map(l=>l.name)),c=[];for(let l of i)a.has(l)||c.push({bump:"major",source:"manifest",message:`Removed ${o(l)} from ${s}`});for(let l of a)i.has(l)||c.push({bump:"minor",source:"manifest",message:`Added ${o(l)} to ${s}`});return c}function Yl(e,t,n){let r=Yo(t),o=Yo(n);return[...ql(e,t,n,r,o),...Kl(e,r,o),...kt(e,"event",t.events,n.events),...kt(e,"slot",t.slots,n.slots),...kt(e,"CSS part",t.cssParts,n.cssParts),...kt(e,"CSS custom property",t.cssProperties,n.cssProperties)]}function es(e,t){let n=Ko(e),r=Ko(t),o=[],s=new Map;for(let[a,c]of n){if(r.has(a))continue;let l=[...r.values()].find(m=>m.className===c.className&&!n.has(m.tagName));l&&s.set(a,l.tagName)}let i=new Set(s.values());for(let[a,c]of n){let l=r.get(a);if(l){o.push(...Yl(a,c.declaration,l.declaration));continue}let m=s.get(a);o.push({bump:"major",source:"manifest",message:m?`Renamed element \`<${a}>\` to \`<${m}>\``:`Removed element \`<${a}>\``})}for(let a of r.keys())!n.has(a)&&!i.has(a)&&o.push({bump:"minor",source:"manifest",message:`Added element \`<${a}>\``});return o}import Et from"semver";function ts(e){if(e==null)return new Set;if(typeof e=="object"&&!Array.isArray(e)){let t=Object.keys(e);if(t.every(n=>n.startsWith(".")))return new Set(t)}return new Set(["."])}function ns(e){try{let t=Et.minVersion(e);return t?t.major>0?`${t.major}`:`0.${t.minor}`:null}catch{return null}}function rs(e,t={},n={}){let r=[];for(let[o,s]of Object.entries(n)){let i=t[o];if(i===void 0)continue;let a=ns(i),c=ns(s);a!==null&&c!==null&&a!==c&&r.push({bump:"major",source:"package",message:`Bumped ${e} \`${o}\` from \`${i}\` to \`${s}\``})}return r}function Xl(e={},t={}){let n=[];for(let[r,o]of Object.entries(t)){let s=e[r],i=`engine \`${r}\``;if(s===void 0){n.push({bump:"major",source:"package",message:`Added ${i} requirement \`${o}\``});continue}let a=null,c=null;try{a=Et.minVersion(s),c=Et.minVersion(o)}catch{continue}a&&c&&Et.gt(c,a)&&n.push({bump:"major",source:"package",message:`Tightened ${i} from \`${s}\` to \`${o}\``})}return n}function os(e,t){let n=[],r=ts(e.exports),o=ts(t.exports),s=e.exports===void 0&&t.exports!==void 0;s&&n.push({bump:"major",source:"package",message:"Added `exports`, which blocks imports of unlisted paths"});for(let a of r)o.has(a)||n.push({bump:"major",source:"package",message:`Removed export \`${a}\``});for(let a of o)!s&&!r.has(a)&&n.push({bump:"minor",source:"package",message:`Added export \`${a}\``});for(let a of["main","types","typings"])e[a]!==void 0&&t[a]===void 0&&n.push({bump:"major",source:"package",message:`Removed \`${a}\` (\`${e[a]}\`)`});let i=new Set(t.files??[]);for(let a of e.files??[])i.has(a)||n.push({bump:"major",source:"package",message:`Removed \`files\` entry \`${a}\``});return n.push(...rs("peer dependency",e.peerDependencies,t.peerDependencies),...rs("dependency",e.dependencies,t.dependencies),...Xl(e.engines,t.engines)),n}var Zl=["test/","tests/",".github/","docs/"];function On(e){return Zl.some(t=>e.startsWith(t))}function Ql(e){return On(e)?!1:/(^|\/)(src|demo)\//u.test(e)||/(^|\/)README\.md$/u.test(e)}function ss(e){let t=e.filter(Ql);if(t.length===0)return[];let n=t.slice(0,5).map(o=>`\`${o}\``),r=t.length>n.length?` and ${t.length-n.length} more`:"";return[{bump:"patch",source:"files",message:`Changed published files: ${n.join(", ")}${r}`}]}var $t={install:"npm ci --no-audit --no-fund",build:"npm run build"},eu="custom-elements.json";function jn(e){if(e===null)return null;try{return JSON.parse(e)}catch{return null}}function tu(e){return e.charAt(0).toLowerCase()+e.slice(1)}function nu(e,t,n,r){let o="Commits declare no release.";if(e!=="none"){let c=[...new Set(r.filter(m=>m.bump===e).map(m=>m.type??"breaking change"))];o=`Commits declare ${c.length?c.map(m=>`\`${m}\``).join(", "):"a release"} (${e}).`}if(t==="none")return`${o} Code requires no release.`;let s=n.filter(c=>c.bump===t).map(c=>tu(c.message)),i=s.slice(0,3).join("; "),a=s.length>3?`; and ${s.length-3} more`:"";return`${o} Code requires ${t}: ${i}${a}.`}async function ru(e,t,n,r,o,s,i){let a=async m=>jn(await vt(e,m,r)),c;if(o)try{c=await In(e,n,r,s)}catch(m){throw new Error(`Could not build ${r} at the head ref: ${m.message}`)}else c=await a(n);let l=null;if(o)try{l=await In(e,t,r,s)}catch(m){l=await a(t),i.push(l?`The base ref didn't build, so its committed ${r} was used: ${m.message.split(`
|
|
254
|
-
`)[0]}`:`The base ref didn't build and has no committed ${
|
|
255
|
-
`)
|
|
256
|
-
|
|
254
|
+
${a}`))})})}var Et="@aurodesignsystem/auro-cli",Bn="@custom-elements-manifest/analyzer";function Fn(e,t){for(let n of[J(e,"node_modules",t),J(e,"node_modules",Et,"node_modules",t)])if(es(J(n,"package.json")))return n;return null}async function Qo(e,t){let n=Fn(e,t);if(n)return JSON.parse(await Ln(J(n,"package.json"),"utf-8")).version}function as(e,t){return e.auroCli!==t.auroCli||e.analyzer!==t.analyzer}async function wu(e){let t=await Qo(e,Et),n=await Qo(e,Bn);return t||n?{auroCli:t,analyzer:n}:null}async function vu(e){if(JSON.parse(await Ln(J(e,"package.json"),"utf-8")).scripts?.analyze)return"npm run analyze";let n=Fn(e,Et),r=Fn(e,Bn),o=n?J(n,"dist","configs","custom-elements-manifest.config.mjs"):null;return!o||!es(o)||!r?null:`node "${J(r,"cem.js")}" analyze --config "${o}"`}async function St(e,t,n,r,o){let s=await lu(J(pu(),"auro-api-diff-"));yu(s,e);try{if(await me(e,["worktree","add","--detach","--force",s,t]),await _n(r.install,s),o){let c=[o.auroCli&&`${Et}@${o.auroCli}`,o.analyzer&&`${Bn}@${o.analyzer}`].filter(Boolean);await _n(`${r.pin} ${c.join(" ")}`,s)}let i=await wu(s),a=o?await vu(s):null;return await _n(a??r.build,s),{manifest:JSON.parse(await Ln(J(s,n),"utf-8")),generator:i}}finally{await me(e,["worktree","remove","--force",s]).catch(()=>{}),await uu(s,{recursive:!0,force:!0}).catch(()=>{}),bu(s)}}function cs(e){let t=new Map;for(let n of e.modules??[])for(let r of n.declarations??[]){let{tagName:o}=r;o&&!t.has(o)&&t.set(o,{tagName:o,className:r.name,declaration:r})}return t}function we(e){return e.privacy===void 0||e.privacy==="public"}function ku(e){return e.static?`static ${e.name}`:e.name}function Wn(e){let t=e.kind==="field"?"property":e.kind;return e.static?`static ${t}`:t}function At(e){return e.replace(/['`]/gu,'"').replace(/\s+/gu," ").trim()}function $u(e){let t=At(e),n=/^\{\s*("[^"]*"|-?\d+(?:\.\d+)?|true|false|null|undefined)\s*\}$/u.exec(t);return n?n[1]:t}function ls(e){let t=[],n=0,r=null,o="";for(let i of e){if(r)i===r&&(r=null);else if(i==='"'||i==="'"||i==="`")r=i;else if("([{<".includes(i))n++;else if(")]}>".includes(i)&&!(i===">"&&o.endsWith("=")))n--;else if((i==="|"||i===",")&&n===0){t.push(o),o="";continue}o+=i}t.push(o);let s={String:"string",Number:"number",Boolean:"boolean"};return t.map(At).filter(i=>i.length>0).map(i=>s[i]??i)}function Eu(e){return/^".*"$/u.test(e)?"string":/^-?\d+(?:\.\d+)?$/u.test(e)?"number":e==="true"||e==="false"?"boolean":null}function us(e,t){let n=Eu(t);return e.includes(t)||n!==null&&e.includes(n)}function Un(e,t,n){if(t===void 0||n===void 0)return null;let r=ls(t),o=ls(n),s=r.filter(c=>!us(o,c)),i=o.filter(c=>!us(r,c));if(s.length===0&&i.length===0)return null;let a=c=>c.map(l=>`\`${l}\``).join(", ");return s.length>0&&i.length>0?{bump:"major",source:"manifest",message:`Changed type of ${e} from \`${At(t)}\` to \`${At(n)}\``}:s.length>0?{bump:"major",source:"manifest",message:`Narrowed type of ${e} (removed ${a(s)})`}:{bump:"minor",source:"manifest",message:`Widened type of ${e} (added ${a(i)})`}}function ds(e,t,n){let r=i=>{let a=i===void 0?void 0:$u(i);return a==="undefined"?void 0:a},o=r(t),s=r(n);return o===s?null:o===void 0?{bump:"minor",source:"manifest",message:`Added default \`${s}\` to ${e}`}:s===void 0?{bump:"minor",source:"manifest",message:`Removed default \`${o}\` from ${e}`}:{bump:"major",source:"manifest",message:`Changed default of ${e} from \`${o}\` to \`${s}\``}}function Hn(e){return typeof e.name=="string"&&e.name!==""}function Jn(e,t,n){let r=[],o=(c,l)=>r.push({bump:c,source:"manifest",message:l}),s=t.requiredWhen,i=n.requiredWhen;s!==i&&(s===void 0?o("major",`Made ${e} required when \`${i}\``):i===void 0?o("minor",`Made ${e} no longer required`):s==="always"?o("minor",`Made ${e} required only when \`${i}\``):o("major",`Changed when ${e} is required from \`${s}\` to \`${i}\``));let a=(c,l)=>{let m=t[c],u=n[c];if(m===u)return;let p=c==="minimum"?"minimum":"maximum";m===void 0?o("major",`Added ${p} \`${u}\` to ${e}`):u===void 0?o("minor",`Removed ${p} \`${m}\` from ${e}`):l(u,m)?o("major",`Tightened ${p} of ${e} from \`${m}\` to \`${u}\``):o("minor",`Loosened ${p} of ${e} from \`${m}\` to \`${u}\``)};a("minimum",(c,l)=>c>l),a("maximum",(c,l)=>c<l),!t.readonly&&n.readonly?o("major",`Made ${e} read-only`):t.readonly&&!n.readonly&&o("minor",`Made ${e} writable`),!t.deprecated&&n.deprecated?o("minor",`Deprecated ${e}`):t.deprecated&&!n.deprecated&&o("minor",`Removed the deprecation of ${e}`);for(let c of["relevantWhen","category"]){let l=t[c],m=n[c];l!==m&&(l===void 0?o("minor",`Added \`${c}\` \`${m}\` to ${e}`):m===void 0?o("minor",`Removed \`${c}\` \`${l}\` from ${e}`):o("minor",`Changed \`${c}\` of ${e} from \`${l}\` to \`${m}\``))}return r}function Su(e,t=[],n=[]){let r=[],o=(i,a)=>r.push({bump:i,source:"manifest",message:a}),s=i=>!!(i.optional||i.rest);for(let i=0;i<Math.max(t.length,n.length);i++){let a=t[i],c=n[i];if(a&&!c)o("major",`Removed parameter \`${a.name}\` from ${e}`);else if(!a&&c)o(s(c)?"minor":"major",`Added ${s(c)?"optional":"required"} parameter \`${c.name}\` to ${e}`);else if(a&&c){let l=`parameter \`${c.name}\` of ${e}`;s(a)&&!s(c)?o("major",`Made ${l} required`):!s(a)&&s(c)&&o("minor",`Made ${l} optional`);let m=Un(l,a.type?.text,c.type?.text);m&&r.push(m)}}return r}function ms(e){let t=new Map;for(let n of e.members??[])Hn(n)&&t.set(ku(n),n);return t}function ps(e,t){let n=new Map;for(let r of e.attributes??[]){let o=r.fieldName?t.get(r.fieldName):void 0;!Hn(r)||r.internal||o&&!we(o)||n.set(r.name.toLowerCase(),r)}return n}function Cu(e,t,n){let r=[],o=`\`<${e}>\``;for(let[s,i]of t){if(!we(i))continue;let a=n.get(s),c=Wn(i);if(!a){r.push({bump:"major",source:"manifest",message:`Removed ${c} \`${i.name}\` from ${o}`});continue}if(!we(a)){r.push({bump:"major",source:"manifest",message:`Made ${c} \`${i.name}\` on ${o} ${a.privacy}`});continue}if(a.kind!==i.kind){r.push({bump:"major",source:"manifest",message:`Changed \`${i.name}\` on ${o} from a ${c} to a ${Wn(a)}`});continue}let l=`${c} \`${i.name}\` on ${o}`;if(r.push(...Jn(l,i,a)),i.kind==="method"&&r.push(...Su(l,i.parameters,a.parameters)),i.kind==="field"){i.reflects&&!a.reflects&&r.push({bump:"major",source:"manifest",message:`Attribute \`${i.attribute??i.name}\` on ${o} no longer reflects`});for(let m of[Un(l,i.type?.text,a.type?.text),ds(l,i.default,a.default)])m&&r.push(m)}}for(let[s,i]of n){if(!we(i))continue;let a=t.get(s),c=Wn(i);a?we(a)||r.push({bump:"minor",source:"manifest",message:`Made ${a.privacy} ${c} \`${i.name}\` on ${o} public`}):r.push({bump:"minor",source:"manifest",message:`Added ${c} \`${i.name}\` to ${o}`})}return r}function Au(e,t,n,r,o){let s=[],i=`\`<${e}>\``,a=ps(t,r),c=ps(n,o),l=d=>new Set((d.attributes??[]).filter(Hn).map(f=>f.name.toLowerCase())),m=l(n),u=l(t),p=(d,f)=>{let g=d.fieldName?f.get(d.fieldName):void 0;return g!==void 0&&we(g)};for(let[d,f]of a){let{name:g}=f,h=c.get(d);if(!h){s.push({bump:"major",source:"manifest",message:m.has(d)?`Made attribute \`${g}\` on ${i} private`:`Removed attribute \`${g}\` from ${i}`});continue}if(p(f,r)||p(h,o))continue;let b=`attribute \`${g}\` on ${i}`;for(let v of[Un(b,f.type?.text,h.type?.text),ds(b,f.default,h.default)])v&&s.push(v);s.push(...Jn(b,f,h))}for(let[d,{name:f}]of c)a.has(d)||s.push({bump:"minor",source:"manifest",message:u.has(d)?`Made private attribute \`${f}\` on ${i} public`:`Added attribute \`${f}\` to ${i}`});return s}function Ct(e,t,n,r){let o=m=>t==="slot"&&m===""?"default slot":`${t} \`${m}\``,s=`\`<${e}>\``,i=m=>new Set((m??[]).map(u=>u.name).filter(u=>typeof u=="string")),a=i(n),c=i(r),l=[];for(let m of a)c.has(m)||l.push({bump:"major",source:"manifest",message:`Removed ${o(m)} from ${s}`});for(let m of c)a.has(m)||l.push({bump:"minor",source:"manifest",message:`Added ${o(m)} to ${s}`});return l}function xu(e,t,n){let r=new Map((n.slots??[]).map(o=>[o.name,o]));return(t.slots??[]).flatMap(o=>{let s=r.get(o.name);if(typeof o.name!="string"||!s)return[];let i=o.name===""?`default slot of \`<${e}>\``:`slot \`${o.name}\` on \`<${e}>\``;return Jn(i,o,s)})}function Tu(e,t,n){let r=ms(t),o=ms(n);return[...xu(e,t,n),...Au(e,t,n,r,o),...Cu(e,r,o),...Ct(e,"event",t.events,n.events),...Ct(e,"slot",t.slots,n.slots),...Ct(e,"CSS part",t.cssParts,n.cssParts),...Ct(e,"CSS custom property",t.cssProperties,n.cssProperties)]}function zn(e,t){let n=cs(e),r=cs(t),o=[],s=new Map;for(let[a,c]of n){if(r.has(a))continue;let l=[...r.values()].find(m=>m.className===c.className&&!n.has(m.tagName));l&&s.set(a,l.tagName)}let i=new Set(s.values());for(let[a,c]of n){let l=r.get(a);if(l){o.push(...Tu(a,c.declaration,l.declaration));continue}let m=s.get(a);o.push({bump:"major",source:"manifest",message:m?`Renamed element \`<${a}>\` to \`<${m}>\``:`Removed element \`<${a}>\``})}for(let a of r.keys())!n.has(a)&&!i.has(a)&&o.push({bump:"minor",source:"manifest",message:`Added element \`<${a}>\``});return o}import xt from"semver";function fs(e){if(e==null)return new Set;if(typeof e=="object"&&!Array.isArray(e)){let t=Object.keys(e);if(t.every(n=>n.startsWith(".")))return new Set(t)}return new Set(["."])}function Ru(e,t){let n=e;if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let s=e;Object.keys(s).every(i=>i.startsWith("."))&&(n=s[t])}let r=[],o=s=>{typeof s=="string"?r.push(s):Array.isArray(s)?s.forEach(o):s&&typeof s=="object"&&Object.values(s).forEach(o)};return o(n),r}var Pu=/^(package-lock\.json|\.npmrc|node_modules\/|\.git\/)/u,Du=/^(package\.json|readme(\.[^/]*)?|licen[cs]e(\.[^/]*)?)$/iu;function gs(e){let t=e.indexOf("*");return t===-1?e:e.slice(0,t)}function Mu(e,t){let n=e.replace(/^\.\//u,"");if(Pu.test(n))return!1;if(!t||Du.test(n))return!0;let r=gs(n);return t.some(o=>{let s=o.replace(/^\.\//u,"").replace(/\/$/u,"");return s.includes("*")?r.startsWith(gs(s)):n===s||n.startsWith(`${s}/`)})}function hs(e,t){return Ru(e.exports,t).some(n=>Mu(n,e.files))}function ys(e){try{let t=xt.minVersion(e);return t?t.major>0?`${t.major}`:`0.${t.minor}`:null}catch{return null}}function bs(e,t={},n={}){let r=[];for(let[o,s]of Object.entries(n)){let i=t[o];if(i===void 0)continue;let a=ys(i),c=ys(s);a!==null&&c!==null&&a!==c&&r.push({bump:"major",source:"package",message:`Bumped ${e} \`${o}\` from \`${i}\` to \`${s}\``})}return r}function Nu(e={},t={}){let n=[];for(let[r,o]of Object.entries(t)){let s=e[r],i=`engine \`${r}\``;if(s===void 0){n.push({bump:"major",source:"package",message:`Added ${i} requirement \`${o}\``});continue}let a=null,c=null;try{a=xt.minVersion(s),c=xt.minVersion(o)}catch{continue}a&&c&&xt.gt(c,a)&&n.push({bump:"major",source:"package",message:`Tightened ${i} from \`${s}\` to \`${o}\``})}return n}function ws(e,t){let n=[],r=fs(e.exports),o=fs(t.exports),s=e.exports===void 0&&t.exports!==void 0;s&&n.push({bump:"major",source:"package",message:"Added `exports`, which blocks imports of unlisted paths"});for(let a of r)o.has(a)||n.push(hs(e,a)?{bump:"major",source:"package",message:`Removed export \`${a}\``}:{bump:"patch",source:"package",message:`Removed export \`${a}\`, which never resolved: its target isn't in the published package`});for(let a of o)!s&&!r.has(a)&&n.push(hs(t,a)?{bump:"minor",source:"package",message:`Added export \`${a}\``}:{bump:"patch",source:"package",message:`Added export \`${a}\`, which won't resolve: its target isn't in the published package`});for(let a of["main","types","typings"])e[a]!==void 0&&t[a]===void 0&&n.push({bump:"major",source:"package",message:`Removed \`${a}\` (\`${e[a]}\`)`});let i=new Set(t.files??[]);for(let a of e.files??[])i.has(a)||n.push({bump:"major",source:"package",message:`Removed \`files\` entry \`${a}\``});return n.push(...bs("peer dependency",e.peerDependencies,t.peerDependencies),...bs("dependency",e.dependencies,t.dependencies),...Nu(e.engines,t.engines)),n}var Iu=["test/","tests/",".github/","docs/"];function Vn(e){return Iu.some(t=>e.startsWith(t))}function Ou(e){return Vn(e)?!1:/(^|\/)(src|demo)\//u.test(e)||/(^|\/)README\.md$/u.test(e)}function vs(e){let t=e.filter(Ou);if(t.length===0)return[];let n=t.slice(0,5).map(o=>`\`${o}\``),r=t.length>n.length?` and ${t.length-n.length} more`:"";return[{bump:"patch",source:"files",message:`Changed published files: ${n.join(", ")}${r}`}]}var Tt={install:"npm ci --no-audit --no-fund",build:"npm run build",pin:"npm install --no-save --no-audit --no-fund"},ju="custom-elements.json";function Kn(e){if(e===null)return null;try{return JSON.parse(e)}catch{return null}}function _u(e){return e.charAt(0).toLowerCase()+e.slice(1)}function Fu(e,t,n,r){let o="Commits declare no release.";if(e!=="none"){let c=[...new Set(r.filter(m=>m.bump===e).map(m=>m.type??"breaking change"))];o=`Commits declare ${c.length?c.map(m=>`\`${m}\``).join(", "):"a release"} (${e}).`}if(t==="none")return`${o} Code requires no release.`;let s=n.filter(c=>c.bump===t).map(c=>_u(c.message)),i=s.slice(0,3).join("; "),a=s.length>3?`; and ${s.length-3} more`:"";return`${o} Code requires ${t}: ${i}${a}.`}async function Lu(e,t,n){let{baseSha:r,headSha:o,manifestPath:s,rebuild:i,commands:a}=t,c=async d=>Kn(await $t(e,d,s)),l={manifests:null,baseWithHeadGenerator:null,generators:null};if(!i){let d=await c(o),f=await c(r);return!d||!f?(n.push(`No ${s} at the ${d?"base":"head"} ref, so the public API wasn't compared.`),l):{...l,manifests:{base:f,head:d}}}let m;try{m=await St(e,o,s,a)}catch(d){throw new Error(`Could not build ${s} at the head ref: ${d.message}`)}let u=null;try{u=await St(e,r,s,a)}catch(d){let f=await c(r);if(n.push(f?`The base ref didn't build, so its committed ${s} was used: ${d.message.split(`
|
|
255
|
+
`)[0]}`:`The base ref didn't build and has no committed ${s}, so the public API wasn't compared.`),!f)return{...l,generators:{base:null,head:m.generator}};u={manifest:f,generator:null}}let p=null;if(m.generator&&u.generator&&as(u.generator,m.generator))try{p=(await St(e,r,s,a,m.generator)).manifest}catch(d){n.push(`The base didn't build with the head's generator, so changes couldn't be split between the code and the generator upgrade: ${d.message.split(`
|
|
256
|
+
`)[0]}`)}return{manifests:{base:u.manifest,head:m.manifest},baseWithHeadGenerator:p,generators:{base:u.generator,head:m.generator}}}function ks(e){return e?e.auroCli?`auro-cli ${e.auroCli}`:`analyzer ${e.analyzer}`:"unknown"}async function $s(e,t="HEAD",n={}){let r=n.cwd??process.cwd(),o=n.rebuild??!0,s={...Tt,...n.commands},i=[],a=await Gn(r,e),c=await Gn(r,t),l=await ts(r,a,c),m=await ns(r,l,c),u=Kn(await $t(r,l,"package.json"))??{},p=Kn(await $t(r,c,"package.json"))??{},d=n.manifest??p.customElements??ju,f=[],g=null,h=0;if(m.some(w=>!Vn(w))){let w=n.manifests?{manifests:n.manifests,baseWithHeadGenerator:null,generators:null}:await Lu(r,{baseSha:l,headSha:c,manifestPath:d,rebuild:o,commands:s},i);if(g=w.generators,w.manifests){let te=zn(w.manifests.base,w.manifests.head);if(w.baseWithHeadGenerator){let ne=new Set(zn(w.baseWithHeadGenerator,w.manifests.head).map(fe=>fe.message));for(let fe of te)fe.cause=ne.has(fe.message)?"code":"generator";h=te.filter(fe=>fe.cause==="generator").length}f.push(...te)}}f.push(...ws(u,p),...vs(m));let b=Vo(f),v=Jo(b.map(w=>w.bump)),j=Xo(r),A=await rs(r,l,c),k=await Zo(A,j,r);A.length>0&&j.source==="default"&&i.push("The repo's release config couldn't be resolved, so commits were read with the shared auro-config rules, which may differ from how the repo releases.");let y=Fu(k.bump,v,b,k.commits);return h>0&&g&&(y+=` ${h} of the manifest changes come from upgrading ${ks(g.base)} to ${ks(g.head)}, not from the component's code; they still change the published manifest.`),{required:v,reasons:b.map(w=>w.message),declared:k.bump,outcome:zo(k.bump,v),summary:y,base:a,head:c,mergeBase:l,changes:b,commits:k.commits,releaseConfig:j.source,generators:g,warnings:i}}var Wu={pass:"\u2714",warn:"\u26A0",fail:"\u2716"};async function Uu(e,t,n={}){let r=n.json?null:Bu(`Comparing ${e}...${t??"HEAD"}...`).start(),o;try{o=await $s(e,t,{rebuild:n.rebuild,manifest:n.manifest,commands:{install:n.installCommand,build:n.buildCommand}})}catch(i){let a=`api-diff failed: ${i.message}`;r?r.fail(a):console.error(a),qn.exit(2)}let s=!!n.enforce&&o.outcome==="fail";if(n.json)qn.stdout.write(`${JSON.stringify(o,null,2)}
|
|
257
|
+
`);else{if(r?.stop(),console.error(`${Wu[o.outcome]} ${o.summary}`),o.changes.length>0){console.error(`
|
|
258
|
+
Changes:`);for(let i of o.changes){let a=i.cause==="generator"?" (generator upgrade)":"";console.error(` [${i.bump}] ${i.message}${a}`)}}if(o.commits.length>0){console.error(`
|
|
257
259
|
Commits:`);for(let i of o.commits)console.error(` [${i.bump}] ${i.hash.slice(0,7)} ${i.subject}`)}for(let i of o.warnings)console.error(`
|
|
258
|
-
\u26A0 ${i}`)}s&&
|
|
259
|
-
|---|---|---|`,
|
|
260
|
-
`)}var
|
|
260
|
+
\u26A0 ${i}`)}s&&qn.exit(1)}var tb=Gu.command("api-diff <baseRef> [headRef]").description("Work out the smallest version bump the changes from baseRef to headRef (default HEAD) require, and check the commits declare at least that much.").option("--json","Output the result as JSON on stdout",!1).option("--enforce","Exit 1 when the commits declare a smaller bump than the code requires",!1).option("--no-rebuild","Compare the committed custom-elements.json files instead of rebuilding them").option("--manifest <path>","Manifest path relative to the repo root (default: package.json customElements, else custom-elements.json)").option("--install-command <cmd>","Command that installs dependencies in each rebuilt checkout",Tt.install).option("--build-command <cmd>","Command that writes the manifest in each rebuilt checkout",Tt.build).action(Uu);import Xu from"node:fs/promises";import Zu from"node:path";import{program as Qu}from"commander";import tr from"ora";var Hu='# Auro Design System \u2014 AI Assistant Context\nAlaska Airlines open-source design system | https://auro.alaskaair.com\n\n## What is Auro?\nAuro is Alaska Airlines\' design system built on Web Components (Custom Elements v1) using the Lit library.\n- npm scope: `@aurodesignsystem/` (current), `@alaskaairux/` (legacy)\n- Framework-agnostic: works with React, Angular, Vue, Svelte, or plain HTML\n- Each component is a separate npm package\n- All components use the `<auro-*>` custom element tag\n\n## Rules for Writing Auro Code\n\n1. **Use `<auro-*>` custom element tags \u2014 never plain HTML equivalents**\n - \u2717 `<button>` \u2192 \u2713 `<auro-button>`\n - \u2717 `<a href="...">` \u2192 \u2713 `<auro-hyperlink href="...">`\n - \u2717 `<input>` \u2192 \u2713 `<auro-input>` (from auro-formkit)\n\n2. **Install and register each component before use**\n ```bash\n npm install @aurodesignsystem/auro-button\n ```\n ```js\n import "@aurodesignsystem/auro-button"; // registers <auro-button> globally\n ```\n\n3. **Props are HTML attributes in templates; camelCase properties in JS**\n ```html\n <auro-button disabled loading>Save</auro-button>\n ```\n ```js\n document.querySelector(\'auro-button\').loading = true;\n ```\n\n4. **Content goes in named slots, not innerHTML**\n ```html\n <auro-dialog>\n <span slot="header">Title</span>\n <div slot="content">Body content here</div>\n </auro-dialog>\n ```\n\n5. **Design tokens are CSS custom properties**\n ```bash\n npm install @aurodesignsystem/design-tokens\n ```\n ```css\n @import "@aurodesignsystem/design-tokens/dist/themes/CSSCustomProperties--bundled.css";\n ```\n Token naming: `--ds-basic-*` and `--ds-advanced-*` (e.g. `--ds-advanced-color-*`, `--ds-basic-color-*`)\n\n## Component Reference\n\n',Ju=`| Element Tag | Package | Description |
|
|
261
|
+
|---|---|---|`,Yn=[{tag:"auro-accordion",pkg:"@aurodesignsystem/auro-accordion",description:"Expandable content sections"},{tag:"auro-alert",pkg:"@aurodesignsystem/auro-alert",description:"Inline status messages: error, warning, success, information"},{tag:"auro-avatar",pkg:"@aurodesignsystem/auro-avatar",description:"User or entity avatar"},{tag:"auro-background",pkg:"@aurodesignsystem/auro-background",description:"Themed background wrapper"},{tag:"auro-backtotop",pkg:"@aurodesignsystem/auro-backtotop",description:"Scroll-to-top button"},{tag:"auro-badge",pkg:"@aurodesignsystem/auro-badge",description:"Status or count badge"},{tag:"auro-banner",pkg:"@aurodesignsystem/auro-banner",description:"Full-width promotional banner"},{tag:"auro-button",pkg:"@aurodesignsystem/auro-button",description:"Interactive button; supports `loading`, `disabled`, `shape`"},{tag:"auro-card",pkg:"@aurodesignsystem/auro-card",description:"Content card container"},{tag:"auro-carousel",pkg:"@aurodesignsystem/auro-carousel",description:"Horizontally scrollable carousel"},{tag:"auro-datetime",pkg:"@aurodesignsystem/auro-datetime",description:"Localized date and time formatting"},{tag:"auro-dialog",pkg:"@aurodesignsystem/auro-dialog",description:"Modal dialog; slots: header, content, footer"},{tag:"auro-drawer",pkg:"@aurodesignsystem/auro-drawer",description:"Slide-in panel; slots: header, content, footer"},{tag:"auro-flight",pkg:"@aurodesignsystem/auro-flight",description:"Flight segment display (origin, destination, stops)"},{tag:"auro-flightline",pkg:"@aurodesignsystem/auro-flightline",description:"Visual flight path/stop indicator"},{tag:"auro-input",pkg:"@aurodesignsystem/auro-formkit",description:"Text input field"},{tag:"auro-select",pkg:"@aurodesignsystem/auro-formkit",description:"Select/dropdown"},{tag:"auro-datepicker",pkg:"@aurodesignsystem/auro-formkit",description:"Date picker input"},{tag:"auro-combobox",pkg:"@aurodesignsystem/auro-formkit",description:"Combobox with search"},{tag:"auro-checkbox",pkg:"@aurodesignsystem/auro-formkit",description:"Checkbox input"},{tag:"auro-radio",pkg:"@aurodesignsystem/auro-formkit",description:"Radio button input"},{tag:"auro-header",pkg:"@aurodesignsystem/auro-header",description:"Page/section heading"},{tag:"auro-hyperlink",pkg:"@aurodesignsystem/auro-hyperlink",description:"Accessible anchor link"},{tag:"auro-icon",pkg:"@aurodesignsystem/auro-icon",description:"Alaska Airlines icon: `category` + `name` attributes"},{tag:"auro-loader",pkg:"@aurodesignsystem/auro-loader",description:"Loading spinner"},{tag:"auro-lockup",pkg:"@aurodesignsystem/auro-lockup",description:"Image + text layout lockup"},{tag:"auro-nav",pkg:"@aurodesignsystem/auro-nav",description:"Secondary navigation aid (relation to higher-level pages)"},{tag:"auro-pane",pkg:"@aurodesignsystem/auro-pane",description:"Selectable shoulder dates with associated prices"},{tag:"auro-popover",pkg:"@aurodesignsystem/auro-popover",description:"Tooltip-style popover"},{tag:"auro-sidenav",pkg:"@aurodesignsystem/auro-sidenav",description:"Vertical side navigation"},{tag:"auro-skeleton",pkg:"@aurodesignsystem/auro-skeleton",description:"Loading placeholder skeleton"},{tag:"auro-slideshow",pkg:"@aurodesignsystem/auro-slideshow",description:"Image/content slideshow"},{tag:"auro-table",pkg:"@aurodesignsystem/auro-table",description:"Accessible data table"},{tag:"auro-tabs",pkg:"@aurodesignsystem/auro-tabs",description:"Tabbed content panels"},{tag:"auro-tail",pkg:"@aurodesignsystem/auro-tail",description:"Alaska, Hawaiian, and partner airline tail graphics"},{tag:"auro-toast",pkg:"@aurodesignsystem/auro-toast",description:"Transient notification toast"},{tag:"auro-tokenlist",pkg:"@aurodesignsystem/auro-tokenlist",description:"Design token display utilities"}];function Xn(e){return e.map(t=>`| \`<${t.tag}>\` | \`${t.pkg}\` | ${t.description.replace(/\|/gu,"\\|")} |`).join(`
|
|
262
|
+
`)}var zu=Xn(Yn),Vu=`## Common Patterns
|
|
261
263
|
|
|
262
264
|
### Button (default, secondary, tertiary)
|
|
263
265
|
\`\`\`html
|
|
@@ -335,14 +337,14 @@ document.querySelector('#confirmDialog').show();
|
|
|
335
337
|
- Design tokens: https://auro.alaskaair.com/getting-started/developers/token-usage
|
|
336
338
|
- Contributing: https://auro.alaskaair.com/getting-started/developers/contributing
|
|
337
339
|
- GitHub: https://github.com/AlaskaAirlines
|
|
338
|
-
`;function
|
|
340
|
+
`;function Zn(e){return`${Hu}${Ju}
|
|
339
341
|
${e}
|
|
340
342
|
|
|
341
|
-
${
|
|
342
|
-
`)}async function
|
|
343
|
-
Paste this file into your AI coding tool (Claude, Cursor, Copilot, etc.) to prime it on Auro components.`)}catch(l){let m=l instanceof Error?l.message:String(l);c.fail(`Failed to write context: ${m}`),process.exit(1)}}else process.stdout.write(a);t&&i.size>0&&await
|
|
343
|
+
${Vu}`}var rb=Zn(zu);function S(e){return(e??"").replace(/\s+/gu," ").trim()}import T from"chalk";var G="@aurodesignsystem/auro-formkit",Qn=["@aurodesignsystem/auro-input","@aurodesignsystem/auro-select","@aurodesignsystem/auro-combobox","@aurodesignsystem/auro-menu","@aurodesignsystem/auro-checkbox","@aurodesignsystem/auro-radio","@aurodesignsystem/auro-datepicker","@aurodesignsystem/auro-dropdown","@aurodesignsystem/auro-form"],Ku=new Set(Qn);function Y(e){return Ku.has(e)}function er(e){return e.slice(18)}function ve(e){return`${G}/${er(e)}`}var qu=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/u;function Es(e){let t=qu.exec(e.trim());return t?{main:[Number(t[1]),Number(t[2]),Number(t[3])],pre:t[4]?t[4].split("."):[]}:null}function Yu(e,t){let n=Es(e),r=Es(t);if(!n||!r)return null;for(let s=0;s<3;s+=1)if(n.main[s]!==r.main[s])return n.main[s]<r.main[s]?-1:1;if(n.pre.length===0&&r.pre.length===0)return 0;if(n.pre.length===0)return 1;if(r.pre.length===0)return-1;let o=Math.max(n.pre.length,r.pre.length);for(let s=0;s<o;s+=1){let i=n.pre[s],a=r.pre[s];if(i===void 0)return-1;if(a===void 0)return 1;let c=/^\d+$/u.test(i),l=/^\d+$/u.test(a);if(c&&l){let m=Number(i)-Number(a);if(m!==0)return m<0?-1:1}else{if(c!==l)return c?-1:1;if(i!==a)return i<a?-1:1}}return 0}async function ke(e){let t=[...e.entries()],n=await Promise.all(t.map(([o])=>$o(o))),r=[];return t.forEach(([o,s],i)=>{let a=n[i];if(!a)return;let c=Yu(s,a);c!==null&&c<0&&r.push({pkg:o,installed:s,latest:a})}),r}var Ss=" \u21E2 auro-formkit";function $e(e){if(e.length===0)return"";let t=e.filter(p=>Y(p.pkg)),n=e.filter(p=>!Y(p.pkg)),r=`\u26A0 ${e.length} Auro component(s) are NOT on the latest release`,o=Math.max(...e.map(p=>p.pkg.length)),s=Math.max(...e.map(p=>p.installed.length)),i=p=>Y(p.pkg),a=e.map(p=>{let d=` ${T.bold(p.pkg.padEnd(o))} ${T.dim(p.installed.padStart(s))} ${T.dim("\u2192")} ${T.green.bold(p.latest)}`;return i(p)?`${d}${T.yellow(Ss)}`:d}),c=[];if(n.length>0){let p=`npm install ${n.map(d=>`${d.pkg}@latest`).join(" ")}`;c.push("",T.dim(" Update to latest with:"),` ${T.cyan(p)}`)}if(t.length>0){c.push("",T.dim(" Migrate to auro-formkit (run `auro init`):"));for(let p of t)c.push(` ${T.dim(p.pkg)} ${T.dim("\u2192")} ${T.cyan(ve(p.pkg))}`)}let l=[r.length+1,...e.map(p=>{let d=2+o+2+s+3+p.latest.length;return i(p)?d+Ss.length:d})],m=Math.min(Math.max(...l),78),u="\u2500".repeat(m);return["",T.yellow.bold(`\u250C${u}\u2510`),T.yellow.bold(r),T.yellow.bold(`\u2514${u}\u2518`),...a,...c,""].join(`
|
|
344
|
+
`)}async function em(e){let t=new Map;for(let i of Yn)t.set(i.tag,{...i});let n=await Promise.all(I.map(i=>O(i,{allowNetwork:e}))),r=new Map(An(n).map(i=>[i.pkg,i.version])),o=0,s=0;for(let i of n){if(!i.manifest)continue;o+=1;let a=(i.manifest.modules??[]).flatMap(c=>c.declarations??[]).filter(c=>c.customElement&&c.tagName);for(let c of a){let l=c.tagName,m=S(c.summary||c.description),u=t.get(l);t.set(l,{tag:l,pkg:i.target,description:m||u?.description||""}),m&&(s+=1)}}return{rows:Xn([...t.values()]),resolved:o,enriched:s,local:r}}async function tm(e){let t=tr("Checking for newer component releases...").start(),n=await ke(e);if(n.length===0){t.succeed("All installed Auro components are on the latest release.");return}t.stop(),console.error($e(n))}async function nm(e){let t=!e.offline,n=tr(t?"Resolving component manifests...":"Reading installed component manifests...").start(),{rows:r,resolved:o,enriched:s,local:i}=await em(t),a=Zn(r);if(t?s>0?n.succeed(i.size>0?`Enriched ${s} component description(s); ${i.size} package(s) resolved from local node_modules.`:`Enriched ${s} component description(s) from unpkg.`):o>0?n.succeed(`Resolved ${o} component manifest(s); none documented a description, using the built-in table.`):n.warn("No manifests available; using the built-in component table."):i.size>0?n.succeed(s>0?`Read ${i.size} installed component manifest(s) from local node_modules; enriched ${s} description(s).`:`Read ${i.size} installed component manifest(s) from local node_modules; none documented a description, using the built-in table.`):n.warn("No installed component manifests found; using the built-in component table."),e.output){let c=tr(`Writing context to ${e.output}...`).start();try{let l=Zu.resolve(process.cwd(),e.output);await Xu.writeFile(l,a,"utf-8"),c.succeed(`Auro context written to ${e.output}`),console.error(`
|
|
345
|
+
Paste this file into your AI coding tool (Claude, Cursor, Copilot, etc.) to prime it on Auro components.`)}catch(l){let m=l instanceof Error?l.message:String(l);c.fail(`Failed to write context: ${m}`),process.exit(1)}}else process.stdout.write(a);t&&i.size>0&&await tm(i)}var kb=Qu.command("context").description("Generate an AI assistant context document for the Auro Design System").option("-o, --output <path>","Write context to a file instead of stdout (e.g. AURO_CONTEXT.md)").option("--offline","Skip network fetches; use locally installed manifests and the built-in table",!1).action(nm);import ip from"node:fs/promises";import ap from"node:path";import Q from"node:process";import{program as cp}from"commander";import ee from"inquirer";import Ue from"ora";var M="auro.config.json";import{existsSync as Cs,readFileSync as As,statSync as rm}from"node:fs";import Rt from"node:path";import{parse as xs}from"jsonc-parser";var Ts=["vscode","jsx","svelte","cssSnippets"];function Rs(e,t){try{return rm(Rt.join(e,t)).isDirectory()}catch{return!1}}function Ps(e){try{let t=As(Rt.join(e,"package.json"),"utf-8"),n=xs(t,[],{allowTrailingComma:!0});return typeof n!="object"||n===null?new Set:new Set([...Object.keys(n.dependencies??{}),...Object.keys(n.devDependencies??{})])}catch{return new Set}}function om(e){return Rs(e,x)}function sm(e){return Rs(e,x)}function im(e){let t=Rt.join(e,"tsconfig.json");if(Cs(t))try{let n=As(t,"utf-8"),r=xs(n,[],{allowTrailingComma:!0});if(typeof r=="object"&&r!==null&&r.compilerOptions?.jsx!==void 0)return!0}catch{}return Ps(e).has("react")}function am(e){return Ps(e).has("svelte")?!0:["js","ts","mjs","cjs"].some(t=>Cs(Rt.join(e,`svelte.config.${t}`)))}function Ds(e){return{vscode:om(e),jsx:im(e),svelte:am(e),cssSnippets:sm(e)}}import{existsSync as nr,readFileSync as cm}from"node:fs";import Ms from"node:path";import{parse as Ns}from"jsonc-parser";function Pt(e,t){return Ms.join(e,...t.split("/"))}function Is(e){try{return cm(e,"utf-8")}catch{return null}}function lm(e){let t=Is(Pt(e,`${x}/${ae}`));if(t===null)return!1;let r=Ns(t,[],{allowTrailingComma:!0})?.[P];return typeof r=="string"?r===U:Array.isArray(r)?r.includes(U):!1}function um(e){for(let t of["tsconfig.json","jsconfig.json"]){let n=Is(Ms.join(e,t));if(n===null)continue;let r=Ns(n,[],{allowTrailingComma:!0}),o=r?.[D];return Array.isArray(o)?o.includes(H):!(o!==void 0||"files"in(r??{}))}return!0}function rr(e,t){let n=[];return t.vscode&&(nr(Pt(e,ce))||n.push(`${ce} is missing \u2014 VS Code markup completions will not work.`),lm(e)||n.push(`${x}/${ae} does not register "${U}" under "${P}".`)),t.svelte&&!nr(Pt(e,ue))&&n.push(`${ue} is missing.`),t.jsx&&!nr(Pt(e,le))&&n.push(`${le} is missing.`),(t.svelte||t.jsx)&&!um(e)&&n.push(`${H} is not on the TypeScript program (missing from "${D}").`),{inconsistencies:n,markupDisabled:!t.vscode}}import Ee from"node:fs/promises";import Nt from"node:path";var mm="css,scss,less";function pm(e){return!/[,|}]/u.test(e)}function dm(e){return(e.declaration.cssParts??[]).map(t=>t.name).filter(t=>typeof t=="string"&&t!=="").filter(pm)}function fm(e,t){let n=`\${1|${t.join(",")}|}`;return{scope:mm,prefix:`${e}::part`,body:[`${e}::part(${n}) {`," $0","}"],description:`Style a shadow part of <${e}> (${t.join(", ")})`}}function Os(e,t){let n={};for(let r of e){let o=dm(r);if(o.length===0)continue;let s=Cn(r,t);n[`Auro <${s}> ::part`]=fm(s,o)}return Object.keys(n).length===0?null:{filename:dt,contents:q(JSON.stringify(n,null,2))}}import{getVsCodeHtmlCustomData as gm}from"custom-element-vs-code-integration";function js(e,t){let n=ge(e,t),r=K(o=>gm(n,{outdir:o,htmlFileName:"auro.html-custom-data.json",hideLogs:!0}));return{filename:ce,contents:q(r)}}import{applyEdits as _s,modify as Fs,parse as hm,parseTree as ym}from"jsonc-parser";var Ls={tabSize:2,insertSpaces:!0};function bm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Dt(e,t){if(e.trim()==="")return{data:{}};let n=[],r=hm(e,n,{allowTrailingComma:!0});return n.length>0?{warning:`${t} is not valid JSON \u2014 leaving it untouched.`}:bm(r)?{data:r}:{warning:`${t} is not a JSON object \u2014 leaving it untouched.`}}function We(e,t,n){let r=e.trim()===""?"{}":e,o=Fs(r,t,n,{formattingOptions:Ls});return _s(r,o)}function wm(e,t){let n=ym(e);if(!n||n.type!=="object"||n.children?.length!==1)return null;let r=n.children[0];if(r.children?.[0]?.value!==t)return null;let o=r.offset+r.length;for(;o<e.length&&e[o]===",";)o++;return e.slice(0,r.offset)+e.slice(o)}function or(e,t){if(t.length===1){let r=wm(e,t[0]);if(r!==null)return r}let n=Fs(e,t,void 0,{formattingOptions:Ls});return _s(e,n)}function Gs(e,t=U){let n=Dt(e,".vscode/settings.json");if("warning"in n)return{contents:e,changed:!1,warning:n.warning};let r=n.data[P],o;if(r===void 0)o=[t];else if(typeof r=="string"){if(r===t)return{contents:e,changed:!1};o=[r,t]}else if(Array.isArray(r)){if(r.includes(t))return{contents:e,changed:!1};o=[...r,t]}else return{contents:e,changed:!1,warning:`.vscode/settings.json "${P}" is not a string or array \u2014 leaving it untouched.`};return{contents:We(e,[P],o),changed:!0}}function Bs(e,t=H,n="tsconfig.json"){let r=Dt(e,n);if("warning"in r)return{contents:e,changed:!1,warning:r.warning};let{data:o}=r,s=o[D];return Array.isArray(s)?s.includes(t)?{contents:e,changed:!1}:{contents:We(e,[D],[...s,t]),changed:!0}:s!==void 0?{contents:e,changed:!1,warning:`${n} "${D}" is not an array \u2014 leaving it untouched.`}:"files"in o?{contents:We(e,[D],[t]),changed:!0}:{contents:e,changed:!1}}function Ws(e,t=U){let n=Dt(e,".vscode/settings.json");if("warning"in n)return{contents:e,changed:!1,warning:n.warning};let r=n.data[P];if(typeof r=="string")return r!==t?{contents:e,changed:!1}:{contents:or(e,[P]),changed:!0};if(Array.isArray(r)){if(!r.includes(t))return{contents:e,changed:!1};let o=r.filter(i=>i!==t);return{contents:o.length===0?or(e,[P]):We(e,[P],o),changed:!0}}return{contents:e,changed:!1}}function Us(e,t=H,n="tsconfig.json"){let r=Dt(e,n);if("warning"in r)return{contents:e,changed:!1,warning:r.warning};let o=r.data[D];if(!Array.isArray(o)||!o.includes(t))return{contents:e,changed:!1};let s=o.filter(a=>a!==t);return{contents:s.length===0?or(e,[D]):We(e,[D],s),changed:!0}}function Js(e,t){return Nt.join(e,...t.split("/"))}async function Mt(e,t){let n=Js(e,t.filename);return await Ee.mkdir(Nt.dirname(n),{recursive:!0}),await Ee.writeFile(n,t.contents,"utf-8"),t.filename}async function Hs(e){try{return await Ee.readFile(e,"utf-8")}catch(t){if(t.code==="ENOENT")return"";throw t}}async function sr(e,t,n,r){let o=[],s=[];if(r.vscode){o.push(await Mt(e,js(t,n)));let i=`${x}/${ae}`,a=Js(e,i),c=Gs(await Hs(a));c.warning?s.push(`${c.warning} Add "${U}" to "${P}" in ${i} by hand.`):c.changed&&(await Ee.mkdir(Nt.dirname(a),{recursive:!0}),await Ee.writeFile(a,c.contents,"utf-8"),o.push(i))}if(r.jsx&&o.push(await Mt(e,gt(t,n))),r.svelte&&o.push(await Mt(e,ht(t,n))),r.cssSnippets){let i=Os(t,n);i&&o.push(await Mt(e,i))}if(r.jsx||r.svelte)for(let i of["tsconfig.json","jsconfig.json"]){let a=Nt.join(e,i),c=await Hs(a);if(c==="")continue;let l=Bs(c,H,i);l.warning?s.push(`${l.warning} Add "${H}" to "${D}" in ${i} by hand.`):l.changed&&(await Ee.writeFile(a,l.contents,"utf-8"),o.push(i));break}return{written:o,warnings:s}}var X="AGENTS.md",pe="CLAUDE.md";var It="Generated by `auro init`",zs=`# Auro Design System \u2014 AI Assistant Grounding
|
|
344
346
|
|
|
345
|
-
<!-- ${
|
|
347
|
+
<!-- ${It}. Do not edit by hand \u2014 re-run \`auro init\` to
|
|
346
348
|
regenerate. Custom element tags are governed by \`auro.config.json\`. -->
|
|
347
349
|
|
|
348
350
|
Alaska Airlines open-source design system | https://auro.alaskaair.com
|
|
@@ -359,9 +361,9 @@ v1) using the Lit library.
|
|
|
359
361
|
- npm scope: \`@aurodesignsystem/\` (current), \`@alaskaairux/\` (legacy)
|
|
360
362
|
- Framework-agnostic: works with React, Angular, Vue, Svelte, or plain HTML
|
|
361
363
|
- Each component is a separate npm package and registers a custom element tag
|
|
362
|
-
`,
|
|
363
|
-
|---|---|---|---|`,
|
|
364
|
-
`;var
|
|
364
|
+
`,Vs=`| Tag | Package | Version | Import |
|
|
365
|
+
|---|---|---|---|`,Ks="## Regeneration\n\nThis file is generated by `auro init`. Re-run it after adding or removing an Auro\ndependency to update the component list and APIs. Custom element tags are governed\nby `auro.config.json` (committed by default) \u2014 change prefixes there, not in this\nfile, then re-run `auro init`.\n",Ot=`@${X}
|
|
366
|
+
`;var qs=`## Auro Coding Rules
|
|
365
367
|
|
|
366
368
|
These rules apply to every Auro component in this project. Use the exact
|
|
367
369
|
registered tags listed under **Installed Components** below: this project uses
|
|
@@ -402,35 +404,35 @@ name.
|
|
|
402
404
|
6. **Accessibility is built in \u2014 don't override it.** Auro components ship WCAG
|
|
403
405
|
2.1 AA behavior (focus management, ARIA, error messaging). Prefer the provided
|
|
404
406
|
slots and attributes over custom ARIA.
|
|
405
|
-
`;var
|
|
406
|
-
`)}function
|
|
407
|
-
`)}function
|
|
408
|
-
`)}function
|
|
407
|
+
`;var Ys="@aurodesignsystem";function Zs(e){let t=e.trim();if(t.startsWith("@"))return t;let n=t.toLowerCase();return n.startsWith("auro-")?`${Ys}/${n}`:`${Ys}/auro-${n}`}function vm(e){return e.replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}function Xs(e){return e?typeof e=="string"?` [deprecated: ${S(e)}]`:" [deprecated]":""}function Se(e){if(e.length===0)return" (none)";let t=Math.max(...e.map(([n])=>(n??"").length));return e.map(([n,r])=>` ${(n??"").padEnd(t)} ${r??""}`.trimEnd()).join(`
|
|
408
|
+
`)}function Qs(e,t,n={}){let{installPkg:r=e,importSpecifier:o=e}=n,s=[];s.push(`${t.tagName} (${e})`);let i=t.summary||t.description;i&&s.push(S(i));let a=t.superclass?.name?`${t.name} extends ${t.superclass.name}`:t.name;return s.push(`Class: ${a}`),s.push(""),s.push("Install:"),s.push(` npm i ${r}`),s.push(` import "${o}";`),s.push(...ir(t)),s.join(`
|
|
409
|
+
`)}function ir(e){let t=[],n=e.attributes??[];t.push(""),t.push(`Attributes (${n.length}):`),t.push(Se(n.map(l=>{let m=l.type?.text?` {${S(l.type.text)}}`:"",u=l.default?` = ${S(l.default)}`:"";return[l.name,`${S(l.description)}${m}${u}${Xs(l.deprecated)}`.trim()]})));let r=new Set(n.flatMap(l=>l.fieldName?[l.fieldName]:[l.name,vm(l.name)])),o=(e.members??[]).filter(l=>l.name&&(l.privacy===void 0||l.privacy==="public")&&!l.static&&!(l.kind==="field"&&r.has(l.name)));t.push(""),t.push(`Properties & Methods (${o.length}):`),t.push(Se(o.map(l=>{let m=l.kind==="method",u=m?`${l.name}()`:l.name,p=m?l.return?.type?.text:l.type?.text,d=p?` {${S(p)}}`:"",f=!m&&l.default?` = ${S(l.default)}`:"";return[u,`${S(l.description)}${d}${f}${Xs(l.deprecated)}`.trim()]})));let s=e.slots??[];t.push(""),t.push(`Slots (${s.length}):`),t.push(Se(s.map(l=>[l.name||"(default)",S(l.description)])));let i=e.events??[];t.push(""),t.push(`Events (${i.length}):`),t.push(Se(i.map(l=>{let m=l.type?.text?` {${S(l.type.text)}}`:"";return[l.name,`${S(l.description)}${m}`.trim()]})));let a=e.cssParts??[];a.length>0&&(t.push(""),t.push(`CSS Parts (${a.length}):`),t.push(Se(a.map(l=>[l.name,S(l.description)]))));let c=e.cssProperties??[];return c.length>0&&(t.push(""),t.push(`CSS Custom Properties (${c.length}):`),t.push(Se(c.map(l=>[l.name,S(l.description)])))),t}function ei(e,t){return t.get(e.tagName)??e.tagName}function km(e,t){let{pkg:n,importPath:r,declaration:o}=e,s=[`${t} (${n})`],i=o.summary||o.description;i&&s.push(S(i));let a=o.superclass?.name?`${o.name} extends ${o.superclass.name}`:o.name;return s.push(`Class: ${a}`),s.push(""),s.push("Install:"),s.push(` npm i ${n}`),s.push(` import "${r}";`),s.push(` ${o.name}.register('${t}');`),s.push(...ir(o)),s.join(`
|
|
410
|
+
`)}function $m(e,t=new Map){let n=e.map(i=>`| \`<${ei(i,t)}>\` | \`${i.pkg}\` | ${i.version} | \`${i.importPath}\` |`),r=e.map(i=>{let a=ei(i,t);return`### \`<${a}>\`
|
|
409
411
|
|
|
410
412
|
\`\`\`
|
|
411
|
-
${
|
|
412
|
-
\`\`\``}),o=["## Installed Components","",
|
|
413
|
+
${km(i,a)}
|
|
414
|
+
\`\`\``}),o=["## Installed Components","",Vs,...n];r.length>0&&o.push("",r.join(`
|
|
413
415
|
|
|
414
416
|
`));let s=o.join(`
|
|
415
|
-
`);return`${[
|
|
417
|
+
`);return`${[zs.trimEnd(),qs.trimEnd(),s,Ks.trimEnd()].join(`
|
|
416
418
|
|
|
417
419
|
`)}
|
|
418
|
-
`}function
|
|
420
|
+
`}function Em(){return Ot}function ti(e,t=new Map){return[{filename:X,contents:$m(e,t)},{filename:pe,contents:Em()}]}import{appendFileSync as Sm,readFileSync as oi}from"node:fs";import _t from"node:path";import{simpleGit as Cm}from"simple-git";var Am="# Added by auro init \u2014 keep generated grounding/IntelliSense files tracked";function ni(e){return e.split(_t.sep).join("/")}async function jt(e,t){if(t.length===0)return[];try{return(await Cm({baseDir:e}).checkIgnore(t.map(ni))).map(ni)}catch{return[]}}function xm(e){let t=_t.posix.dirname(e);return t==="."?"":t}function Tm(e){try{let t=oi(_t.join(e,".gitignore"),"utf-8");return new Set(t.split(/\r?\n/).map(n=>n.trim()))}catch{return new Set}}function ri(e,t,n=!0){let r=_t.join(e,".gitignore"),o="";try{o=oi(r,"utf-8")}catch{}let s=new Set(o.split(/\r?\n/).map(c=>c.trim())),i=n?t.filter(c=>!s.has(c.trim())):t;if(i.length===0)return;let a=o===""||o.endsWith(`
|
|
419
421
|
`)?"":`
|
|
420
|
-
`;try{
|
|
422
|
+
`;try{Sm(r,`${a}${i.join(`
|
|
421
423
|
`)}
|
|
422
|
-
`,"utf-8")}catch{}}async function
|
|
423
|
-
`,"utf-8")}function
|
|
424
|
-
`,"utf-8")}let s=
|
|
425
|
-
`)}function ke(e){return!Z.stdin.isTTY||!!Z.env.CI||!!e.nonInteractive||!!e.yes}async function xm(e){if(e.suggestedDefault){let{accept:n}=await Q.prompt([{type:"confirm",name:"accept",message:e.mixedPrefixes?`Existing registrations use more than one prefix. Use the most common, '${e.suggestedDefault}', as the default for the remaining components?`:`Use the detected prefix '${e.suggestedDefault}' as the default for the remaining components?`,default:!0}]);if(n)return e.suggestedDefault}let{prefix:t}=await Q.prompt([{type:"input",name:"prefix",message:"Prefix for Auro custom-element tags (e.g. myapp-; blank keeps the bare auro-* tags):",default:e.suggestedDefault??""}]);return String(t).trim()}function Tm(e){let t=e.trim();return/^[a-z][a-z0-9-]*$/.test(t)?t.includes("-")?!0:"A custom-element tag must contain a hyphen (e.g. nav-menu).":"Use a lowercase tag starting with a letter (letters, digits, and hyphens only)."}async function Rm(e,t){let{customize:n}=await Q.prompt([{type:"confirm",name:"customize",message:"Define a custom tag name for any installed component? (you'll be prompted per component; Enter keeps the calculated name)",default:!1}]);if(!n)return{};let r={};for(let o of e){let s=o.tagName,i=t.get(s)??s,{tag:a}=await Q.prompt([{type:"input",name:"tag",message:`Tag for ${o.declaration.name} (<${s}>):`,default:i,validate:Tm}]),c=String(a).trim();c!==i&&(r[s]=c)}return r}function Pm(e,t){let n=e??Vs();return{...n,init:{...n.init,prefix:{default:n.init.prefix.default,overrides:{...n.init.prefix.overrides,...t}}}}}var Dm={vscode:{label:"VS Code HTML custom-data",artifact:".vscode/auro.html-custom-data.json"},jsx:{label:"JSX/React type declarations",artifact:"auro-types/auro-jsx.d.ts"},svelte:{label:"Svelte type declarations",artifact:"auro-types/auro-svelte.d.ts"},cssSnippets:{label:"CSS ::part() snippets",artifact:".vscode/auro.code-snippets"}};async function Nm(e,t,n){let r=n?.init.editors,o=gs(e),s=!ke(t),i={vscode:!1,jsx:!1,svelte:!1,cssSnippets:!1},a=[];for(let c of ps){let l=t[c];if(l!==void 0){i[c]=l;continue}let m=r?.[c];if(m!==void 0){i[c]=m;continue}if(s){let{label:u,artifact:p}=Dm[c];a.push({type:"confirm",name:c,message:`Generate ${u} (${p})?`,default:o[c]})}else i[c]=o[c]}if(a.length>0){let c=await Q.prompt(a);for(let{name:l}of a)i[l]=!!c[l]}return i}async function Im(e,t){let n;try{n=Qs(e)}catch(a){let c=a instanceof Error?a.message:String(a);return console.error(`\u26A0 Skipping formkit migration check: ${c}`),!1}if(n.length===0)return!1;let r=n.map(a=>a.pkg).join(", ");if(ke(t))return console.error(`\u26A0 ${n.length} legacy standalone package(s) can be migrated to @aurodesignsystem/auro-formkit: ${r}. Run \`auro init\` interactively to apply the migration.`),!1;let{migrate:o}=await Q.prompt([{type:"confirm",name:"migrate",message:`${n.length} legacy standalone package(s) now live in auro-formkit (${r}). Migrate to auro-formkit now? This edits package.json and rewrites import specifiers.`,default:!1}]);if(!o)return!1;let s=Ge("Migrating to auro-formkit...").start(),i=ei(e,n);s.succeed(`Migrated ${i.packagesMigrated.length} package(s) to auro-formkit; rewrote ${i.rewriteCount} import(s) across ${i.filesChanged.length} file(s).`);for(let{file:a,specifier:c}of i.deepImports)console.error(`\u26A0 ${a}: left deep import '${c}' unchanged \u2014 update it to an @aurodesignsystem/auro-formkit subpath by hand.`);return console.error("Next: run `npm install`, then re-run `auro init` to regenerate grounding for auro-formkit."),!0}async function Mm(e){let t=new Map(e.map(o=>[o.pkg,o.version])),n=Ge("Checking for newer component releases...").start(),r=await ye(t);if(r.length===0){n.succeed("All installed Auro components are on the latest release.");return}n.stop(),console.error(be(r))}async function Om(e){let t=Z.cwd();if(e.reset){await Fm(t,e);return}let n=Ge("Detecting installed Auro components...").start(),{components:r,duplicates:o}=await yo();if(r.length===0){n.warn("No installed Auro components found; nothing to ground. Install an Auro component package and re-run `auro init`.");return}if(n.succeed(`Detected ${r.length} installed component(s) to ground.`),await Im(t,e))return;let s;try{s=jt(t)}catch(g){let b=g instanceof G||g instanceof Error?g.message:String(g);console.error(`Cannot read ${N}: ${b}`),Z.exit(1)}let i=Ks(t),a=_t(r,{config:s,scan:i,prefix:e.prefix}),l=!(e.prefix!==void 0||s?.init.prefix.default!==void 0)&&(a.needsDefaultPrefix||a.mixedPrefixes),m=e.prefix;if(l){if(ke(e)){let g=a.needsDefaultPrefix?`${a.needingDefault.length} component(s) have no resolvable tag and no default prefix`:"existing registrations use inconsistent prefixes";console.error(`Cannot resolve component tags non-interactively: ${g}. Re-run with --prefix <prefix> (e.g. --prefix myapp-).`),Z.exit(1)}m=await xm(a),a=_t(r,{config:s,scan:i,prefix:m})}if(a.needsDefaultPrefix&&(console.error("Unable to resolve a default prefix for every component. Re-run with --prefix <prefix>."),Z.exit(1)),!ke(e)){let g=await Rm(r,a.resolvedTags);Object.keys(g).length>0&&(a=_t(r,{config:Pm(s,g),scan:i,prefix:m}))}let u=await Nm(t,e,s);a.config.init.editors=u;let p=Ge("Writing generated files...").start(),f={written:[],warnings:[]};try{for(let b of Ls(r,a.resolvedTags))await Sm.writeFile(Am.join(t,b.filename),b.contents,"utf-8");f=await zn(t,r,a.resolvedTags,u),zs(t,a.config);let g=f.written.length>0?` Editor IntelliSense: ${f.written.join(", ")}.`:"";p.succeed(`Wrote ${Y}, ${le}, and ${N} for ${r.length} component(s).${g}`)}catch(g){let b=g instanceof Error?g.message:String(g);p.fail(`Failed to write generated files: ${b}`),Z.exit(1)}for(let g of f.warnings)console.error(`\u26A0 ${g}`);for(let g of a.warnings)console.error(`\u26A0 ${g}`);for(let g of o)console.error(`\u26A0 Tag <${g.tagName}> is registered by multiple installed packages: ${g.packages.join(", ")}. Grounded once \u2014 verify which package you intend to use.`);a.reconciliationWarnings.length>0&&console.error(ue(`\u26A0 ${a.reconciliationWarnings.length} component tag(s) may not match your app's registered tags`,a.reconciliationWarnings,"red")),a.noPrefixWarnings.length>0&&console.error(ue(`\u26A0 ${a.noPrefixWarnings.length} component(s) grounded under bare 'auro-*' tags \u2014 pass a prefix to avoid collisions`,a.noPrefixWarnings,"yellow"));let d=Jn(t,u);if(d.inconsistencies.length>0)try{let g=await zn(t,r,a.resolvedTags,u),b=new Set(f.warnings);for(let $ of g.warnings)b.has($)||console.error(`\u26A0 ${$}`);d=Jn(t,u)}catch(g){let b=g instanceof Error?g.message:String(g);console.error(`\u26A0 Could not re-write editor artifacts to self-heal wiring: ${b}`)}d.inconsistencies.length>0&&console.error(ue("\u26A0 Editor IntelliSense wiring is incomplete after writing",d.inconsistencies,"red")),d.markupDisabled&&console.error(ue("\u26A0 VS Code markup IntelliSense is off \u2014 no <auro-*> completions or hover docs",["Type-checking may still work, but tag/attribute completions will not.","Re-run `auro init --vscode` to generate them."],"yellow"));let h=[...new Set([Y,le,N,...f.written])];await jm(t,h,e),e.offline||await Mm(r)}async function jm(e,t,n){let r=await Dt(e,t);if(r.length===0)return;if(console.error(ue(`\u26A0 ${r.length} file(s) auro init wrote are git-ignored and won't be committed`,[...r,"These are meant to be committed so your team and CI share the same grounding/IntelliSense."],"red")),ke(n)&&!n.yes){console.error("\u26A0 Un-ignore them in .gitignore (or re-run with --yes) so they get committed.");return}if(!n.yes){let{fix:i}=await Q.prompt([{type:"confirm",name:"fix",message:"Add entries to .gitignore so these files stay tracked (committed)?",default:!0}]);if(!i)return}let{fixed:o,unfixable:s}=await Ws(e,r);o.length>0&&console.error(`\u2714 Un-ignored ${o.length} file(s) in .gitignore so they will be committed.`),s.length>0&&console.error(ue(`\u26A0 ${s.length} file(s) are still git-ignored \u2014 un-ignore them by hand`,[...s,"A parent directory is ignored by a rule auro init won't rewrite; edit .gitignore to re-include these paths."],"red"))}function _m(e){return e.filesToRemove.length===0&&e.unmerges.length===0}async function Fm(e,t){let n=ni(e);if(_m(n)){console.log("Nothing to reset \u2014 no `auro init` output found.");for(let c of n.filesToSkip)console.error(`\u26A0 Left ${c.path} in place: ${c.reason}.`);return}console.log("`auro init --reset` will:");for(let c of n.filesToRemove)console.log(` \u2022 remove ${c}`);for(let c of n.unmerges)console.log(` \u2022 remove the Auro entry from ${c.path}`);for(let c of n.dirsToPrune)console.log(` \u2022 remove ${c}/ if it is left empty`);for(let c of n.filesToSkip)console.log(` \u2022 keep ${c.path} (${c.reason})`);if(!ke(t)){let{confirm:c}=await Q.prompt([{type:"confirm",name:"confirm",message:"Remove these files and config entries?",default:!1}]);if(!c){console.log("Reset aborted \u2014 nothing was changed.");return}}let r=Ge("Removing `auro init` output...").start(),o;try{o=ri(e,n)}catch(c){let l=c instanceof Error?c.message:String(c);r.fail(`Failed to reset: ${l}`),Z.exit(1)}let s=o.removed.length>0?`Removed ${o.removed.length} file(s)`:"Removed no files",i=o.unmerged.length>0?`, un-merged ${o.unmerged.join(", ")}`:"",a=o.prunedDirs.length>0?`, pruned ${o.prunedDirs.map(c=>`${c}/`).join(", ")}`:"";r.succeed(`${s}${i}${a}.`);for(let c of o.warnings)console.error(`\u26A0 ${c}`);for(let c of o.skipped)console.error(`\u26A0 Left ${c.path} in place: ${c.reason}.`);console.error("\u2139 Reset does not undo an `auro-formkit` migration. If you migrated a legacy standalone form package, revert those package.json and import changes with git.")}var fw=Cm.command("init").description("Generate AI grounding files (AGENTS.md + CLAUDE.md) for the installed Auro components").option("--prefix <prefix>","Default custom-element tag prefix (e.g. myapp-) for components without an existing registration").option("--non-interactive","Never prompt; take the prefix from --prefix or fail cleanly (implied by a non-TTY stdin or CI)",!1).option("--yes","Alias for --non-interactive",!1).option("--offline","Skip the network check for newer component releases",!1).option("--vscode","Generate VS Code HTML custom-data IntelliSense (use --no-vscode to skip; default: auto-detect)").option("--no-vscode","Skip the VS Code HTML custom-data artifact").option("--jsx","Generate JSX/React type declarations (use --no-jsx to skip; default: auto-detect)").option("--no-jsx","Skip the JSX/React type declarations").option("--svelte","Generate Svelte type declarations (use --no-svelte to skip; default: auto-detect)").option("--no-svelte","Skip the Svelte type declarations").option("--css-snippets","Generate VS Code CSS ::part() snippets (use --no-css-snippets to skip; default: auto-detect)").option("--no-css-snippets","Skip the VS Code CSS ::part() snippets").option("--reset","Remove every file and config entry a previous `auro init` run created (does not undo an auro-formkit migration)",!1).action(Om);import Lt from"node:process";import{Logger as Lm}from"@aurodesignsystem/auro-library/scripts/utils/logger.mjs";import{program as Bm}from"commander";import ai from"ora";async function Gm(e,t){let n=r=>({headerPkg:e,installPkg:e,importSpecifier:e,redirectedToFormkit:!1,result:r});if(t.tag)return n(await j(`${e}@${t.tag}`));if(q(e)){let r=await j(e,{allowNetwork:!1});return r.manifest?n(r):{headerPkg:B,installPkg:B,importSpecifier:he(e),tagFilter:Un(e),redirectedToFormkit:!0,result:await j(B)}}return n(await j(e))}async function Um(e,t){let n=js(e),r=ai(`Fetching ${n}...`).start(),o=await Gm(n,t),{result:s}=o,i=s.target;s.manifest||(r.fail(s.transient?`Failed to fetch ${i}: ${s.reason}.`:`No custom-elements.json published for ${i}. It may not exist or may not publish a manifest yet.`),Lt.exit(1));let c=(s.manifest.modules??[]).flatMap(u=>u.declarations??[]).filter(u=>u.customElement&&u.tagName).filter(u=>!o.tagFilter||u.tagName===o.tagFilter);c.length===0&&(r.fail(o.tagFilter?`No <${o.tagFilter}> element found in ${i}.`:`No registered custom elements found for ${i}.`),Lt.exit(1));let l=s.source==="local"?` (local${s.version?` v${s.version}`:""})`:" (unpkg)";r.succeed(`${i} \u2014 ${c.length} custom element${c.length===1?"":"s"}${l}`),o.redirectedToFormkit&&console.error(`\u2139 ${o.tagFilter} now ships in ${B} \u2014 showing the monorepo version (the legacy standalone isn't installed).`);let m=null;if(s.source==="local"&&s.version){let u=ai("Checking for a newer release...").start(),p=await ye(new Map([[o.headerPkg,s.version]]));u.stop(),p.length>0&&(m=be(p))}if(t.json){Lt.stdout.write(`${JSON.stringify(c,null,2)}
|
|
426
|
-
`),m&&console.error(m);return}
|
|
427
|
-
${c.map(u=>
|
|
424
|
+
`,"utf-8")}catch{}}async function si(e,t){if(t.length===0)return{fixed:[],unfixable:[]};ri(e,[Am,...t.map(o=>`!${o}`)]);let n=await jt(e,t);if(n.length>0){let o=Tm(e),s=[],i=new Set;for(let a of n){let c=xm(a);(c===""||o.has(`${c}/*`))&&o.has(`!${a}`)||(c!==""&&!i.has(c)&&!o.has(`${c}/*`)&&(i.add(c),s.push(`!${c}/`,`${c}/*`)),s.push(`!${a}`))}s.length>0&&(ri(e,s,!1),n=await jt(e,t))}let r=new Set(n);return{fixed:t.filter(o=>!r.has(o)),unfixable:[...r]}}import{readFileSync as di,writeFileSync as pi}from"node:fs";import Ut from"node:path";import{globSync as Gm}from"glob";import{readFileSync as ai,writeFileSync as Rm}from"node:fs";import Gt from"node:path";import{globSync as Pm}from"glob";import R from"typescript";var Lt="auro-",cr="**/*.{js,jsx,ts,tsx,mjs,cjs,svelte}",lr=["**/node_modules/**","**/dist/**","**/build/**","**/coverage/**"],B=class extends Error{constructor(t){super(t),this.name="RegistryError"}};function ci(e=""){return{version:1,init:{prefix:{default:e,overrides:{}}}}}function Dm(e,t){let n=e;if(!n||typeof n!="object")throw new B(`${t}: not a JSON object.`);if(n.version!==1)throw new B(`${t}: unsupported config version ${String(n.version)} (expected ${1}). Upgrade the CLI or remove the file.`);let r=n.init?.prefix;if(!r||typeof r.default!="string"||typeof r.overrides!="object"||r.overrides===null)throw new B(`${t}: malformed init.prefix block.`);return n}function Bt(e){let t=Gt.join(e,M),n;try{n=ai(t,"utf-8")}catch(o){if(o.code==="ENOENT")return null;throw o}let r;try{r=JSON.parse(n)}catch{throw new B(`${M}: invalid JSON.`)}return Dm(r,M)}function li(e,t){let n=Gt.join(e,M);Rm(n,`${JSON.stringify(t,null,2)}
|
|
425
|
+
`,"utf-8")}function Mm(e){switch(Gt.extname(e).toLowerCase()){case".tsx":return R.ScriptKind.TSX;case".jsx":return R.ScriptKind.JSX;case".ts":case".mts":case".cts":return R.ScriptKind.TS;default:return R.ScriptKind.JS}}function Nm(e){return e&&(R.isStringLiteral(e)||R.isNoSubstitutionTemplateLiteral(e))?e.text:null}function ii(e,t,n=Mm(e)){let r=[],o=[],s=[],i;try{i=R.createSourceFile(e,t,R.ScriptTarget.ES2022,!0,n)}catch{return{matches:r,defaultRegistrations:o,warnings:[`${e}: could not be parsed; skipped.`]}}let a=c=>{if(R.isCallExpression(c)&&R.isPropertyAccessExpression(c.expression)&&c.expression.name.text==="register"){let l=c.expression.expression,m=R.isIdentifier(l)?l.text:void 0;if(c.arguments.length===0)m&&o.push(m);else{let u=Nm(c.arguments[0]);u===null?s.push(`${e}: register() with a non-literal tag could not be resolved; skipped.`):r.push({className:m,tag:u})}}R.forEachChild(c,a)};return a(i),{matches:r,defaultRegistrations:o,warnings:s}}var ar=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,Im=/\blang\s*=\s*["']?(?:ts|typescript)["']?/i;function Om(e){let t=[];ar.lastIndex=0;let n=ar.exec(e);for(;n!==null;){let[,r,o]=n;t.push({content:o,scriptKind:Im.test(r)?R.ScriptKind.TS:R.ScriptKind.JS}),n=ar.exec(e)}return t}function ui(e){let t=Pm(cr,{cwd:e,absolute:!0,nodir:!0,ignore:lr}),n=[],r=[],o=[],s=i=>{n.push(...i.matches),r.push(...i.defaultRegistrations??[]),o.push(...i.warnings)};for(let i of t){let a;try{a=ai(i,"utf-8")}catch{o.push(`${i}: could not be read; skipped.`);continue}if(Gt.extname(i).toLowerCase()===".svelte")for(let{content:c,scriptKind:l}of Om(a))s(ii(i,c,l));else s(ii(i,a))}return{matches:n,defaultRegistrations:r,warnings:o}}function mi(e){return e.startsWith(Lt)?e.slice(Lt.length):e}function jm(e,t){let n=mi(e);return t.endsWith(n)?t.slice(0,t.length-n.length):null}function _m(e){let t=new Map;for(let o of e)!o||o===Lt||t.set(o,(t.get(o)??0)+1);if(t.size===0)return{mixed:!1};let n,r=-1;for(let[o,s]of t)s>r&&(r=s,n=o);return{suggestion:n,mixed:t.size>1}}function Fm(e,t,n=[]){let r=new Map;for(let a of e)r.set(a.declaration.name,a.tagName);let o=new Map,s=[];for(let a of t){let c=a.className?r.get(a.className):void 0;if(!c){s.push(`Found register('${a.tag}')${a.className?` on ${a.className}`:""} but could not tie it to an installed Auro component; ignored.`);continue}o.set(c,a.tag)}let i=new Map;for(let a of n){let c=r.get(a);c&&i.set(c,a)}return{overrides:o,defaultRegistered:i,warnings:s}}function Lm(e,t){return!e||e===Lt?t:e+mi(t)}function Wt(e,t={}){let{config:n,scan:r,prefix:o}=t,s=n?.init.prefix.overrides??{},i=Fm(e,r?.matches??[],r?.defaultRegistrations??[]),a=n?.init.prefix.default,c=o??a,l=new Map,m={...s},u=[],p=[...r?.warnings??[],...i.warnings],d=[],f=[];for(let k of e){let y=k.tagName,w=s[y];if(w!==void 0){l.set(y,w);continue}let te=i.overrides.get(y);if(te!==void 0){l.set(y,te),m[y]=te;continue}if(c===void 0){u.push(y);continue}let ne=Lm(c,y);l.set(y,ne),ne===y?f.push(`${y}: no custom prefix \u2014 grounding it under its bare 'auro-*' tag. Pass a prefix to avoid registration collisions.`):i.defaultRegistered.has(y)||d.push(`${y}: grounded as '<${ne}>' from the '${c}' prefix, but no register('${ne}') was found in your source. If ${k.declaration.name} is registered under a different tag (e.g. the default '<${y}>' from a side-effect import), IntelliSense will not match your markup \u2014 call ${k.declaration.name}.register('${ne}') so your app matches the generated tags.`)}for(let[k,y]of i.defaultRegistered){let w=l.get(k);w!==void 0&&w!==k&&d.push(`${y}.register() uses the default '<${k}>' tag, but this project grounds it as '<${w}>'. Update the register() call to '${w}' so your app matches AGENTS.md.`)}let g=[...Object.entries(s),...i.overrides].map(([k,y])=>jm(k,y)),{suggestion:h,mixed:b}=_m(g),v=u.length>0&&c===void 0;return{resolvedTags:l,config:{version:1,init:{prefix:{default:c??h??"",overrides:m}}},needingDefault:u,needsDefaultPrefix:v,suggestedDefault:h,mixedPrefixes:b,warnings:p,reconciliationWarnings:d,noPrefixWarnings:f}}var ur="package.json";function Bm(e){let t=e.match(/\n([ \t]+)\S/u);return t?t[1]:2}function fi(e){let t;try{t=di(Ut.join(e,ur),"utf-8")}catch(n){if(n.code==="ENOENT")return null;throw n}try{return{pkgJson:JSON.parse(t),indent:Bm(t)}}catch{throw new Error(`${ur}: invalid JSON.`)}}function gi(e){let t=fi(e);if(!t)return[];let{pkgJson:n}=t,r=[],o=["dependencies","devDependencies"];for(let s of Qn)for(let i of o){let a=n[i]?.[s];if(typeof a=="string"){r.push({pkg:s,version:a,field:i});break}}return r}function Wm(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Um(e){return e.split(Ut.sep).join("/")}function Hm(e,t){let n=e,r=0,o=[];for(let s of t){let i=Wm(s),a=new RegExp(`(['"\`])${i}\\1`,"g");n=n.replace(a,(m,u)=>(r+=1,`${u}${ve(s)}${u}`));let c=new RegExp(`(['"\`])(${i}/[^'"\`]*)\\1`,"g"),l=c.exec(n);for(;l!==null;)o.push(l[2]),l=c.exec(n)}return{next:n,rewrites:r,deep:o}}function hi(e,t){let n=[...new Set(t.map(i=>i.pkg).filter(Y))],r={packagesMigrated:[],formkit:"present",filesChanged:[],rewriteCount:0,deepImports:[]};if(n.length===0)return r;let o=fi(e);if(o){let{pkgJson:i,indent:a}=o;for(let l of["dependencies","devDependencies"]){let m=i[l];if(m)for(let u of n)u in m&&(delete m[u],r.packagesMigrated.includes(u)||r.packagesMigrated.push(u))}!!i.dependencies?.[G]||!!i.devDependencies?.[G]?r.formkit="present":(i.dependencies??={},i.dependencies[G]="latest",r.formkit="added"),pi(Ut.join(e,ur),`${JSON.stringify(i,null,a)}
|
|
426
|
+
`,"utf-8")}let s=Gm(cr,{cwd:e,absolute:!0,nodir:!0,ignore:lr});for(let i of s){let a;try{a=di(i,"utf-8")}catch{continue}let{next:c,rewrites:l,deep:m}=Hm(a,n),u=Um(Ut.relative(e,i));for(let p of m)r.deepImports.push({file:u,specifier:p});l>0&&c!==a&&(pi(i,c,"utf-8"),r.filesChanged.push(u),r.rewriteCount+=l)}return r}import{existsSync as yi,readdirSync as Jm,readFileSync as zm,rmdirSync as Vm,rmSync as Km,writeFileSync as qm}from"node:fs";import Ym from"node:path";import{parse as Xm}from"jsonc-parser";function Z(e,t){return Ym.join(e,...t.split("/"))}function Zm(e){let t=Xm(e,[],{allowTrailingComma:!0});return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length===0}function Qm(e){return e.includes("//")||e.includes("/*")}function mr(e){try{return zm(e,"utf-8")}catch(t){if(t.code==="ENOENT")return null;throw t}}var ep=[ce,dt,le,ue];function tp(e,t){return e===null?null:t==="agents"?e.includes(It)?"remove":`not recognized as an \`auro init\` file (missing the "${It}" marker)`:e.trim()===Ot.trim()?"remove":"contains content beyond the generated `@AGENTS.md` import"}function bi(e){let t=[],n=[],r=[];for(let[a,c]of[[X,"agents"],[pe,"claude"]]){let l=tp(mr(Z(e,a)),c);l==="remove"?t.push(a):l!==null&&n.push({path:a,reason:l})}if(yi(Z(e,M)))try{Bt(e)&&t.push(M)}catch(a){let c=a instanceof B?a.message:String(a);n.push({path:M,reason:c})}for(let a of ep)yi(Z(e,a))&&t.push(a);let o=[],s=`${x}/${ae}`,i=mr(Z(e,s));if(i!==null){let a=Ws(i);a.warning?r.push(a.warning):a.changed&&(Zm(a.contents)&&!Qm(a.contents)?t.push(s):o.push({path:s,result:a}))}for(let a of["tsconfig.json","jsconfig.json"]){let c=mr(Z(e,a));if(c===null)continue;let l=Us(c,void 0,a);l.warning?r.push(l.warning):l.changed&&o.push({path:a,result:l});break}return{filesToRemove:t,filesToSkip:n,unmerges:o,warnings:r,dirsToPrune:[Ge,x]}}function np(e){try{return Jm(e).length===0}catch{return!1}}function wi(e,t){let n=[];for(let s of t.filesToRemove)Km(Z(e,s),{force:!0}),n.push(s);let r=[];for(let{path:s,result:i}of t.unmerges)qm(Z(e,s),i.contents,"utf-8"),r.push(s);let o=[];for(let s of t.dirsToPrune){let i=Z(e,s);np(i)&&(Vm(i),o.push(s))}return{removed:n,unmerged:r,prunedDirs:o,skipped:t.filesToSkip,warnings:t.warnings}}import vi from"chalk";var rp=78,ki=74,$i=" \u2022 ",op=" ";function sp(e,t){let n=e.split(/\s+/u).filter(Boolean);if(n.length===0)return[""];let r=[],o=n[0];for(let s of n.slice(1))o.length+1+s.length<=t?o+=` ${s}`:(r.push(o),o=s);return r.push(o),r}function de(e,t,n="red"){if(t.length===0)return"";let r=vi[n].bold,o=[];t.forEach((c,l)=>{sp(c,ki-$i.length).forEach((u,p)=>{let d=p===0?$i:op;o.push(vi[n](d+u))}),l<t.length-1&&o.push("")});let s=e.length+(e.includes("\u26A0")?1:0),i=Math.min(Math.max(s,ki),rp),a="\u2500".repeat(i);return["",r(`\u250C${a}\u2510`),r(e),r(`\u2514${a}\u2518`),...o,""].join(`
|
|
427
|
+
`)}function Ce(e){return!Q.stdin.isTTY||!!Q.env.CI||!!e.nonInteractive||!!e.yes}async function lp(e){if(e.suggestedDefault){let{accept:n}=await ee.prompt([{type:"confirm",name:"accept",message:e.mixedPrefixes?`Existing registrations use more than one prefix. Use the most common, '${e.suggestedDefault}', as the default for the remaining components?`:`Use the detected prefix '${e.suggestedDefault}' as the default for the remaining components?`,default:!0}]);if(n)return e.suggestedDefault}let{prefix:t}=await ee.prompt([{type:"input",name:"prefix",message:"Prefix for Auro custom-element tags (e.g. myapp-; blank keeps the bare auro-* tags):",default:e.suggestedDefault??""}]);return String(t).trim()}function up(e){let t=e.trim();return/^[a-z][a-z0-9-]*$/.test(t)?t.includes("-")?!0:"A custom-element tag must contain a hyphen (e.g. nav-menu).":"Use a lowercase tag starting with a letter (letters, digits, and hyphens only)."}async function mp(e,t){let{customize:n}=await ee.prompt([{type:"confirm",name:"customize",message:"Define a custom tag name for any installed component? (you'll be prompted per component; Enter keeps the calculated name)",default:!1}]);if(!n)return{};let r={};for(let o of e){let s=o.tagName,i=t.get(s)??s,{tag:a}=await ee.prompt([{type:"input",name:"tag",message:`Tag for ${o.declaration.name} (<${s}>):`,default:i,validate:up}]),c=String(a).trim();c!==i&&(r[s]=c)}return r}function pp(e,t){let n=e??ci();return{...n,init:{...n.init,prefix:{default:n.init.prefix.default,overrides:{...n.init.prefix.overrides,...t}}}}}var dp={vscode:{label:"VS Code HTML custom-data",artifact:".vscode/auro.html-custom-data.json"},jsx:{label:"JSX/React type declarations",artifact:"auro-types/auro-jsx.d.ts"},svelte:{label:"Svelte type declarations",artifact:"auro-types/auro-svelte.d.ts"},cssSnippets:{label:"CSS ::part() snippets",artifact:".vscode/auro.code-snippets"}};async function fp(e,t,n){let r=n?.init.editors,o=Ds(e),s=!Ce(t),i={vscode:!1,jsx:!1,svelte:!1,cssSnippets:!1},a=[];for(let c of Ts){let l=t[c];if(l!==void 0){i[c]=l;continue}let m=r?.[c];if(m!==void 0){i[c]=m;continue}if(s){let{label:u,artifact:p}=dp[c];a.push({type:"confirm",name:c,message:`Generate ${u} (${p})?`,default:o[c]})}else i[c]=o[c]}if(a.length>0){let c=await ee.prompt(a);for(let{name:l}of a)i[l]=!!c[l]}return i}async function gp(e,t){let n;try{n=gi(e)}catch(a){let c=a instanceof Error?a.message:String(a);return console.error(`\u26A0 Skipping formkit migration check: ${c}`),!1}if(n.length===0)return!1;let r=n.map(a=>a.pkg).join(", ");if(Ce(t))return console.error(`\u26A0 ${n.length} legacy standalone package(s) can be migrated to @aurodesignsystem/auro-formkit: ${r}. Run \`auro init\` interactively to apply the migration.`),!1;let{migrate:o}=await ee.prompt([{type:"confirm",name:"migrate",message:`${n.length} legacy standalone package(s) now live in auro-formkit (${r}). Migrate to auro-formkit now? This edits package.json and rewrites import specifiers.`,default:!1}]);if(!o)return!1;let s=Ue("Migrating to auro-formkit...").start(),i=hi(e,n);s.succeed(`Migrated ${i.packagesMigrated.length} package(s) to auro-formkit; rewrote ${i.rewriteCount} import(s) across ${i.filesChanged.length} file(s).`);for(let{file:a,specifier:c}of i.deepImports)console.error(`\u26A0 ${a}: left deep import '${c}' unchanged \u2014 update it to an @aurodesignsystem/auro-formkit subpath by hand.`);return console.error("Next: run `npm install`, then re-run `auro init` to regenerate grounding for auro-formkit."),!0}async function hp(e){let t=new Map(e.map(o=>[o.pkg,o.version])),n=Ue("Checking for newer component releases...").start(),r=await ke(t);if(r.length===0){n.succeed("All installed Auro components are on the latest release.");return}n.stop(),console.error($e(r))}async function yp(e){let t=Q.cwd();if(e.reset){await vp(t,e);return}let n=Ue("Detecting installed Auro components...").start(),{components:r,duplicates:o}=await Ro();if(r.length===0){n.warn("No installed Auro components found; nothing to ground. Install an Auro component package and re-run `auro init`.");return}if(n.succeed(`Detected ${r.length} installed component(s) to ground.`),await gp(t,e))return;let s;try{s=Bt(t)}catch(h){let b=h instanceof B||h instanceof Error?h.message:String(h);console.error(`Cannot read ${M}: ${b}`),Q.exit(1)}let i=ui(t),a=Wt(r,{config:s,scan:i,prefix:e.prefix}),l=!(e.prefix!==void 0||s?.init.prefix.default!==void 0)&&(a.needsDefaultPrefix||a.mixedPrefixes),m=e.prefix;if(l){if(Ce(e)){let h=a.needsDefaultPrefix?`${a.needingDefault.length} component(s) have no resolvable tag and no default prefix`:"existing registrations use inconsistent prefixes";console.error(`Cannot resolve component tags non-interactively: ${h}. Re-run with --prefix <prefix> (e.g. --prefix myapp-).`),Q.exit(1)}m=await lp(a),a=Wt(r,{config:s,scan:i,prefix:m})}if(a.needsDefaultPrefix&&(console.error("Unable to resolve a default prefix for every component. Re-run with --prefix <prefix>."),Q.exit(1)),!Ce(e)){let h=await mp(r,a.resolvedTags);Object.keys(h).length>0&&(a=Wt(r,{config:pp(s,h),scan:i,prefix:m}))}let u=await fp(t,e,s);a.config.init.editors=u;let p=Ue("Writing generated files...").start(),d={written:[],warnings:[]};try{for(let b of ti(r,a.resolvedTags))await ip.writeFile(ap.join(t,b.filename),b.contents,"utf-8");d=await sr(t,r,a.resolvedTags,u),li(t,a.config);let h=d.written.length>0?` Editor IntelliSense: ${d.written.join(", ")}.`:"";p.succeed(`Wrote ${X}, ${pe}, and ${M} for ${r.length} component(s).${h}`)}catch(h){let b=h instanceof Error?h.message:String(h);p.fail(`Failed to write generated files: ${b}`),Q.exit(1)}for(let h of d.warnings)console.error(`\u26A0 ${h}`);for(let h of a.warnings)console.error(`\u26A0 ${h}`);for(let h of o)console.error(`\u26A0 Tag <${h.tagName}> is registered by multiple installed packages: ${h.packages.join(", ")}. Grounded once \u2014 verify which package you intend to use.`);a.reconciliationWarnings.length>0&&console.error(de(`\u26A0 ${a.reconciliationWarnings.length} component tag(s) may not match your app's registered tags`,a.reconciliationWarnings,"red")),a.noPrefixWarnings.length>0&&console.error(de(`\u26A0 ${a.noPrefixWarnings.length} component(s) grounded under bare 'auro-*' tags \u2014 pass a prefix to avoid collisions`,a.noPrefixWarnings,"yellow"));let f=rr(t,u);if(f.inconsistencies.length>0)try{let h=await sr(t,r,a.resolvedTags,u),b=new Set(d.warnings);for(let v of h.warnings)b.has(v)||console.error(`\u26A0 ${v}`);f=rr(t,u)}catch(h){let b=h instanceof Error?h.message:String(h);console.error(`\u26A0 Could not re-write editor artifacts to self-heal wiring: ${b}`)}f.inconsistencies.length>0&&console.error(de("\u26A0 Editor IntelliSense wiring is incomplete after writing",f.inconsistencies,"red")),f.markupDisabled&&console.error(de("\u26A0 VS Code markup IntelliSense is off \u2014 no <auro-*> completions or hover docs",["Type-checking may still work, but tag/attribute completions will not.","Re-run `auro init --vscode` to generate them."],"yellow"));let g=[...new Set([X,pe,M,...d.written])];await bp(t,g,e),e.offline||await hp(r)}async function bp(e,t,n){let r=await jt(e,t);if(r.length===0)return;if(console.error(de(`\u26A0 ${r.length} file(s) auro init wrote are git-ignored and won't be committed`,[...r,"These are meant to be committed so your team and CI share the same grounding/IntelliSense."],"red")),Ce(n)&&!n.yes){console.error("\u26A0 Un-ignore them in .gitignore (or re-run with --yes) so they get committed.");return}if(!n.yes){let{fix:i}=await ee.prompt([{type:"confirm",name:"fix",message:"Add entries to .gitignore so these files stay tracked (committed)?",default:!0}]);if(!i)return}let{fixed:o,unfixable:s}=await si(e,r);o.length>0&&console.error(`\u2714 Un-ignored ${o.length} file(s) in .gitignore so they will be committed.`),s.length>0&&console.error(de(`\u26A0 ${s.length} file(s) are still git-ignored \u2014 un-ignore them by hand`,[...s,"A parent directory is ignored by a rule auro init won't rewrite; edit .gitignore to re-include these paths."],"red"))}function wp(e){return e.filesToRemove.length===0&&e.unmerges.length===0}async function vp(e,t){let n=bi(e);if(wp(n)){console.log("Nothing to reset \u2014 no `auro init` output found.");for(let c of n.filesToSkip)console.error(`\u26A0 Left ${c.path} in place: ${c.reason}.`);return}console.log("`auro init --reset` will:");for(let c of n.filesToRemove)console.log(` \u2022 remove ${c}`);for(let c of n.unmerges)console.log(` \u2022 remove the Auro entry from ${c.path}`);for(let c of n.dirsToPrune)console.log(` \u2022 remove ${c}/ if it is left empty`);for(let c of n.filesToSkip)console.log(` \u2022 keep ${c.path} (${c.reason})`);if(!Ce(t)){let{confirm:c}=await ee.prompt([{type:"confirm",name:"confirm",message:"Remove these files and config entries?",default:!1}]);if(!c){console.log("Reset aborted \u2014 nothing was changed.");return}}let r=Ue("Removing `auro init` output...").start(),o;try{o=wi(e,n)}catch(c){let l=c instanceof Error?c.message:String(c);r.fail(`Failed to reset: ${l}`),Q.exit(1)}let s=o.removed.length>0?`Removed ${o.removed.length} file(s)`:"Removed no files",i=o.unmerged.length>0?`, un-merged ${o.unmerged.join(", ")}`:"",a=o.prunedDirs.length>0?`, pruned ${o.prunedDirs.map(c=>`${c}/`).join(", ")}`:"";r.succeed(`${s}${i}${a}.`);for(let c of o.warnings)console.error(`\u26A0 ${c}`);for(let c of o.skipped)console.error(`\u26A0 Left ${c.path} in place: ${c.reason}.`);console.error("\u2139 Reset does not undo an `auro-formkit` migration. If you migrated a legacy standalone form package, revert those package.json and import changes with git.")}var ev=cp.command("init").description("Generate AI grounding files (AGENTS.md + CLAUDE.md) for the installed Auro components").option("--prefix <prefix>","Default custom-element tag prefix (e.g. myapp-) for components without an existing registration").option("--non-interactive","Never prompt; take the prefix from --prefix or fail cleanly (implied by a non-TTY stdin or CI)",!1).option("--yes","Alias for --non-interactive",!1).option("--offline","Skip the network check for newer component releases",!1).option("--vscode","Generate VS Code HTML custom-data IntelliSense (use --no-vscode to skip; default: auto-detect)").option("--no-vscode","Skip the VS Code HTML custom-data artifact").option("--jsx","Generate JSX/React type declarations (use --no-jsx to skip; default: auto-detect)").option("--no-jsx","Skip the JSX/React type declarations").option("--svelte","Generate Svelte type declarations (use --no-svelte to skip; default: auto-detect)").option("--no-svelte","Skip the Svelte type declarations").option("--css-snippets","Generate VS Code CSS ::part() snippets (use --no-css-snippets to skip; default: auto-detect)").option("--no-css-snippets","Skip the VS Code CSS ::part() snippets").option("--reset","Remove every file and config entry a previous `auro init` run created (does not undo an auro-formkit migration)",!1).action(yp);import Ht from"node:process";import{Logger as kp}from"@aurodesignsystem/auro-library/scripts/utils/logger.mjs";import{program as $p}from"commander";import Ei from"ora";async function Ep(e,t){let n=r=>({headerPkg:e,installPkg:e,importSpecifier:e,redirectedToFormkit:!1,result:r});if(t.tag)return n(await O(`${e}@${t.tag}`));if(Y(e)){let r=await O(e,{allowNetwork:!1});return r.manifest?n(r):{headerPkg:G,installPkg:G,importSpecifier:ve(e),tagFilter:er(e),redirectedToFormkit:!0,result:await O(G)}}return n(await O(e))}async function Sp(e,t){let n=Zs(e),r=Ei(`Fetching ${n}...`).start(),o=await Ep(n,t),{result:s}=o,i=s.target;s.manifest||(r.fail(s.transient?`Failed to fetch ${i}: ${s.reason}.`:`No custom-elements.json published for ${i}. It may not exist or may not publish a manifest yet.`),Ht.exit(1));let c=(s.manifest.modules??[]).flatMap(u=>u.declarations??[]).filter(u=>u.customElement&&u.tagName).filter(u=>!o.tagFilter||u.tagName===o.tagFilter);c.length===0&&(r.fail(o.tagFilter?`No <${o.tagFilter}> element found in ${i}.`:`No registered custom elements found for ${i}.`),Ht.exit(1));let l=s.source==="local"?` (local${s.version?` v${s.version}`:""})`:" (unpkg)";r.succeed(`${i} \u2014 ${c.length} custom element${c.length===1?"":"s"}${l}`),o.redirectedToFormkit&&console.error(`\u2139 ${o.tagFilter} now ships in ${G} \u2014 showing the monorepo version (the legacy standalone isn't installed).`);let m=null;if(s.source==="local"&&s.version){let u=Ei("Checking for a newer release...").start(),p=await ke(new Map([[o.headerPkg,s.version]]));u.stop(),p.length>0&&(m=$e(p))}if(t.json){Ht.stdout.write(`${JSON.stringify(c,null,2)}
|
|
428
|
+
`),m&&console.error(m);return}Ht.stdout.write(`
|
|
429
|
+
${c.map(u=>Qs(o.headerPkg,u,{installPkg:o.installPkg,importSpecifier:o.importSpecifier})).join(`
|
|
428
430
|
|
|
429
431
|
---
|
|
430
432
|
|
|
431
433
|
`)}
|
|
432
|
-
`),
|
|
433
|
-
Full docs: https://auro.alaskaair.com`),m&&console.error(m)}var
|
|
434
|
+
`),kp.info(`
|
|
435
|
+
Full docs: https://auro.alaskaair.com`),m&&console.error(m)}var uv=$p.command("component <name>").description("Look up an Auro component's API (attributes, properties, slots, events, CSS parts) from its published Custom Elements Manifest").option("-t, --tag <version>","npm dist-tag or version to look up (default: latest); pins the standalone package for a legacy form component").option("--json","Output the raw manifest declaration(s) as JSON",!1).action(Sp);import{program as Cp}from"commander";import Ap from"ora";var pr=Cp.command("docs").description("Generate API documentation").option("-c, --cem","Generate Custom Elements Manifest (CEM) file",!1).option("-a, --api","Creates api md file from CEM",!1).option("-w, --watch","Watch for changes and rebuild docs",!1).option("-r, --readme-template <url>","URL to the README template file").option("--skip-readme","Skip README.md processing",!1);pr=Ve(pr);var xp={cem:et,api:tt,docs:Nr,serve:Or,watchDocs:jr};async function Tp(e,t=xp){try{e.cem&&await t.cem(),e.api&&await t.api();try{await t.docs(e)}catch(n){if(!e.watch)throw n}e.serve&&await t.serve(e),e.watch&&await t.watchDocs(e)}catch(n){Ap().fail(`Docs failed: ${n instanceof Error?n.message:String(n)}`),process.exit(1)}}var hv=pr.action(e=>Tp(e));import{program as Np}from"commander";import{Octokit as dr}from"@octokit/rest";import*as zt from"azure-devops-node-api";import Jt from"ora";var Rp=async e=>{let t=process.env.GH_TOKEN;if(!t)throw new Error("GH_TOKEN environment variable is required");let n=new dr({auth:t}),r,o,s;if(e.includes("github.com")){let a=e.match(/github\.com\/([^\/]+)\/([^\/]+)\/issues\/(\d+)/);if(!a)throw new Error("Invalid GitHub issue URL format");[,r,o,s]=a}else if(e.includes("#")){let a=e.match(/([^\/]+)\/([^#]+)#(\d+)/);if(!a)throw new Error("Invalid GitHub issue reference format");[,r,o,s]=a}else throw new Error("Issue must be provided as full URL or in format 'owner/repo#number'");let i=Number.parseInt(s,10);try{let{data:a}=await n.rest.issues.get({owner:r,repo:o,issue_number:i});return{title:a.title,body:a.body??null,html_url:a.html_url,number:a.number,repository:{owner:{login:r},name:o}}}catch(a){throw new Error(`Failed to fetch GitHub issue: ${a}`)}},Pp=async e=>{let t=process.env.GH_TOKEN;if(!t)return null;let n=new dr({auth:t});try{let r=`
|
|
434
436
|
query($owner: String!, $repo: String!, $issueNumber: Int!) {
|
|
435
437
|
repository(owner: $owner, name: $repo) {
|
|
436
438
|
issue(number: $issueNumber) {
|
|
@@ -456,7 +458,7 @@ Full docs: https://auro.alaskaair.com`),m&&console.error(m)}var Sw=Bm.command("c
|
|
|
456
458
|
}
|
|
457
459
|
}
|
|
458
460
|
}
|
|
459
|
-
`,o={owner:e.repository.owner.login,repo:e.repository.name,issueNumber:e.number},i=(await n.graphql(r,o)).repository.issue.projectItems.nodes.find(a=>a.project.number===19);if(i){let a=i.fieldValues.nodes.find(c=>c.field?.name?.toLowerCase()==="ado"&&c.text?.trim());if(a?.text?.trim())return a.text.trim()}return null}catch(r){return console.error(`Failed to check existing ADO link: ${r}`),null}},
|
|
461
|
+
`,o={owner:e.repository.owner.login,repo:e.repository.name,issueNumber:e.number},i=(await n.graphql(r,o)).repository.issue.projectItems.nodes.find(a=>a.project.number===19);if(i){let a=i.fieldValues.nodes.find(c=>c.field?.name?.toLowerCase()==="ado"&&c.text?.trim());if(a?.text?.trim())return a.text.trim()}return null}catch(r){return console.error(`Failed to check existing ADO link: ${r}`),null}},Dp=async(e,t)=>{let n=process.env.GH_TOKEN;if(!n)throw new Error("GH_TOKEN environment variable is required");let r=new dr({auth:n}),o=19;try{let s=`
|
|
460
462
|
query($org: String!, $projectNumber: Int!, $owner: String!, $repo: String!, $issueNumber: Int!) {
|
|
461
463
|
organization(login: $org) {
|
|
462
464
|
projectV2(number: $projectNumber) {
|
|
@@ -523,12 +525,12 @@ Full docs: https://auro.alaskaair.com`),m&&console.error(m)}var Sw=Bm.command("c
|
|
|
523
525
|
}
|
|
524
526
|
}
|
|
525
527
|
}
|
|
526
|
-
`,{projectId:c,itemId:u,fieldId:m.id,value:t});else if(!m)throw new Error("No 'ado' field found in GitHub project")}catch(s){console.error(`Failed to update GitHub project: ${s}`)}},
|
|
527
|
-
${r.body??""}`;for(let s of o.matchAll(n)){let i=Number.parseInt(s[1],10);Number.isNaN(i)||t.add(i)}}return[...t]}async function
|
|
528
|
-
${n.map(
|
|
529
|
-
`)}`),t}function
|
|
530
|
-
${e.map(
|
|
531
|
-
`)}`;for(let[o,s]of[["Area Path",
|
|
532
|
-
${i.map(
|
|
528
|
+
`,{projectId:c,itemId:u,fieldId:m.id,value:t});else if(!m)throw new Error("No 'ado' field found in GitHub project")}catch(s){console.error(`Failed to update GitHub project: ${s}`)}},Mp=async e=>{let t=process.env.ADO_TOKEN;if(!t)throw new Error("ADO_TOKEN environment variable is required");let n="https://dev.azure.com/itsals",r="E_Retain_Content",o="E_Retain_Content\\Auro Design System",s=zt.getPersonalAccessTokenHandler(t),a=await new zt.WebApi(n,s).getWorkItemTrackingApi();try{let c=[{op:"add",path:"/fields/System.Title",value:e.title},{op:"add",path:"/fields/System.Description",value:`GitHub Issue: <a href="${e.html_url}">${e.html_url}</a>`},{op:"add",path:"/fields/System.AreaPath",value:o}];return await a.createWorkItem(null,c,r,"User Story")}catch(c){throw new Error(`Failed to create ADO work item: ${c}`)}},Si=async e=>{let t=Jt(`Processing GitHub issue: ${e}`).start();try{if(!process.env.GH_TOKEN)throw new Error("GH_TOKEN environment variable is required");if(!process.env.ADO_TOKEN)throw new Error("ADO_TOKEN environment variable is required");t.text="Fetching GitHub issue details...";let n=await Rp(e);t.succeed(`Found issue: "${n.title}"`);let r=Jt("Checking for existing ADO work item...").start(),o=await Pp(n);if(o){r.succeed("ADO work item already exists for this issue!"),console.log(`${o}`);return}r.succeed("No existing ADO work item found");let s=Jt("Creating new ADO work item...").start(),i=await Mp(n);if(s.succeed(`Successfully created ADO work item #${i.id}`),console.log(`Work item: ${i._links?.html?.href||"N/A"}`),i._links?.html?.href){let a=Jt("Adding to GitHub project and updating ADO field...").start();await Dp(n,i._links.html.href),a.succeed("Updated GitHub project with ADO link")}}catch(n){t.fail(`Error: ${n instanceof Error?n.message:n}`),process.exit(1)}};var Ev=Np.command("ado").description("Generate ADO item from GitHub issue").option("-g, --gh-issue <issue>","What GitHub issue to use").action(async e=>{e.ghIssue&&await Si(e.ghIssue)});import{program as Vp}from"commander";import{Octokit as Hp}from"@octokit/rest";import{simpleGit as Jp}from"simple-git";import*as Vt from"azure-devops-node-api";import{WorkItemErrorPolicy as Ci,WorkItemExpand as Ip}from"azure-devops-node-api/interfaces/WorkItemTrackingInterfaces.js";var xi="https://dev.azure.com/itsals",fr="E_Retain_Content",Ti="auro-rcs",Op=new Set(["closed","removed"]);function Ri(e){let t=new Set,n=/AB#(\d+)/gi;for(let r of e){let o=r.message??`${r.subject??""}
|
|
529
|
+
${r.body??""}`;for(let s of o.matchAll(n)){let i=Number.parseInt(s[1],10);Number.isNaN(i)||t.add(i)}}return[...t]}async function jp(){let e=process.env.ADO_TOKEN;if(!e)throw new Error("ADO_TOKEN environment variable is required to resolve the Release ticket.");let t=Vt.getPersonalAccessTokenHandler(e);return new Vt.WebApi(xi,t).getWorkItemTrackingApi()}function _p(e){if(!e)return null;let t=e.match(/\/workItems\/(\d+)(?:\/)?$/i);return t?Number.parseInt(t[1],10):null}function Fp(e){let t=e.fields?.["System.Tags"];return typeof t!="string"?!1:t.split(";").map(n=>n.trim().toLowerCase()).includes(Ti)}function Ai(e){let t=e.fields?.["System.State"];return typeof t!="string"||!Op.has(t.toLowerCase())}function Lp(e){let t=e.filter(Ai),n=e.filter(r=>!Ai(r));return n.length>0&&console.log(`Ignoring ${n.length} closed Release ticket(s):
|
|
530
|
+
${n.map(gr).join(`
|
|
531
|
+
`)}`),t}function hr(e){return e.toLowerCase().replace(/[^a-z0-9]+/g," ").trim()}function Gp(e){let t=hr(e),n=t.replace(/^auro /,"");return[...new Set([t,n])].filter(Boolean)}function Bp(e,t){let n=e.fields?.["System.AreaPath"];return typeof n!="string"?!1:n.split("\\").map(hr).some(r=>t.includes(r))}function Wp(e,t){let n=e.fields?.["System.Title"];if(typeof n!="string")return!1;let r=` ${hr(n)} `;return t.some(o=>r.includes(` ${o} `))}function gr(e){let t=e.fields?.["System.Title"]??"(no title)",n=e.fields?.["System.AreaPath"]??"(no area path)",r=e.fields?.["System.State"]??"(no state)";return`#${e.id} "${t}" [${n}] (${r})`}function Up(e,t){let n=Gp(t),r=`
|
|
532
|
+
${e.map(gr).join(`
|
|
533
|
+
`)}`;for(let[o,s]of[["Area Path",Bp],["title",Wp]]){let i=e.filter(a=>s(a,n));if(i.length===1)return console.log(`Found ${e.length} Release tickets; selected #${i[0].id} for "${t}" by ${o}.`),i[0];if(i.length>1)throw new Error(`Found ${i.length} Release tickets whose ${o} matches "${t}":
|
|
534
|
+
${i.map(gr).join(`
|
|
533
535
|
`)}
|
|
534
|
-
Only one Release Candidate ticket per repo is supported.`)}throw new Error(`Found ${e.length} Release tickets but none could be matched to "${t}" by Area Path or title:${r}`)}async function
|
|
536
|
+
Only one Release Candidate ticket per repo is supported.`)}throw new Error(`Found ${e.length} Release tickets but none could be matched to "${t}" by Area Path or title:${r}`)}async function Pi(e,t){if(e.length===0)return console.log("No ADO work item references (AB#<id>) found in the RC commits."),null;let n=await jp(),r=await n.getWorkItems(e,void 0,void 0,Ip.Relations,Ci.Omit,fr),o=new Set;for(let m of r??[])for(let u of m.relations??[]){let p=_p(u.url);p!==null&&o.add(p)}if(o.size===0)return console.log(`None of the committed work items (${e.join(", ")}) link to another work item in ADO.`),null;let s=await n.getWorkItems([...o],["System.Title","System.Tags","System.AreaPath","System.State"],void 0,void 0,Ci.Omit,fr),i=Lp((s??[]).filter(Fp));if(i.length===0)return console.log(`No open Release ticket (tagged "${Ti}") is linked to the committed work items (${e.join(", ")}).`),null;let a=i.length===1?i[0]:Up(i,t);if(a.id===void 0)throw new Error("Failed to resolve the Release ticket details from ADO.");let c=typeof a.fields?.["System.Title"]=="string"?a.fields["System.Title"]:`Work item ${a.id}`,l=a._links?.html?.href??`${xi}/${fr}/_workitems/edit/${a.id}`;return{id:a.id,url:l,title:c}}var He="dev",zp="main",Kt=class e{constructor(t,n,r){this.repoInfo={owner:t,repo:n},this.octokit=r}static async create(){let t=process.env.GITHUB_TOKEN;if(!t)throw new Error("GITHUB_TOKEN is required to run RC workflow.");if(!process.env.ADO_TOKEN)throw new Error("ADO_TOKEN is required to resolve the ADO Release ticket for the RC workflow.");let n=await V.getRepoOwnerAndName(),r=new Hp({auth:t});if(!n)throw new Error("Failed to retrieve repository information. Ensure you're in a valid git repository.");let o=await e.getTriggerBranchName();return o&&o!==He&&(console.log(`Switching from ${o} to ${He} branch...`),await Jp().checkout(He)),new e(n.owner,n.repo,r)}get owner(){return this.repoInfo.owner}get repo(){return this.repoInfo.repo}get repoData(){return{...this.repoInfo}}async createReleaseCandidate(){let t=await this.resolveReleaseTicket();if(!t){console.log("No ADO Release ticket is linked to the new commits on `dev`. Skipping Release PR.");return}console.log(`Using ADO Release ticket #${t.id} (${t.title}) -> ${t.url}`);let n=await this.getLinkedPrByHead(t.id);if(n?.multipleOpen)throw new Error("Multiple open RC PRs found for the same rc/<ticketId> branch.");n?.state==="closed"&&(console.log("Linked RC PR is closed. Creating a new RC PR on the same branch."),n=null),await this.createOrUpdateRcBranch(t.id),n?await this.updateRcPr(t,n.number):n=await this.createRcPr(t)}async resolveReleaseTicket(){let t=await V.getCommitMessages(He),n=Ri(t);return Pi(n,this.repoInfo.repo)}async createOrUpdateRcBranch(t){let n=`heads/rc/${t}`,r=`rc/${t}`,{data:o}=await this.octokit.rest.repos.getBranch({owner:this.repoInfo.owner,repo:this.repoInfo.repo,branch:He}),{data:s}=await this.octokit.rest.git.listMatchingRefs({owner:this.repoInfo.owner,repo:this.repoInfo.repo,ref:n}),i=s.length>0;try{i?(console.log(`Updating existing RC branch: ${r}`),await this.octokit.rest.git.updateRef({owner:this.repoInfo.owner,repo:this.repoInfo.repo,ref:n,sha:o.commit.sha,force:!0})):(console.log(`Creating new RC branch: ${r}`),await this.octokit.rest.git.createRef({owner:this.repoInfo.owner,repo:this.repoInfo.repo,ref:`refs/${n}`,sha:o.commit.sha}))}catch(a){throw new Error(`Failed to create or update ${r} branch: ${a}`)}}async getLinkedPrByHead(t){let n=`${this.repoInfo.owner}:rc/${t}`,{data:r}=await this.octokit.rest.pulls.list({owner:this.repoInfo.owner,repo:this.repoInfo.repo,state:"all",head:n,per_page:30}),o=r.filter(i=>i.state==="open");if(o.length>1)return{state:"open",multipleOpen:!0};if(o.length===1)return{state:"open",html_url:o[0].html_url,number:o[0].number};let s=r.filter(i=>i.state==="closed");return s.length>0?{state:"closed",html_url:s[0].html_url,number:s[0].number}:null}rcReference(t){return`Release candidate pull request. Tracked by ADO Release ticket [AB#${t.id}](${t.url}) \u2014 ${t.title}.`}async buildPrBody(t){let n=this.rcReference(t);try{let{data:r}=await this.octokit.rest.repos.getContent({owner:this.repoInfo.owner,repo:this.repoInfo.repo,path:".github/PULL_REQUEST_TEMPLATE.md"});if("content"in r&&r.type==="file"){let o=Buffer.from(r.content,"base64").toString("utf-8");return o=o.replace("Please include a summary of the change and which issue is fixed. Please also include relevant motivation and context. List any dependencies that are required for this change.",n),o=o.replace(/<details>/g,"<details open>"),o}}catch(r){r&&typeof r=="object"&&"status"in r&&r.status===404?console.log("No PR template found in repo, using default message."):console.warn("Failed to fetch PR template:",r)}return n}async createRcPr(t){try{let n=await this.buildPrBody(t),{data:r}=await this.octokit.request(`POST /repos/${this.repoInfo.owner}/${this.repoInfo.repo}/pulls`,{owner:this.repoInfo.owner,repo:this.repoInfo.repo,title:`RC #${t.id}`,body:n,head:`rc/${t.id}`,base:zp,headers:{"X-GitHub-Api-Version":"2022-11-28"}});return console.log(`Created Release Candidate pull request: #${r.number} (${r.html_url})`),{state:"open",html_url:r.html_url,number:r.number}}catch(n){throw console.error("Failed to create RC PR:",n),n}}async updateRcPr(t,n){try{let r=await this.buildPrBody(t);await this.octokit.rest.pulls.update({owner:this.repoInfo.owner,repo:this.repoInfo.repo,pull_number:n,body:r}),console.log(`Updated Release Candidate pull request: #${n}`)}catch(r){throw console.error("Failed to update RC PR:",r),r}}static async getTriggerBranchName(){return process.env.GITHUB_REF_NAME?process.env.GITHUB_REF_NAME:process.env.GITHUB_REF?.startsWith("refs/heads/")?process.env.GITHUB_REF.replace("refs/heads/",""):V.getCurrentBranchName()}};var Iv=Vp.command("rc-workflow").description("Generate RC issue and pull request").action(async()=>{await(await Kt.create()).createReleaseCandidate()});yr.name("auro").version(qt()).description("A cli tool to support the Auro Design System");yr.addHelpText("beforeAll",br());yr.parse();
|