/**
 * Skipped minification because the original files appears to be already minified.
 * Original file: /npm/ng2ninja@7.0.0/dist/ng2ninja.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
#!/usr/bin/env node
import{parseArgs as e}from"node:util";import{rimrafSync as r}from"rimraf";import t from"node:fs";import o from"node:fs/promises";import s from"crypto";import n from"child_process";import a from"util";import i from"prompt";import{glob as c}from"glob";import u from"chalk";import l from"axios";const d=a.promisify(n.exec),g=e=>o.readFile(e,"utf8"),h=e=>d(e,{maxBuffer:1024e3}),f=e=>{const r=t.readFileSync(e),o=s.createHash("sha256");return o.update(r),o.digest("hex")},w={log:console.log,error:e=>console.log(u.red(e)),warn:e=>console.log(u.yellow(e)),success:e=>console.log(u.green(e)),debug:(e,r,t)=>{e.verbose&&(t?console.log(u.gray(r),u.gray(t)):console.log(u.gray(r)))}};function y(e){const r=JSON.parse(e);if(!r)throw w.error("An error occurred during the unit tests."),w.error("Run `ng test` to see the problem."),new Error("Invalid test results");const t={failed:r.numFailedTests?r.numFailedTests:r.numFailedTestSuites,success:r.numPassedTests};return 0!==t.failed?function(e){const r=function(e){if(void 0===e.failed)return 0;const r=100-5*e.failed;return r>=0?r:0}(e);w.warn("Unit tests score: "+r+"%"),w.warn("Looks like you have "+(e.failed?e.failed:"a few")+" unit test(s) failing."),w.warn("Run `ng test` and try to fix them.")}(t):w.success("Unit tests score: 100%"),t}function p(){return c("./{e2e,src}/**/*.ts",{nodir:!0,posix:!0})}function m(){return p().then(e=>function(e){return e.map(e=>({name:e,hash:f(e)}))}(e))}const v={covered:0,total:10};const b="results/lint-results.json";const k="https://angular-exercises.ninja-squad.com",x="http://localhost:8080";async function E(e,r,t){if((r+=1)>3)return w.error("Aborting authentication after 3 failures"),Promise.reject();const o={properties:{email:{required:!0},password:{hidden:!0,required:!0}}};try{const s=await(e=>new Promise((r,t)=>{i.start(),i.get(e,(e,o)=>{e?t(e):r(o)})}))(o),n=await l.post(`${e["local-server"]?x:k}/api/authentications`,s);return 201!==n.status?(w.error("Authentication failed, try again."),w.debug(e,`Authentication request returned with status: ${n.status}`),E(e,r,t)):(w.debug(e,"Authentication succeeded and we can store credentials"),function(e,r){return w.success("Authentication success"),e.token=r,e}(t,n.data.token))}catch(o){return w.error("Authentication failed, try again."),w.debug(e,"An error occurred during authentication: ",o),E(e,r,t)}}function S(e,r){let t=100-5*e.vitest.failed-e.lint.errors-(e.coverage.total-e.coverage.covered)-e.e2e.failed;var o;return t<10&&(t=10),r.local?(100!==t&&(w.error("Score is not perfect! "+t+"%"),o=1,process.exit(o)),w.success("Exercise score: "+t+"%")):100!==t?w.warn("Score is not perfect yet: "+t+"%"):w.success("Perfect score, congrats! "+t+"%"),t}const j=process.argv.slice(2),{values:N}=e({args:j,parseArgsOptions:{local:{type:"boolean"},"local-server":{type:"boolean"},verbose:{type:"boolean"},"skip-check":{type:"boolean"}},strict:!1});r("results");try{const e=await async function(e){let r;w.log("Checking submission...");try{r=JSON.parse(await g("./exercise.json"))}catch(r){throw w.error("Looks like you have no exercise.json file."),w.debug(e,"An error occurred while reading exercise.json: ",r),new Error("No exercise.json file")}if(w.success(`Pack V${r.pack} - Exercise ${r.id} - ${r.title}`),e["skip-check"])return r;let t=[];try{t=await m()}catch(r){throw w.debug(e,"Error while computing the hash of the spec files. ",r),r}w.debug(e,"Exercise :",JSON.stringify(r)),w.debug(e,"Hashes :",JSON.stringify(t));const o=[],s=[];if(r.specs.forEach(e=>{const r=function(e,r){return e.find(e=>e.name.includes(r))}(t,e.name);r?r.hash!==e.hash&&o.push(e.name):s.push(e.name)}),0!==o.length||0!==s.length)throw 0!==o.length&&(w.error("It looks like you forgot to update these spec files"),w.error("or that you modified them manually:"),o.forEach(e=>w.error(` - ${e}`))),0!==s.length&&(w.error("It looks like you forgot to add these spec files:"),s.forEach(e=>w.error(` - ${e}`))),w.error("Copy the new specs and try again."),new Error("Specs are not up to date");return r}(N);w.debug(N,"Exercise: ",e.title);const r=await async function(e){w.log("Starting unit tests...");try{await h("ng test --no-watch --coverage")}catch(r){w.debug(e,"Unit test failed",r)}try{return y(await g("results/vitest-results.json"))}catch(r){throw w.debug(e,"An error occurred while reading vitest results: ",r),w.error("Error while running unit tests."),w.error("Maybe your code doesn't compile?"),w.error("Run `ng test` to see more."),r}}(N);w.debug(N,"Vitest results: ",JSON.stringify(r));const t=await async function(e){let r;w.log("Starting code coverage...");try{r=await g("coverage/ponyracer/coverage-summary.json")}catch(e){return w.warn("Code coverage score: 0%"),w.warn("No coverage found, probably because some unit tests failed."),v}try{return function(e){const r=e.replace(/\\/g,"/"),t=JSON.parse(r),o={covered:t.total.lines.covered,total:t.total.lines.total},s=function(e){const r=100+e.covered-e.total;return r<0?0:r}(o);return 100!==s?(w.warn("Code coverage score: "+s+"%"),w.warn("Looks like you don't have a perfect code coverage."),w.warn("Maybe you skipped/deleted some unit tests?"),w.warn("Or maybe you added some code to try something, and this is not covered by a unit test?"),w.warn("To have more info open `coverage/ponyracer/index.html`"),w.warn("You should see which file has a problem.")):w.success("Code coverage score: 100%"),o}(r)}catch(r){throw w.error("Error while reading the code coverage results. Try to run `ng test --watch=false --code-coverage`."),w.debug(e,"Error while reading the code coverage results was: ",r),r}}(N);w.debug(N,"Coverage results: ",JSON.stringify(t));const o=await async function(e){w.log("Starting code analysis...");try{await h(`ng lint --format=json --output-file=${b}`)}catch(e){}try{const e=await g(b),r=JSON.parse(e),t={errors:0};if(t.errors=r.map(e=>e.errorCount+e.warningCount).reduce((e,r)=>e+r,0),0!==t.errors){const e=Math.max(0,100-t.errors);w.warn("Code quality score: "+e+"%"),w.warn("Looks like you have some issues in your code."),w.warn("Try to run `ng lint` to see what you can fix.")}else w.success("Code quality score: 100%");return t}catch(r){throw w.error("Error while running `ng lint`."),w.error("Try to run `ng lint`."),w.debug(e,"Error while running lint was: ",r),r}}(N);w.debug(N,"Linter results: ",JSON.stringify(o));const s=await async function(e){w.log("Starting end to end tests...");try{await h("ng e2e")}catch(r){w.debug(e,"Error while running e2e tests: ",r)}try{return function(e){const r=JSON.parse(e),t=r.stats.unexpected,o=r.stats.expected,s={success:o,failed:t};return t?(w.warn("Looks like you have "+t+" e2e tests failing."),w.warn("Try to launch the tests using `ng e2e`."),w.warn(`E2e tests score: ${Math.round(100*o/(o+t))}%`)):w.success("E2e tests score: 100%"),s}(await g("results/playwright-results.json"))}catch(r){throw w.debug(e,"Error while reading e2e results: ",r),w.error("Error while running end-to-end tests."),w.error("Check if your app is running with no error in the browser console,"),w.error("and try to launch the tests using `ng e2e`."),r}}(N);w.debug(N,"E2e results: ",JSON.stringify(s));const n={exercise:e,vitest:r,coverage:t,lint:o,e2e:s};await async function(e,r){let t;try{t=JSON.parse(await g("./exercise.json"))}catch(e){throw w.error("Looks like you have no exercise.json file."),w.debug(r,"An error occurred while reading exercise.json: ",e),e}return t.score=S(e,r),r.local?t:async function(e,r){const t={Authorization:`Bearer: ${r.token}`},o=e["local-server"]?x:k,s={score:r.score};try{const n=await l.post(`${o}/api/packs/${r.pack}/exercises/${r.id}/scores`,s,{headers:t});return 201!==n.status?(w.error("Error while sending the results."),w.debug(e,`${n.status}`,JSON.stringify(n.data)),Promise.reject()):(w.log("Score submitted."),r)}catch(r){throw w.error("Error while sending the results."),w.error("Maybe check your connection?"),w.debug(e,"Error while sending the result was: ",r),r}}(r,await E(r,0,t))}(n,N)}catch(e){w.error("Try to fix it and retry!"),N.verbose&&w.error(e),N.local&&(w.error("Running locally, we exit"),process.exit(1))}
