@goodfellow-cms/broker 0.5.0 → 0.6.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 +2 -2
- package/package.json +6 -5
- package/site/assets/content-repository-setup-3Z0i5cMx.js +4 -0
- package/site/assets/dist-CLietd1m.js +5 -0
- package/site/assets/dist-DuGHJcqN.js +2 -0
- package/site/assets/dist-Dz15_FP0.js +6 -0
- package/site/assets/index-j9FvrqIj.js +56 -0
- package/site/assets/scheduled-builds-BPfDaBYt.js +1 -0
- package/site/assets/setup-host-B_uhd1y7.js +2 -0
- package/site/assets/store-CNLNNQkL.js +1 -0
- package/site/files.json +8 -5
- package/site/index.html +2 -2
- package/site/assets/dist-C20K9oCc.js +0 -5
- package/site/assets/dist-cedgnWG_.js +0 -6
- package/site/assets/index-Cb7Ya0Pj.js +0 -2
- package/site/assets/setup-host-w4Qxug91.js +0 -5
- package/site/assets/store-5raQS3us.js +0 -1
package/README.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# @goodfellow-cms/broker
|
|
2
2
|
|
|
3
|
-
Goodfellow's token broker: a small static page, on an address of its own, where editors sign in. It keeps their GitHub or
|
|
3
|
+
Goodfellow's token broker: a small static page, on an address of its own, where editors sign in. It keeps their GitHub, GitLab or Bitbucket sign-in and AI keys in its own storage, shows the site's admin panel in a frame, and makes every call to the git host and AI services for it, so nothing on the site's own address can read them. It asks the editor, outside the admin panel's frame, before publishing the site's code, and never changes its workflows.
|
|
4
4
|
|
|
5
5
|
The package is the built page, in `site/`, with `site/files.json` listing its files. The quickest way to run one is **Site Settings → Security → Add a token broker** in the site's admin panel, or `npx goodfellow broker add` in the site's folder, which make its repository from this page. By hand, copy `site/` into a repository of its own, add a `broker.json` naming the site (see `site/broker.example.json`), put it online at an address that serves nothing else, and set that address in the site's admin panel, under **Site Settings → Security**.
|
|
6
6
|
|
|
7
|
-
[Goodfellow](https://github.com/goodfellow-cms/goodfellow-cms) is a website builder for people who aren't developers, with no server or database: pages are files in your own GitHub or
|
|
7
|
+
[Goodfellow](https://github.com/goodfellow-cms/goodfellow-cms) is a website builder for people who aren't developers, with no server or database: pages are files in your own GitHub, GitLab or Bitbucket repository, edited in a visual editor built on [Puck](https://puckeditor.com). To start a new site, run `npm create goodfellow@latest my-site`. See the [documentation](https://goodfellow-cms.github.io/goodfellow-cms/) for everything else.
|
|
8
8
|
|
|
9
9
|
More in the docs: [Token broker](https://goodfellow-cms.github.io/goodfellow-cms/docs/token-broker).
|
|
10
10
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@goodfellow-cms/broker",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Goodfellow's token broker: a page of its own that keeps editors' sign-in and AI keys, and shows the site's admin panel in a frame.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"goodfellow",
|
|
@@ -26,10 +26,11 @@
|
|
|
26
26
|
"site"
|
|
27
27
|
],
|
|
28
28
|
"devDependencies": {
|
|
29
|
-
"@goodfellow-cms/ai": "0.
|
|
30
|
-
"@goodfellow-cms/core": "0.
|
|
31
|
-
"@goodfellow-cms/
|
|
32
|
-
"@goodfellow-cms/
|
|
29
|
+
"@goodfellow-cms/ai": "0.6.0",
|
|
30
|
+
"@goodfellow-cms/core": "0.6.0",
|
|
31
|
+
"@goodfellow-cms/bitbucket": "0.6.0",
|
|
32
|
+
"@goodfellow-cms/github": "0.6.0",
|
|
33
|
+
"@goodfellow-cms/gitlab": "0.6.0",
|
|
33
34
|
"happy-dom": "21.0.4",
|
|
34
35
|
"vite": "8.3.4"
|
|
35
36
|
},
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import{o as e}from"./store-CNLNNQkL.js";var t=class extends Error{problem;name=`DomainError`;constructor(e,t){super(t),this.problem=e}},n=`goodfellow-build-problem `;function r(e){let t=e.split(`
|
|
2
|
+
`);for(let e=t.length-1;e>=0;e--){let r=t[e]??``,i=r.indexOf(n);if(i!==-1)try{let e=JSON.parse(r.slice(i+25).trim());if((e.kind===`content`||e.kind===`code`)&&typeof e.message==`string`)return{kind:e.kind,message:e.message,...typeof e.file==`string`&&e.file&&{file:e.file}}}catch{}}}function i(e){let t=e.toLowerCase();if(/deploy-pages|deploy to |pages:deploy/.test(t))return`deploy`;if(/configure-pages|upload-pages-artifact|setup pages|set up pages/.test(t))return`pages`;if(/\b(npm (ci|install)|pnpm install|yarn( install)?|install packages)\b/.test(t))return`install`;if(/\bbuild\b/.test(t))return`build`}var a=`rebuild`;`${a}`;function o(e,t=`# `){let n=[];for(let r of e.split(`
|
|
3
|
+
`)){let e=``;for(let i of r.split(` `))e&&e.length+i.length+1>78-t.length?(n.push(e),e=i):e=e?`${e} ${i}`:i;n.push(e)}return n.map(e=>`${t}${e}`.trimEnd()).join(`
|
|
4
|
+
`)}`${o(`Drafts, from the admin panel's Add to draft and from Claude, are kept on branches named goodfellow-draft-…, and plugins' tasks answer on branches named goodfellow-task-…, which visitors never see, so Vercel doesn't build previews of them.`,` // `)}`,o(`The admin address's header rules, from the code's goodfellow.config.tsx: goodfellow admin and goodfellow broker, run in the code's folder, copy them here, since Vercel reads this file before the code is cloned.`,` // `),`${e}${e}`;export{t as i,i as n,r,a as t};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./deploy-keys-DAj2oX-N-DRd_HmOG.js","./git-eGyMXUIu.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{r as e,t}from"./store-CNLNNQkL.js";import{a as n,f as r,g as i,h as a,i as o,m as s,n as c,o as l,p as u,r as d,s as f,t as p,u as m,v as h,y as g}from"./setup-host-B_uhd1y7.js";import{i as _,n as v,t as y}from"./content-repository-setup-3Z0i5cMx.js";import{a as b,i as x,n as S,o as C,r as w,s as ee,t as T}from"./git-eGyMXUIu.js";import{t as te}from"./preload-helper-khBccGFq.js";async function E({apiUrl:e,token:t,fetch:n},r,i={}){let a=async a=>n(`${e}${r}`,{method:i.method??`GET`,headers:{accept:i.accept??`application/vnd.github+json`,authorization:`Bearer ${typeof t==`string`?t:await t({refresh:a})}`,"x-github-api-version":`2022-11-28`,...i.body!==void 0&&{"content-type":`application/json`}},body:i.body===void 0?void 0:JSON.stringify(i.body),cache:`no-store`}),o=await a(!1);if(o.status===401&&typeof t!=`string`&&(o=await a(!0)),o.status===401)throw new S(`invalid`,`GitHub didn't accept the sign-in. It may have expired.`);if(!o.ok&&!i.allow?.includes(o.status)){let e=await o.json().catch(()=>({}));throw new T(o.status,`GitHub answered ${o.status}: ${e.message??o.statusText}`)}return o}async function D(e,t,n){return await(await E(e,t,n)).json()}function O(e){return e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`)}var ne=/^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$/i,k=`invitation:`;function re(e){return e?.admin?`owner`:e?.maintain||e?.push?`editor`:`viewer`}function ie(e){return e===`admin`?`owner`:e===`write`||e===`maintain`?`editor`:`viewer`}function A(e){return e instanceof T&&(e.status===403||e.status===404)}function ae(e,t,n,r){let i=`/repos/${n}`;function a(){let e=t();if(!e)throw new c(`not-allowed`,`Changing editors on GitHub needs an owner token.`);return e}async function o(e){try{await e(a())}catch(e){throw A(e)?new c(`not-allowed`,`This token can't change the site's editors.`):e}}async function s(e){let t=[];for(let n=1;n<=10;n++){let r=await D(e,`${i}/collaborators?per_page=100&page=${n}`);if(t.push(...r),r.length<100)break}return t}return{invitesByEmail:!1,async list(){let n=t()??e,a=await s(n),o;try{o=await D(n,`${i}/invitations?per_page=100`)}catch(e){if(!A(e))throw e}let c=[...a.map(e=>({id:e.login,login:e.login,avatarUrl:e.avatar_url,role:re(e.permissions),...e.login.toLowerCase()===r.toLowerCase()&&{self:!0}})),...(o??[]).flatMap(e=>e.invitee?[{id:`${k}${e.id}`,login:e.invitee.login,avatarUrl:e.invitee.avatar_url,role:ie(e.permissions),invited:!0}]:[])],l=c.some(e=>e.self&&e.role===`owner`);return{editors:c,manage:o?`yes`:l?`token`:`no`,editorsCanPublish:!0}},async invite(e,t){let n=e.trim().replace(/^@/,``);if(!ne.test(n))throw new c(`invalid`,`That isn't a GitHub username.`);let r=a();try{await E(r,`${i}/collaborators/${encodeURIComponent(n)}`,{method:`PUT`,body:{permission:t===`owner`?`admin`:`push`}})}catch(e){throw e instanceof T&&e.status===404&&(await E(r,`/users/${encodeURIComponent(n)}`,{allow:[404]})).status===404?new c(`not-found`,`There's no GitHub account named ${n}.`):A(e)?new c(`not-allowed`,`This token can't change the site's editors.`):e instanceof T&&e.status===422?new c(`invalid`,`GitHub didn't accept the invitation: ${e.message}`):e}},async setRole(e,t){await o(async n=>{e.id.startsWith(k)?await E(n,`${i}/invitations/${e.id.slice(11)}`,{method:`PATCH`,body:{permissions:t===`owner`?`admin`:`write`}}):await E(n,`${i}/collaborators/${encodeURIComponent(e.id)}`,{method:`PUT`,body:{permission:t===`owner`?`admin`:`push`}})})},async remove(e){await o(t=>E(t,e.id.startsWith(k)?`${i}/invitations/${e.id.slice(11)}`:`${i}/collaborators/${encodeURIComponent(e.id)}`,{method:`DELETE`}))}}}function j(e,t,n,r){let i,a,o,s;return{access:{tokenLink:n,get active(){return i!==void 0},get problem(){return s},...r&&{async startRedirect(e){s=void 0,await r(e)}},async applyToken(n){let r={...e,token:n.trim()};try{if(!(await D(r,`/repos/${t}`)).permissions?.admin)throw new c(`not-allowed`,`This token's account isn't an owner of the site.`);await D(r,`/repos/${t}/invitations?per_page=1`)}catch(e){throw e instanceof c?e:e instanceof S||A(e)?new c(`not-allowed`,`This token can't change the site's editors.`):e}i=r,a=r,s=void 0},forget(){i=void 0,a=void 0,o?.(),o=void 0}},api:()=>i,codeApi:()=>a,useSignIn(t,n,r){i={...e,token:t},a=r?{...e,token:r}:void 0,o=n,s=void 0},failed(e){s=e}}}var oe=[`185.199.108.153`,`185.199.109.153`,`185.199.110.153`,`185.199.111.153`],se=[`2606:50c0:8000::153`,`2606:50c0:8001::153`,`2606:50c0:8002::153`,`2606:50c0:8003::153`],ce=new Set([`approved`,`issued`,`uploaded`]),le=new Set([`errored`,`bad_authz`,`authorization_revoked`]);function M(e,t,{apex:n,www:r}){let i=`${(e.split(`/`)[0]??``).toLowerCase()}.github.io`;return n?[...oe.map(e=>({type:`A`,name:t,value:e,purpose:`site`})),...se.map(e=>({type:`AAAA`,name:t,value:e,purpose:`site`,optional:!0})),...r?[{type:`CNAME`,name:`www.${t}`,value:i,purpose:`www`,optional:!0}]:[]]:[{type:`CNAME`,name:t,value:i,purpose:`site`}]}function ue(e,t){let n=`/repos/${t}/pages`;async function r(){let t=await E(e(),n,{allow:[404]});return t.status===404?void 0:await t.json()}async function i(t){try{await E(e(),n,{method:`PUT`,body:t})}catch(e){throw e instanceof T&&(e.status===403||e.status===404)?new _(`not-allowed`,`This sign-in can't change the site's GitHub Pages settings.`):e instanceof T&&(e.status===400||e.status===422)?/taken|already/i.test(e.message)?new _(`taken`,`Another GitHub Pages site already uses this domain.`):`https_enforced`in t?new _(`not-ready`,`The domain's certificate isn't ready yet.`):new _(`invalid`,`GitHub Pages doesn't accept this domain.`):e}}return{severalDomains:!1,async site(){let e=await r();return e&&{url:e.html_url,domain:e.cname??void 0}},async connect(e,n){return await i({cname:e}),M(t,e,n)},async records(e,n){return M(t,e,n)},async status(t){let r=await D(e(),n),i=r.https_certificate?.state??``;return{verified:!0,certificate:ce.has(i)?`ready`:le.has(i)?`failed`:`pending`,httpsOnly:r.https_enforced===!0,primary:r.cname===t}},async secure(){await i({https_enforced:!0})},async disconnect(){await i({cname:null})}}}var de=`.github/workflows/scheduled.yml`,fe=[`.github/workflows/deploy.yml`,`.github/workflows/rebuild.yml`];function pe(e){return{async timing(){let[t,...n]=await Promise.all([de,...fe].map(e));return t&&/\bdue\b/.test(t)&&/\bschedule:/.test(t)?`hourly`:n.some(e=>e&&/\bschedule:/.test(e))?`nightly`:`none`}}}function me(e){let t=new URL(e);return t.hostname===`api.github.com`?`https://github.com`:`${t.origin}${t.pathname.replace(/\/api\/v3\/?$/,``)}`.replace(/\/+$/,``)}function he(e,t,i,a={}){let o=a.wait??(e=>new Promise(t=>setTimeout(t,e))),s=(n,r)=>E(e,`/repos/${t}/contents/${n}?ref=${encodeURIComponent(r)}`,{allow:[404]}),c=async()=>(await s(`.github/workflows/${r}`,i)).ok;return{supported:c,secretsPlace:async()=>({kind:`github`,url:`${me(e.apiUrl)}/${t}/settings/secrets/actions/new`}),async run(r){let i=u(r);if(i)throw new n(`failed`,i);if(!await c())throw new n(`missing`,`The site's setup files don't run plugins' tasks: it needs plugin-task.yml.`);try{await E(e,`/repos/${t}/dispatches`,{method:`POST`,body:{event_type:f,client_payload:{request:r.id,plugin:r.plugin,task:r.task,input:r.input,key:r.key}}})}catch(e){throw e instanceof T&&(e.status===403||e.status===404)?new n(`not-allowed`,`Running plugins' tasks needs a sign-in that can publish to the site.`):e}let d=`${l}${r.id}`,p=Date.now()+(a.timeoutMs??3e5);for(;;){let r=await s(m,d);if(r.ok){let{content:n=``}=await r.json();return await E(e,`/repos/${t}/git/refs/heads/${encodeURIComponent(d)}`,{method:`DELETE`,allow:[404,422]}).catch(()=>{}),new TextDecoder().decode(x(n.replace(/\s/g,``)))}if(Date.now()>=p)throw new n(`timeout`,`The site's build service didn't answer in time.`);await o(a.pollMs??4e3)}}}}var ge=`deploy.yml`,_e=`update.yml`,ve=`publish-update`;function N(e,t,n,r,o,s=ge){let c=`/repos/${n}/actions/workflows/${s}`,l=`.github/workflows/${s}`;return{async setup(){let e=await o.read(l);return e&&/update --(publish|commit)\b/.test(e)?`ready`:`missing`},async lastRun(){let t=await E(e,`${c}/runs?branch=${encodeURIComponent(r)}&per_page=20`,{allow:[403,404]});if(!t.ok)return;let{workflow_runs:a=[]}=await t.json();for(let t of a.filter(e=>[`schedule`,`workflow_dispatch`].includes(e.event))){let r={date:t.created_at,detailsUrl:t.html_url};if(t.status!==`completed`)return{state:`running`,...r};let{jobs:a=[]}=await D(e,`/repos/${n}/actions/runs/${t.id}/jobs`),s=a.find(e=>e.name===`update`);if(!s||s.conclusion===`skipped`)continue;if(s.conclusion!==`success`)return{state:`failed`,...r};let c=a.find(e=>e.name===ve);if(c&&c.conclusion!==`success`&&c.conclusion!==`skipped`)return{state:`failed`,...r};let l=g(await o.readAt(`package.json`,t.head_sha)??``),u=g(await o.read(`package.json`)??``);if(!l||!u||l===u)return{state:`up-to-date`,...r};let d=i(u,l)<0;return{state:`updated`,...r,result:{state:`updated`,from:l,to:u,...d&&{rollback:d}}}}},nightly:P(e,t,n,()=>o.read(l)),async rebuild(){await u({})},async start(e){await u({update:e})}};async function u(n){try{await E(t()??e,`${c}/dispatches`,{method:`POST`,body:{ref:r,inputs:n}})}catch(e){throw e instanceof T&&(e.status===403||e.status===401)?new a(`not-allowed`,`Running the site's build needs a token that can run its workflows.`):e instanceof T&&(e.status===404||e.status===422)?new a(`missing`,`The site's GitHub Pages workflow doesn't update Goodfellow.`):e}}}function P(e,t,n,r){let i=`/repos/${n}/actions/variables`,o=e=>{throw e instanceof T&&(e.status===401||e.status===403)?new a(`not-allowed`,`Changing when the site rebuilds needs GitHub's Variables permission.`):e};return{async supported(){return(await r())?.includes(`GOODFELLOW_NIGHTLY`)??!1},async get(){let n=await E(t()??e,`${i}/${s}`,{allow:[403,404]});if(n.status===404)return`changed`;if(n.ok)return h((await n.json()).value)},async set(n){let r=t()??e;if(n===`changed`){await E(r,`${i}/${s}`,{method:`DELETE`,allow:[404]}).catch(o);return}let a={name:s,value:n};(await E(r,`${i}/GOODFELLOW_NIGHTLY`,{method:`PATCH`,body:a,allow:[404]}).catch(o)).status===404&&await E(r,i,{method:`POST`,body:a}).catch(o)}}}function F(e){return e instanceof S&&e.problem===`no-access`||e instanceof T&&(e.status===403||e.status===404)}function ye(e){let{read:t}=e,n=O(e.repo),r,i=e=>(r??=D(e,`/repos/${n}`).then(e=>e.default_branch),r.catch(()=>{r=void 0}),r);async function a(){if(!t)throw new S(`no-access`,`This sign-in has no access to ${e.repo}.`);return e.open(t,await i(t))}async function o(e){let t=await a();return t.readAt(e,await t.revision())}async function s(){if(!t)throw new S(`no-access`,`This sign-in has no access to ${e.repo}.`);let r=await i(t);return N(t,e.manage,n,r,{read:o,readAt:async(e,t)=>(await a()).readAt(e,t)},_e)}return{code:{repo:e.repo,webUrl:`${e.webUrl}/${e.repo}`,read:o,history:async(e,t)=>(await a()).history(e,t),readAt:async(e,t)=>(await a()).readAt(e,t)},async setup(){try{return await(await s()).setup()}catch(e){if(F(e))return`no-access`;throw e}},async lastRun(){try{return await(await s()).lastRun()}catch(e){if(F(e))return;throw e}},async start(e){await(await s()).start(e)},async rebuild(){await(await s()).rebuild?.()}}}var I=/cloudflare/i,L=100,be=`mutation ($input: CreateCommitOnBranchInput!) {
|
|
3
|
+
createCommitOnBranch(input: $input) { commit { oid } }
|
|
4
|
+
}`;function R(e,t){let n=`${t}/`;return[...e.keys()].filter(e=>e.startsWith(n)).sort()}var z=class n{user;pages;editors;ownerAccess;updates;drafts;scheduledBuilds;tasks;contentOnly;options;api;repo;branch;onSignOut;author;owner;pinned;trees=new Map;treeSizes=new Map;blobs=new Map;constructor(e){this.options=e,this.api=e.api,this.repo=O(e.repo),this.branch=e.branch,this.user=e.user,this.onSignOut=e.onSignOut,this.author=e.author,this.pinned=e.revision;let t=j(this.api,this.repo,e.ownerTokenLink,e.ownerRedirect);this.owner=t,this.ownerAccess=t.access,this.pages=ue(()=>t.api()??this.api,this.repo),this.editors=ae(this.api,t.api,this.repo,this.user.login),this.contentOnly=e.contentOnly===!0,this.contentOnly?e.code&&(this.updates=ye({repo:e.code.repo,webUrl:e.code.webUrl,read:e.code.api,manage:t.codeApi,open:(t,r)=>new n({api:t,repo:e.code?.repo??``,branch:r,user:this.user,onSignOut:()=>{},ownerTokenLink:e.ownerTokenLink})})):this.updates=N(this.api,t.api,this.repo,this.branch,this),this.drafts=o(this,this.draftHost()),this.scheduledBuilds=pe(e=>this.read(e)),this.tasks=he(this.api,this.repo,this.branch,e.tasks)}async repositoryVisibility(){let e=await D(this.api,`/repos/${this.repo}`);return e.visibility===`internal`?`internal`:e.private===!1||e.visibility===`public`?`public`:`private`}draftHost(){let e=`/repos/${this.repo}`,t=t=>`${e}/git/refs/heads/${encodeURIComponent(t)}`;return{liveBranch:this.branch,branchStore:e=>new n({...this.options,branch:e}),createBranch:async(t,n)=>{if((await E(this.api,`${e}/git/refs`,{method:`POST`,body:{ref:`refs/heads/${t}`,sha:n},allow:[422]})).status===422)throw new d(`exists`,`There's already a draft called ${t}.`)},deleteBranch:async e=>{await E(this.api,t(e),{method:`DELETE`,allow:[404,422]})},mergeBase:async t=>{let n=await E(this.api,`${e}/compare/${encodeURIComponent(this.branch)}...${encodeURIComponent(t)}`,{allow:[404]});if(n.status===404)throw new d(`not-found`,`There's no draft ${t}.`);return(await n.json()).merge_base_commit.sha},listBranches:async t=>(await D(this.api,`${e}/git/matching-refs/heads/${encodeURIComponent(t)}`)).map(e=>e.ref.replace(/^refs\/heads\//,``)),openReview:async({branch:t,title:n,description:r})=>{let i=await E(this.api,`${e}/pulls`,{method:`POST`,body:{title:n,head:t,base:this.branch,body:r},allow:[403,404,422]});if(i.ok)return{url:(await i.json()).html_url};if(i.status!==422)throw new d(`no-reviews`,`This sign-in can't open pull requests on the site's repository.`);let a=decodeURIComponent(this.repo).split(`/`)[0],o=new URLSearchParams({head:`${a}:${t}`,state:`open`}),[s]=await D(this.api,`${e}/pulls?${o}`);if(!s)throw new T(422,`GitHub couldn't open the pull request.`);return{url:s.html_url}}}}async revision(){return this.pinned=await this.head(),this.pinned}async head(){return(await D(this.api,`/repos/${this.repo}/git/ref/heads/${encodeURIComponent(this.branch)}`)).object.sha}tree(e){let t=this.trees.get(e);return t||(t=D(this.api,`/repos/${this.repo}/git/trees/${e}?recursive=1`).then(t=>{if(t.truncated)throw new T(413,`The repository has too many files for GitHub to list at once.`);let n=t.tree.filter(e=>e.type===`blob`);return this.treeSizes.set(e,new Map(n.flatMap(e=>e.size===void 0?[]:[[e.path,e.size]]))),new Map(n.map(e=>[e.path,e.sha]))}),t.catch(()=>this.trees.delete(e)),this.trees.set(e,t)),t}async currentTree(){return this.tree(this.pinned??await this.revision())}async read(e){return this.readFrom(await this.currentTree(),e)}readFrom(e,t){let n=e.get(t);if(!n)return Promise.resolve(void 0);let r=this.blobs.get(n);return r||(r=E(this.api,`/repos/${this.repo}/git/blobs/${n}`,{accept:`application/vnd.github.raw+json`}).then(e=>e.text()),r.catch(()=>this.blobs.delete(n)),this.blobs.set(n,r)),r}async readFiles(e){return this.readFilesFrom(await this.currentTree(),e)}async readFilesFrom(e,t){let n=t.flatMap(t=>{let n=e.get(t);return n?[[t,n]]:[]}),r=[...new Set(n.map(([,e])=>e).filter(e=>!this.blobs.has(e)))],[i,a]=decodeURIComponent(this.repo).split(`/`);for(let e=0;e<r.length;e+=L){let t=r.slice(e,e+L),n=t.map((e,t)=>`f${t}: object(oid: "${e}") { ... on Blob { text isBinary } }`),o=await D(this.api,`/graphql`,{method:`POST`,body:{query:`query ($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${n.join(` `)} } }`,variables:{owner:i,name:a}}});t.forEach((e,t)=>{let n=o.data?.repository?.[`f${t}`];n&&!n.isBinary&&typeof n.text==`string`&&this.blobs.set(e,Promise.resolve(n.text))})}let o=new Map;for(let[t]of n){let n=await this.readFrom(e,t);n!==void 0&&o.set(t,n)}return o}async readBytes(e){return this.bytesFrom(await this.currentTree(),e)}async bytesFrom(e,t){let n=e.get(t);if(!n)return;let r=await E(this.api,`/repos/${this.repo}/git/blobs/${n}`,{accept:`application/vnd.github.raw+json`});return new Uint8Array(await r.arrayBuffer())}async list(e){return R(await this.currentTree(),e)}filesAt(e){return{read:async t=>this.readFrom(await this.tree(e),t),readFiles:async t=>this.readFilesFrom(await this.tree(e),t),readBytes:async t=>this.bytesFrom(await this.tree(e),t),list:async t=>R(await this.tree(e),t)}}async fileSizes(e){let t=`${e}/`;await this.currentTree();let n=this.treeSizes.get(this.pinned??``)??new Map;return new Map([...n].filter(([e])=>e.startsWith(t)))}useOwnerSignIn(e,t,n){this.owner.useSignIn(e,t,n)}ownerSignInFailed(e){this.owner.failed(e)}async write(t,n){return this.contentOnly&&e(t),this.author?this.writeCommit(t,n,this.author):this.writeGraphQL(t,n)}async writeCommit(e,{message:n,expectedRevision:r},i){let a=await this.tree(r),o=`/repos/${this.repo}`,s=[];try{for(let t of e)if(`delete`in t)a.has(t.path)&&s.push({path:t.path,mode:`100644`,type:`blob`,sha:null});else if(`bytes`in t){let e=await D(this.api,`${o}/git/blobs`,{method:`POST`,body:{content:C(t.bytes),encoding:`base64`}});s.push({path:t.path,mode:`100644`,type:`blob`,sha:e.sha})}else s.push({path:t.path,mode:`100644`,type:`blob`,content:t.content});if(s.length===0)return{revision:r};let c=await D(this.api,`${o}/git/commits/${r}`),l=await D(this.api,`${o}/git/trees`,{method:`POST`,body:{base_tree:c.tree.sha,tree:s}}),u=await D(this.api,`${o}/git/commits`,{method:`POST`,body:{message:n,tree:l.sha,parents:[r],author:{...i,date:new Date().toISOString()}}});if((await E(this.api,`${o}/git/refs/heads/${encodeURIComponent(this.branch)}`,{method:`PATCH`,body:{sha:u.sha,force:!1},allow:[422]})).status===422)throw await this.revision()===r?new T(422,`GitHub couldn't save the changes.`):new t;return this.pinned=u.sha,{revision:u.sha}}catch(e){throw e instanceof T&&(e.status===403||e.status===404)?new S(`cant-publish`,`This sign-in can't publish to the site.`):e}}async writeGraphQL(e,{message:n,expectedRevision:r}){let i=await this.tree(r),a=e.flatMap(e=>`delete`in e?[]:[{path:e.path,contents:`bytes`in e?C(e.bytes):b(e.content)}]),o=e.flatMap(e=>`delete`in e&&i.has(e.path)?[{path:e.path}]:[]);if(a.length===0&&o.length===0)return{revision:r};let s=await D(this.api,`/graphql`,{method:`POST`,body:{query:be,variables:{input:{branch:{repositoryNameWithOwner:decodeURIComponent(this.repo),branchName:this.branch},message:{headline:n},expectedHeadOid:r,fileChanges:{additions:a,deletions:o}}}}}),c=s.data?.createCommitOnBranch?.commit?.oid;if(c)return this.pinned=c,{revision:c};if(await this.revision()!==r)throw new t;let l=s.errors?.[0];throw l?.type===`FORBIDDEN`?new S(`cant-publish`,`This GitHub account can't publish to the site.`):new T(422,`GitHub couldn't save the changes: ${l?.message??`unknown error`}`)}async history(e,{page:t=1,perPage:n=20}={}){let r=new URLSearchParams({sha:this.pinned??await this.revision(),path:e,per_page:String(n),page:String(t)});return(await D(this.api,`/repos/${this.repo}/commits?${r}`)).map(e=>({revision:e.sha,date:e.commit.author?.date??``,author:e.commit.author?.name||e.author?.login||void 0,message:e.commit.message.split(`
|
|
5
|
+
`)[0]??``}))}async readAt(e,t){return this.readFrom(await this.tree(t),e)}async changedPaths(e,t){let n=await D(this.api,`/repos/${this.repo}/compare/${e}...${t}`);return[...new Set((n.files??[]).flatMap(e=>[e.filename,e.previous_filename??[]].flat()))]}async deployStatus(e){try{let t=(await D(this.api,`/repos/${this.repo}/deployments?sha=${e}&per_page=5`))[0];if(t){let[n]=await D(this.api,`/repos/${this.repo}/deployments/${t.id}/statuses?per_page=1`),r=n?.log_url||n?.target_url||void 0;switch(n?.state){case`success`:case`inactive`:return{state:`live`,detailsUrl:r};case`failure`:case`error`:{let t=await this.workflowRun(e);return{state:`failed`,detailsUrl:r,problem:t?await this.runProblem(t):{step:`deploy`}}}default:return{state:`building`,detailsUrl:r}}}let n=await this.cloudflareBuild(e);if(n)return n;let r=await this.workflowRun(e);if(r?.status===`completed`&&r.conclusion===`cancelled`){let t=await this.head();if(t!==e)return this.deployStatus(t)}if(r?.status===`completed`&&r.conclusion!==`success`&&r.conclusion!==`skipped`)return{state:`failed`,detailsUrl:r.html_url,problem:await this.runProblem(r)};if(r)return{state:`building`,detailsUrl:r.html_url};if((await D(this.api,`/repos/${this.repo}/deployments?per_page=1`)).length>0)return{state:`building`};let i=await this.parentOf(e);return{state:i&&await this.cloudflareBuild(i)?`building`:`unknown`}}catch(e){if(e instanceof T)return{state:`unknown`};throw e}}async cloudflareBuild(e){let t=await E(this.api,`/repos/${this.repo}/commits/${e}/check-runs?per_page=50`,{allow:[403,404]});if(t.ok){let{check_runs:e=[]}=await t.json(),n=e.find(e=>I.test(`${e.app?.slug??``} ${e.name}`));if(n){let e=n.details_url??n.html_url??void 0;return n.status===`completed`?n.conclusion===`success`||n.conclusion===`neutral`||n.conclusion===`skipped`?{state:`live`,detailsUrl:e}:{state:`failed`,detailsUrl:e,problem:{step:`build`,detail:n.output?.title??void 0}}:{state:`building`,detailsUrl:e}}}let n=await E(this.api,`/repos/${this.repo}/commits/${e}/statuses?per_page=50`,{allow:[403,404]});if(!n.ok)return;let r=(await n.json()).find(e=>I.test(e.context));if(!r)return;let i=r.target_url??void 0;return r.state===`success`?{state:`live`,detailsUrl:i}:r.state===`pending`?{state:`building`,detailsUrl:i}:{state:`failed`,detailsUrl:i,problem:{step:`build`,detail:r.description??void 0}}}async parentOf(e){let t=await E(this.api,`/repos/${this.repo}/commits/${e}`,{allow:[403,404,422]});if(t.ok)return(await t.json()).parents?.[0]?.sha}async workflowRun(e){let t=await E(this.api,`/repos/${this.repo}/actions/runs?head_sha=${e}&per_page=20`,{allow:[403,404]});if(!t.ok)return;let{workflow_runs:n=[]}=await t.json(),r=n.filter(e=>!e.path?.endsWith(`/${y}.yml`));return r.find(e=>/deploy|pages/i.test(`${e.path??``} ${e.name??``}`))??r[0]}async runProblem(e){let t=await E(this.api,`/repos/${this.repo}/actions/runs/${e.id}/jobs?per_page=50`,{allow:[403,404]}),n=(t.ok?(await t.json()).jobs??[]:[]).find(e=>e.conclusion===`failure`);if(!n)return{step:e.conclusion===`startup_failure`?`not-started`:`host`,detail:e.conclusion??void 0};let r=n.steps?.find(e=>e.conclusion===`failure`);return r?{step:v(r.name)??(/deploy/i.test(n.name)?`deploy`:`build`),detail:`${n.name}: ${r.name}`}:{step:`not-started`,detail:n.name}}signOut(){this.ownerAccess.forget(),this.onSignOut()}},xe={invalid:`invalid`,"no-access":`no-access`,"cant-publish":`cant-publish`,cancelled:`redirect-failed`,"not-installed":`not-installed`,"no-address":`no-address`,"wrong-address":`wrong-address`,"local-address":`local-address`,"not-owner":`not-owner`};function B(e){let t=xe[String(e.problem)]??`unavailable`,n=typeof e.installUrl==`string`&&/^https:\/\//.test(e.installUrl)?e.installUrl:void 0;return new S(t,`The sign-in service said: ${String(e.problem??`no answer`)}.`,n)}function V(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!0}return t===`localhost`||t.endsWith(`.localhost`)||t===`0.0.0.0`||t===`[::1]`||/^127(\.\d{1,3}){3}$/.test(t)}function H(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}async function U(){let e=H(crypto.getRandomValues(new Uint8Array(32))),t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return{verifier:e,challenge:H(new Uint8Array(t))}}function W(){if(typeof window<`u`)return{href:()=>window.location.href,assign:e=>window.location.assign(e),replace:e=>window.history.replaceState(window.history.state,``,e)}}var G=`goodfellow_sign_in`,K=`goodfellow_sign_in_error`,q=class{url;fetcher;constructor(e,t){this.url=e.replace(/\/$/,``),this.fetcher=t}async answer(e,t){let n;try{n=await this.fetcher(`${this.url}${e}`,t)}catch(e){throw new S(`unavailable`,`Couldn't reach the sign-in service: ${e.message}`)}let r=await n.json().catch(()=>({}));if(!n.ok)throw B(r);return r}post(e,t){return this.answer(e,{method:`POST`,headers:{"content-type":`text/plain`},body:JSON.stringify(t)})}async postAnswer(e,t){let n;try{n=await this.fetcher(`${this.url}${e}`,{method:`POST`,headers:{"content-type":`text/plain`},body:JSON.stringify(t)})}catch(e){throw new S(`unavailable`,`Couldn't reach the sign-in service: ${e.message}`)}return{ok:n.ok,body:await n.json().catch(()=>({}))}}async health(){if((await this.answer(`/health`)).ok!==!0)throw new S(`unavailable`,`The sign-in service isn't set up.`)}async check(e,t){await this.answer(`/github/check?${new URLSearchParams({repo:e,purpose:t})}`)}startUrl(e){let t=new URLSearchParams({purpose:e.purpose,...e.repo&&{repo:e.repo},return:e.back,challenge:e.challenge,remember:e.remember?`1`:`0`,...e.install&&{install:`1`}});return`${this.url}/github/start?${t}`}session(e,t,n){return this.post(`/github/session`,{grant:e,verifier:t,...n&&{code:n}})}token(e,t){return this.post(`/github/token`,{session:e,...t&&{code:t}})}};function J(e,t,n,r){let i=t,a;async function o({refresh:t=!1}={}){return(t||Date.parse(i.expiresAt)-3e5<Date.now())&&(a??=e.token(i.session,r).finally(()=>{a=void 0}),i=await a,n(i)),i.token}return{current:()=>i,token:o,async codeToken(e){if(await o(e),!i.code)throw new S(`no-access`,`The sign-in service gave no token for the code repository.`);return i.code.token}}}var Y=`main`;function X(e=`https://github.com`){let t=new URLSearchParams({name:`Goodfellow site setup`,description:`Create a Goodfellow site. It can be deleted once the site is created.`,expires_in:`7`,administration:`write`,contents:`write`,workflows:`write`,pages:`write`,secrets:`write`}),n=new URLSearchParams({scopes:`repo,workflow`,description:`Goodfellow site setup`});return{fineGrained:`${e}/settings/personal-access-tokens/new?${t}`,classic:`${e}/settings/tokens/new?${n}`}}function Z(e){let t=new Map;async function n(e,t){if(t.default_branch===Y)return;let n=`/repos/${O(t.full_name)}`,r=await D(e,`${n}/git/ref/heads/${t.default_branch}`);await E(e,`${n}/git/refs`,{method:`POST`,body:{ref:`refs/heads/${Y}`,sha:r.object.sha}}),await E(e,n,{method:`PATCH`,body:{default_branch:Y}}),await E(e,`${n}/git/refs/heads/${t.default_branch}`,{method:`DELETE`})}async function r(e,t){try{return(await D(e,`/repos/${O(t.full_name)}/pages`,{method:`POST`,body:{build_type:`workflow`}})).html_url}catch(e){if(e instanceof T&&[403,404,409,422].includes(e.status))return;throw e}}async function i(e,t,n){try{return await E(e,`/repos/${O(t.full_name)}/pages`,{method:`PUT`,body:{cname:n}}),!0}catch(e){if(e instanceof T&&[400,403,404,409,422].includes(e.status))return!1;throw e}}async function a(t,n,r){let i=`/repos/${O(n.full_name)}`,a=[];for(let e of r.files){if(`delete`in e)continue;if(`content`in e){a.push({path:e.path,mode:`100644`,type:`blob`,content:e.content});continue}let n=await D(t,`${i}/git/blobs`,{method:`POST`,body:{content:C(e.bytes),encoding:`base64`}});a.push({path:e.path,mode:`100644`,type:`blob`,sha:n.sha})}try{let n=await D(t,`${i}/git/trees`,{method:`POST`,body:{tree:a}}),o=await D(t,`${i}/git/commits`,{method:`POST`,body:{message:r.message,tree:n.sha,parents:[],...e.author&&{author:{...e.author,date:new Date().toISOString()}}}});await E(t,`${i}/git/refs/heads/${Y}`,{method:`PATCH`,body:{sha:o.sha,force:!0}})}catch(e){throw e instanceof T&&(e.status===403||e.status===404)?new p(`not-allowed`,`This sign-in can't write the site's files, or its build setup.`):e}}async function o(e,t){return(await E(e,`/repos/${O(t.full_name)}/rulesets`,{method:`POST`,body:{name:`Protect the published history`,target:`branch`,enforcement:`active`,conditions:{ref_name:{include:[`~DEFAULT_BRANCH`],exclude:[]}},rules:[{type:`non_fast_forward`},{type:`deletion`}]},allow:[403,404,422]})).ok}async function s(e){if(!e.private)return!0;let{newDeployKey:n,sealSecret:r}=await te(()=>import(`./deploy-keys-DAj2oX-N-DRd_HmOG.js`).then(e=>e.t),__vite__mapDeps([0,1]),import.meta.url);try{for(let{reader:i,read:a,secret:o}of e.links.reads){if(!o)continue;let s=e[i],c=e[a],l=t.get(s.toLowerCase()),u=t.get(c.toLowerCase());if(!l||!u)throw Error(`${s} and ${c} have to be created first.`);let d=await n(`goodfellow-${o.toLowerCase()}`);await E(u,`/repos/${O(c)}/keys`,{method:`POST`,body:{title:`${s}'s builds`,key:d.publicKey,read_only:!0}});let f=`/repos/${O(s)}/actions/secrets`,p=await D(l,`${f}/public-key`),m=await r(d.privateKey,x(p.key));await E(l,`${f}/${o}`,{method:`PUT`,body:{encrypted_value:C(m),key_id:p.key_id}})}return!0}catch(e){if(e instanceof T&&[403,404,422].includes(e.status))return!1;throw e}}return{user:e.user,owners:()=>e.owners(),isAvailable:(t,n)=>e.isAvailable(t,n),async createSite(c,l){let u=[];l?.(`repository`);let{repo:d,api:f,signInInstallUrl:p}=await e.create(c),m=async e=>(l?.(`connect`),s(e));await n(f,d);let h;return c.pages&&(l?.(`pages`),h=await r(f,d),h?c.domain&&(await i(f,d,c.domain)?h=`https://${c.domain}/`:u.push(`domain-unavailable`)):u.push(`pages-unavailable`)),t.set(d.full_name.toLowerCase(),f),c.link&&!await m(c.link)&&u.push(`connect-unavailable`),l?.(`files`),await a(f,d,c),l?.(`protection`),await o(f,d)||u.push(`protection-unavailable`),p&&u.push(`sign-in-not-installed`),{repo:d.full_name,webUrl:d.html_url,siteUrl:h,buildsUrl:`${d.html_url}/actions`,pagesUrl:c.pages?`${d.html_url}/settings/pages`:void 0,...p&&{signInInstallUrl:p},warnings:u}}}}async function Se(e){let t=await D(e,`/user`);async function n(t,n){return(await E(e,`/repos/${O(`${t.path}/${n}`)}`,{allow:[404]})).status===404}return{user:{login:t.login,name:t.name??void 0,avatarUrl:t.avatar_url},async owners(){return[{path:t.login,name:t.name||t.login,kind:`personal`},...(await D(e,`/user/orgs?per_page=100`).catch(()=>[])).map(e=>({path:e.login,name:e.login,kind:`organization`}))]},isAvailable:n,async create(t){let r=t.owner.kind===`personal`?`/user/repos`:`/orgs/${encodeURIComponent(t.owner.path)}/repos`;if(!await n(t.owner,t.name))throw new p(`name-taken`,`There's already a repository called ${t.owner.path}/${t.name}.`);try{return{repo:await D(e,r,{method:`POST`,body:{name:t.name,private:t.private,description:t.description,auto_init:!0}}),api:e}}catch(e){throw e instanceof T&&e.status===422?new p(`name-invalid`,`GitHub can't use "${t.name}" as a repository name.`):e instanceof T&&(e.status===403||e.status===404)?new p(`not-allowed`,`This sign-in can't create repositories in ${t.owner.path}.`):e}}}}function Ce(e,t,n,r){let i=r.session;async function a(t,n){let r=await e.postAnswer(t,{session:i,...n});if(typeof r.body.session==`string`&&(i=r.body.session),!r.ok)throw we(r.body);return r.body}let{user:o}=r;return{user:{login:o.login,name:o.name,avatarUrl:o.avatarUrl},author:{name:o.name||o.login,email:o.email},async owners(){let e=await a(`/github/setup/owners`,{});return(e.owners??[]).map(({installed:t,...n})=>({...n,...!t&&e.installUrl&&{installUrl:e.installUrl}}))},async isAvailable(e,t){return(await a(`/github/setup/available`,{owner:e.path,name:t})).available===!0},async create(e){if(e.owner.installUrl)throw new p(`not-installed`,`Goodfellow isn't installed on ${e.owner.path}.`,e.owner.installUrl);let r=await a(`/github/setup/repository`,{owner:e.owner.path,name:e.name,private:e.private,description:e.description,...e.more&&{more:!0}});if(!r.repo||!r.token)throw new S(`unavailable`,`The sign-in service didn't answer.`);return{repo:r.repo,api:{apiUrl:t,token:r.token,fetch:n},...r.editInstallUrl&&{signInInstallUrl:r.editInstallUrl}}}}}function we(e){switch(e.problem){case`name-taken`:return new p(`name-taken`,`There's already a repository with that name.`);case`name-invalid`:return new p(`name-invalid`,`GitHub can't use that as a repository name.`);case`not-allowed`:return new p(`not-allowed`,`This sign-in can't create repositories there.`);case`not-installed`:return new p(`not-installed`,`Goodfellow isn't installed there.`,e.installUrl);default:return B(e)}}function Q(e={}){let t=(e.apiUrl??`https://api.github.com`).replace(/\/$/,``),n=X(e.webUrl),r=e.fetch??((e,t)=>globalThis.fetch(e,t)),i=e.location??W(),a=e.signIn,o=a&&i&&!V(i.href())?new q(a,r):void 0,s=w(`goodfellow:github:setup:pending`,e.storage);return{name:`GitHub`,canRedirect:o!==void 0,tokenLinks:[{url:n.fineGrained,label:`signIn.token.create`},{url:n.classic,label:`signIn.token.createBroad`,hint:`signIn.token.createBroadHint`}],async restore(){if(!i)return null;let e=new URL(i.href()),n=e.searchParams.get(G),a=e.searchParams.get(K);if(!n&&!a)return null;e.searchParams.delete(G),e.searchParams.delete(K),i.replace(e.toString());let c=s.load();if(s.clear(),a||!n||!c||!o)throw B({problem:a??`cancelled`});let l=await o.session(n,c);return Z(Ce(o,t,r,l))},async signInWithToken(e){let n=e.trim();if(!n)throw new S(`invalid`,`Paste a token to sign in.`);return Z(await Se({apiUrl:t,token:n,fetch:r}))},async startRedirect({install:e}={}){if(!o||!i)throw new S(`unavailable`,`Signing in with GitHub isn't available here.`);await o.health();let{verifier:t,challenge:n}=await U();s.save(t,!1),i.assign(o.startUrl({purpose:`setup`,back:i.href(),challenge:n,remember:!1,install:e}))}}}function Te(e){return e instanceof S&&e.problem!==`unavailable`}function $(e,t=`https://github.com`){let[n=``]=e.split(`/`),r=new URLSearchParams({name:`Goodfellow admin`,description:`Edit ${e} in its admin panel`,target_name:n,expires_in:`90`,contents:`write`,deployments:`read`,actions:`read`,statuses:`read`}),i=new URLSearchParams({scopes:`repo`,description:`Goodfellow admin for ${e}`}),a=new URLSearchParams({name:`Goodfellow owner`,description:`Manage the editors, domain and updates of ${e}`,target_name:n,expires_in:`1`,administration:`write`,pages:`write`,actions:`write`,variables:`write`});return{fineGrained:`${t}/settings/personal-access-tokens/new?${r}`,classic:`${t}/settings/tokens/new?${i}`,owner:`${t}/settings/personal-access-tokens/new?${a}`}}function Ee(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e.repo))throw Error(`github({ repo }) must look like "owner/name" (got "${e.repo}").`);if(e.code!==void 0&&!/^[\w.-]+\/[\w.-]+$/.test(e.code))throw Error(`github({ code }) must look like "owner/name" (got "${e.code}").`);let t=(e.apiUrl??`https://api.github.com`).replace(/\/$/,``),n=(e.webUrl??`https://github.com`).replace(/\/$/,``),r=t=>e.contentOnly&&e.code?{code:{repo:e.code,webUrl:n,...t&&{api:t}}}:{},i=$(e.repo,e.webUrl),a=w(`goodfellow:github:${e.repo}`,e.storage),o=w(`goodfellow:github:pending:${e.repo}`,e.storage),s=e.fetch??((e,t)=>globalThis.fetch(e,t)),c=e.location??W(),l=e.signIn,u=l&&c&&!V(c.href())?new q(l,s):void 0,d=()=>e.contentOnly?e.code:void 0;function f(e,t){a.save(e.type===`token`?e.token:JSON.stringify(e),t)}function p(){let e=a.load();if(e){try{let t=JSON.parse(e);if(t.type===`worker`||t.type===`token`)return t}catch{}return{type:`token`,token:e}}}async function m(t,n,{install:r}={}){if(!u||!c)throw new S(`unavailable`,`Signing in with GitHub isn't available here.`);r||await u.check(e.repo,t);let{verifier:i,challenge:a}=await U();o.save(JSON.stringify({verifier:i,purpose:t,remember:n}),!1),c.assign(u.startUrl({purpose:t,repo:e.repo,back:c.href(),challenge:a,remember:n,install:r}))}async function h(n,o){let c=J(u,n,e=>f({type:`worker`,session:e.session},o),e.code);f({type:`worker`,session:n.session},o);let l={apiUrl:t,token:c.token,fetch:s},d=await D(l,`/repos/${O(e.repo)}`),{user:p}=n;return new z({api:l,repo:e.repo,branch:e.branch??d.default_branch,...e.contentOnly&&{contentOnly:!0},...r({apiUrl:t,token:c.codeToken,fetch:s}),user:{login:p.login,name:p.name,avatarUrl:p.avatarUrl},author:{name:p.name||p.login,email:p.email},onSignOut:()=>{a.clear(),_(c.current())},ownerTokenLink:{url:i.owner,label:`owner.token.create`},ownerRedirect:e=>m(`owner`,!1,e)})}function g(e){E({apiUrl:t,token:e,fetch:s},`/installation/token`,{method:`DELETE`}).catch(()=>{})}function _(e){g(e.token),e.code&&g(e.code.token)}async function v(e,t,n){let r=u;try{let i=J(r,await r.session(t,n,d()),()=>{},d());e.useOwnerSignIn(i.token,()=>_(i.current()),d()?i.codeToken:void 0)}catch(t){e.ownerSignInFailed(t)}}async function y(){if(!c)return;let e=new URL(c.href()),t=e.searchParams.get(G),n=e.searchParams.get(K);if(!t&&!n)return;e.searchParams.delete(G),e.searchParams.delete(K),c.replace(e.toString());let r=o.load();o.clear();let i=r?JSON.parse(r):void 0;if(!i||!u)throw new S(`redirect-failed`,`Signing in with GitHub didn't finish in this tab.`);if(i.purpose===`owner`){let e=await b();if(!e)throw new S(`redirect-failed`,`Sign in again, then sign in as an owner.`);return n?e.ownerSignInFailed(B({problem:n})):t&&await v(e,t,i.verifier),e}if(n||!t)throw B({problem:n});return h(await u.session(t,i.verifier,d()),i.remember)}async function b(){let e=p();if(!e)return null;try{return e.type===`token`?await x(e.token):u?await h(await u.token(e.session,d()),a.remembered()):(a.clear(),null)}catch(e){throw Te(e)&&a.clear(),e}}async function x(n){let o={apiUrl:t,token:n,fetch:s},c=await D(o,`/user`),l;try{l=await D(o,`/repos/${O(e.repo)}`)}catch(t){throw t instanceof T&&(t.status===404||t.status===403)?new S(`no-access`,`The GitHub account ${c.login} can't see ${e.repo}.`):t}if(l.permissions?.push===!1)throw new S(`cant-publish`,`The GitHub account ${c.login} can see ${e.repo} but can't publish to it.`);return new z({api:o,repo:e.repo,branch:e.branch??l.default_branch,...e.contentOnly&&{contentOnly:!0},...r(o),user:{login:c.login,name:c.name??void 0,avatarUrl:c.avatar_url},onSignOut:()=>a.clear(),ownerTokenLink:{url:i.owner,label:`owner.token.create`},...u&&{ownerRedirect:e=>m(`owner`,!1,e)}})}function C({token:n}){let r={apiUrl:t,token:typeof n==`string`?n:()=>n(),fetch:s},a,o=()=>(a??=e.branch?Promise.resolve(e.branch):D(r,`/repos/${O(e.repo)}`).then(e=>e.default_branch),a.catch(()=>{a=void 0}),a),c=async(t,n)=>new z({api:r,repo:e.repo,branch:await o(),...e.contentOnly&&{contentOnly:!0},user:{login:n?.name??e.repo,...n&&{name:n.name}},onSignOut:()=>{},ownerTokenLink:{url:i.owner,label:`owner.token.create`},...t&&{revision:t},...n&&{author:n}});return{...e.contentOnly&&{contentOnly:!0},async revision(){return(await c()).revision()},at:c}}return{name:`GitHub`,source:ee(`@goodfellow-cms/github`,`github`,e,[`fetch`,`storage`,`location`]),canRedirect:u!==void 0,setup:()=>Q({...e.apiUrl&&{apiUrl:e.apiUrl},...e.webUrl&&{webUrl:e.webUrl},...e.fetch&&{fetch:e.fetch},...e.storage&&{storage:e.storage},...e.location&&{location:e.location},signIn:!1}),tokenLinks:[{url:i.fineGrained,label:`signIn.token.create`},{url:i.classic,label:`signIn.token.createBroad`,hint:`signIn.token.createBroadHint`}],async restore(){let e=await y();return e===void 0?b():e},async signInWithToken(e,t){let n=e.trim();if(!n)throw new S(`invalid`,`Paste a token to sign in.`);let r=await x(n);return f({type:`token`,token:n},t),r},startRedirect(e,t){return m(`edit`,e,t)},server:C}}export{z as GitHubBackend,Ee as github,M as githubPagesRecords,Q as githubSetup,X as githubSetupTokenLinks,$ as githubTokenLinks};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{n as e,r as t,t as n}from"./store-CNLNNQkL.js";import{_ as r,a as i,c as a,h as o,i as s,m as c,n as l,o as u,p as d,r as f,t as p,u as m}from"./setup-host-B_uhd1y7.js";import{n as h,r as g,s as _,t as v}from"./git-eGyMXUIu.js";import{t as ee}from"./scheduled-builds-BPfDaBYt.js";var te=`bitbucket-pipelines.yml`,y=`VERCEL_DEPLOY_HOOK`,b={update:`update`,scheduled:`scheduled`,task:a,rebuild:`rebuild`},ne={update:`0 17 4 * * ? *`};function x(e){return`0 ${e.getUTCMinutes()} ${e.getUTCHours()} ${e.getUTCDate()} ${e.getUTCMonth()+1} ? ${e.getUTCFullYear()}`}function re(e){let t=/^0 (\d{1,2}) (\d{1,2}) (\d{1,2}) (\d{1,2}) \? (\d{4})$/.exec(e.trim());if(!t)return;let[,n,r,i,a,o]=t.map(Number);return new Date(Date.UTC(o??0,(a??1)-1,i,r,n))}`${y}${y}${y}`;function S(e){return e.type===`api-token`?`Basic ${btoa(`${e.email}:${e.token}`)}`:`Bearer ${e.type===`oauth`?e.access:e.token}`}function C(e){let t=e.trim(),n=t.indexOf(`:`),r=t.slice(0,n);return n>0&&/^[^\s@:]+@[^\s@:]+$/.test(r)?{type:`api-token`,email:r,token:t.slice(n+1)}:{type:`token`,token:t}}async function w(e){let t=await e.json().catch(()=>({})),n=t.error?.message??t.message;return typeof n==`string`?n:``}async function T(e,t,n={}){let r=t.startsWith(`https://`)||t.startsWith(`http://`)?t:`${e.apiUrl}${t}`,i=await e.fetch(r,{method:n.method??(n.body!==void 0||n.form?`POST`:`GET`),headers:{authorization:await e.authorization(),...n.body!==void 0&&{"content-type":`application/json`}},body:n.form??(n.body===void 0?void 0:JSON.stringify(n.body)),cache:`no-store`});if(i.status===401&&!n.allow?.includes(401))throw new h(`invalid`,`Bitbucket didn't accept the sign-in. It may have expired.`);if(!i.ok&&!n.allow?.includes(i.status)){let e=await w(i);throw new v(i.status,`Bitbucket answered ${i.status}: ${e||i.statusText}`)}return i}async function E(e,t,n){return await(await T(e,t,n)).json()}async function D(e,t,n=20){let r=[],i=t;for(let t=0;i&&t<n;t++){let t=await E(e,i);r.push(...t.values),i=t.next}return r}function O(e){return`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`}async function k(e,t,n,r,i={}){return E(e,`/repositories/${t}/pipelines/`,{body:{target:{type:`pipeline_ref_target`,ref_type:`branch`,ref_name:n,selector:{type:`custom`,pattern:r}},variables:Object.entries(i).map(([e,t])=>({key:e,value:t,secured:!1}))}})}function A(e,t){return D(e,`/repositories/${t}/pipelines_config/schedules?pagelen=100`,5)}function j(e,t){return e.find(e=>e.target?.selector?.pattern===t)}function ie(e,t,n){return`${e}/${t}/pipelines/results/${n.build_number??encodeURIComponent(n.uuid)}`}var M=`https://bitbucket.org`,N=`https://api.bitbucket.org/2.0`;function P(e){throw e instanceof h||e instanceof v&&(e.status===403||e.status===404)?new o(`not-allowed`,`Setting up updates on Bitbucket needs the repository's Admin permission: use an owner token.`):e}function F(e){return e instanceof v&&(e.status===403||e.status===404)}function I(e,t,n,i,a){let{update:s}=b,l=`/repositories/${n}/pipelines_config`,u=()=>t()??e;async function d(){return j(await A(u(),n),s)}async function f(){return D(u(),`${l}/variables?pagelen=100`,5)}return{async setup(){if(!(await a())?.includes(`update --publish`))return`missing`;try{let[e,t]=await Promise.all([E(u(),l),A(u(),n)]);return e.enabled&&j(t,s)?`ready`:`needs-setup`}catch(e){if(F(e))return`needs-setup`;throw e}},async enable(){(await E(u(),l).catch(P)).enabled||await T(u(),l,{method:`PUT`,body:{enabled:!0}}).catch(P),!j(await A(u(),n).catch(P),s)&&await T(u(),`${l}/schedules`,{body:{type:`pipeline_schedule`,enabled:!0,cron_pattern:ne.update,target:{type:`pipeline_ref_target`,ref_type:`branch`,ref_name:i,selector:{type:`custom`,pattern:s}}}}).catch(P)},async lastRun(){let t=await E(e,`/repositories/${n}/pipelines/?${new URLSearchParams({"target.selector.pattern":s,sort:`-created_on`,pagelen:`10`})}`);for(let i of t.values){let t={date:i.created_on,detailsUrl:ie(M,n,i)};if(i.state?.name!==`COMPLETED`)return{state:`running`,...t};let a=`/repositories/${n}/pipelines/${encodeURIComponent(i.uuid)}/steps`,[o]=(await E(e,a)).values;if(!o)continue;let s;try{let t=await T(e,`${a}/${encodeURIComponent(o.uuid)}/log`,{allow:[404]});s=t.ok?await t.text():``}catch(e){if(e instanceof h)throw e;return{state:`unknown`,...t}}let c=r(s);if(c)return{state:c.state,result:c,...t}}},async start(e){await k(u(),n,i,s,{GOODFELLOW_UPDATE:e}).catch(P)},nightly:{async supported(){return(await a())?.includes(` nightly `)??!1},async get(){try{let e=await d();return e?e.enabled?(await f()).find(e=>e.key===`GOODFELLOW_NIGHTLY`)?.value===`always`?`always`:`changed`:`off`:void 0}catch(e){if(F(e))return;throw e}},async set(e){let t=await d().catch(P);if(!t)throw new o(`missing`,`The site has no nightly schedule yet: turn on updates first.`);await T(u(),`${l}/schedules/${encodeURIComponent(t.uuid)}`,{method:`PUT`,body:{enabled:e!==`off`}}).catch(P);let n=(await f().catch(P)).find(e=>e.key===c);e===`always`&&n?await T(u(),`${l}/variables/${encodeURIComponent(n.uuid)}`,{method:`PUT`,body:{key:c,value:`always`,secured:!1}}).catch(P):e===`always`?await T(u(),`${l}/variables`,{body:{key:c,value:`always`,secured:!1}}).catch(P):n&&await T(u(),`${l}/variables/${encodeURIComponent(n.uuid)}`,{method:`DELETE`,allow:[404]}).catch(P)}},async rebuild(){await k(u(),n,i,s,{GOODFELLOW_REBUILD:`true`}).catch(P)}}}function L(e){return e instanceof h&&e.problem===`no-access`||e instanceof v&&(e.status===403||e.status===404)}function R(e,t,n,r){let i,a=()=>(i??=E(e,`/repositories/${n}`).then(e=>e.mainbranch?.name??`main`),i.catch(()=>{i=void 0}),i);async function o(){return r(await a())}async function s(e){let t=await o();return t.readAt(e,await t.revision())}async function c(){return I(e,t,n,await a(),()=>s(te))}return{code:{repo:n,webUrl:`${M}/${n}`,read:s,history:async(e,t)=>(await o()).history(e,t),readAt:async(e,t)=>(await o()).readAt(e,t)},async setup(){try{return await(await c()).setup()}catch(e){if(L(e))return`no-access`;throw e}},async enable(){await(await c()).enable?.()},async lastRun(){try{return await(await c()).lastRun()}catch(e){if(L(e))return;throw e}},async start(e){await(await c()).start(e)},async rebuild(){await(await c()).rebuild?.()}}}function z(e){return e===`admin`?`owner`:e===`write`?`editor`:`viewer`}function B(e){return e===`owner`?`admin`:`write`}function V(e){return e instanceof v&&(e.status===403||e.status===404)}function ae(e,t){let n=t.toLowerCase();return[e.nickname,e.display_name,e.account_id,e.uuid].some(e=>e?.toLowerCase()===n)}function oe(e,t,n,r,i){let a=`/repositories/${n}/permissions-config/users`,o=n.split(`/`)[0]??``;function s(){let n=t()??(i===`admin`?e:void 0);if(!n)throw new l(`not-allowed`,`Changing editors on Bitbucket needs an owner token.`);return n}async function c(e){try{await e(s())}catch(e){throw e instanceof l?e:V(e)?new l(`not-allowed`,`This token can't change the site's editors.`):e}}async function u(e,t){if(t.includes(`@`)){let n=new URLSearchParams({q:`user.email IN (${O(t)})`});return(await E(e,`/workspaces/${o}/members?${n}`).catch(()=>void 0))?.values[0]?.user}return(await D(e,`/workspaces/${o}/members?pagelen=100`,10)).map(e=>e.user).find(e=>ae(e,t))}return{invitesByEmail:!1,membersOnly:!0,async list(){let n=t()??e,o;try{o=await D(n,`${a}?pagelen=100`,10)}catch(e){if(!V(e))throw e;return{editors:[{id:r.login,login:r.login,name:r.name,role:z(i??`write`),self:!0}],manage:i===`admin`?`token`:`no`,editorsCanPublish:!0}}return{editors:o.filter(e=>e.permission!==`none`).map(e=>({id:e.user.uuid,login:e.user.nickname,name:e.user.display_name,avatarUrl:e.user.links?.avatar?.href,role:z(e.permission),...e.user.nickname?.toLowerCase()===r.login.toLowerCase()&&{self:!0}})),manage:t()||i===`admin`?`yes`:`no`,editorsCanPublish:!0}},async invite(e,t){let n=e.trim().replace(/^@/,``);if(!n||/\s{2,}|[/\\]/.test(n))throw new l(`invalid`,`That isn't a Bitbucket account name or email address.`);let r=s(),i=await u(r,n);if(!i)throw new l(`not-found`,`Nobody called ${n} is in the Bitbucket workspace ${o}: add them to the workspace on Bitbucket first.`);let c=`${a}/${encodeURIComponent(i.uuid)}`,d=await T(r,c,{allow:[403,404]});if(d.ok&&(await d.json()).permission!==`none`)throw new l(`already`,`${n} already edits the site.`);let f=await T(r,c,{method:`PUT`,body:{permission:B(t)},allow:[400,402,403,404]});if(!f.ok)throw f.status===402?new l(`invalid`,`The Bitbucket workspace's plan has as many users as it allows.`):f.status===400?new l(`invalid`,`Bitbucket didn't accept ${n}.`):new l(`not-allowed`,`This token can't change the site's editors.`)},async setRole(e,t){await c(n=>T(n,`${a}/${encodeURIComponent(e.id)}`,{method:`PUT`,body:{permission:B(t)}}))},async remove(e){await c(t=>T(t,`${a}/${encodeURIComponent(e.id)}`,{method:`DELETE`,allow:[404]}))}}}function se(e,t,n){let r;return{access:{tokenLink:n,get active(){return r!==void 0},async applyToken(n){let i=C(n),a={...e,authorization:async()=>S(i)};try{await E(a,`/repositories/${t}/permissions-config/users?pagelen=1`)}catch(e){throw e instanceof h||V(e)?new l(`not-allowed`,`This token can't change the site's editors.`):e}r=a},forget(){r=void 0}},api:()=>r}}var H=`name: Scheduled change`;function U(e){return e instanceof v&&(e.status===401||e.status===403)}function W(e){throw U(e)?new ee(`not-allowed`,`Adding Pipelines schedules on Bitbucket needs permission to change the repository's Pipelines settings.`):e}function G(e){return e.toISOString().slice(0,16)}function ce(e,t,n,r,i,a=()=>new Date){let{scheduled:o}=b,s=`/repositories/${n}/pipelines_config/schedules`;return{async timing(){let e=await i().catch(()=>void 0);return e?.includes(H)?`exact`:e?.includes(` nightly `)?`nightly`:`none`},async sync(i){let c=t()??e,l=a(),u=new Map;for(let e of[...i].filter(e=>e>l).sort((e,t)=>e.getTime()-t.getTime())){if(u.size>=50)break;u.set(G(e),e)}let d=new Map;for(let e of await A(c,n).catch(W)){if(e.target?.selector?.pattern!==o)continue;let t=re(e.cron_pattern);t&&d.set(G(t),e)}for(let[e,t]of d)u.has(e)||await T(c,`${s}/${encodeURIComponent(t.uuid)}`,{method:`DELETE`,allow:[403,404]});for(let[e,t]of u)d.has(e)||await E(c,s,{body:{type:`pipeline_schedule`,enabled:!0,cron_pattern:x(t),target:{type:`pipeline_ref_target`,ref_type:`branch`,ref_name:r,selector:{type:`custom`,pattern:o}}}}).catch(W)}}}function le(e,t,n,r,a={}){let o=a.wait??(e=>new Promise(t=>setTimeout(t,e))),s=async()=>(await r().catch(()=>void 0)??``).includes(`GOODFELLOW_TASK_PLUGIN`);return{supported:s,secretsPlace:async()=>({kind:`bitbucket`,url:`${M}/${t}/admin/pipelines/repository-variables`}),async run(r){let c=d(r);if(c)throw new i(`failed`,c);if(!await s())throw new i(`missing`,`The site's setup files don't run plugins' tasks: bitbucket-pipelines.yml needs the plugin-task pipeline.`);let l;try{l=await k(e,t,n,b.task,{GOODFELLOW_TASK_REQUEST:r.id,GOODFELLOW_TASK_PLUGIN:r.plugin,GOODFELLOW_TASK_NAME:r.task,GOODFELLOW_TASK_INPUT:r.input,GOODFELLOW_TASK_KEY:r.key})}catch(e){throw e instanceof v&&e.status===400?new i(`missing`,`The site's repository doesn't have Bitbucket Pipelines turned on.`):e instanceof v&&(e.status===403||e.status===404)?new i(`not-allowed`,`Running plugins' tasks needs a sign-in that can run the site's pipelines.`):e}let f=`${u}${r.id}`,p=`/repositories/${t}/pipelines/${encodeURIComponent(l.uuid)}`,g=Date.now()+(a.timeoutMs??3e5),_=!1;for(;;){let n=await T(e,`/repositories/${t}/src/${encodeURIComponent(f)}/${m}`,{allow:[404]});if(n.ok){let r=await n.text();return await T(e,`/repositories/${t}/refs/branches/${encodeURIComponent(f)}`,{method:`DELETE`,allow:[403,404]}).catch(()=>{}),r}if(_)throw new i(`failed`,`The site's build service couldn't run the task.`);if(_=(await E(e,p).catch(e=>{if(e instanceof h)throw e}))?.state?.name===`COMPLETED`,!_){if(Date.now()>=g)throw new i(`timeout`,`The site's build service didn't answer in time.`);await o(a.pollMs??4e3)}}}}}var ue=10,K=8;function q(e){return!(e.url??``).startsWith(`${M}/`)}function J(e){return e.split(`/`).map(encodeURIComponent).join(`/`)}function Y(e,t){let n=`${t}/`;return[...e.keys()].filter(e=>e.startsWith(n)).sort()}function X(e){return(e??``).split(`
|
|
2
|
+
`)[0]?.trim()??``}function de(e){return e.author?.user?.display_name||e.author?.raw?.replace(/\s*<[^>]*>\s*$/,``).trim()||void 0}var Z=class r{user;editors;ownerAccess;updates;drafts;scheduledBuilds;tasks;contentOnly;options;api;repo;branch;onSignOut;owner;pinned;trees=new Map;texts=new Map;constructor(e){this.options=e,this.api=e.api,this.repo=e.repo,this.branch=e.branch,this.user=e.user,this.onSignOut=e.onSignOut,this.pinned=e.revision,this.contentOnly=e.contentOnly===!0,this.owner=se(this.api,this.repo,e.ownerTokenLink??{url:`https://bitbucket.org/${this.repo}/admin/access-tokens`,label:`owner.token.create`}),this.ownerAccess=this.owner.access;let t=async()=>this.readAt(`bitbucket-pipelines.yml`,this.pinned??await this.revision());if(this.editors=oe(this.api,this.owner.api,this.repo,this.user,e.permission),!this.contentOnly)this.updates=I(this.api,this.owner.api,this.repo,this.branch,t);else if(e.code){let t=e.code;this.updates=R(this.api,this.owner.api,t,e=>new r({api:this.api,repo:t,branch:e,user:this.user,onSignOut:()=>{}}))}this.drafts=s(this,this.draftHost()),this.scheduledBuilds=ce(this.api,this.owner.api,this.repo,this.branch,t),this.tasks=le(this.api,this.repo,this.branch,t,e.tasks)}path(e){return`/repositories/${this.repo}${e}`}async repositoryVisibility(){let{is_private:e}=await E(this.api,this.path(``));return e===!1?`public`:`private`}draftHost(){let e=async e=>{let t=await T(this.api,this.path(`/refs/branches/${encodeURIComponent(e)}`),{allow:[404]});if(t.ok)return(await t.json()).target.hash};return{liveBranch:this.branch,branchStore:e=>new r({...this.options,branch:e,revision:void 0}),createBranch:async(t,n)=>{let r=await T(this.api,this.path(`/refs/branches`),{body:{name:t,target:{hash:n}},allow:[400,409]});if(!r.ok)throw await e(t)?new f(`exists`,`There's already a draft called ${t}.`):new v(r.status,`Bitbucket couldn't make the branch ${t}.`)},deleteBranch:async e=>{await T(this.api,this.path(`/refs/branches/${encodeURIComponent(e)}`),{method:`DELETE`,allow:[404]})},mergeBase:async t=>{let[n,r]=await Promise.all([e(t),e(this.branch)]);if(!n||!r)throw new f(`not-found`,`There's no draft ${t}.`);return(await E(this.api,this.path(`/merge-base/${n}..${r}`))).hash},listBranches:async e=>{let t=new URLSearchParams({q:`name ~ ${O(e)}`,pagelen:`100`});return(await D(this.api,this.path(`/refs/branches?${t}`),5)).map(e=>e.name).filter(t=>t.startsWith(e))},openReview:async({branch:e,title:t,description:n})=>{let r=await T(this.api,this.path(`/pullrequests`),{body:{title:t,description:n,source:{branch:{name:e}},destination:{branch:{name:this.branch}},close_source_branch:!0},allow:[400,403,404]});if(r.ok)return{url:(await r.json()).links.html.href};if(r.status!==400)throw new f(`no-reviews`,`This sign-in can't open pull requests on the site's repository.`);let i=new URLSearchParams({q:`source.branch.name = ${O(e)} AND state = "OPEN"`}),a=(await E(this.api,this.path(`/pullrequests?${i}`))).values[0];if(!a)throw new f(`no-reviews`,`Bitbucket couldn't open the pull request.`);return{url:a.links.html.href}}}}async revision(){let e=this.pinned;if(this.pinned=await this.head(),e&&e!==this.pinned&&this.hasTextsAt(e)){let t=await this.changedPaths(e,this.pinned).catch(()=>void 0);t&&this.carryOver(e,this.pinned,new Set(t))}return this.pinned}async head(){return(await E(this.api,this.path(`/refs/branches/${encodeURIComponent(this.branch)}`))).target.hash}hasTextsAt(e){for(let t of this.texts.keys())if(t.startsWith(`${e}:`))return!0;return!1}carryOver(e,t,n){for(let[r,i]of[...this.texts]){if(!r.startsWith(`${e}:`))continue;let a=r.slice(e.length+1);!n.has(a)&&!this.texts.has(`${t}:${a}`)&&this.texts.set(`${t}:${a}`,i)}}async listFolder(e,t){let n=new URLSearchParams({max_depth:String(ue),pagelen:`100`}),r=await T(this.api,this.path(`/src/${e}/${J(t)}/?${n}`),{allow:[404]});if(r.status===404)return[];let i=[],a=await r.json();for(;;){for(let e of a.values)e.type===`commit_file`&&i.push([e.path,e.size??0]);if(!a.next)return i;a=await E(this.api,a.next)}}tree(t){let n=this.trees.get(t);return n||(n=Promise.all(e.map(e=>this.listFolder(t,e))).then(e=>new Map(e.flat())),n.catch(()=>this.trees.delete(t)),this.trees.set(t,n)),n}async current(){return this.pinned??await this.revision()}async read(e){let t=await this.current();return this.readFrom(t,await this.tree(t),e)}readFrom(e,t,n){if(!t.has(n))return Promise.resolve(void 0);let r=`${e}:${n}`,i=this.texts.get(r);return i||(i=T(this.api,this.path(`/src/${e}/${J(n)}`)).then(e=>e.text()),i.catch(()=>this.texts.delete(r)),this.texts.set(r,i)),i}async readFiles(e){let t=await this.current();return this.readFilesFrom(t,await this.tree(t),e)}async readFilesFrom(e,t,n){let r=new Map,i=n.filter(e=>t.has(e));for(let n=0;n<i.length;n+=K){let a=i.slice(n,n+K),o=await Promise.all(a.map(n=>this.readFrom(e,t,n)));a.forEach((e,t)=>{let n=o[t];n!==void 0&&r.set(e,n)})}return r}async readBytes(e){let t=await this.current();return this.bytesFrom(t,await this.tree(t),e)}async bytesFrom(e,t,n){if(!t.has(n))return;let r=await T(this.api,this.path(`/src/${e}/${J(n)}`));return new Uint8Array(await r.arrayBuffer())}async list(e){return Y(await this.tree(await this.current()),e)}filesAt(e){return{read:async t=>this.readFrom(e,await this.tree(e),t),readFiles:async t=>this.readFilesFrom(e,await this.tree(e),t),readBytes:async t=>this.bytesFrom(e,await this.tree(e),t),list:async t=>Y(await this.tree(e),t)}}async fileSizes(e){let t=await this.tree(await this.current());return new Map(Y(t,e).map(e=>[e,t.get(e)??0]))}async existsAt(t,n,r){return e.some(e=>n.startsWith(`${e}/`))?t.has(n):(await T(this.api,this.path(`/src/${r}/${J(n)}?format=meta`),{allow:[404]})).ok}async write(e,{message:r,expectedRevision:i}){this.contentOnly&&t(e);let a=await this.tree(i),o=new FormData,s=0;for(let t of e){if(`delete`in t){if(!await this.existsAt(a,t.path,i))continue;o.append(`files`,t.path)}else{let e=`bytes`in t?new Uint8Array(t.bytes):t.content;o.append(`/${t.path}`,new Blob([e]),t.path.split(`/`).at(-1)??t.path)}s+=1}if(s===0)return{revision:i};o.append(`message`,r),o.append(`branch`,this.branch),o.append(`parents`,i),this.options.author&&o.append(`author`,`${this.options.author.name} <${this.options.author.email}>`);let c=await T(this.api,this.path(`/src`),{form:o,allow:[403,409]});if(c.status===409)throw new n;if(c.status===403)throw new h(`cant-publish`,`This Bitbucket account can't publish to the site.`);let l=await this.commitAfter(i,r);return this.carryOver(i,l,new Set(e.map(e=>e.path))),this.pinned=l,{revision:l}}async commitAfter(e,t){let n=new URLSearchParams({pagelen:`20`}),r=await E(this.api,this.path(`/commits/${encodeURIComponent(this.branch)}?${n}`)),i=r.values.find(n=>n.parents?.[0]?.hash===e&&X(n.message)===X(t))??r.values.find(t=>t.parents?.[0]?.hash===e);return i?i.hash:this.head()}async history(e,{page:t=1,perPage:n=20}={}){let r=new URLSearchParams({path:e,pagelen:String(n)}),i=this.path(`/commits/${await this.current()}?${r}`),a={values:[]};for(let e=1;i&&e<=t;e++)if(a=await E(this.api,i),i=a.next,e<t&&!i)return[];return a.values.map(e=>({revision:e.hash,date:e.date??``,author:de(e),message:X(e.message)}))}async readAt(e,t){let n=await T(this.api,this.path(`/src/${t}/${J(e)}`),{allow:[404]});return n.ok?n.text():void 0}async changedPaths(e,t){let n=new URLSearchParams({topic:`false`,pagelen:`500`}),r=(await D(this.api,this.path(`/diffstat/${t}..${e}?${n}`))).flatMap(e=>[e.old?.path,e.new?.path]);return[...new Set(r.filter(e=>!!e))]}async deployStatus(e){try{let t=await this.statuses(e),n=t.filter(q);if(n.length===0){if(t.length>0)return{state:`unknown`};let n=(await E(this.api,this.path(`/commit/${e}`))).parents?.[0]?.hash;return{state:(n?(await this.statuses(n)).filter(q):[]).length>0?`building`:`unknown`}}let r=n.find(e=>e.state===`FAILED`)??n.find(e=>e.state===`STOPPED`);if(r?.state===`STOPPED`){let t=await this.head();if(t!==e)return this.deployStatus(t)}if(r)return{state:`failed`,...r.url&&{detailsUrl:r.url}};let i=n[0]?.url;return{state:n.every(e=>e.state===`SUCCESSFUL`)?`live`:`building`,...i&&{detailsUrl:i}}}catch(e){if(e instanceof v)return{state:`unknown`};throw e}}statuses(e){return D(this.api,this.path(`/commit/${e}/statuses?pagelen=100`),3)}signOut(){this.ownerAccess.forget(),this.onSignOut()}},Q=`main`,fe=/^[a-z0-9][a-z0-9_.-]{0,61}$/;function $(e={}){let t=e.fetch??((e,t)=>globalThis.fetch(e,t));async function n(e){let n={apiUrl:N,authorization:async()=>S(e),fetch:t},r=await E(n,`/user`,{allow:[403]}).catch(e=>{throw e instanceof v?new h(`invalid`,`Creating a repository on Bitbucket needs an API token, not an access token.`):e}),i=r.username??r.nickname??``;if(!i)throw new h(`invalid`,`Creating a repository on Bitbucket needs an API token, not an access token.`);return{user:{login:i,name:r.display_name},owners:async()=>{let e=await D(n,`/user/workspaces?pagelen=100`,5);return e.filter(t=>t.permission!==`member`||e.length===1).map(({workspace:e})=>({path:e.slug,name:e.name??e.slug,kind:e.slug===i?`personal`:`organization`})).sort((e,t)=>e.kind===t.kind?e.name.localeCompare(t.name):e.kind===`personal`?-1:1)},async isAvailable(e,t){return(await T(n,`/repositories/${e.path}/${t.toLowerCase()}`,{allow:[403,404]})).status===404},async createSite(e,t){let r=e.name.toLowerCase();if(!fe.test(r))throw new p(`name-invalid`,`That name can't be used for a repository.`);let i=`${e.owner.path}/${r}`;t?.(`repository`);let a=await T(n,`/repositories/${i}`,{body:{scm:`git`,is_private:e.private,...e.description&&{description:e.description}},allow:[400,403]});if(a.status===400)throw new p(`name-taken`,`There's already a repository called ${i}.`);if(a.status===403)throw new p(`not-allowed`,`This account can't create repositories in ${e.owner.name}.`);t?.(`files`);let o=new FormData;for(let t of e.files){if(`delete`in t)continue;let e=`bytes`in t?new Uint8Array(t.bytes):t.content;o.append(`/${t.path}`,new Blob([e]),t.path.split(`/`).at(-1)??t.path)}if(o.append(`message`,e.message),o.append(`branch`,Q),(await T(n,`/repositories/${i}/src`,{form:o,allow:[403]})).status===403)throw new p(`not-allowed`,`This account can't write to the new repository.`);await T(n,`/repositories/${i}`,{method:`PUT`,body:{mainbranch:{name:Q}},allow:[400,403]});let s=e.pages?[`pages-unavailable`]:[];return{repo:i,webUrl:`${M}/${i}`,buildsUrl:`${M}/${i}/pipelines`,warnings:s}}}}return{name:`Bitbucket`,canRedirect:!1,tokenLinks:[{url:`https://id.atlassian.com/manage-profile/security/api-tokens`,label:`signIn.token.create`,hint:`signIn.token.apiTokenHint`}],async restore(){return null},async signInWithToken(e){let t=e.trim();if(!t)throw new h(`invalid`,`Paste a token to sign in.`);return n(C(t))},async startRedirect(){throw Error(`Creating repositories on Bitbucket needs a token.`)}}}function pe(){return{href:()=>window.location.href,assign:e=>window.location.assign(e),replace:e=>window.history.replaceState(window.history.state,``,e)}}function me(){return[...crypto.getRandomValues(new Uint8Array(16))].map(e=>e.toString(16).padStart(2,`0`)).join(``)}function he(e){let t=e.fetch??((e,t)=>globalThis.fetch(e,t)),n=g(`goodfellow:bitbucket:${e.repo}`,e.storage),r=g(`goodfellow:bitbucket:pending:${e.repo}`,e.storage),i=()=>e.location??pe(),[a=``]=e.repo.split(`/`);async function o(r,i){if(r.type===`oauth`&&r.expiresAt<Date.now())throw new h(`invalid`,`The Bitbucket sign-in has expired.`);let o={apiUrl:N,authorization:async()=>S(r),fetch:t},s=await T(o,`/repositories/${e.repo}`,{allow:[403,404]});if(!s.ok)throw new h(`no-access`,`This Bitbucket sign-in can't see ${e.repo}.`);let c=await s.json(),l=await T(o,`/user`,{allow:[401,403]}),u=l.ok?await l.json():void 0,d=u?.username??u?.nickname,f;if(d){let t=new URLSearchParams({q:`repository.full_name = ${O(e.repo)}`});if(f=await E(o,`/user/workspaces/${a}/permissions/repositories?${t}`).then(e=>e.values[0]?.permission,()=>void 0),f===`read`)throw new h(`cant-publish`,`The Bitbucket account ${d} can see ${e.repo} but can't publish to it.`)}return n.save(JSON.stringify(r),i),new Z({api:o,repo:e.repo,branch:e.branch??c.mainbranch?.name??`main`,user:d?{login:d,name:u?.display_name,avatarUrl:u?.links?.avatar?.href}:{login:`access-token`,name:`Access token`},...f&&{permission:f},...e.contentOnly&&{contentOnly:!0,...e.code&&{code:e.code}},onSignOut:()=>n.clear()})}async function s(){let e=new URL(i().href()),t=new URLSearchParams(e.hash.replace(/^#/,``)),n=t.get(`access_token`),a=t.get(`error`)??e.searchParams.get(`error`);if(!n&&!a)return null;let s=r.load();if(!s)return null;r.clear();let c=JSON.parse(s);e.hash=c.hash;for(let t of[`error`,`error_description`])e.searchParams.delete(t);if(i().replace(e.toString()),a||!n||t.get(`state`)!==c.state)throw new h(`redirect-failed`,`Signing in with Bitbucket was cancelled or didn't finish.`);let l=Number(t.get(`expires_in`)??7200);return o({type:`oauth`,access:n,expiresAt:Date.now()+(Number.isFinite(l)?l:7200)*1e3},c.remember)}function c({token:n}){let r={apiUrl:N,authorization:async()=>S(C(typeof n==`string`?n:await n())),fetch:t},i,a=()=>(i??=e.branch?Promise.resolve(e.branch):E(r,`/repositories/${e.repo}`).then(e=>e.mainbranch?.name??`main`),i.catch(()=>{i=void 0}),i),o=async(t,n)=>new Z({api:r,repo:e.repo,branch:await a(),...e.contentOnly&&{contentOnly:!0,...e.code&&{code:e.code}},user:{login:n?.name??e.repo,...n&&{name:n.name}},onSignOut:()=>{},...t&&{revision:t},...n&&{author:n}});return{...e.contentOnly&&{contentOnly:!0,...e.code&&{code:e.code}},async revision(){return(await o()).revision()},at:o}}return{name:`Bitbucket`,source:_(`@goodfellow-cms/bitbucket`,`bitbucket`,e,[`fetch`,`storage`,`location`]),canRedirect:!!e.clientId,redirectAddressesListed:!!e.clientId,setup:()=>$({...e.fetch&&{fetch:e.fetch}}),tokenLinks:[{url:`${M}/${e.repo}/admin/access-tokens`,label:`signIn.token.create`},{url:`https://id.atlassian.com/manage-profile/security/api-tokens`,label:`signIn.token.createBroad`,hint:`signIn.token.apiTokenHint`}],async restore(){let e=await s();if(e)return e;let t=n.load();if(!t)return null;try{return await o(JSON.parse(t),n.remembered())}catch(e){throw e instanceof h&&n.clear(),e}},async signInWithToken(e,t){let n=e.trim();if(!n)throw new h(`invalid`,`Paste a token to sign in.`);return o(C(n),t)},async startRedirect(t){if(!e.clientId)throw Error(`bitbucket({ clientId }) is needed to sign in with Bitbucket.`);let n=me(),a={state:n,remember:t,hash:new URL(i().href()).hash};r.save(JSON.stringify(a),!1);let o=new URLSearchParams({client_id:e.clientId,response_type:`token`,state:n});i().assign(`${M}/site/oauth2/authorize?${o}`)},server:c}}export{N as BITBUCKET_API,M as BITBUCKET_WEB,Z as BitbucketBackend,he as bitbucket,$ as bitbucketSetup,J as encodePath};
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import{n as e,r as t,t as n}from"./store-CNLNNQkL.js";import{_ as r,a as i,c as a,h as o,i as s,m as c,n as l,p as u,r as d,t as f,u as p}from"./setup-host-B_uhd1y7.js";import{i as m,n as ee,r as h}from"./content-repository-setup-3Z0i5cMx.js";import{n as g,o as _,r as v,s as te,t as y}from"./git-eGyMXUIu.js";import{t as ne}from"./scheduled-builds-BPfDaBYt.js";async function b(e,t,n={}){let r=async r=>e.fetch(`${e.apiUrl}${t}`,{method:n.method??`GET`,headers:{authorization:`Bearer ${await e.token({refresh:r})}`,...n.body!==void 0&&{"content-type":`application/json`}},body:n.body===void 0?void 0:JSON.stringify(n.body),cache:`no-store`}),i=await r(!1);if(i.status===401&&e.canRefresh&&(i=await r(!0)),i.status===401)throw new g(`invalid`,`GitLab didn't accept the sign-in. It may have expired.`);if(!i.ok&&!n.allow?.includes(i.status)){let e=await i.json().catch(()=>({})),t=typeof e.message==`string`?e.message:JSON.stringify(e.message??e.error??``);throw new y(i.status,`GitLab answered ${i.status}: ${t||i.statusText}`)}return i}async function x(e,t,n){return await(await b(e,t,n)).json()}var S=30,C=40,w=`member:`,T=`invitation:`,E=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,re=/^[\w][\w.-]*$/;function D(e){return e>=C?`owner`:e>=S?`editor`:`viewer`}function O(e){return e===`owner`?C:S}function k(e){throw e instanceof y&&(e.status===401||e.status===403)?new l(`not-allowed`,`Changing editors on GitLab needs the Maintainer role in the project.`):e}function ie(e,t,n,r){let i=`/projects/${encodeURIComponent(t)}`,a=`${i}/protected_branches/${encodeURIComponent(n)}`;async function o(t){let n=[];for(let r=1;r<=10;r++){let i=await x(e,`${t}${t.includes(`?`)?`&`:`?`}per_page=100&page=${r}`);if(n.push(...i),i.length<100)break}return n}return{invitesByEmail:!0,async list(){let[t,n]=await Promise.all([o(`${i}/members/all`),o(`${i}/members`)]),s=new Set(n.map(e=>e.id)),c=t.find(e=>e.username.toLowerCase()===r.toLowerCase()),l=(c?.access_level??0)>=C,u=l?await o(`${i}/invitations`).catch(()=>[]):[],d=await b(e,a,{allow:[404]}),f=d.ok?(await d.json()).push_access_levels??[]:[],p=!d.ok||f.some(e=>e.access_level!==null&&e.access_level<=S);return{editors:[...t.map(e=>({id:`${w}${e.id}`,login:e.username,name:e.name,avatarUrl:e.avatar_url,role:D(e.access_level),...!s.has(e.id)&&{inherited:!0},...e.id===c?.id&&{self:!0}})),...u.map(e=>({id:`${T}${e.invite_email}`,email:e.invite_email,role:D(e.access_level),invited:!0}))],manage:l?`yes`:`no`,editorsCanPublish:p}},async invite(t,n){let r=t.trim().replace(/^@/,``);if(r.includes(`@`)){if(!E.test(r))throw new l(`invalid`,`That isn't an email address.`);let t=await x(e,`${i}/invitations`,{method:`POST`,body:{email:r,access_level:O(n)}}).catch(k);if(t.status!==`success`){let e=typeof t.message==`string`?t.message:Object.values(t.message??{})[0];throw/already/i.test(e??``)?new l(`already`,`They've already been invited.`):new l(`invalid`,`GitLab didn't accept the invitation: ${e??t.status}`)}return}if(!re.test(r))throw new l(`invalid`,`That isn't a GitLab username or email address.`);let[a]=await x(e,`/users?${new URLSearchParams({username:r})}`);if(!a)throw new l(`not-found`,`There's no GitLab account named ${r}.`);try{await b(e,`${i}/members`,{method:`POST`,body:{user_id:a.id,access_level:O(n)}})}catch(e){if(e instanceof y&&e.status===409)throw new l(`already`,`${r} already edits the site.`);k(e)}},async setRole(t,n){await b(e,t.id.startsWith(T)?`${i}/invitations/${encodeURIComponent(t.id.slice(11))}`:`${i}/members/${t.id.slice(7)}`,{method:`PUT`,body:{access_level:O(n)}}).catch(k)},async remove(t){await b(e,t.id.startsWith(T)?`${i}/invitations/${encodeURIComponent(t.id.slice(11))}`:`${i}/members/${t.id.slice(7)}`,{method:`DELETE`}).catch(k)},async letEditorsPublish(){let t=t=>b(e,`${i}/protected_branches`,{method:`POST`,body:{name:n,push_access_level:t,merge_access_level:t,allow_force_push:!1}});await b(e,a,{method:`DELETE`,allow:[404]}).catch(k);try{await t(S)}catch(e){await t(C).catch(()=>void 0),k(e)}}}}var ae=`35.185.44.232`,A=`2600:1901:0:7b8a::`;function j(e,{apex:t,www:n}){return t&&n?[e,`www.${e}`]:[e]}function M(e,t,n,r){let i=`${(e.split(`/`)[0]??``).toLowerCase()}.gitlab.io`,a=n.apex?[{type:`A`,name:t,value:ae,purpose:`site`},{type:`AAAA`,name:t,value:A,purpose:`site`,optional:!0}]:[{type:`CNAME`,name:t,value:i,purpose:`site`}],o=n.apex&&n.www?[{type:`CNAME`,name:`www.${t}`,value:i,purpose:`www`,optional:!0}]:[],s=j(t,n).flatMap(e=>{let n=r[e];if(!n)return[];let i=n.startsWith(`gitlab-pages-verification-code=`)?n:`gitlab-pages-verification-code=${n}`;return[{type:`TXT`,name:`_gitlab-pages-verification-code.${e}`,value:i,purpose:`verification`,optional:e!==t}]});return[...a,...o,...s]}function N(e,t){let n=`/projects/${encodeURIComponent(t)}/pages`,r=e=>`${n}/domains/${encodeURIComponent(e)}`;function i(e){throw e instanceof y&&(e.status===401||e.status===403)?new m(`not-allowed`,`Connecting a domain on GitLab needs the Maintainer role in the project.`):e}async function a(){let t=await b(e,n,{allow:[404]}).catch(i);return t.ok?await t.json():void 0}async function o(t){let n=await Promise.all(t.map(async t=>{let n=await b(e,r(t),{allow:[404]});return n.ok?[t,(await n.json()).verification_code??``]:[t,``]}));return Object.fromEntries(n)}async function s(t){let n=await x(e,r(t)).catch(i);if(n.verified)return n;let a=await b(e,`${r(t)}/verify`,{method:`PUT`,allow:[400,404,422]});return a.ok?await a.json():n}return{severalDomains:!0,async site(){let t=await a();if(!t)return;let r=(await x(e,`${n}/domains`).catch(()=>[])).map(e=>e.domain),i=(t.primary_domain&&r.includes(t.primary_domain)?t.primary_domain:void 0)??r.sort((e,t)=>e.length-t.length)[0];return{url:t.url,domain:i}},async connect(s,c){let l=await a();l&&l.is_unique_domain_enabled===!1&&await b(e,n,{method:`PATCH`,body:{pages_unique_domain_enabled:!0}}).catch(i);for(let t of j(s,c))try{await b(e,`${n}/domains`,{method:`POST`,body:{domain:t,auto_ssl_enabled:!0}})}catch(n){if(n instanceof y&&n.status===400){if(/taken/i.test(n.message)){if((await b(e,r(t),{allow:[404]})).ok)continue;throw new m(`taken`,`Another GitLab Pages site already uses this domain.`)}throw new m(`invalid`,`GitLab Pages doesn't accept this domain.`)}i(n)}return M(t,s,c,await o(j(s,c)))},async records(e,n){return M(t,e,n,await o(j(e,n)))},async status(t){let n=await s(t),i=await b(e,r(`www.${t}`),{allow:[404]});i.ok&&!(await i.json()).verified&&await s(`www.${t}`);let o=await a();return{verified:n.verified,certificate:n.certificate&&!n.certificate.expired?`ready`:`pending`,httpsOnly:o?.force_https===!0,primary:o?.primary_domain===void 0||o.primary_domain===t}},async secure(t,{primary:a=!0}={}){let o=await x(e,r(t)).catch(i);if(!o.verified||!o.certificate)throw new m(`not-ready`,`The domain's certificate isn't ready yet.`);if(!a){await b(e,n,{method:`PATCH`,body:{pages_https_only:!0}}).catch(i);return}try{await b(e,n,{method:`PATCH`,body:{pages_https_only:!0,pages_primary_domain:t}})}catch(t){t instanceof y&&t.status===400||i(t),await b(e,n,{method:`PATCH`,body:{pages_https_only:!0}}).catch(i)}},async disconnect(t){for(let n of[t,`www.${t}`])await b(e,r(n),{method:`DELETE`,allow:[404]}).catch(i)}}}var oe=`Goodfellow: build the site for a scheduled change at `,se=`GOODFELLOW_SCHEDULED_CHANGE`;function P(e){throw e instanceof y&&(e.status===401||e.status===403)?new ne(`not-allowed`,`Adding pipeline schedules on GitLab needs the Developer role, with permission to merge to the main branch.`):e}function ce(e){return`${e.getUTCMinutes()} ${e.getUTCHours()} ${e.getUTCDate()} ${e.getUTCMonth()+1} *`}function le(e){return`${e.toISOString().slice(0,16)}Z`}function ue(e,t,n,r,i=()=>new Date){let a=`/projects/${encodeURIComponent(t)}/pipeline_schedules`;return{async timing(){return await r()===void 0?`none`:`exact`},async sync(t){let r=i(),o=new Map;for(let e of[...t].filter(e=>e>r).sort((e,t)=>e.getTime()-t.getTime())){if(o.size>=50)break;o.set(le(e),e)}let s=await x(e,`${a}?per_page=100`).catch(P),c=new Map;for(let e of s)e.description?.startsWith(`Goodfellow: build the site for a scheduled change at `)&&c.set(e.description.slice(53),e);for(let[t,n]of c)o.has(t)||await b(e,`${a}/${n.id}`,{method:`DELETE`,allow:[403,404]});for(let[t,r]of o){if(c.has(t))continue;let i=await x(e,a,{method:`POST`,body:{description:`${oe}${t}`,ref:n,cron:ce(r),cron_timezone:`UTC`,active:!0}}).catch(P);await b(e,`${a}/${i.id}/variables`,{method:`POST`,body:{key:se,value:t,variable_type:`env_var`}}).catch(P)}}}}function F(e,t,n,r,o={}){let s=`/projects/${encodeURIComponent(t)}`,c=o.wait??(e=>new Promise(t=>setTimeout(t,e))),l=async()=>(await r().catch(()=>void 0)??``).includes(`$GOODFELLOW_TASK_PLUGIN`);return{supported:l,secretsPlace:async()=>({kind:`gitlab`,url:`${e.apiUrl.replace(/\/api\/v4\/?$/,``)}/${t}/-/settings/ci_cd#js-cicd-variables-settings`}),async run(t){let r=u(t);if(r)throw new i(`failed`,r);if(!await l())throw new i(`missing`,`The site's setup files don't run plugins' tasks: .gitlab-ci.yml needs the plugin-task job.`);let d=(e,t)=>({key:e,variable_type:`env_var`,value:t}),f;try{f=await x(e,`${s}/pipeline`,{method:`POST`,body:{ref:n,variables:[d(`GOODFELLOW_TASK_REQUEST`,t.id),d(`GOODFELLOW_TASK_PLUGIN`,t.plugin),d(`GOODFELLOW_TASK_NAME`,t.task),d(`GOODFELLOW_TASK_INPUT`,t.input),d(`GOODFELLOW_TASK_KEY`,t.key)]}})}catch(e){throw e instanceof y&&(e.status===403||e.status===401)?new i(`not-allowed`,`Running plugins' tasks needs a sign-in that can publish to the site.`):e}let m=Date.now()+(o.timeoutMs??3e5);for(;;){let t=(await x(e,`${s}/pipelines/${f.id}/jobs?per_page=100`)).find(e=>e.name===a);if(t?.status===`success`){let n=await b(e,`${s}/jobs/${t.id}/artifacts/${p}`,{allow:[404]});if(n.ok)return await n.text();throw new i(`failed`,`The site's build service ran the task but left no answer.`)}if(t&&[`failed`,`canceled`,`skipped`].includes(t.status))throw new i(`failed`,`The site's build service couldn't run the task.`);if(Date.now()>=m)throw new i(`timeout`,`The site's build service didn't answer in time.`);await c(o.pollMs??4e3)}}}}var I=`.gitlab-ci.yml`,L=`17 4 * * *`;function R(e){throw e instanceof y&&(e.status===401||e.status===403)?new o(`not-allowed`,`Setting up updates on GitLab needs the Maintainer role in the project.`):e}function z(e,t,n,i,a=`pages`){let s=`/projects/${encodeURIComponent(t)}`;async function l(){return x(e,`${s}/pipeline_schedules`)}async function u(){return(await l()).find(e=>(e.ref===n||e.ref===`refs/heads/${n}`)&&!e.description?.startsWith(`Goodfellow: build the site for a scheduled change at `))}return{async setup(){if(!(await i(I))?.includes(`update --publish`))return`missing`;try{let[t,r]=await Promise.all([x(e,s),l()]),i=r.some(e=>(e.ref===n||e.ref===`refs/heads/${n}`)&&(e.active||!e.description?.startsWith(`Goodfellow: build the site for a scheduled change at `)));return t.ci_push_repository_for_job_token_allowed&&i?`ready`:`needs-setup`}catch(e){if(e instanceof y&&e.status===403)return`needs-setup`;throw e}},async enable(){await b(e,s,{method:`PUT`,body:{ci_push_repository_for_job_token_allowed:!0}}).catch(R),await u().catch(R)||await b(e,`${s}/pipeline_schedules`,{method:`POST`,body:{description:`Rebuild the site and install Goodfellow's fixes each night`,ref:n,cron:L,cron_timezone:`UTC`,active:!0}}).catch(R)},async lastRun(){let t=await x(e,`${s}/pipelines?${new URLSearchParams({ref:n,per_page:`20`})}`);for(let n of t){if(n.source!==`schedule`&&n.source!==`api`)continue;let t={date:n.created_at,detailsUrl:n.web_url};if([`created`,`pending`,`running`,`waiting_for_resource`,`preparing`].includes(n.status))return{state:`running`,...t};let i=(await x(e,`${s}/pipelines/${n.id}/jobs?per_page=100`)).find(e=>e.name===a||e.name===`update`);if(!i)continue;let o=await b(e,`${s}/jobs/${i.id}/trace`,{allow:[403,404]}),c=o.ok?r(await o.text()):void 0;if(c)return{state:c.state,result:c,...t}}},async start(t){await b(e,`${s}/pipeline`,{method:`POST`,body:{ref:n,variables:[{key:`GOODFELLOW_UPDATE`,variable_type:`env_var`,value:t}]}}).catch(R)},nightly:{async supported(){return(await i(I))?.includes(`nightly`)??!1},async get(){try{let t=await u();return t?t.active?(await x(e,`${s}/pipeline_schedules/${t.id}`)).variables?.find(e=>e.key===`GOODFELLOW_NIGHTLY`)?.value===`always`?`always`:`changed`:`off`:void 0}catch(e){if(e instanceof y&&e.status===403)return;throw e}},async set(t){let n=await u().catch(R);if(!n)throw new o(`missing`,`The site has no nightly schedule yet: turn on updates first.`);let r=`${s}/pipeline_schedules/${n.id}`;if(await b(e,r,{method:`PUT`,body:{active:t!==`off`}}).catch(R),t===`always`){let t={key:c,value:`always`};(await b(e,`${r}/variables/GOODFELLOW_NIGHTLY`,{method:`PUT`,body:t,allow:[404]}).catch(R)).status===404&&await b(e,`${r}/variables`,{method:`POST`,body:t}).catch(R)}else t===`changed`&&await b(e,`${r}/variables/${c}`,{method:`DELETE`,allow:[404]}).catch(R)}},async rebuild(){await b(e,`${s}/pipeline`,{method:`POST`,body:{ref:n,variables:[{key:`GOODFELLOW_REBUILD`,variable_type:`env_var`,value:`true`}]}}).catch(R)}}}function B(e){return e instanceof y&&(e.status===403||e.status===404)}function V(e){let{api:t,project:n}=e,r,i=()=>(r??=x(t,`/projects/${encodeURIComponent(n)}`).then(e=>e.default_branch),r.catch(()=>{r=void 0}),r),a=async()=>e.open(await i()),o=async e=>{let t=await a();return t.readAt(e,await t.revision())},s=async()=>z(t,n,await i(),o,`update`);return{code:{repo:n,webUrl:`${e.webUrl}/${n}`,read:o,history:async(e,t)=>(await a()).history(e,t),readAt:async(e,t)=>(await a()).readAt(e,t)},async setup(){try{return await(await s()).setup()}catch(e){if(B(e))return`no-access`;throw e}},async enable(){await(await s()).enable?.()},async lastRun(){try{return await(await s()).lastRun()}catch(e){if(B(e))return;throw e}},async start(e){await(await s()).start(e)},async rebuild(){await(await s()).rebuild?.()}}}var H=100,U=50,de=RegExp(`\x1B\\[[\\d;]*[A-Za-z]`,`g`);function W(e){return e.name!==`rebuild`&&e.name!==`update`&&e.name!==`lockfile`}function G(e,t){let n=`${t}/`;return[...e.keys()].filter(e=>e.startsWith(n)).sort()}var K=class r{user;pages;editors;updates;drafts;scheduledBuilds;tasks;contentOnly;options;api;project;branch;onSignOut;pinned;trees=new Map;blobs=new Map;constructor(e){if(this.options=e,this.api=e.api,this.project=encodeURIComponent(e.project),this.branch=e.branch,this.user=e.user,this.onSignOut=e.onSignOut,this.pinned=e.revision,this.pages=N(this.api,e.project),this.editors=ie(this.api,e.project,this.branch,this.user.login),this.contentOnly=e.contentOnly===!0,!this.contentOnly)this.updates=z(this.api,e.project,this.branch,async e=>this.readAt(e,this.pinned??await this.revision()));else if(e.code){let t=e.code;this.updates=V({api:this.api,project:t.project,webUrl:t.webUrl,open:e=>new r({api:this.api,project:t.project,branch:e,user:this.user,onSignOut:()=>{}})})}this.drafts=s(this,this.draftHost()),this.scheduledBuilds=ue(this.api,e.project,this.branch,async()=>this.readAt(`.gitlab-ci.yml`,this.pinned??await this.revision())),this.tasks=F(this.api,e.project,this.branch,async()=>this.readAt(`.gitlab-ci.yml`,this.pinned??await this.revision()),e.tasks)}async repositoryVisibility(){let{visibility:e}=await x(this.api,`/projects/${this.project}`);return e===`public`||e===`internal`?e:`private`}draftHost(){let e=`/projects/${this.project}`;return{liveBranch:this.branch,branchStore:e=>new r({...this.options,branch:e}),createBranch:async(e,t)=>{if((await b(this.api,this.repo(`/branches?${new URLSearchParams({branch:e,ref:t})}`),{method:`POST`,allow:[400]})).status===400)throw new d(`exists`,`There's already a draft called ${e}.`)},deleteBranch:async e=>{await b(this.api,this.repo(`/branches/${encodeURIComponent(e)}`),{method:`DELETE`,allow:[404]})},mergeBase:async e=>{let t=new URLSearchParams;t.append(`refs[]`,this.branch),t.append(`refs[]`,e);let n=await b(this.api,this.repo(`/merge_base?${t}`),{allow:[400,404]});if(!n.ok)throw new d(`not-found`,`There's no draft ${e}.`);return(await n.json()).id},listBranches:async e=>{let t=new URLSearchParams({search:`^${e}`,per_page:`100`});return(await x(this.api,this.repo(`/branches?${t}`))).map(e=>e.name).filter(t=>t.startsWith(e))},openReview:async({branch:t,title:n,description:r})=>{let i=await b(this.api,`${e}/merge_requests`,{method:`POST`,body:{source_branch:t,target_branch:this.branch,title:n,description:r,remove_source_branch:!0},allow:[403,404,409]});if(i.ok)return{url:(await i.json()).web_url};if(i.status!==409)throw new d(`no-reviews`,`This sign-in can't open merge requests on the site's project.`);let a=new URLSearchParams({source_branch:t,state:`opened`}),[o]=await x(this.api,`${e}/merge_requests?${a}`);if(!o)throw new y(409,`GitLab couldn't open the merge request.`);return{url:o.web_url}}}}repo(e){return`/projects/${this.project}/repository${e}`}async revision(){return this.pinned=await this.head(),this.pinned}async head(){return(await x(this.api,this.repo(`/branches/${encodeURIComponent(this.branch)}`))).commit.id}async listFolder(e,t){let n=[];for(let r=1;;r++){let i=new URLSearchParams({ref:e,path:t,recursive:`true`,per_page:String(H),page:String(r)}),a=await b(this.api,this.repo(`/tree?${i}`),{allow:[404]});if(a.status===404)return n;let o=await a.json();for(let e of o)e.type===`blob`&&n.push([e.path,e.id]);if(o.length<H)return n}}tree(t){let n=this.trees.get(t);return n||(n=Promise.all(e.map(e=>this.listFolder(t,e))).then(e=>new Map(e.flat())),n.catch(()=>this.trees.delete(t)),this.trees.set(t,n)),n}async currentTree(){return this.tree(this.pinned??await this.revision())}async read(e){return this.readFrom(await this.currentTree(),e)}readFrom(e,t){let n=e.get(t);if(!n)return Promise.resolve(void 0);let r=this.blobs.get(n);return r||(r=b(this.api,this.repo(`/blobs/${n}/raw`)).then(e=>e.text()),r.catch(()=>this.blobs.delete(n)),this.blobs.set(n,r)),r}async readFiles(e){let t=this.pinned??await this.revision();return this.readFilesFrom(t,await this.tree(t),e)}async readFilesFrom(e,t,n){let r=n.filter(e=>t.has(e)),i=r.filter(e=>!this.blobs.has(t.get(e)??``));for(let n=0;n<i.length;n+=U){let r=i.slice(n,n+U),a=await x(this.api,`/../graphql`,{method:`POST`,body:{query:`query ($project: ID!, $ref: String!, $paths: [String!]!) {
|
|
2
|
+
project(fullPath: $project) { repository { blobs(ref: $ref, paths: $paths) { nodes { path rawTextBlob } } } }
|
|
3
|
+
}`,variables:{project:decodeURIComponent(this.project),ref:e,paths:r}}});for(let e of a.data?.project?.repository?.blobs?.nodes??[]){let n=t.get(e.path);n&&typeof e.rawTextBlob==`string`&&this.blobs.set(n,Promise.resolve(e.rawTextBlob))}}let a=new Map;for(let e of r){let n=await this.readFrom(t,e);n!==void 0&&a.set(e,n)}return a}async readBytes(e){return this.bytesFrom(await this.currentTree(),e)}async bytesFrom(e,t){let n=e.get(t);if(!n)return;let r=await b(this.api,this.repo(`/blobs/${n}/raw`));return new Uint8Array(await r.arrayBuffer())}async list(e){return G(await this.currentTree(),e)}filesAt(e){return{read:async t=>this.readFrom(await this.tree(e),t),readFiles:async t=>this.readFilesFrom(e,await this.tree(e),t),readBytes:async t=>this.bytesFrom(await this.tree(e),t),list:async t=>G(await this.tree(e),t)}}async fileSizes(e){let t=await this.list(e),n=this.pinned??await this.revision(),r=new Map;for(let e=0;e<t.length;e+=U){let i=await x(this.api,`/../graphql`,{method:`POST`,body:{query:`query ($project: ID!, $ref: String!, $paths: [String!]!) {
|
|
4
|
+
project(fullPath: $project) { repository { blobs(ref: $ref, paths: $paths) { nodes { path size } } } }
|
|
5
|
+
}`,variables:{project:decodeURIComponent(this.project),ref:n,paths:t.slice(e,e+U)}}});for(let e of i.data?.project?.repository?.blobs?.nodes??[]){let t=Number(e.size);Number.isFinite(t)&&r.set(e.path,t)}}return r}async lastCommitFor(e,t){return(await x(this.api,this.repo(`/files/${encodeURIComponent(e)}?ref=${t}`))).last_commit_id}async existsAt(t,n,r){return e.some(e=>n.startsWith(`${e}/`))?t.has(n):this.lastCommitFor(n,r).then(()=>!0,e=>{if(e instanceof y&&e.status===404)return!1;throw e})}async write(e,{message:r,expectedRevision:i}){if(this.contentOnly&&t(e),await this.revision()!==i)throw new n;let a=await this.tree(i),o=(await Promise.all(e.map(async e=>{let t=await this.existsAt(a,e.path,i);if(`delete`in e)return t?{action:`delete`,file_path:e.path,last_commit_id:await this.lastCommitFor(e.path,i)}:void 0;let n=`bytes`in e?{content:_(e.bytes),encoding:`base64`}:{content:e.content};return t?{action:`update`,file_path:e.path,...n,last_commit_id:await this.lastCommitFor(e.path,i)}:{action:`create`,file_path:e.path,...n}}))).filter(e=>e!==void 0);if(o.length===0)return{revision:i};try{let e=await x(this.api,this.repo(`/commits`),{method:`POST`,body:{branch:this.branch,commit_message:r,actions:o,...this.options.author&&{author_name:this.options.author.name,author_email:this.options.author.email}}});return this.pinned=e.id,{revision:e.id}}catch(e){throw e instanceof y?e.status===403?new g(`cant-publish`,`This GitLab account can't publish to the site.`):e.status===400&&/already exists|changed since/i.test(e.message)||await this.revision()!==i?new n:e:e}}async history(e,{page:t=1,perPage:n=20}={}){let r=new URLSearchParams({ref_name:this.pinned??await this.revision(),path:e,per_page:String(n),page:String(t)});return(await x(this.api,this.repo(`/commits?${r}`))).map(e=>({revision:e.id,date:e.authored_date??e.committed_date??``,author:e.author_name||void 0,message:e.title}))}async readAt(e,t){let n=await b(this.api,this.repo(`/files/${encodeURIComponent(e)}/raw?${new URLSearchParams({ref:t})}`),{allow:[404]});return n.ok?n.text():void 0}async changedPaths(e,t){let n=await x(this.api,this.repo(`/compare?${new URLSearchParams({from:e,to:t,straight:`true`})}`));return[...new Set((n.diffs??[]).flatMap(e=>[e.old_path,e.new_path]))]}async deployStatus(e){try{let t=await this.statuses(e),n=t.filter(W);if(t.length>0&&n.length===0)return{state:`unknown`};if(n.length===0){if((await x(this.api,`/projects/${this.project}/pipelines?per_page=1`)).length>0)return{state:`building`};let{parent_ids:t=[]}=await x(this.api,this.repo(`/commits/${e}`));return{state:(t[0]?(await this.statuses(t[0])).filter(W):[]).length>0?`building`:`unknown`}}let r=n.find(e=>e.status===`failed`)??n.find(e=>e.status===`canceled`);if(r?.status===`canceled`){let t=await this.head();if(t!==e)return this.deployStatus(t)}if(r){let t=await this.jobProblem(e).catch(()=>void 0);return{state:`failed`,detailsUrl:r.target_url??void 0,...t&&{problem:t}}}return n.every(e=>e.status===`success`||e.status===`skipped`)?{state:`live`,detailsUrl:n[0]?.target_url??void 0}:{state:`building`,detailsUrl:n[0]?.target_url??void 0}}catch(e){if(e instanceof y)return{state:`unknown`};throw e}}statuses(e){return x(this.api,this.repo(`/commits/${e}/statuses`))}async jobProblem(e){let[t]=await x(this.api,`/projects/${this.project}/pipelines?${new URLSearchParams({sha:e,per_page:`1`})}`);if(!t)return;let n=(await x(this.api,`/projects/${this.project}/pipelines/${t.id}/jobs?per_page=100`)).find(e=>e.status===`failed`);if(!n)return;let r=n.failure_reason??``,i=`${n.name}: ${r}`;if(r===`ci_quota_exceeded`)return{step:`not-started`,detail:i};if(/runner_system|stuck_or_timeout|scheduler|api_failure|data_integrity|job_execution_timeout/.test(r))return{step:`host`,detail:i};if(n.name===`pages:deploy`)return{step:`deploy`,detail:i};let a=await b(this.api,`/projects/${this.project}/jobs/${n.id}/trace`,{allow:[403,404]}),o=a.ok?await a.text():``,s=h(o),c=o.split(`
|
|
6
|
+
`).map(e=>e.replace(de,``).replace(/^.*\r/,``)).filter(e=>e.startsWith(`$ `)).at(-1);return{step:s?`build`:(c?ee(c):void 0)??`build`,detail:i,...s&&{cause:s}}}signOut(){this.onSignOut()}};function q(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function J(e=32){return q(crypto.getRandomValues(new Uint8Array(e)))}async function Y(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return q(new Uint8Array(t))}function X(e,t,n=Date.now()){return{type:`oauth`,access:e.access_token,refresh:e.refresh_token,expiresAt:n+(e.expires_in??7200)*1e3,verifier:t}}function Z(e){let t=new URL(e);return`${t.origin}${t.pathname.replace(/\/?$/,`/`)}`}var Q=`main`;function fe(){return{href:()=>window.location.href,assign:e=>window.location.assign(e),replace:e=>window.history.replaceState(window.history.state,``,e)}}function $(e={}){let t=(e.url??`https://gitlab.com`).replace(/\/$/,``),n=`${t}/api/v4`,r=e.fetch??((e,t)=>globalThis.fetch(e,t)),i=v(`goodfellow:gitlab-setup:pending`,e.storage),a=()=>e.location??fe();async function o(e){let n=await r(`${t}/oauth/token`,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams(e)});if(!n.ok)throw new g(`invalid`,`GitLab didn't accept the sign-in (${n.status}).`);return await n.json()}async function s(t){let i=t,s={apiUrl:n,token:async({refresh:t}={})=>{if(i.type===`token`)return i.token;if(t||i.expiresAt-6e4<Date.now()){let{verifier:t}=i;i=X(await o({client_id:e.clientId??``,refresh_token:i.refresh,grant_type:`refresh_token`,redirect_uri:Z(a().href()),code_verifier:t}),t)}return i.access},canRefresh:i.type===`oauth`,fetch:r},c=await x(s,`/user`);async function l(e,t){return(await b(s,`/projects/${encodeURIComponent(`${e.path}/${t}`)}`,{allow:[404]})).status===404}async function u(e){let t=e=>`/projects/${encodeURIComponent(e)}`;try{let n=new Map;for(let r of[`code`,`content`])n.set(r,(await x(s,t(e[r]))).id);for(let{reader:r,read:i}of e.links.reads)await b(s,`${t(e[i])}/job_token_scope/allowlist`,{method:`POST`,body:{target_project_id:n.get(r)}});e.links.updates&&await b(s,t(e[e.links.updates]),{method:`PUT`,body:{ci_push_repository_for_job_token_allowed:!0}});for(let n of e.links.nightly)await b(s,`${t(e[n])}/pipeline_schedules`,{method:`POST`,body:{description:n===e.links.updates?`Rebuild the site and install Goodfellow's fixes each night`:`Rebuild the site each night`,ref:Q,cron:L,cron_timezone:`UTC`,active:!0}});return!0}catch(e){if(e instanceof y&&[400,403,404].includes(e.status))return!1;throw e}}return{user:{login:c.username,name:c.name,avatarUrl:c.avatar_url},async owners(){let e=(await x(s,`/namespaces?per_page=100`)).map(e=>({path:e.full_path,name:e.kind===`user`?c.name??e.name:e.name,kind:e.kind===`user`?`personal`:`organization`,id:e.id}));return[...e.filter(e=>e.kind===`personal`),...e.filter(e=>e.kind!==`personal`)]},isAvailable:l,async createSite(e,t){if(t?.(`repository`),!await l(e.owner,e.name))throw new f(`name-taken`,`There's already a project called ${e.owner.path}/${e.name}.`);let n;try{n=await x(s,`/projects`,{method:`POST`,body:{name:e.name,path:e.name,namespace_id:e.owner.id,visibility:e.private?`private`:`public`,description:e.description,...e.pages&&{pages_access_level:e.private?`public`:`enabled`}}})}catch(t){throw t instanceof y&&t.status===400?new f(`name-invalid`,`GitLab can't use "${e.name}" as a project name.`):t instanceof y&&(t.status===403||t.status===404)?new f(`not-allowed`,`This sign-in can't create projects in ${e.owner.path}.`):t}let r=[];e.link&&(t?.(`connect`),await u(e.link)||r.push(`connect-unavailable`));let i;if(e.pages&&e.domain){t?.(`pages`);try{await b(s,`/projects/${n.id}/pages/domains`,{method:`POST`,body:{domain:e.domain,auto_ssl_enabled:!0}}),i=`https://${e.domain}/`}catch(e){if(!(e instanceof y)||![400,403,404,409,422].includes(e.status))throw e;r.push(`domain-unavailable`)}}return t?.(`files`),await b(s,`/projects/${n.id}/repository/commits`,{method:`POST`,body:{branch:Q,commit_message:e.message,actions:e.files.flatMap(e=>`delete`in e?[]:`content`in e?[{action:`create`,file_path:e.path,content:e.content}]:[{action:`create`,file_path:e.path,content:_(e.bytes),encoding:`base64`}])}}),{repo:n.path_with_namespace,webUrl:n.web_url,...i&&{siteUrl:i},buildsUrl:`${n.web_url}/-/pipelines`,pagesUrl:e.pages?`${n.web_url}/pages`:void 0,warnings:r}}}}return{name:`GitLab`,canRedirect:!!e.clientId,tokenLinks:[{url:`${t}/-/user_settings/personal_access_tokens?${new URLSearchParams({name:`Goodfellow site setup`,scopes:`api`})}`,label:`signIn.token.create`}],async restore(){let t=new URL(a().href()),n=t.searchParams.get(`code`),r=t.searchParams.get(`error`);if(!n&&!r)return null;let c=i.load();if(!c)return null;i.clear();let l=JSON.parse(c),u=t.searchParams.get(`state`);for(let e of[`code`,`state`,`error`,`error_description`])t.searchParams.delete(e);if(a().replace(t.toString()),r||!n||u!==l.state)throw new g(`redirect-failed`,`Signing in with GitLab was cancelled or didn't finish.`);return s(X(await o({client_id:e.clientId??``,code:n,grant_type:`authorization_code`,redirect_uri:Z(t.toString()),code_verifier:l.verifier}),l.verifier))},async signInWithToken(e){let t=e.trim();if(!t)throw new g(`invalid`,`Paste a token to sign in.`);return s({type:`token`,token:t})},async startRedirect(){if(!e.clientId)throw Error(`gitlabSetup({ clientId }) is needed to sign in with GitLab.`);let n={state:J(16),verifier:J(48)};i.save(JSON.stringify(n),!1);let r=new URLSearchParams({client_id:e.clientId,redirect_uri:Z(a().href()),response_type:`code`,state:n.state,scope:`api`,code_challenge:await Y(n.verifier),code_challenge_method:`S256`});a().assign(`${t}/oauth/authorize?${r}`)}}}var pe=30;function me(){return{href:()=>window.location.href,assign:e=>window.location.assign(e),replace:e=>window.history.replaceState(window.history.state,``,e)}}function he(e){let t=(e.url??`https://gitlab.com`).replace(/\/$/,``),n=`${t}/api/v4`,r=e.fetch??((e,t)=>globalThis.fetch(e,t)),i=v(`goodfellow:gitlab:${t}:${e.project}`,e.storage),a=v(`goodfellow:gitlab:pending:${e.project}`,e.storage),o=()=>e.location??me();async function s(e){let n=await r(`${t}/oauth/token`,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams(e)});if(!n.ok)throw new g(`invalid`,`GitLab didn't accept the sign-in (${n.status}).`);return await n.json()}async function c(a,c){let l=a,u={apiUrl:n,token:async({refresh:t}={})=>{if(l.type===`token`)return l.token;if(t||l.expiresAt-6e4<Date.now()){let{verifier:t}=l;l=X(await s({client_id:e.clientId??``,refresh_token:l.refresh,grant_type:`refresh_token`,redirect_uri:Z(o().href()),code_verifier:t}),t),i.save(JSON.stringify(l),c)}return l.access},canRefresh:l.type===`oauth`,fetch:r},d=await x(u,`/user`),f;try{f=await x(u,`/projects/${encodeURIComponent(e.project)}`)}catch(t){throw t instanceof y&&(t.status===404||t.status===403)?new g(`no-access`,`The GitLab account ${d.username} can't see ${e.project}.`):t}if(Math.max(f.permissions?.project_access?.access_level??0,f.permissions?.group_access?.access_level??0)<pe)throw new g(`cant-publish`,`The GitLab account ${d.username} can see ${e.project} but can't publish to it.`);return i.save(JSON.stringify(l),c),new K({api:u,project:e.project,branch:e.branch??f.default_branch,...e.contentOnly&&{contentOnly:!0},...e.contentOnly&&e.code&&{code:{project:e.code,webUrl:t}},user:{login:d.username,name:d.name,avatarUrl:d.avatar_url},onSignOut:()=>i.clear()})}async function l(){let t=new URL(o().href()),n=t.searchParams.get(`code`),r=t.searchParams.get(`state`),i=t.searchParams.get(`error`);if(!n&&!i)return null;let l=a.load();if(!l)return null;a.clear();let u=JSON.parse(l);for(let e of[`code`,`state`,`error`,`error_description`])t.searchParams.delete(e);if(t.hash=u.hash,o().replace(t.toString()),i||!n||r!==u.state)throw new g(`redirect-failed`,`Signing in with GitLab was cancelled or didn't finish.`);return c(X(await s({client_id:e.clientId??``,code:n,grant_type:`authorization_code`,redirect_uri:Z(t.toString()),code_verifier:u.verifier}),u.verifier),u.remember)}function u({token:t}){let i={apiUrl:n,token:async()=>typeof t==`string`?t:t(),canRefresh:!1,fetch:r},a,o=()=>(a??=e.branch?Promise.resolve(e.branch):x(i,`/projects/${encodeURIComponent(e.project)}`).then(e=>e.default_branch),a.catch(()=>{a=void 0}),a),s=async(t,n)=>new K({api:i,project:e.project,branch:await o(),...e.contentOnly&&{contentOnly:!0},user:{login:n?.name??e.project,...n&&{name:n.name}},onSignOut:()=>{},...t&&{revision:t},...n&&{author:n}});return{...e.contentOnly&&{contentOnly:!0},async revision(){return(await s()).revision()},at:s}}return{name:`GitLab`,source:te(`@goodfellow-cms/gitlab`,`gitlab`,e,[`fetch`,`storage`,`location`]),canRedirect:!!e.clientId,setup:()=>$({...e.url&&{url:e.url},...e.fetch&&{fetch:e.fetch},...e.storage&&{storage:e.storage},...e.location&&{location:e.location}}),redirectAddressesListed:!!e.clientId,tokenLinks:[{url:`${t}/-/user_settings/personal_access_tokens?${new URLSearchParams({name:`Goodfellow admin`,scopes:`api`})}`,label:`signIn.token.create`}],async restore(){let e=await l();if(e)return e;let t=i.load();if(!t)return null;try{return await c(JSON.parse(t),i.remembered())}catch(e){throw e instanceof g&&i.clear(),e}},async signInWithToken(e,t){let n=e.trim();if(!n)throw new g(`invalid`,`Paste a token to sign in.`);return c({type:`token`,token:n},t)},async startRedirect(n){if(!e.clientId)throw Error(`gitlab({ clientId }) is needed to sign in with GitLab.`);let r=J(48),i=J(16),s=new URL(o().href()),c={state:i,verifier:r,remember:n,hash:s.hash};a.save(JSON.stringify(c),!1);let l=new URLSearchParams({client_id:e.clientId,redirect_uri:Z(s.toString()),response_type:`code`,state:i,scope:`api`,code_challenge:await Y(r),code_challenge_method:`S256`});o().assign(`${t}/oauth/authorize?${l}`)},server:u}}export{K as GitLabBackend,he as gitlab,M as gitlabPagesRecords,$ as gitlabSetup,Z as redirectUri};
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./dist-DuGHJcqN.js","./store-CNLNNQkL.js","./setup-host-B_uhd1y7.js","./git-eGyMXUIu.js","./scheduled-builds-BPfDaBYt.js","./dist-CLietd1m.js","./content-repository-setup-3Z0i5cMx.js","./preload-helper-khBccGFq.js","./dist-Dz15_FP0.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{i as e,s as t}from"./store-CNLNNQkL.js";import{t as n}from"./preload-helper-khBccGFq.js";function r(e){if(e)try{let t=new URL(e.url),n=t.hostname===`localhost`||t.hostname===`127.0.0.1`;return(t.protocol===`https:`||t.protocol===`http:`&&n)&&t.pathname===`/`&&!t.search&&!t.hash?t.origin:void 0}catch{return}}var i=/^[ \t]*admin:[ \t]*\{[^\n]*\},?[ \t]*\n/m;function a(e){let t=i.exec(e)?.[0],n=t&&/url:\s*"([^"\\]+)"/.exec(t)?.[1];if(t&&n)return{url:n,.../checked:\s*true/.test(t)&&{checked:!0}}}function o(e,t,{start:n=!0,end:r=!0}={}){let i=0,a=e.length;for(;n&&i<a&&t.includes(e.charAt(i));)i++;for(;r&&a>i&&t.includes(e.charAt(a-1));)a--;return e.slice(i,a)}function s(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function c(e,t=`|`){return e.map(e=>ue(e)).join(t)}function l(e,t){return typeof t==`bigint`?t.toString():t}var u=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function d(e){return new u(e)}function f(e){return e==null}function p(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function m(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function h(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function g(e){return h(e._zod.def)??e._zod.def.shape}function ee(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return m(this,t,e),e},enumerable:!0,configurable:!0})}function te(e,t,n){t in e?m(e,t,n):e[t]=n}function _(e,t,n,r){let i=g(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?ee(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):te(e,a,r?r(n.value,a):n.value))}}function ne(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?ee(e,n,()=>t[n]):te(e,n,r.value))}}function v(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function re(e){return JSON.stringify(e)}function ie(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var ae=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function oe(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var se=d(()=>{if(j.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function y(e){if(oe(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return oe(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function ce(e){return y(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var le=new Set([`string`,`number`,`symbol`]);function b(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function x(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function S(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function ue(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function de(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}var fe={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},pe={int64:[BigInt(`-9223372036854775808`),BigInt(`9223372036854775807`)],uint64:[BigInt(0),BigInt(`18446744073709551615`)]};function me(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return _(i,e,he(e,t)),x(e,v(n,{shape:i,checks:[]}))}function he(e,t){let n=g(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function ge(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(he(e,t)),a={};return _(a,e,Reflect.ownKeys(g(e)).filter(e=>!i.has(e))),x(e,v(n,{shape:a,checks:[]}))}function _e(e,t){if(!y(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=g(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return x(e,v(e._zod.def,{shape:ve(e,t)}))}function ve(e,t){let n={};return _(n,e,Reflect.ownKeys(g(e))),ne(n,t),n}function ye(e,t){if(!y(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return x(e,v(e._zod.def,{shape:ve(e,t)}))}function be(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return _(n,e,Reflect.ownKeys(g(e))),_(n,t,Reflect.ownKeys(g(t))),x(e,v(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function xe(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(he(t,n)):void 0,o={};return _(o,t,Reflect.ownKeys(g(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),x(t,v(t._zod.def,{shape:o,checks:[]}))}function Se(e,t,n){let r=n?new Set(he(t,n)):void 0,i={};return _(i,t,Reflect.ownKeys(g(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),x(t,v(t._zod.def,{shape:i}))}function C(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function Ce(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function w(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function we(e){return typeof e==`string`?e:e?.message}function Te(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function Ee(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function T(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:we(e.inst?._zod.def?.error?.(e))??we(a?.(e))??we(t?.error?.(e))??we(n.customError?.(e))??we(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}var De=/[\uD800-\uDBFF]/;function Oe(e){let t=e.length;if(!De.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function ke(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function Ae(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function je(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function Me(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):Fe(e,n,r.value)}}function E(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function Ne(e,t,n){return E(e,t,n,!1)}function Pe(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return E(this,n,r(this))},set(e){E(this,n,e)}})}return t}function Fe(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:E(this,t,n.bind(this))},set(e){E(this,t,e)}})}function Ie(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var Le,D=!1,Re={configurable:!0,get(){D=!0}};function O(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&Le!==e._zod){Le=void 0;return}Le=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Re);let e=D;D=!1;try{let r=n(this);return D?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),D||=e,r}catch(n){throw delete this[t],D||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})}function ze(e,t,n,r){let i=Ie(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}var Be=`~constantCatch`;function Ve(e){let t=()=>e;return t[Be]=!0,t}var He,Ue={value:void 0,enumerable:!1},We=`captureStackTrace`in Error?Error:null;function Ge(e){let t=We;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return We=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function k(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){Ue.value=new a(r);try{Object.defineProperty(n,"_zod",Ue)}finally{Ue.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),Me(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?Ge(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var A=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Ke=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(He=globalThis).__zod_globalConfig??(He.__zod_globalConfig={});var j=globalThis.__zod_globalConfig;function M(e){return e&&Object.assign(j,e),j}function qe(){let e=this._zod;return e.message??=JSON.stringify(e.def,l,2),e.message}function Je(e){this._zod.message=e}var Ye={get:qe,set:Je,enumerable:!0,configurable:!0},Xe={value:void 0,enumerable:!1},Ze=new WeakSet([Object.prototype,Error.prototype]),Qe=(e,t)=>{e.name=`$ZodError`,Xe.value=t,Object.defineProperty(e,"issues",Xe),Xe.value=void 0,Object.defineProperty(e,"message",Ye);let n=Object.getPrototypeOf(e);Ze.has(n)||(Ze.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},$e=k(`$ZodError`,Qe);k(`$ZodError`,Qe,void 0,{Parent:Error});function et(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function tt(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?et(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function nt(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function rt(e,t){return{callee:t?.callee??e,Err:t?.Err}}var it=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new A;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>T(e,o,M())));throw ae(n,a?.callee??t),n}return s.value};return t},at=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>T(e,o,M())));throw ae(n,a?.callee??t),n}return s.value};return t},ot=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new A;return a.issues.length?st(e,a.issues,i):{success:!0,data:a.value}};function st(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>T(e,n,M()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}var ct=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?st(e,a.issues,i):{success:!0,data:a.value}},lt=Symbol.for(`zod.compile.invalid`),ut=Symbol.for(`zod.compile.fallback`),dt=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==lt)return!0;if(r.definite===!0&&n===void 0)return!1}return ft(e,t,n)});function ft(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[ut]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new A;return a.issues.length===0}var pt=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},mt=e=>{let t=it(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,rt(n,a))};return n},ht=e=>{let t=it(e),n=(e,r,i,a)=>t(e,r,i,rt(n,a));return n},gt=e=>{let t=at(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,rt(n,a))};return n},_t=e=>{let t=at(e),n=async(e,r,i,a)=>await t(e,r,i,rt(n,a));return n},vt=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ot(e)(t,n,i)},yt=e=>(t,n,r)=>ot(e)(t,n,r),bt=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ct(e)(t,n,i)},xt=e=>async(t,n,r)=>ct(e)(t,n,r),St=/^[cC][0-9a-z]{6,}$/,Ct=/^[0-9a-z]+$/,wt=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,Tt=/^[0-9a-vA-V]{20}$/,Et=/^[A-Za-z0-9]{27}$/,Dt=/^[a-zA-Z0-9_-]{21}$/;function Ot(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var kt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,At=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,jt=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Mt=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,Nt=`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;function Pt(){return new RegExp(Nt,`u`)}var Ft=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,It=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Lt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,Rt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,zt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Bt=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Vt=/^https?$/,Ht=/^\+[1-9]\d{6,14}$/,Ut=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function Wt(e){return RegExp(`^${e}$`)}var Gt=Wt(Ut);function Kt(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function qt(e){return RegExp(`^${Kt(e)}$`)}function Jt(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${Kt({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${Kt({precision:e.precision})}`:n;return RegExp(`^${Ut}T(?:${r})$`)}var Yt=/^[\s\S]{0,}$/,Xt=/^-?\d+$/,Zt=/^-?\d+(?:\.\d+)?$/,Qt=/^(?:true|false)$/i,$t=/^[^A-Z]*$/,en=/^[^a-z]*$/,N=k(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),tn=e=>{let t=e.value;return!f(t)&&t.length!==void 0},nn=k(`$ZodCheckMaxLength`,(e,t)=>{var n;N.init(e,t),(n=e._zod.def).when??(n.when=tn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?Oe(r):i)<=t.maximum)return;let a=ke(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),rn=k(`$ZodCheckMinLength`,(e,t)=>{var n;N.init(e,t),(n=e._zod.def).when??(n.when=tn),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?Oe(r):i)>=t.minimum)return;let a=ke(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),an=k(`$ZodCheckLengthEquals`,(e,t)=>{var n;N.init(e,t),(n=e._zod.def).when??(n.when=tn),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?Oe(r):i;if(a===t.length)return;let o=ke(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),on=k(`$ZodCheckStringFormat`,(e,t)=>{var n,r;N.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),sn=k(`$ZodCheckRegex`,(e,t)=>{on.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),cn=k(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=$t,on.init(e,t)}),ln=k(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=en,on.init(e,t)}),un=k(`$ZodCheckIncludes`,(e,t)=>{N.init(e,t);let n=b(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),dn=k(`$ZodCheckStartsWith`,(e,t)=>{N.init(e,t);let n=RegExp(`^${b(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),fn=k(`$ZodCheckEndsWith`,(e,t)=>{N.init(e,t);let n=RegExp(`.*${b(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),pn=k(`$ZodCheckOverwrite`,(e,t)=>{N.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),mn=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
|
|
3
|
+
`).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
|
|
4
|
+
`)}\n};`)(...Object.values(this.closed))}},hn={major:4,minor:6,patch:6},P=k(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=hn;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=C(t),a;for(let o of n){if(o._zod.def.when){if(Ce(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new A;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(Ee(t.issues,n,e),i||=C(t,n))});else{if(t.issues.length===n)continue;Ee(t.issues,n,e),i||=C(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(C(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new A;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new A;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return Ne(this,`~standard`,vn(this))},set"~standard"(e){E(this,`~standard`,e)}}),gn=(e,t)=>e.issues.length?{issues:e.issues.map(e=>T(e,t,M()))}:{value:e.value};async function _n(e,t){let n={async:!0};return gn(await e._zod.run({value:t,issues:[]},n),n)}function vn(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return gn(r,n)}catch{}return _n(e,t)},vendor:`zod`,version:1}}var yn=k(`$ZodString`,(e,t)=>{P.init(e,t),e._zod.pattern=t.pattern??Yt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),F=k(`$ZodStringFormat`,(e,t)=>{on.init(e,t),yn.init(e,t)}),bn=k(`$ZodGUID`,(e,t)=>{t.pattern??=At,F.init(e,t)}),xn=k(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=jt(e)}else t.pattern??=jt();F.init(e,t)}),Sn=k(`$ZodEmail`,(e,t)=>{t.pattern??=Mt,F.init(e,t)});function Cn(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function wn(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?Cn(e)||2:Tn(e,t)}function Tn(e,t){if(!t.normalize&&t.protocol?.source===Vt.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}var En=/[\t\n\r]/g;function Dn(e){return e.replace(En,``)}function On(e,t){return t.lastIndex=0,t.test(e.hostname)}function kn(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}var An=k(`$ZodURL`,(e,t)=>{F.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=wn(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=Dn(r);return}t.hostname&&!On(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!kn(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:Dn(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),jn=k(`$ZodEmoji`,(e,t)=>{t.pattern??=Pt(),F.init(e,t)}),Mn=k(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?Dt:Ot(t.length),F.init(e,t)}),Nn=k(`$ZodCUID`,(e,t)=>{t.pattern??=St,F.init(e,t)}),Pn=k(`$ZodCUID2`,(e,t)=>{t.pattern??=Ct,F.init(e,t)}),Fn=k(`$ZodULID`,(e,t)=>{t.pattern??=wt,F.init(e,t)}),In=k(`$ZodXID`,(e,t)=>{t.pattern??=Tt,F.init(e,t)}),Ln=k(`$ZodKSUID`,(e,t)=>{t.pattern??=Et,F.init(e,t)}),Rn=k(`$ZodISODateTime`,(e,t)=>{t.pattern??=Jt(t),F.init(e,t)}),zn=k(`$ZodISODate`,(e,t)=>{t.pattern??=Gt,F.init(e,t)}),Bn=k(`$ZodISOTime`,(e,t)=>{t.pattern??=qt(t),F.init(e,t)}),Vn=k(`$ZodISODuration`,(e,t)=>{t.pattern??=kt,F.init(e,t)}),Hn=k(`$ZodIPv4`,(e,t)=>{t.pattern??=Ft,F.init(e,t)}),Un=/^[0-9a-fA-F:.]+$/;function Wn(e){return Un.test(e)?Cn(`http://[${e}]`):!1}var Gn=k(`$ZodIPv6`,(e,t)=>{t.pattern??=It,F.init(e,t),e._zod.check=n=>{Wn(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Kn=k(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Lt,F.init(e,t)});function qn(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:Wn(n)}var Jn=k(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Rt,F.init(e,t),e._zod.check=n=>{qn(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Yn(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Xn=/^[0-9a-zA-Z+/]*={0,2}$/,Zn=k(`$ZodBase64`,(e,t)=>{t.pattern??=Xn,F.init(e,t),e._zod.check=n=>{Yn(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Qn=/^[A-Za-z0-9_-]*$/;function $n(e){if(!Qn.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Yn(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var er=k(`$ZodBase64URL`,(e,t)=>{t.pattern??=Qn,F.init(e,t),e._zod.check=n=>{$n(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),tr=k(`$ZodE164`,(e,t)=>{t.pattern??=Ht,F.init(e,t)});function nr(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var rr=k(`$ZodJWT`,(e,t)=>{F.init(e,t),e._zod.check=n=>{nr(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),ir=k(`$ZodBoolean`,(e,t)=>{P.init(e,t),e._zod.pattern=Qt,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),ar=k(`$ZodUnknown`,(e,t)=>{P.init(e,t),e._zod.parse=e=>e}),or=k(`$ZodNever`,(e,t)=>{P.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function sr(e,t){let n=Te(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of Te(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,Ee(n.issues,t,e),n}}return i(n,a)}}var cr=e=>Array.isArray(e)?e.length:-1;function lr(e,t,n){e.issues.length&&t.issues.push(...w(n,e.issues)),t.value[n]=e.value}var ur=k(`$ZodArray`,(e,t)=>{P.init(e,t);let n=j.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>lr(t,r,e)));else if(lr(c,r,e),s&&c.issues.length!==0&&C(c))break}return o.length?Promise.all(o).then(()=>r):r},sr(e,cr)});function dr(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...w(n,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}var fr=[];function pr(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:fr,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=de(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function mr(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(C(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>dr(e,n,i,t,d,f))):dr(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var hr=k(`$ZodObject`,(e,t)=>{P.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=d(()=>pr(t));O(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||m(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=oe,o=t.catchall,s,c=j.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(C(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>dr(n,t,e,r,a,o))):dr(s,t,e,r,a,o)}return o?mr(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),gr=k(`$ZodObjectJIT`,(e,t)=>{hr.init(e,t);let n=e._zod.parse,r=d(()=>pr(t)),i=j.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new mn([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
|
|
5
|
+
let ${e}_ab = false;
|
|
6
|
+
for (let i = 0; i < ${e}.issues.length; i++) {
|
|
7
|
+
const iss = ${e}.issues[i];
|
|
8
|
+
iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
|
|
9
|
+
payload.issues.push(iss);
|
|
10
|
+
if (iss.continue !== true) ${e}_ab = true;
|
|
11
|
+
}
|
|
12
|
+
if (${e}_ab && ctx && ctx.abortEarly) {
|
|
13
|
+
payload.value = newResult;
|
|
14
|
+
return payload;
|
|
15
|
+
}`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:re(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
|
|
16
|
+
const ${n}_present = ${i};
|
|
17
|
+
if (!${n}.issues.length || ${n}_present) {
|
|
18
|
+
if (${n}.issues.length) {${c(n,r)}
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (${e}) {
|
|
22
|
+
newResult[${r}] = ${n}.value;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
`)}else f?(o.write(`
|
|
27
|
+
if (${n}.issues.length) {${c(n,r)}
|
|
28
|
+
}
|
|
29
|
+
`),d===`defaulted`?o.write(`newResult[${r}] = ${n}.value;`):o.write(`
|
|
30
|
+
if (${n}.value !== undefined || ${i}) {
|
|
31
|
+
newResult[${r}] = ${n}.value;
|
|
32
|
+
}
|
|
33
|
+
`)):o.write(`
|
|
34
|
+
const ${n}_present = ${i};
|
|
35
|
+
if (${n}.issues.length) {${c(n,r)}
|
|
36
|
+
}
|
|
37
|
+
if (!${n}_present && !${n}.issues.length) {
|
|
38
|
+
payload.issues.push({
|
|
39
|
+
code: "invalid_type",
|
|
40
|
+
expected: "nonoptional",
|
|
41
|
+
input: undefined,
|
|
42
|
+
path: [${r}]
|
|
43
|
+
});
|
|
44
|
+
if (ctx && ctx.abortEarly) {
|
|
45
|
+
payload.value = newResult;
|
|
46
|
+
return payload;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (${n}_present) {
|
|
51
|
+
newResult[${r}] = ${n}.value;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
`)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=oe,c=!j.jitless,l=c&&se.value,u=t.catchall,f;e._zod.parse=(i,d)=>{f??=r.value;let p=i.value;return s(p)?c&&l&&d?.async===!1&&d.jitless!==!0?(o||=a(t.shape),i=o(i,d),u?mr([],p,i,d,f,e,d?.abortEarly===!0):i):n(i,d):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function _r(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!C(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>T(e,r,M())))}),t)}var vr=k(`$ZodUnion`,(e,t)=>{P.init(e,t),O(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),O(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),O(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),O(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>p(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>_r(t,r,e,i)):_r(o,r,e,i)}}),yr=k(`$ZodIntersection`,(e,t)=>{P.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>xr(e,t,n)):xr(e,i,a)}});function br(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(y(e)&&y(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=br(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=br(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function xr(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=br(t.value,n.value);if(!c.valid){if(C(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var Sr=k(`$ZodRecord`,(e,t)=>{P.init(e,t);let n=j.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!y(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>T(e,i,M())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...w(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...w(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&Zt.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>T(e,i,M())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...w(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...w(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Cr=k(`$ZodEnum`,(e,t)=>{P.init(e,t);let n=s(t.entries),r=new Set(n);e._zod.values=r,O(e,`pattern`,e=>{let t=s(e.def.entries).filter(e=>le.has(typeof e));return RegExp(t.length?`^(${t.map(e=>b(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),wr=k(`$ZodLiteral`,(e,t)=>{P.init(e,t);let n=new Set(t.values);e._zod.values=n,O(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?b(e):e?b(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Tr=k(`$ZodTransform`,(e,t)=>{P.init(e,t),e._zod.optin=`optional`,j.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ke(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new A;return n.value=i,n}});function Er(e,t){return e.value=t.issues.length?void 0:t.value,e}var Dr=k(`$ZodOptional`,(e,t)=>{P.init(e,t),O(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,O(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),O(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${p(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>Er(e,t)):Er(e,r)}return t.innerType._zod.run(e,n)}}),Or=k(`$ZodExactOptional`,(e,t)=>{Dr.init(e,t),O(e,`values`,e=>e.def.innerType._zod.values),O(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),kr=k(`$ZodNullable`,(e,t)=>{P.init(e,t),O(e,`optin`,e=>e.def.innerType._zod.optin),O(e,`optout`,e=>e.def.innerType._zod.optout),O(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${p(t.source)}|null)$`):void 0}),O(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Ar=k(`$ZodDefault`,(e,t)=>{P.init(e,t),e._zod.optin=`defaulted`,O(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>jr(e,t)):jr(r,t)}});function jr(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var Mr=k(`$ZodPrefault`,(e,t)=>{P.init(e,t),e._zod.optin=`defaulted`,O(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Nr=k(`$ZodNonOptional`,(e,t)=>{P.init(e,t),O(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Pr(t,e)):Pr(i,e)}});function Pr(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function Fr(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>T(e,r,M()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var Ir=k(`$ZodCatch`,(e,t)=>{P.init(e,t),O(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),O(e,`optout`,e=>e.def.innerType._zod.optout),O(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>Fr(e,r,t,n)):Fr(e,r,t,n)}}),Lr=k(`$ZodPipe`,(e,t)=>{P.init(e,t),O(e,`values`,e=>e.def.in._zod.values),O(e,`optin`,e=>e.def.in._zod.optin),O(e,`optout`,e=>e.def.out._zod.optout),O(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Rr(e,t.in,n)):Rr(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Rr(e,t.out,n)):Rr(r,t.out,n)}});function Rr(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var zr=k(`$ZodReadonly`,(e,t)=>{P.init(e,t),O(e,`propValues`,e=>e.def.innerType._zod.propValues),O(e,`values`,e=>e.def.innerType._zod.values),O(e,`optin`,e=>e.def.innerType?._zod?.optin),O(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Br):Br(r)}});function Br(e){return e.memo||(e.value=Object.freeze(e.value)),e}var Vr=k(`$ZodCustom`,(e,t)=>{N.init(e,t),P.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Hr(t,n,r,e));Hr(i,n,r,e)}});function Hr(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(je(e))}}var Ur=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},Wr=`~memo`,Gr=[];function Kr(e){return typeof e==`object`&&!!e}function qr(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var Jr=new WeakMap,Yr=0,Xr=1,Zr=2;function Qr(e,t,n){let r=Jr.get(e);if(r!==void 0)return r?Zr:Yr;if(t.has(e))return Zr;t.add(e);let i=Yr,a=e=>{if(i!==Zr&&e?._zod){let r=Qr(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=Yr;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?Xr:o.value?._zod?Qr(o.value,t,n):Yr;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=h(c);s(e?o(e,!0):Xr),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?Qr(r,t,!1):Xr);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),$r(e,i)}function $r(e,t){return t!==Xr&&Jr.set(e,t===Zr),t}function ei(e,t){let n=e.buckets.get(t);return n||(n=new WeakMap,e.buckets.set(t,n)),n}var ti,ni=[],ri={alloc(e,t,n){let r=ti;if(!r)return n;ti=void 0;let i={value:n,issues:null};return r.set(t.value,i),ni.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&ai(n,e.value))throw new Ur;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=Qr(e,new Set,!1);if(i===Yr)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===Zr||r?n=!0:r=!0}let l=s.value;if(!Kr(l))return t(s,c);let u=c[Wr];u||(u={buckets:new WeakMap,backEdges:void 0},c[Wr]=u);let d;i===c?d=a:(d=ei(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...qr(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=new WeakSet),u.backEdges.add(f.value)),s;ti=d;let p=ni.length,m=t(s,c);ti=void 0;let h=ni.length>p?ni.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?qr(e.issues):Gr),e)):(h&&(h.issues=m.issues.length?qr(m.issues):Gr),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function ii(){return ri}function ai(e,t){let n=e[Wr]?.backEdges;return n!==void 0&&Kr(t)&&n.has(t)}var oi=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(Ae(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${ue(e.values[0])}`:`Invalid option: expected one of ${c(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${c(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function si(){return{localeError:oi()}}var ci,li=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function ui(){return new li}(ci=globalThis).__zod_globalRegistry??(ci.__zod_globalRegistry=ui());var di=globalThis.__zod_globalRegistry;function fi(e){return e.checks&&=[...e.checks],e}function pi(e,t){return new e(fi({type:`string`,...S(t)}))}function mi(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...S(t)})}function hi(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...S(t)})}function gi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...S(t)})}function _i(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...S(t)})}function vi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...S(t)})}function yi(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...S(t)})}function bi(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...S(t)})}function xi(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...S(t)})}function Si(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...S(t)})}function Ci(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...S(t)})}function wi(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...S(t)})}function Ti(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...S(t)})}function Ei(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...S(t)})}function Di(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...S(t)})}function Oi(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...S(t)})}function ki(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...S(t)})}function Ai(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...S(t)})}function ji(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...S(t)})}function Mi(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...S(t)})}function Ni(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...S(t)})}function Pi(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...S(t)})}function Fi(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...S(t)})}function Ii(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...S(t)})}function Li(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...S(t)})}function Ri(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...S(t)})}function zi(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...S(t)})}function Bi(e,t){return new e({type:`boolean`,...S(t)})}function Vi(e){return new e({type:`unknown`})}function Hi(e,t){return new e({type:`never`,...S(t)})}function Ui(e,t){return new nn({check:`max_length`,...S(t),maximum:e})}function Wi(e,t){return new rn({check:`min_length`,...S(t),minimum:e})}function Gi(e,t){return new an({check:`length_equals`,...S(t),length:e})}function Ki(e,t){return new sn({check:`string_format`,format:`regex`,...S(t),pattern:e})}function qi(e){return new cn({check:`string_format`,format:`lowercase`,...S(e)})}function Ji(e){return new ln({check:`string_format`,format:`uppercase`,...S(e)})}function Yi(e,t){return new un({check:`string_format`,format:`includes`,...S(t),includes:e})}function Xi(e,t){return new dn({check:`string_format`,format:`starts_with`,...S(t),prefix:e})}function Zi(e,t){return new fn({check:`string_format`,format:`ends_with`,...S(t),suffix:e})}function I(e){return new pn({check:`overwrite`,tx:e})}function Qi(e){return I(t=>t.normalize(e))}function $i(){return I(e=>e.trim())}function ea(){return I(e=>e.toLowerCase())}function ta(){return I(e=>e.toUpperCase())}function na(){return I(e=>ie(e))}function ra(e,t,n){return new e({type:`array`,element:t,...S(n)})}function ia(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...S(n)})}function aa(e,t){let n=oa(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(je(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(je(r))}},e(t.value,t)),t);return n}function oa(e,t){let n=new N({check:`custom`,...S(t)});return n._zod.check=e,n}function sa(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&m(e,t,n[t]);return e}function ca(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??di,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function L(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function R(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,R(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&sa(o.schema,c),t.io===`input`&&z(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function la(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function ua(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${la(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+la(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
|
|
55
|
+
|
|
56
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}r.count>1&&e.reused===`ref`&&a(n)}e.external&&(e.sharedDefsExtractedFor=e.external)}function da(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;da(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var fa=new Set([`type`,`properties`,`required`,`additionalProperties`]),pa=[`oneOf`,`anyOf`];function ma(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function ha(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!fa.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??ma(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}m(n,r,e.length===1?e[0]:ha(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=ma(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function ga(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of fa)if(t in e)return;let n=t.filter(e=>pa.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=ha(t);else{let e=n[0],i=pa.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>ha([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,sa(e,r))}function _a(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):sa(i,s),sa(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())da(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])ga(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}sa(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,m(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:ya(t,`input`,e.processors),output:ya(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function z(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return z(r.element,n);if(r.type===`set`)return z(r.valueType,n);if(r.type===`lazy`)return z(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return z(r.innerType,n);if(r.type===`intersection`)return z(r.left,n)||z(r.right,n);if(r.type===`record`||r.type===`map`)return z(r.keyType,n)||z(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:z(r.in,n)||z(r.out,n);if(r.type===`object`){for(let e in r.shape)if(z(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(z(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(z(e,n))return!0;return!!(r.rest&&z(r.rest,n))}return!1}var va=(e,t={})=>n=>{let r=ca({...n,processors:t});return R(e,r),ua(r,e),_a(r,e)},ya=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=ca({...i??{},target:a,io:t,processors:n});return R(e,o),ua(o,e),_a(o,e)},B=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},V=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},ba=(e,t)=>{B(e,`minimum`,t),V(e,`maximum`,t)},xa=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Sa=(e,t)=>{e.patterns??=new Set,e.patterns.add(t)},Ca=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},wa=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Ta=(e,t)=>B(e,`minimum`,t.minimum),Ea=(e,t)=>V(e,`maximum`,t.maximum),Da=e=>(t,n)=>{wa(t,n.format);let[r,i]=e[n.format];B(t,`minimum`,r),V(t,`maximum`,i)},Oa={greater_than:(e,t)=>B(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>V(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>xa(e,t.value),number_format:Da(fe),bigint_format:Da(pe),min_length:Ta,max_length:Ea,length_equals:(e,t)=>ba(e,t.length),min_size:Ta,max_size:Ea,size_equals:(e,t)=>ba(e,t.size),string_format:(e,t)=>{wa(e,t.format),t.pattern&&Sa(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Ca(e,t.mime)};function H(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Oa[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&B(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&B(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&V(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&V(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&xa(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Ca(t,i.mime);for(let e of i.patterns??[])Sa(t,e);return t}var ka={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Aa=new Map([[Xn,zt],[Qn,Bt]]),ja=e=>Aa.get(e)??e,Ma=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=H(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=ka[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(ja);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Na=(e,t,n,r)=>{n.type=`boolean`},Pa=(e,t,n,r)=>{n.not={}},Fa=(e,t,n,r)=>{let i=e._zod.def,a=s(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},Ia=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(L(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(L(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},La=(e,t,n,r)=>{L(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Ra=(e,t,n,r)=>{L(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},za=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=H(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=R(a.element,t,{...r,path:[...r.path,`items`]})};function Ba(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Ba(t.out):t.type===`catch`?Ba(t.innerType):e._zod.optin}var Va=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&L(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)m(i.properties,e,R(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Ba(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=R(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Ha=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>R(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ua=(e,t,n,r)=>{let i=e._zod.def,a=R(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=R(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)};function Wa(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Wa(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Wa(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?Zt:Xt).source),p):p}var Ga=new WeakMap;function Ka(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of Ga.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Wa(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var qa=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=H(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=R(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)m(i.patternProperties,ja(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=R(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=Ga.get(t);n||(n=[],Ga.set(t,n),t.deferred.push(()=>Ka(t))),n.push(e)}i.additionalProperties=R(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Ba(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},Ja=(e,t,n,r)=>{let i=e._zod.def,a=R(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Ya=(e,t,n,r)=>{let i=e._zod.def;R(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Xa=Symbol();function Za(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(L(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Xa):JSON.parse(o)}var Qa=(e,t,n,r)=>{let i=e._zod.def;R(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=Za(i.defaultValue,e,t,n,r);o!==Xa&&(n.default=o)},$a=(e,t,n,r)=>{let i=e._zod.def;R(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=Za(i.defaultValue,e,t,n,r);o!==Xa&&(n._prefault=o)},eo=(e,t,n,r)=>{let i=e._zod.def;R(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{L(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},to=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;R(o,t,r);let s=t.seen.get(e);s.ref=o},no=(e,t,n,r)=>{let i=e._zod.def;R(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},ro=(e,t,n,r)=>{let i=e._zod.def;R(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},io=new WeakSet([Object.prototype,Error.prototype]);function ao(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var U=k(`ZodError`,(e,t)=>{$e.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);io.has(n)||(io.add(n),ao(n,`format`,e=>t=>nt(e,t)),ao(n,`flatten`,e=>t=>tt(e,t)),ao(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,l,2)}),ao(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,l,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),oo=it(U),so=at(U),co=ot(U),lo=ct(U),uo=mt(U),fo=ht(U),po=gt(U),mo=_t(U),ho=vt(U),go=yt(U),_o=bt(U),vo=xt(U);function yo(){j.localeError||M(si())}function bo(){j.memoizer||M({memoizer:ii()})}var W=k(`ZodType`,(e,t)=>(yo(),P.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(v(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return x(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(js(e,t))},superRefine(e,t){return this.check(Ms(e,t))},overwrite(e){return this.check(I(e))},optional(){return ps(this)},exactOptional(){return hs(this)},nullable(){return _s(this)},nullish(){return ps(_s(this))},nonoptional(e){return Cs(this,e)},array(){return q(this)},or(e){return ts([this,e])},and(e){return rs(this,e)},transform(e){return Ds(this,ds(e))},default(e){return ys(this,e)},prefault(e){return xs(this,e)},catch(e){return Ts(this,e)},pipe(e){return Ds(this,e)},readonly(){return ks(this)},describe(e){let t=this.clone();return di.add(t,{description:e}),t},meta(...e){if(e.length===0)return di.get(this);let t=this.clone();return di.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return Ne(this,`~standard`,{...vn(this),jsonSchema:{input:ya(this,`input`),output:ya(this,`output`)}})},set"~standard"(e){E(this,`~standard`,e)},parse:function e(t,n){return oo(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await so(this,t,n,{callee:e})},safeParse(e,t){return co(this,e,t)},async safeParseAsync(e,t){return lo(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){E(this,`spa`,e)},validate(e,t){return dt(this,e,t)},validateAsync(e,t){return pt(this,e,t)},encode:function e(t,n){return uo(this,t,n,{callee:e})},decode:function e(t,n){return fo(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await po(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await mo(this,t,n,{callee:e})},safeEncode(e,t){return ho(this,e,t)},safeDecode(e,t){return go(this,e,t)},async safeEncodeAsync(e,t){return _o(this,e,t)},async safeDecodeAsync(e,t){return vo(this,e,t)},toJSONSchema(e){return va(this,{})(e)},get description(){return di.get(this)?.description},get _def(){return this._zod.def}}),xo=k(`_ZodString`,(e,t)=>{yn.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ma(e,t,n,r)},Pe({format:e=>H(e).format??null,minLength:e=>H(e).minimum??null,maxLength:e=>H(e).maximum??null},{regex(...e){return this.check(Ki(...e))},includes(...e){return this.check(Yi(...e))},startsWith(...e){return this.check(Xi(...e))},endsWith(...e){return this.check(Zi(...e))},min(...e){return this.check(Wi(...e))},max(...e){return this.check(Ui(...e))},length(...e){return this.check(Gi(...e))},nonempty(...e){return this.check(Wi(1,...e))},lowercase(e){return this.check(qi(e))},uppercase(e){return this.check(Ji(e))},trim(){return this.check($i())},normalize(...e){return this.check(Qi(...e))},toLowerCase(){return this.check(ea())},toUpperCase(){return this.check(ta())},slugify(){return this.check(na())}})),So=k(`ZodString`,(e,t)=>{yn.init(e,t),xo.init(e,t)},{email(e){return this.check(mi(Do,e))},url(e){return this.check(bi(Ao,e))},jwt(e){return this.check(Fi(Go,e))},emoji(e){return this.check(xi(jo,e))},guid(e){return this.check(hi(Oo,e))},uuid(e){return this.check(gi(ko,e))},uuidv4(e){return this.check(_i(ko,e))},uuidv6(e){return this.check(vi(ko,e))},uuidv7(e){return this.check(yi(ko,e))},nanoid(e){return this.check(Si(Mo,e))},cuid(e){return this.check(Ci(No,e))},cuid2(e){return this.check(wi(Po,e))},ulid(e){return this.check(Ti(Fo,e))},base64(e){return this.check(Mi(Ho,e))},base64url(e){return this.check(Ni(Uo,e))},xid(e){return this.check(Ei(Io,e))},ksuid(e){return this.check(Di(Lo,e))},ipv4(e){return this.check(Oi(Ro,e))},ipv6(e){return this.check(ki(zo,e))},cidrv4(e){return this.check(Ai(Bo,e))},cidrv6(e){return this.check(ji(Vo,e))},e164(e){return this.check(Pi(Wo,e))},datetime(e){return this.check(Ii(Co,e))},date(e){return this.check(Li(wo,e))},time(e){return this.check(Ri(To,e))},duration(e){return this.check(zi(Eo,e))}});function G(e){return pi(So,e)}var K=k(`ZodStringFormat`,(e,t)=>{F.init(e,t),xo.init(e,t)}),Co=k(`ZodISODateTime`,(e,t)=>{Rn.init(e,t),K.init(e,t)}),wo=k(`ZodISODate`,(e,t)=>{zn.init(e,t),K.init(e,t)}),To=k(`ZodISOTime`,(e,t)=>{Bn.init(e,t),K.init(e,t)}),Eo=k(`ZodISODuration`,(e,t)=>{Vn.init(e,t),K.init(e,t)}),Do=k(`ZodEmail`,(e,t)=>{Sn.init(e,t),K.init(e,t)}),Oo=k(`ZodGUID`,(e,t)=>{bn.init(e,t),K.init(e,t)}),ko=k(`ZodUUID`,(e,t)=>{xn.init(e,t),K.init(e,t)}),Ao=k(`ZodURL`,(e,t)=>{An.init(e,t),K.init(e,t)}),jo=k(`ZodEmoji`,(e,t)=>{jn.init(e,t),K.init(e,t)}),Mo=k(`ZodNanoID`,(e,t)=>{Mn.init(e,t),K.init(e,t)}),No=k(`ZodCUID`,(e,t)=>{Nn.init(e,t),K.init(e,t)}),Po=k(`ZodCUID2`,(e,t)=>{Pn.init(e,t),K.init(e,t)}),Fo=k(`ZodULID`,(e,t)=>{Fn.init(e,t),K.init(e,t)}),Io=k(`ZodXID`,(e,t)=>{In.init(e,t),K.init(e,t)}),Lo=k(`ZodKSUID`,(e,t)=>{Ln.init(e,t),K.init(e,t)}),Ro=k(`ZodIPv4`,(e,t)=>{Hn.init(e,t),K.init(e,t)}),zo=k(`ZodIPv6`,(e,t)=>{Gn.init(e,t),K.init(e,t)}),Bo=k(`ZodCIDRv4`,(e,t)=>{Kn.init(e,t),K.init(e,t)}),Vo=k(`ZodCIDRv6`,(e,t)=>{Jn.init(e,t),K.init(e,t)}),Ho=k(`ZodBase64`,(e,t)=>{Zn.init(e,t),K.init(e,t)}),Uo=k(`ZodBase64URL`,(e,t)=>{er.init(e,t),K.init(e,t)}),Wo=k(`ZodE164`,(e,t)=>{tr.init(e,t),K.init(e,t)}),Go=k(`ZodJWT`,(e,t)=>{rr.init(e,t),K.init(e,t)}),Ko=k(`ZodBoolean`,(e,t)=>{ir.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Na(e,t,n,r)});function qo(e){return Bi(Ko,e)}var Jo=k(`ZodUnknown`,(e,t)=>{ar.init(e,t),W.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function Yo(){return Vi(Jo)}var Xo=k(`ZodNever`,(e,t)=>{or.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pa(e,t,n,r)});function Zo(e){return Hi(Xo,e)}var Qo=k(`ZodArray`,(e,t)=>{bo(),ur.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>za(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Wi(e,t))},nonempty(e){return this.check(Wi(1,e))},max(e,t){return this.check(Ui(e,t))},length(e,t){return this.check(Gi(e,t))},unwrap(){return this.element}});function q(e,t){return ra(Qo,e,t)}var $o=k(`ZodObject`,(e,t)=>{bo(),gr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Va(e,t,n,r),ze(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return ss(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(v(this._zod.def,{catchall:e}))},passthrough(){return this.clone(v(this._zod.def,{catchall:Yo()}))},loose(){return this.clone(v(this._zod.def,{catchall:Yo()}))},strict(){return this.clone(v(this._zod.def,{catchall:Zo()}))},strip(){return this.clone(v(this._zod.def,{catchall:void 0}))},extend(e){return _e(this,e)},safeExtend(e){return ye(this,e)},merge(e){return be(this,e)},pick(e){return me(this,e)},omit(e){return ge(this,e)},partial(...e){return xe(fs,this,e[0])},exactPartial(...e){return xe(ms,this,e[0],`exactPartial`)},required(...e){return Se(Ss,this,e[0])}});function J(e,t){return new $o({type:`object`,shape:e??{},...S(t)})}var es=k(`ZodUnion`,(e,t)=>{vr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ha(e,t,n,r),e.options=t.options});function ts(e,t){return new es({type:`union`,options:e,...S(t)})}var ns=k(`ZodIntersection`,(e,t)=>{yr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ua(e,t,n,r)});function rs(e,t){return new ns({type:`intersection`,left:e,right:t})}var is=k(`ZodRecord`,(e,t)=>{bo(),Sr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>qa(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function as(e,t,n){return!t||!t._zod?new is({type:`record`,keyType:G(),valueType:e,...S(t)}):new is({type:`record`,keyType:e,valueType:t,...S(n)})}var os=k(`ZodEnum`,(e,t)=>{Cr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Fa(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new os({...t,checks:[],...S(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new os({...t,checks:[],...S(r),entries:i})}});function ss(e,t){return new os({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...S(t)})}var cs=k(`ZodLiteral`,(e,t)=>{wr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ia(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function ls(e,t){return new cs({type:`literal`,values:Array.isArray(e)?e:[e],...S(t)})}var us=k(`ZodTransform`,(e,t)=>{bo(),Tr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ra(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Ke(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(je(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(je(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function ds(e){return new us({type:`transform`,transform:e})}var fs=k(`ZodOptional`,(e,t)=>{Dr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ro(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ps(e){return new fs({type:`optional`,innerType:e})}var ms=k(`ZodExactOptional`,(e,t)=>{Or.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ro(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function hs(e){return new ms({type:`optional`,innerType:e})}var gs=k(`ZodNullable`,(e,t)=>{kr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ja(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function _s(e){return new gs({type:`nullable`,innerType:e})}var vs=k(`ZodDefault`,(e,t)=>{Ar.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qa(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function ys(e,t){return new vs({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var bs=k(`ZodPrefault`,(e,t)=>{Mr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$a(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function xs(e,t){return new bs({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():ce(t)}})}var Ss=k(`ZodNonOptional`,(e,t)=>{Nr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ya(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Cs(e,t){return new Ss({type:`nonoptional`,innerType:e,...S(t)})}var ws=k(`ZodCatch`,(e,t)=>{Ir.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>eo(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Ts(e,t){return new ws({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Ve(t)})}var Es=k(`ZodPipe`,(e,t)=>{Lr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>to(e,t,n,r),e.in=t.in,e.out=t.out});function Ds(e,t){return new Es({type:`pipe`,in:e,out:t})}var Os=k(`ZodReadonly`,(e,t)=>{zr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>no(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function ks(e){return new Os({type:`readonly`,innerType:e})}var As=k(`ZodCustom`,(e,t)=>{Vr.init(e,t),W.init(e,t),e._zod.processJSONSchema=(t,n,r)=>La(e,t,n,r)});function js(e,t={}){return ia(As,e,t)}function Ms(e,t){return aa(e,t)}var Ns=`goodfellow:broker-connect`;function Ps(e){return e.startsWith(`.github/`)||e===`.gitlab-ci.yml`||e.startsWith(`.gitlab/`)}function Fs(t,n){let r={refused:[],confirm:[]};for(let i of t){let{path:t}=i;if(Ps(t)||t.startsWith(`/`)||t.split(`/`).includes(`..`))r.refused.push(t);else if(t.startsWith(`content/code/`))r.confirm.push({path:t,kind:`custom-code`});else if(!e(t))r.confirm.push({path:t,kind:`code`});else if(t===`content/site.json`&&`content`in i){let e;try{e=JSON.parse(i.content).url}catch{e=void 0}(e??void 0)!==(n??void 0)&&r.confirm.push({path:t,kind:`site-address`})}}return r}var Y=class extends Error{problem;name=`BrokerRefusedError`;constructor(e,t){super(t),this.problem=e}},Is=[`revision`,`read`,`readBytes`,`list`,`readFiles`,`fileSizes`,`write`,`changedPaths`],Ls={methods:[`read`,`readBytes`,`list`]},Rs={name:`draft`,data:[`name`],methods:[`changes`,`paths`,`publish`,`submitForReview`,`discard`],objects:{store:{methods:Is}}},zs={data:[`user`,`contentOnly`],methods:[...Is,`deployStatus`,`history`,`readAt`,`repositoryVisibility`,`signOut`],sync:{filesAt:Ls},objects:{pages:{data:[`severalDomains`],methods:[`site`,`connect`,`records`,`status`,`secure`,`disconnect`]},editors:{data:[`invitesByEmail`,`membersOnly`],methods:[`list`,`invite`,`setRole`,`remove`,`letEditorsPublish`]},ownerAccess:{data:[`tokenLink`,`active`,`problem`],methods:[`forget`,`startRedirect`,`requestToken`]},updates:{methods:[`setup`,`enable`,`lastRun`,`start`,`rebuild`],objects:{code:{data:[`repo`,`webUrl`],methods:[`read`,`history`,`readAt`]},nightly:{methods:[`supported`,`get`,`set`]}}},drafts:{methods:[`create`,`open`,`list`],returns:{create:Rs,open:Rs}},scheduledBuilds:{methods:[`timing`,`sync`]},tasks:{methods:[`supported`,`secretsPlace`,`run`]}}};function Bs(e){if(!(e instanceof Error))return{name:`Error`,message:String(e),fields:{}};let t={};for(let[n,r]of Object.entries(e))[`string`,`number`,`boolean`].includes(typeof r)&&(t[n]=r);return{name:e.name,message:e.message,fields:t}}function Vs(e){return e instanceof Error?{__error:Bs(e)}:e}function Hs(e,t,n={}){let r=new Map([[0,{target:t,shape:zs,prefix:``}]]),i=1;function a(e,t,r,i){let o=e,s={};for(let e of t.data??[])o[e]!==void 0&&(s[e]=Vs(o[e]));let c=(t.methods??[]).filter(e=>typeof o[e]==`function`||n.extra?.[`${r}${e}`]!==void 0);for(let e of Object.keys(t.sync??{}))typeof o[e]==`function`&&c.push(e);let l={};for(let[e,n]of Object.entries(t.objects??{})){let t=o[e];typeof t==`object`&&t&&(l[e]=a(t,n,`${r}${e}.`,i))}return{handle:i,data:s,methods:c,objects:l}}let o=()=>a(t,zs,``,0);function s(e,t){let n=r.get(e);if(!n)return;let i=n.target,a=n.shape,o=n.prefix;for(let e of t.slice(0,-1))if(a=a?.objects?.[e],i=i?.[e],o+=`${e}.`,!a||typeof i!=`object`||!i)return;let s=t.at(-1)??``;if((a?.methods?.includes(s)||Object.hasOwn(a?.sync??{},s))&&a)return{target:i,shape:a,method:s,name:`${o}${s}`}}async function c(e){let t=s(e.handle,e.path);if(!t)throw new Y(`not-here`,`The broker doesn't offer that.`);let{target:o,shape:c,method:l,name:u}=t,d=Array.isArray(e.args)?e.args:[],f=n.extra?.[u];if(c.sync?.[l]){let t=c.sync[l],[r,i]=e.then??[``,[]];if(!t.methods?.includes(r))throw new Y(`not-here`,`The broker doesn't offer that.`);await n.check?.({path:`${u}.${r}`,args:[...d,...i],target:o});let a=o[l].apply(o,d);return a[r].apply(a,i)}await n.check?.({path:u,args:d,target:o});let p=f?await f(...d):await o[l].apply(o,d),m=c.returns?.[l];if(m&&typeof p==`object`&&p){let e=i++,t=`${m.name??u}.`;return r.set(e,{target:p,shape:m,prefix:t}),{__object:a(p,m,t,e)}}return p}return e.onmessage=async t=>{let n=t.data;if(n?.type===`call`&&Array.isArray(n.path))try{let t=await c(n);e.postMessage({type:`answer`,id:n.id,ok:!0,value:t,state:o()})}catch(t){e.postMessage({type:`answer`,id:n.id,ok:!1,error:Bs(t),state:o()})}},e.postMessage({type:`state`,state:o()}),()=>{e.onmessage=null,r.clear()}}var Us=J(Object.fromEntries([`connect`,`files`,`secrets`,`read`,`write`].map(e=>[e,q(G()).optional()]))).strict(),Ws=J({version:ls(1),title:G().trim().min(1),description:G().optional(),permissions:Us.default({}),blocks:q(G()).optional(),admin:qo().optional(),screens:q(J({id:G(),title:G()}).strict()).optional(),build:q(J({id:G(),title:G().optional()}).strict()).optional(),tasks:q(J({id:G(),title:G().optional()}).strict()).optional(),server:qo().optional(),mediaStorage:qo().optional(),editor:J({title:G().trim().min(1),kinds:q(ss([`page`,`header`,`footer`,`template`])).optional()}).strict().optional()}).strict(),Gs=J({release:G(),installed:G(),goodfellow:G().optional(),manifest:Ws}),Ks=J({version:ls(1),plugins:as(G(),Gs)}),qs={version:1,plugins:{}};function Js(e){return e===void 0?qs:Ks.parse(JSON.parse(e))}var Ys={anthropic:{name:`Claude`,keyUrl:`https://platform.claude.com/settings/keys`,needsKey:!0,models:[`claude-opus-5-5`,`claude-sonnet-5-5`,`claude-haiku-4-5`]},openai:{name:`OpenAI`,keyUrl:`https://platform.openai.com/api-keys`,needsKey:!0,baseUrl:`https://api.openai.com/v1`,structured:`json_schema`},gemini:{name:`Google Gemini`,keyUrl:`https://aistudio.google.com/apikey`,needsKey:!0,baseUrl:`https://generativelanguage.googleapis.com/v1beta/openai`,structured:`json_schema`},groq:{name:`Groq`,keyUrl:`https://console.groq.com/keys`,needsKey:!0,baseUrl:`https://api.groq.com/openai/v1`,structured:`json_object`},mistral:{name:`Mistral`,keyUrl:`https://console.mistral.ai/api-keys`,needsKey:!0,baseUrl:`https://api.mistral.ai/v1`,structured:`json_schema`},openrouter:{name:`OpenRouter`,keyUrl:`https://openrouter.ai/settings/keys`,needsKey:!0,baseUrl:`https://openrouter.ai/api/v1`,structured:`json_schema`},ovhcloud:{name:`OVHcloud AI Endpoints`,needsKey:!1,baseUrl:`https://oai.endpoints.kepler.ai.cloud.ovh.net/v1`,structured:`json_object`,models:[`gpt-oss-120b`]},custom:{name:`OpenAI-compatible`,needsKey:!1,structured:`json_object`},manual:{name:`Chat app`,needsKey:!1}};function Xs(e,t){let n=t?e.split(t).join(`[key]`):e;return n=n.replace(/\b(sk|gsk|AIza)[-_A-Za-z0-9]{12,}/g,`[key]`),n}var Zs=`https://api.anthropic.com`,Qs=10485760,$s=[`content-type`,`accept`,`anthropic-version`,`anthropic-beta`];function ec(e,t,n){return e===`anthropic`?t===`POST`&&n===`v1/messages`:t===`POST`&&n===`chat/completions`||t===`GET`&&n===`models`}function X(e,t){return Response.json({error:{message:t}},{status:e,headers:{"cache-control":`no-store`}})}function tc(e,t={}){let n=t.fetch??((e,t)=>fetch(e,t)),r=Object.entries(e).flatMap(([e,t])=>t&&(typeof t==`string`||t.baseUrl)?[[e,t]]:[]),i=new Map(r);async function a(e,t,r){let a=t,s=i.get(a);if(!s)return X(404,`This site has no key for that service.`);if(!ec(a,e.method,r))return X(404,`The AI assistant doesn't use that.`);let c=typeof s==`string`?s:s.key,l=a===`anthropic`?Zs:typeof s==`object`?s.baseUrl:Ys[a].baseUrl??``;if(!l)return X(404,`This site has no address for that service.`);let u=e.method===`GET`?void 0:await e.arrayBuffer();if(u&&u.byteLength>Qs)return X(413,`That request is too large.`);let d=new Headers;for(let t of $s){let n=e.headers.get(t);n&&d.set(t,n)}c&&(a===`anthropic`?d.set(`x-api-key`,c):d.set(`authorization`,`Bearer ${c}`));let f=`${o(l,`/`,{start:!1})}/${r}${new URL(e.url).search}`,p;try{p=await n(f,{method:e.method,headers:d,body:u,signal:e.signal})}catch(e){if(e.name===`AbortError`)throw e;return X(502,`The AI service couldn't be reached.`)}if(!p.ok){let e=Xs(await p.text().catch(()=>``),c);return new Response(e,{status:p.status,headers:{"content-type":p.headers.get(`content-type`)??`text/plain`,"cache-control":`no-store`}})}return new Response(p.body,{status:p.status,headers:{"content-type":p.headers.get(`content-type`)??`application/json`,"cache-control":`no-store`}})}return{services:[...i.keys()],forward:a}}var nc=new Set([`write`,`draft.store.write`]);async function rc(e,n){let r=e.find(e=>e.path===t);if(r&&`content`in r)try{let e=Js(r.content).plugins,i=Js(await n?.(t)).plugins,a=Object.entries(e).filter(([e,t])=>JSON.stringify(i[e])!==JSON.stringify(t)).map(([e,t])=>({name:e,...t})),o=Object.keys(i).filter(t=>!e[t]);return a.length+o.length>0?{kind:`plugins`,installed:a,removed:o}:void 0}catch{return}}async function ic(e,t,n){let r=Fs(e,t);if(r.refused.length>0)return{action:`refuse`,paths:r.refused};let i=new Map;for(let{path:e,kind:t}of r.confirm)i.set(t,[...i.get(t)??[],e]);let a=await rc(e,n),o=[...a?[a]:[],...[...i].map(([e,t])=>({kind:e,paths:t}))];return o.length>0?{action:`ask`,questions:o}:{action:`allow`}}function ac(e){let t=e?.read;return typeof t==`function`?n=>t.call(e,n):void 0}function oc(e){if(typeof e==`string`)return e;let t=e?.login;return typeof t==`string`?t:``}async function sc(e,t){let{path:n,args:r,target:i}=e;return nc.has(n)?ic(r[0]??[],t,ac(i)):n===`draft.publish`?ic(await i.changes(),t):n===`updates.start`?{action:`ask`,questions:[{kind:`update`,release:String(r[0])}]}:n===`editors.invite`||n===`editors.setRole`?{action:`ask`,questions:[{kind:`editors`,who:oc(r[0]),role:String(r[1])}]}:n===`editors.letEditorsPublish`?{action:`ask`,questions:[{kind:`editors`,who:``}]}:{action:`allow`}}var cc={title:`Sign in`,loading:`Loading…`,framed:`This page can't be shown inside another page. Open it on its own.`,noConfig:`This sign-in page isn't set up yet: it needs a broker.json beside it, naming the site it signs in to. See the token broker page in Goodfellow's documentation.`,signInTitle:`Sign in to edit {site}`,signInIntro:`This page keeps your sign-in and AI keys where the site's pages can't reach them, and shows the admin panel from here.`,signInRedirect:`Sign in with {host}`,signInToken:`Or sign in with an access token`,tokenLabel:`Access token`,remember:`Stay signed in on this device`,signInButton:`Sign in`,signingIn:`Signing in…`,signInError:`That didn't work: {message}`,noSiteAddress:`The site has no address yet, so there's no admin panel to show. Set its address in Site Settings first, or ask its owner to.`,badSiteAddress:`The site's address, {address}, isn't one this page can show the admin panel from.`,signedInAs:`Signed in as {name}`,aiKeys:`AI keys`,signOut:`Sign out`,adminFrame:`Admin panel`,confirmTitle:`Publish this?`,confirmIntro:`The admin panel asked to publish changes that need you to say so here, where nothing it runs can say so for you:`,confirmCode:`The site's code, which runs when the site is built:`,confirmCustomCode:`Code that runs on the site's pages:`,confirmSiteAddress:`A new Site address, which is where this page shows the admin panel from. Only publish it if you changed it yourself:`,confirmUpdate:`Installing Goodfellow {release}, which changes the site's packages.`,confirmPlugin:`Installing the plugin {title} ({name} {release}), whose code is included when the site is built and runs on its pages. It asks to:`,confirmPluginRemove:`Removing the plugin {name}.`,pluginConnect:`Reach these addresses from the admin panel: {list}`,pluginFiles:`Read and publish these files: {list}`,pluginSecrets:`Get these secrets when the site is built: {list}`,pluginRead:`Read these parts of the site when it's built: {list}`,pluginWrite:`Write these parts of the built site: {list}`,pluginBlocks:`Add these blocks: {list}`,pluginAdmin:`Run in the admin panel, in a frame of its own`,pluginBuild:`Run steps when the site is built`,pluginServer:`Answer requests on the site's server, with everything the server can do`,pluginEditor:`Offer its own page editor, {title}, which is given what's edited in it`,pluginNothing:`Nothing more`,confirmEditors:`Giving {who} access to edit the site{role}.`,confirmEditorsPublish:`Letting the site's editors publish to it.`,confirmPublish:`Publish`,confirmAllow:`Allow`,cancel:`Cancel`,refusedWorkflow:`The token broker never changes the site's workflows, which run with its secrets: {paths}.`,declined:`You chose not to publish this.`,ownerTitle:`Owner token`,ownerIntro:`Create a token that can manage the site, then paste it here. This page keeps it for as long as it's open, and the admin panel never sees it.`,ownerCreate:`Create a token`,ownerLabel:`Owner token`,ownerUse:`Use this token`,aiTitle:`AI keys`,aiIntro:`The AI assistant asks these services through this page, with your keys, so the admin panel never sees them. Leave a service empty to not use it.`,aiRemember:`Remember these keys on this device`,aiSave:`Save`};function Z(e,t={}){return cc[e].replace(/\{(\w+)\}/g,(e,n)=>t[n]??e)}var lc=`goodfellow:broker:route`,uc=`goodfellow:broker:ai`,dc=`goodfellow.config.tsx`,fc=Object.keys(Ys).filter(e=>e!==`custom`&&e!==`manual`&&(e===`anthropic`||Ys[e].baseUrl));function Q(e,t={},...n){let r=document.createElement(e);for(let[e,n]of Object.entries(t))r.setAttribute(e,n);return r.append(...n),r}function $(e){return e instanceof Error?e.message:String(e)}function pc(e){let{repo:t,project:n}=e.options;return typeof t==`string`?t:typeof n==`string`?n:e.package}function mc(){for(let e of[sessionStorage,localStorage])try{let t=e.getItem(uc);if(t)return JSON.parse(t)}catch{}return{}}function hc(e,t){gc(),(t?localStorage:sessionStorage).setItem(uc,JSON.stringify(e))}function gc(){sessionStorage.removeItem(uc),localStorage.removeItem(uc)}async function _c(e){let t=await e.revision(),n=JSON.parse(await e.read(`content/site.json`)??`{}`);if(typeof n.url!=`string`||!n.url)return{problem:`noSiteAddress`};let i;try{i=new URL(n.url.replace(/\/?$/,`/`))}catch{return{problem:`badSiteAddress`}}let o=i.hostname===`localhost`||i.hostname===`127.0.0.1`;if(i.protocol!==`https:`&&!(i.protocol===`http:`&&o))return{problem:`badSiteAddress`};let s=await e.readAt(dc,t).catch(()=>void 0),c=s?a(s):void 0;return{url:`${(c?.checked?r(c):void 0)??i.origin}${i.pathname}admin/`,siteUrl:n.url}}async function vc({root:e,config:t,hosts:n}){document.title=Z(`title`);let r=(...t)=>e.replaceChildren(...t);if(window.top!==window){r(Q(`p`,{class:`broker-note`},Z(`framed`)));return}let i=new URLSearchParams(location.search).get(`site`),a=t?.sites.find(e=>!i||pc(e)===i)??t?.sites[0],o=a&&Object.hasOwn(n,a.package)?n[a.package]:void 0,s=o&&(await o())[a?.export??``];if(!a||typeof s!=`function`){r(Q(`p`,{class:`broker-note`},Z(`noConfig`)));return}let c=s(a.options),l=()=>{location.hash&&sessionStorage.setItem(lc,location.hash)};l(),window.addEventListener(`hashchange`,l),r(Q(`p`,{class:`broker-note`},Z(`loading`)));let u=null,d;try{u=await c.restore()}catch(e){d=e}u?await p(u):f(d);function f(e){let t=Q(`form`,{class:`broker-sign-in`}),n=Q(`input`,{type:`checkbox`,id:`broker-remember`}),i=Q(`input`,{type:`password`,id:`broker-token`,autocomplete:`off`}),o=Q(`p`,{class:`broker-error`,role:`alert`});e!==void 0&&(o.textContent=Z(`signInError`,{message:$(e)}));let s=Q(`button`,{type:`submit`},Z(`signInButton`)),l=async e=>{s.disabled=!0,o.textContent=Z(`signingIn`);try{await p(await e())}catch(e){o.textContent=Z(`signInError`,{message:$(e)}),s.disabled=!1}};if(t.append(Q(`h1`,{},Z(`signInTitle`,{site:pc(a)})),Q(`p`,{},Z(`signInIntro`)),o),c.canRedirect){let e=Q(`button`,{type:`button`,class:`broker-primary`},Z(`signInRedirect`,{host:c.name}));e.addEventListener(`click`,()=>void c.startRedirect(n.checked).catch(e=>{o.textContent=Z(`signInError`,{message:$(e)})})),t.append(Q(`div`,{},e))}if(c.tokenLinks){let e=Q(`ul`,{});for(let t of c.tokenLinks)e.append(Q(`li`,{},Q(`a`,{href:t.url,target:`_blank`,rel:`noreferrer`},t.url)));t.append(Q(`h2`,{},Z(`signInToken`)),e,Q(`label`,{for:`broker-token`},Z(`tokenLabel`)),i,Q(`label`,{class:`broker-check`},n,` ${Z(`remember`)}`),Q(`div`,{},s))}t.addEventListener(`submit`,e=>{e.preventDefault(),i.value.trim()&&l(()=>c.signInWithToken(i.value.trim(),n.checked))}),r(t)}async function p(e){let t=await _c(e).catch(e=>({problem:`signInError`,error:e}));if(`problem`in t){r(Q(`p`,{class:`broker-note`,role:`alert`},Z(t.problem,{address:``,message:`error`in t?$(t.error):``})));return}let n=new URL(t.url).origin,i=sessionStorage.getItem(lc)??``,a=Q(`iframe`,{class:`broker-frame`,title:Z(`adminFrame`),src:`${t.url}${i.startsWith(`#`)?i:``}`,sandbox:`allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads allow-modals`,allow:`clipboard-write`}),o=()=>{window.removeEventListener(`message`,d),u?.(),e.signOut(),gc(),sessionStorage.removeItem(lc),f()},s=Q(`button`,{type:`button`},Z(`aiKeys`));s.addEventListener(`click`,()=>_(()=>a.contentWindow?.location.replace(a.src)));let l=Q(`button`,{type:`button`},Z(`signOut`));l.addEventListener(`click`,o),r(Q(`header`,{class:`broker-bar`},Q(`span`,{},Z(`signedInAs`,{name:e.user.name||e.user.login})),s,l),a);let u,d=r=>{if(r.source!==a.contentWindow||r.origin!==n||r.data?.type!==`goodfellow:broker-ready`)return;u?.();let i=new MessageChannel,s=new MessageChannel;u=Hs(i.port1,e,{async check(e){let n=await sc(e,t.siteUrl);if(n.action===`refuse`)throw new Y(`workflow`,Z(`refusedWorkflow`,{paths:n.paths.join(`, `)}));if(n.action===`ask`&&!await ee(n.questions))throw new Y(`declined`,Z(`declined`))},extra:{signOut:o,"ownerAccess.requestToken":()=>te(e)}}),s.port1.onmessage=e=>void m(s.port1,e.data);let l={hostName:c.name,redirectAddressesListed:c.canRedirect&&c.redirectAddressesListed===!0,aiServices:Object.keys(mc())};a.contentWindow?.postMessage({type:Ns,account:l},n,[i.port2,s.port2])};window.addEventListener(`message`,d)}async function m(e,t){if(t?.type===`route`&&typeof t.hash==`string`){sessionStorage.setItem(lc,t.hash);return}if(t?.type!==`ai`)return;let[n=``,...r]=t.path.split(`?`)[0]?.split(`/`)??[],i=t.path.includes(`?`)?t.path.slice(t.path.indexOf(`?`)):``,a=new Request(`https://broker.invalid/${r.join(`/`)}${i}`,{method:t.method,headers:t.headers,...t.body&&t.method!==`GET`&&{body:t.body}}),o=await tc(mc()).forward(a,n,r.join(`/`)),s=await o.arrayBuffer(),c={type:`ai`,id:t.id,status:o.status,headers:[...o.headers.entries()],body:s};e.postMessage(c,[s])}function h(e,t,n){return new Promise(r=>{let i=Q(`dialog`,{class:`broker-dialog`},Q(`h2`,{},e),...t),a=Q(`div`,{class:`broker-actions`});for(let e of n){let t=Q(`button`,{type:`button`,...e.primary&&{class:`broker-primary`}},e.label);t.addEventListener(`click`,()=>i.close(e.value?`yes`:`no`)),a.append(t)}i.append(a),i.addEventListener(`close`,()=>{i.remove(),r(i.returnValue===`yes`)}),document.body.append(i),i.showModal()})}function g(e){let{permissions:t}=e,n=(e,t)=>e?.length?[Z(t,{list:e.join(`, `)})]:[],r=[...n(t.connect,`pluginConnect`),...n(t.files,`pluginFiles`),...n(t.secrets,`pluginSecrets`),...n(t.read,`pluginRead`),...n(t.write,`pluginWrite`),...n(e.blocks,`pluginBlocks`),...e.admin?[Z(`pluginAdmin`)]:[],...e.build?.length?[Z(`pluginBuild`)]:[],...e.server?[Z(`pluginServer`)]:[],...e.editor?[Z(`pluginEditor`,{title:e.editor.title})]:[]];return r.length>0?r:[Z(`pluginNothing`)]}function ee(e){let t=[Q(`p`,{},Z(`confirmIntro`))],n=!1;for(let r of e)if(r.kind===`update`)t.push(Q(`p`,{},Z(`confirmUpdate`,{release:r.release})));else if(r.kind===`plugins`){n=!0;for(let e of r.installed){let{manifest:n}=e;t.push(Q(`p`,{},Z(`confirmPlugin`,{title:n.title,name:e.name,release:e.release})),Q(`ul`,{},...g(n).map(e=>Q(`li`,{},e))))}for(let e of r.removed)t.push(Q(`p`,{},Z(`confirmPluginRemove`,{name:e})))}else if(r.kind===`editors`)t.push(Q(`p`,{},r.who?Z(`confirmEditors`,{who:r.who,role:r.role?` (${r.role})`:``}):Z(`confirmEditorsPublish`)));else{n=!0;let e=r.kind===`code`?`confirmCode`:r.kind===`custom-code`?`confirmCustomCode`:`confirmSiteAddress`;t.push(Q(`p`,{},Z(e)),Q(`ul`,{},...r.paths.map(e=>Q(`li`,{},Q(`code`,{},e)))))}return h(Z(`confirmTitle`),t,[{label:Z(`cancel`),value:!1},{label:Z(n?`confirmPublish`:`confirmAllow`),value:!0,primary:!0}])}async function te(e){let t=e.ownerAccess;if(!t)throw new Y(`not-here`,`This site's host has no owner token.`);let n=Q(`input`,{type:`password`,id:`broker-owner-token`,autocomplete:`off`}),r=Q(`p`,{class:`broker-error`,role:`alert`});for(;;){if(!await h(Z(`ownerTitle`),[Q(`p`,{},Z(`ownerIntro`)),Q(`p`,{},Q(`a`,{href:t.tokenLink.url,target:`_blank`,rel:`noreferrer`},Z(`ownerCreate`))),Q(`label`,{for:`broker-owner-token`},Z(`ownerLabel`)),n,r],[{label:Z(`cancel`),value:!1},{label:Z(`ownerUse`),value:!0,primary:!0}]))throw new Y(`declined`,Z(`declined`));try{await t.applyToken(n.value.trim());return}catch(e){r.textContent=Z(`signInError`,{message:$(e)})}}}async function _(e){let t=mc(),n=new Map,r=fc.map(e=>{let r=Q(`input`,{type:`password`,id:`broker-ai-${e}`,autocomplete:`off`}),i=t[e];return typeof i==`string`&&(r.value=i),n.set(e,r),Q(`div`,{},Q(`label`,{for:`broker-ai-${e}`},Ys[e].name),r)}),i=Q(`input`,{type:`checkbox`,id:`broker-ai-remember`});if(i.checked=localStorage.getItem(uc)!==null,!await h(Z(`aiTitle`),[Q(`p`,{},Z(`aiIntro`)),...r,Q(`label`,{class:`broker-check`},i,` ${Z(`aiRemember`)}`)],[{label:Z(`cancel`),value:!1},{label:Z(`aiSave`),value:!0,primary:!0}]))return;let a={};for(let[e,t]of n)t.value.trim()&&(a[e]=t.value.trim());hc(a,i.checked),e()}}await vc({root:document.getElementById(`broker`),config:await fetch(`./broker.json`,{cache:`no-store`}).then(e=>e.ok?e.json():void 0).catch(()=>void 0),hosts:{"@goodfellow-cms/bitbucket":()=>n(()=>import(`./dist-DuGHJcqN.js`),__vite__mapDeps([0,1,2,3,4]),import.meta.url),"@goodfellow-cms/github":()=>n(()=>import(`./dist-CLietd1m.js`),__vite__mapDeps([5,1,2,6,3,7]),import.meta.url),"@goodfellow-cms/gitlab":()=>n(()=>import(`./dist-Dz15_FP0.js`),__vite__mapDeps([8,1,2,6,3,4]),import.meta.url)}});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=class extends Error{problem;name=`ScheduledBuildsError`;constructor(e,t){super(t),this.problem=e}};export{e as t};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{a as e}from"./store-CNLNNQkL.js";function t(e){let t=/^[\^~=v]*(\d+)\.(\d+)\.(\d+)$/.exec(e.trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:void 0}function n(e,t){return e[0]-t[0]||e[1]-t[1]||e[2]-t[2]}function r(e,r){let i=t(e),a=t(r);return i&&a?n(i,a):0}function i(e){return t(e)?.join(`.`)}function a(e){try{let{dependencies:t={},devDependencies:n={}}=JSON.parse(e),r=t[`@goodfellow-cms/react`]??n[`@goodfellow-cms/react`];return r?i(r):void 0}catch{return}}var o=`goodfellow-update `;function s(e){let t=e.split(`
|
|
2
|
+
`);for(let e=t.length-1;e>=0;e--){let n=t[e]??``,r=n.indexOf(o);if(r!==-1)try{let e=JSON.parse(n.slice(r+18).trim());if([`up-to-date`,`updated`,`failed`].includes(e.state)&&typeof e.from==`string`)return e}catch{}}}var c=`GOODFELLOW_NIGHTLY`,l=[`changed`,`always`,`off`];function u(e){let t=e?.trim().toLowerCase();return l.includes(t)?t:`changed`}var d=class extends Error{problem;name=`UpdatesError`;constructor(e,t){super(t),this.problem=e}},f=/^[a-z0-9]{8,40}$/,p=`goodfellow-task-`,m=`goodfellow-task-result.json`,h=`plugin-task.yml`,g=`plugin-task`,_=`goodfellow-plugin-task`;function v(e){return f.test(e)}function y(e){let{id:t,plugin:n,task:r,input:i,key:a}=e;if(![t,n,r,i,a].every(e=>typeof e==`string`))return`That isn't a task's request.`;if(!v(e.id))return`The request's id isn't one the admin panel makes.`;if(!/^[a-z0-9][a-z0-9._-]*(--[a-z0-9][a-z0-9._-]*)?$/.test(e.plugin))return`That isn't a plugin's id.`;if(!/^[a-z0-9][a-z0-9-]*$/.test(e.task))return`That isn't a task's id.`;if(e.input.length>32e3)return`The task's input is too long.`;try{JSON.parse(e.input);let t=JSON.parse(e.key);if(t.kty!==`EC`||t.crv!==`P-256`||t.d!==void 0)return`The answer's key isn't a public key.`}catch{return`The task's input or key isn't JSON.`}}var b=class extends Error{problem;name=`PluginTaskError`;constructor(e,t){super(t),this.problem=e}},x=3e5,S=4e3,C=`goodfellow-draft-`,w=/^[a-z0-9][a-z0-9-]{0,39}$/;function T(e){return w.test(e)}var E=class extends Error{name=`DraftError`;problem;constructor(e,t){super(t),this.problem=e}};function D(e){if(!T(e))throw new E(`not-found`,`"${e}" isn't a draft's name.`);return`${C}${e}`}function O(t,n){function r(r,i){let a=n.branchStore(i);async function o(){let e=await n.mergeBase(i);return a.changedPaths(e,await a.revision())}async function s(){let e=[];for(let t of await o())if(t.startsWith(`public/media/`)){let n=await a.readBytes(t);e.push(n?{path:t,bytes:n}:{path:t,delete:!0})}else{let n=await a.read(t);e.push(n===void 0?{path:t,delete:!0}:{path:t,content:n})}return e}return{name:r,store:a,changes:s,paths:o,async publish(r){let a=await n.mergeBase(i),o=await s(),c=o.length>0?await e(t,o,{message:r,expectedRevision:a}):{revision:await t.revision()};return await n.deleteBranch(i),c},async submitForReview({title:e,description:t=``}){return n.openReview({branch:i,title:e,description:t})},async discard(){await n.deleteBranch(i)}}}return{async create(e,i){let a=D(e);return await n.createBranch(a,i?.from??await t.revision()),r(e,a)},async open(e){let t=D(e);return await n.mergeBase(t),r(e,t)},async list(){return(await n.listBranches(C)).map(e=>e.slice(17)).filter(T).sort().reverse()}}}var k=class extends Error{problem;name=`EditorsError`;constructor(e,t){super(t),this.problem=e}},A=class extends Error{problem;link;name=`SetupError`;constructor(e,t,n){super(t),this.problem=e,this.link=n}};export{s as _,b as a,g as c,x as d,h as f,r as g,d as h,O as i,S as l,c as m,k as n,p as o,y as p,E as r,_ as s,A as t,m as u,u as v,a as y};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var e=`content`,t=`public/media`,n=`blocks/installed`,r=`plugins/installed`,i=`plugins/installed/installed.json`,a=`components`,o=`hooks`,s=`content-repository`,c=class extends Error{name=`ConflictError`;constructor(e=`The site changed since it was loaded.`){super(e)}},l=[e,t,n,a,`lib`,o,r];function u(e){return e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)||e.split(`/`).some(e=>e===``||e===`.`||e===`..`)?!1:l.some(t=>e.startsWith(`${t}/`))}async function d(e,t,n){let r=n.expectedRevision,i=new Set(t.map(e=>e.path));for(let a=0;;a++)try{return await e.write(t,{...n,expectedRevision:r})}catch(t){if(!(t instanceof c)||!e.changedPaths||a===2)throw t;let o=await e.revision();if(o===r||(await e.changedPaths(n.expectedRevision,o)).some(e=>i.has(e)))throw t;r=o}}var f=[e,t];function p(e){return u(e)&&f.some(t=>e.startsWith(`${t}/`))}var m=class extends Error{name=`CodeChangeError`;constructor(e){super(`${e} is part of the site's code, which is kept in a repository of its own, not the content repository.`)}};function h(e){let t=e.find(e=>!p(e.path));if(t)throw new m(t.path)}export{d as a,p as i,l as n,s as o,h as r,i as s,c as t};
|
package/site/files.json
CHANGED
|
@@ -1,15 +1,18 @@
|
|
|
1
1
|
{
|
|
2
2
|
"files": [
|
|
3
3
|
"_headers",
|
|
4
|
+
"assets/content-repository-setup-3Z0i5cMx.js",
|
|
4
5
|
"assets/deploy-keys-DAj2oX-N-DRd_HmOG.js",
|
|
5
|
-
"assets/dist-
|
|
6
|
-
"assets/dist-
|
|
6
|
+
"assets/dist-CLietd1m.js",
|
|
7
|
+
"assets/dist-DuGHJcqN.js",
|
|
8
|
+
"assets/dist-Dz15_FP0.js",
|
|
7
9
|
"assets/git-eGyMXUIu.js",
|
|
8
10
|
"assets/index-BQoQNxGe.css",
|
|
9
|
-
"assets/index-
|
|
11
|
+
"assets/index-j9FvrqIj.js",
|
|
10
12
|
"assets/preload-helper-khBccGFq.js",
|
|
11
|
-
"assets/
|
|
12
|
-
"assets/
|
|
13
|
+
"assets/scheduled-builds-BPfDaBYt.js",
|
|
14
|
+
"assets/setup-host-B_uhd1y7.js",
|
|
15
|
+
"assets/store-CNLNNQkL.js",
|
|
13
16
|
"broker.example.json",
|
|
14
17
|
"index.html",
|
|
15
18
|
"vercel.json"
|
package/site/index.html
CHANGED
|
@@ -9,8 +9,8 @@
|
|
|
9
9
|
/>
|
|
10
10
|
<meta name="referrer" content="no-referrer" />
|
|
11
11
|
<title>Sign in</title>
|
|
12
|
-
<script type="module" crossorigin src="./assets/index-
|
|
13
|
-
<link rel="modulepreload" crossorigin href="./assets/store-
|
|
12
|
+
<script type="module" crossorigin src="./assets/index-j9FvrqIj.js"></script>
|
|
13
|
+
<link rel="modulepreload" crossorigin href="./assets/store-CNLNNQkL.js">
|
|
14
14
|
<link rel="modulepreload" crossorigin href="./assets/preload-helper-khBccGFq.js">
|
|
15
15
|
<link rel="stylesheet" crossorigin href="./assets/index-BQoQNxGe.css">
|
|
16
16
|
</head>
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./deploy-keys-DAj2oX-N-DRd_HmOG.js","./git-eGyMXUIu.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{r as e,t}from"./store-5raQS3us.js";import{a as n,d as r,f as i,l as a,m as o,n as s,o as c,p as l,r as u,s as d,t as f,u as p}from"./setup-host-w4Qxug91.js";import{a as m,i as h,n as g,o as _,r as v,s as ee,t as y}from"./git-eGyMXUIu.js";import{t as b}from"./preload-helper-khBccGFq.js";async function x({apiUrl:e,token:t,fetch:n},r,i={}){let a=async a=>n(`${e}${r}`,{method:i.method??`GET`,headers:{accept:i.accept??`application/vnd.github+json`,authorization:`Bearer ${typeof t==`string`?t:await t({refresh:a})}`,"x-github-api-version":`2022-11-28`,...i.body!==void 0&&{"content-type":`application/json`}},body:i.body===void 0?void 0:JSON.stringify(i.body),cache:`no-store`}),o=await a(!1);if(o.status===401&&typeof t!=`string`&&(o=await a(!0)),o.status===401)throw new g(`invalid`,`GitHub didn't accept the sign-in. It may have expired.`);if(!o.ok&&!i.allow?.includes(o.status)){let e=await o.json().catch(()=>({}));throw new y(o.status,`GitHub answered ${o.status}: ${e.message??o.statusText}`)}return o}async function S(e,t,n){return await(await x(e,t,n)).json()}function C(e){return e.split(`/`).map(e=>encodeURIComponent(e)).join(`/`)}var w=/^[a-z\d](?:[a-z\d]|-(?=[a-z\d])){0,38}$/i,T=`invitation:`;function E(e){return e?.admin?`owner`:e?.maintain||e?.push?`editor`:`viewer`}function D(e){return e===`admin`?`owner`:e===`write`||e===`maintain`?`editor`:`viewer`}function O(e){return e instanceof y&&(e.status===403||e.status===404)}function te(e,t,n,i){let a=`/repos/${n}`;function o(){let e=t();if(!e)throw new r(`not-allowed`,`Changing editors on GitHub needs an owner token.`);return e}async function s(e){try{await e(o())}catch(e){throw O(e)?new r(`not-allowed`,`This token can't change the site's editors.`):e}}async function c(e){let t=[];for(let n=1;n<=10;n++){let r=await S(e,`${a}/collaborators?per_page=100&page=${n}`);if(t.push(...r),r.length<100)break}return t}return{invitesByEmail:!1,async list(){let n=t()??e,r=await c(n),o;try{o=await S(n,`${a}/invitations?per_page=100`)}catch(e){if(!O(e))throw e}let s=[...r.map(e=>({id:e.login,login:e.login,avatarUrl:e.avatar_url,role:E(e.permissions),...e.login.toLowerCase()===i.toLowerCase()&&{self:!0}})),...(o??[]).flatMap(e=>e.invitee?[{id:`${T}${e.id}`,login:e.invitee.login,avatarUrl:e.invitee.avatar_url,role:D(e.permissions),invited:!0}]:[])],l=s.some(e=>e.self&&e.role===`owner`);return{editors:s,manage:o?`yes`:l?`token`:`no`,editorsCanPublish:!0}},async invite(e,t){let n=e.trim().replace(/^@/,``);if(!w.test(n))throw new r(`invalid`,`That isn't a GitHub username.`);let i=o();try{await x(i,`${a}/collaborators/${encodeURIComponent(n)}`,{method:`PUT`,body:{permission:t===`owner`?`admin`:`push`}})}catch(e){throw e instanceof y&&e.status===404&&(await x(i,`/users/${encodeURIComponent(n)}`,{allow:[404]})).status===404?new r(`not-found`,`There's no GitHub account named ${n}.`):O(e)?new r(`not-allowed`,`This token can't change the site's editors.`):e instanceof y&&e.status===422?new r(`invalid`,`GitHub didn't accept the invitation: ${e.message}`):e}},async setRole(e,t){await s(async n=>{e.id.startsWith(T)?await x(n,`${a}/invitations/${e.id.slice(11)}`,{method:`PATCH`,body:{permissions:t===`owner`?`admin`:`write`}}):await x(n,`${a}/collaborators/${encodeURIComponent(e.id)}`,{method:`PUT`,body:{permission:t===`owner`?`admin`:`push`}})})},async remove(e){await s(t=>x(t,e.id.startsWith(T)?`${a}/invitations/${e.id.slice(11)}`:`${a}/collaborators/${encodeURIComponent(e.id)}`,{method:`DELETE`}))}}}function ne(e,t,n,i){let a,o,s,c;return{access:{tokenLink:n,get active(){return a!==void 0},get problem(){return c},...i&&{async startRedirect(e){c=void 0,await i(e)}},async applyToken(n){let i={...e,token:n.trim()};try{if(!(await S(i,`/repos/${t}`)).permissions?.admin)throw new r(`not-allowed`,`This token's account isn't an owner of the site.`);await S(i,`/repos/${t}/invitations?per_page=1`)}catch(e){throw e instanceof r?e:e instanceof g||O(e)?new r(`not-allowed`,`This token can't change the site's editors.`):e}a=i,o=i,c=void 0},forget(){a=void 0,o=void 0,s?.(),s=void 0}},api:()=>a,codeApi:()=>o,useSignIn(t,n,r){a={...e,token:t},o=r?{...e,token:r}:void 0,s=n,c=void 0},failed(e){c=e}}}var re=[`185.199.108.153`,`185.199.109.153`,`185.199.110.153`,`185.199.111.153`],ie=[`2606:50c0:8000::153`,`2606:50c0:8001::153`,`2606:50c0:8002::153`,`2606:50c0:8003::153`],k=new Set([`approved`,`issued`,`uploaded`]),A=new Set([`errored`,`bad_authz`,`authorization_revoked`]);function j(e,t,{apex:n,www:r}){let i=`${(e.split(`/`)[0]??``).toLowerCase()}.github.io`;return n?[...re.map(e=>({type:`A`,name:t,value:e,purpose:`site`})),...ie.map(e=>({type:`AAAA`,name:t,value:e,purpose:`site`,optional:!0})),...r?[{type:`CNAME`,name:`www.${t}`,value:i,purpose:`www`,optional:!0}]:[]]:[{type:`CNAME`,name:t,value:i,purpose:`site`}]}function ae(e,t){let n=`/repos/${t}/pages`;async function r(){let t=await x(e(),n,{allow:[404]});return t.status===404?void 0:await t.json()}async function i(t){try{await x(e(),n,{method:`PUT`,body:t})}catch(e){throw e instanceof y&&(e.status===403||e.status===404)?new o(`not-allowed`,`This sign-in can't change the site's GitHub Pages settings.`):e instanceof y&&(e.status===400||e.status===422)?/taken|already/i.test(e.message)?new o(`taken`,`Another GitHub Pages site already uses this domain.`):`https_enforced`in t?new o(`not-ready`,`The domain's certificate isn't ready yet.`):new o(`invalid`,`GitHub Pages doesn't accept this domain.`):e}}return{severalDomains:!1,async site(){let e=await r();return e&&{url:e.html_url,domain:e.cname??void 0}},async connect(e,n){return await i({cname:e}),j(t,e,n)},async records(e,n){return j(t,e,n)},async status(t){let r=await S(e(),n),i=r.https_certificate?.state??``;return{verified:!0,certificate:k.has(i)?`ready`:A.has(i)?`failed`:`pending`,httpsOnly:r.https_enforced===!0,primary:r.cname===t}},async secure(){await i({https_enforced:!0})},async disconnect(){await i({cname:null})}}}var oe=`.github/workflows/scheduled.yml`,se=[`.github/workflows/deploy.yml`,`.github/workflows/rebuild.yml`];function ce(e){return{async timing(){let[t,...n]=await Promise.all([oe,...se].map(e));return t&&/\bdue\b/.test(t)&&/\bschedule:/.test(t)?`hourly`:n.some(e=>e&&/\bschedule:/.test(e))?`nightly`:`none`}}}var le=`deploy.yml`,ue=`update.yml`,de=`publish-update`;function M(e,t,n,r,i,a=le){let o=`/repos/${n}/actions/workflows/${a}`,s=`.github/workflows/${a}`;return{async setup(){let e=await i.read(s);return e&&/update --(publish|commit)\b/.test(e)?`ready`:`missing`},async lastRun(){let t=await x(e,`${o}/runs?branch=${encodeURIComponent(r)}&per_page=20`,{allow:[403,404]});if(!t.ok)return;let{workflow_runs:a=[]}=await t.json();for(let t of a.filter(e=>[`schedule`,`workflow_dispatch`].includes(e.event))){let r={date:t.created_at,detailsUrl:t.html_url};if(t.status!==`completed`)return{state:`running`,...r};let{jobs:a=[]}=await S(e,`/repos/${n}/actions/runs/${t.id}/jobs`),o=a.find(e=>e.name===`update`);if(!o||o.conclusion===`skipped`)continue;if(o.conclusion!==`success`)return{state:`failed`,...r};let s=a.find(e=>e.name===de);if(s&&s.conclusion!==`success`&&s.conclusion!==`skipped`)return{state:`failed`,...r};let c=p(await i.readAt(`package.json`,t.head_sha)??``),l=p(await i.read(`package.json`)??``);if(!c||!l||c===l)return{state:`up-to-date`,...r};let u=d(l,c)<0;return{state:`updated`,...r,result:{state:`updated`,from:c,to:l,...u&&{rollback:u}}}}},nightly:fe(e,t,n,()=>i.read(s)),async rebuild(){await l({})},async start(e){await l({update:e})}};async function l(n){try{await x(t()??e,`${o}/dispatches`,{method:`POST`,body:{ref:r,inputs:n}})}catch(e){throw e instanceof y&&(e.status===403||e.status===401)?new c(`not-allowed`,`Running the site's build needs a token that can run its workflows.`):e instanceof y&&(e.status===404||e.status===422)?new c(`missing`,`The site's GitHub Pages workflow doesn't update Goodfellow.`):e}}}function fe(e,t,r,i){let o=`/repos/${r}/actions/variables`,s=e=>{throw e instanceof y&&(e.status===401||e.status===403)?new c(`not-allowed`,`Changing when the site rebuilds needs GitHub's Variables permission.`):e};return{async supported(){return(await i())?.includes(`GOODFELLOW_NIGHTLY`)??!1},async get(){let r=await x(t()??e,`${o}/${n}`,{allow:[403,404]});if(r.status===404)return`changed`;if(r.ok)return a((await r.json()).value)},async set(r){let i=t()??e;if(r===`changed`){await x(i,`${o}/${n}`,{method:`DELETE`,allow:[404]}).catch(s);return}let a={name:n,value:r};(await x(i,`${o}/GOODFELLOW_NIGHTLY`,{method:`PATCH`,body:a,allow:[404]}).catch(s)).status===404&&await x(i,o,{method:`POST`,body:a}).catch(s)}}}function N(e){return e instanceof g&&e.problem===`no-access`||e instanceof y&&(e.status===403||e.status===404)}function pe(e){let{read:t}=e,n=C(e.repo),r,i=e=>(r??=S(e,`/repos/${n}`).then(e=>e.default_branch),r.catch(()=>{r=void 0}),r);async function a(){if(!t)throw new g(`no-access`,`This sign-in has no access to ${e.repo}.`);return e.open(t,await i(t))}async function o(e){let t=await a();return t.readAt(e,await t.revision())}async function s(){if(!t)throw new g(`no-access`,`This sign-in has no access to ${e.repo}.`);let r=await i(t);return M(t,e.manage,n,r,{read:o,readAt:async(e,t)=>(await a()).readAt(e,t)},ue)}return{code:{repo:e.repo,webUrl:`${e.webUrl}/${e.repo}`,read:o,history:async(e,t)=>(await a()).history(e,t),readAt:async(e,t)=>(await a()).readAt(e,t)},async setup(){try{return await(await s()).setup()}catch(e){if(N(e))return`no-access`;throw e}},async lastRun(){try{return await(await s()).lastRun()}catch(e){if(N(e))return;throw e}},async start(e){await(await s()).start(e)},async rebuild(){await(await s()).rebuild?.()}}}var P=/cloudflare/i,F=100,me=`mutation ($input: CreateCommitOnBranchInput!) {
|
|
3
|
-
createCommitOnBranch(input: $input) { commit { oid } }
|
|
4
|
-
}`;function I(e,t){let n=`${t}/`;return[...e.keys()].filter(e=>e.startsWith(n)).sort()}var L=class n{user;pages;editors;ownerAccess;updates;drafts;scheduledBuilds;contentOnly;options;api;repo;branch;onSignOut;author;owner;pinned;trees=new Map;treeSizes=new Map;blobs=new Map;constructor(e){this.options=e,this.api=e.api,this.repo=C(e.repo),this.branch=e.branch,this.user=e.user,this.onSignOut=e.onSignOut,this.author=e.author,this.pinned=e.revision;let t=ne(this.api,this.repo,e.ownerTokenLink,e.ownerRedirect);this.owner=t,this.ownerAccess=t.access,this.pages=ae(()=>t.api()??this.api,this.repo),this.editors=te(this.api,t.api,this.repo,this.user.login),this.contentOnly=e.contentOnly===!0,this.contentOnly?e.code&&(this.updates=pe({repo:e.code.repo,webUrl:e.code.webUrl,read:e.code.api,manage:t.codeApi,open:(t,r)=>new n({api:t,repo:e.code?.repo??``,branch:r,user:this.user,onSignOut:()=>{},ownerTokenLink:e.ownerTokenLink})})):this.updates=M(this.api,t.api,this.repo,this.branch,this),this.drafts=l(this,this.draftHost()),this.scheduledBuilds=ce(e=>this.read(e))}async repositoryVisibility(){let e=await S(this.api,`/repos/${this.repo}`);return e.visibility===`internal`?`internal`:e.private===!1||e.visibility===`public`?`public`:`private`}draftHost(){let e=`/repos/${this.repo}`,t=t=>`${e}/git/refs/heads/${encodeURIComponent(t)}`;return{liveBranch:this.branch,branchStore:e=>new n({...this.options,branch:e}),createBranch:async(t,n)=>{if((await x(this.api,`${e}/git/refs`,{method:`POST`,body:{ref:`refs/heads/${t}`,sha:n},allow:[422]})).status===422)throw new i(`exists`,`There's already a draft called ${t}.`)},deleteBranch:async e=>{await x(this.api,t(e),{method:`DELETE`,allow:[404,422]})},mergeBase:async t=>{let n=await x(this.api,`${e}/compare/${encodeURIComponent(this.branch)}...${encodeURIComponent(t)}`,{allow:[404]});if(n.status===404)throw new i(`not-found`,`There's no draft ${t}.`);return(await n.json()).merge_base_commit.sha},listBranches:async t=>(await S(this.api,`${e}/git/matching-refs/heads/${encodeURIComponent(t)}`)).map(e=>e.ref.replace(/^refs\/heads\//,``)),openReview:async({branch:t,title:n,description:r})=>{let a=await x(this.api,`${e}/pulls`,{method:`POST`,body:{title:n,head:t,base:this.branch,body:r},allow:[403,404,422]});if(a.ok)return{url:(await a.json()).html_url};if(a.status!==422)throw new i(`no-reviews`,`This sign-in can't open pull requests on the site's repository.`);let o=decodeURIComponent(this.repo).split(`/`)[0],s=new URLSearchParams({head:`${o}:${t}`,state:`open`}),[c]=await S(this.api,`${e}/pulls?${s}`);if(!c)throw new y(422,`GitHub couldn't open the pull request.`);return{url:c.html_url}}}}async revision(){return this.pinned=await this.head(),this.pinned}async head(){return(await S(this.api,`/repos/${this.repo}/git/ref/heads/${encodeURIComponent(this.branch)}`)).object.sha}tree(e){let t=this.trees.get(e);return t||(t=S(this.api,`/repos/${this.repo}/git/trees/${e}?recursive=1`).then(t=>{if(t.truncated)throw new y(413,`The repository has too many files for GitHub to list at once.`);let n=t.tree.filter(e=>e.type===`blob`);return this.treeSizes.set(e,new Map(n.flatMap(e=>e.size===void 0?[]:[[e.path,e.size]]))),new Map(n.map(e=>[e.path,e.sha]))}),t.catch(()=>this.trees.delete(e)),this.trees.set(e,t)),t}async currentTree(){return this.tree(this.pinned??await this.revision())}async read(e){return this.readFrom(await this.currentTree(),e)}readFrom(e,t){let n=e.get(t);if(!n)return Promise.resolve(void 0);let r=this.blobs.get(n);return r||(r=x(this.api,`/repos/${this.repo}/git/blobs/${n}`,{accept:`application/vnd.github.raw+json`}).then(e=>e.text()),r.catch(()=>this.blobs.delete(n)),this.blobs.set(n,r)),r}async readFiles(e){return this.readFilesFrom(await this.currentTree(),e)}async readFilesFrom(e,t){let n=t.flatMap(t=>{let n=e.get(t);return n?[[t,n]]:[]}),r=[...new Set(n.map(([,e])=>e).filter(e=>!this.blobs.has(e)))],[i,a]=decodeURIComponent(this.repo).split(`/`);for(let e=0;e<r.length;e+=F){let t=r.slice(e,e+F),n=t.map((e,t)=>`f${t}: object(oid: "${e}") { ... on Blob { text isBinary } }`),o=await S(this.api,`/graphql`,{method:`POST`,body:{query:`query ($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { ${n.join(` `)} } }`,variables:{owner:i,name:a}}});t.forEach((e,t)=>{let n=o.data?.repository?.[`f${t}`];n&&!n.isBinary&&typeof n.text==`string`&&this.blobs.set(e,Promise.resolve(n.text))})}let o=new Map;for(let[t]of n){let n=await this.readFrom(e,t);n!==void 0&&o.set(t,n)}return o}async readBytes(e){return this.bytesFrom(await this.currentTree(),e)}async bytesFrom(e,t){let n=e.get(t);if(!n)return;let r=await x(this.api,`/repos/${this.repo}/git/blobs/${n}`,{accept:`application/vnd.github.raw+json`});return new Uint8Array(await r.arrayBuffer())}async list(e){return I(await this.currentTree(),e)}filesAt(e){return{read:async t=>this.readFrom(await this.tree(e),t),readFiles:async t=>this.readFilesFrom(await this.tree(e),t),readBytes:async t=>this.bytesFrom(await this.tree(e),t),list:async t=>I(await this.tree(e),t)}}async fileSizes(e){let t=`${e}/`;await this.currentTree();let n=this.treeSizes.get(this.pinned??``)??new Map;return new Map([...n].filter(([e])=>e.startsWith(t)))}useOwnerSignIn(e,t,n){this.owner.useSignIn(e,t,n)}ownerSignInFailed(e){this.owner.failed(e)}async write(t,n){return this.contentOnly&&e(t),this.author?this.writeCommit(t,n,this.author):this.writeGraphQL(t,n)}async writeCommit(e,{message:n,expectedRevision:r},i){let a=await this.tree(r),o=`/repos/${this.repo}`,s=[];try{for(let t of e)if(`delete`in t)a.has(t.path)&&s.push({path:t.path,mode:`100644`,type:`blob`,sha:null});else if(`bytes`in t){let e=await S(this.api,`${o}/git/blobs`,{method:`POST`,body:{content:_(t.bytes),encoding:`base64`}});s.push({path:t.path,mode:`100644`,type:`blob`,sha:e.sha})}else s.push({path:t.path,mode:`100644`,type:`blob`,content:t.content});if(s.length===0)return{revision:r};let c=await S(this.api,`${o}/git/commits/${r}`),l=await S(this.api,`${o}/git/trees`,{method:`POST`,body:{base_tree:c.tree.sha,tree:s}}),u=await S(this.api,`${o}/git/commits`,{method:`POST`,body:{message:n,tree:l.sha,parents:[r],author:{...i,date:new Date().toISOString()}}});if((await x(this.api,`${o}/git/refs/heads/${encodeURIComponent(this.branch)}`,{method:`PATCH`,body:{sha:u.sha,force:!1},allow:[422]})).status===422)throw await this.revision()===r?new y(422,`GitHub couldn't save the changes.`):new t;return this.pinned=u.sha,{revision:u.sha}}catch(e){throw e instanceof y&&(e.status===403||e.status===404)?new g(`cant-publish`,`This sign-in can't publish to the site.`):e}}async writeGraphQL(e,{message:n,expectedRevision:r}){let i=await this.tree(r),a=e.flatMap(e=>`delete`in e?[]:[{path:e.path,contents:`bytes`in e?_(e.bytes):m(e.content)}]),o=e.flatMap(e=>`delete`in e&&i.has(e.path)?[{path:e.path}]:[]);if(a.length===0&&o.length===0)return{revision:r};let s=await S(this.api,`/graphql`,{method:`POST`,body:{query:me,variables:{input:{branch:{repositoryNameWithOwner:decodeURIComponent(this.repo),branchName:this.branch},message:{headline:n},expectedHeadOid:r,fileChanges:{additions:a,deletions:o}}}}}),c=s.data?.createCommitOnBranch?.commit?.oid;if(c)return this.pinned=c,{revision:c};if(await this.revision()!==r)throw new t;let l=s.errors?.[0];throw l?.type===`FORBIDDEN`?new g(`cant-publish`,`This GitHub account can't publish to the site.`):new y(422,`GitHub couldn't save the changes: ${l?.message??`unknown error`}`)}async history(e,{page:t=1,perPage:n=20}={}){let r=new URLSearchParams({sha:this.pinned??await this.revision(),path:e,per_page:String(n),page:String(t)});return(await S(this.api,`/repos/${this.repo}/commits?${r}`)).map(e=>({revision:e.sha,date:e.commit.author?.date??``,author:e.commit.author?.name||e.author?.login||void 0,message:e.commit.message.split(`
|
|
5
|
-
`)[0]??``}))}async readAt(e,t){return this.readFrom(await this.tree(t),e)}async changedPaths(e,t){let n=await S(this.api,`/repos/${this.repo}/compare/${e}...${t}`);return[...new Set((n.files??[]).flatMap(e=>[e.filename,e.previous_filename??[]].flat()))]}async deployStatus(e){try{let t=(await S(this.api,`/repos/${this.repo}/deployments?sha=${e}&per_page=5`))[0];if(t){let[n]=await S(this.api,`/repos/${this.repo}/deployments/${t.id}/statuses?per_page=1`),r=n?.log_url||n?.target_url||void 0;switch(n?.state){case`success`:case`inactive`:return{state:`live`,detailsUrl:r};case`failure`:case`error`:{let t=await this.workflowRun(e);return{state:`failed`,detailsUrl:r,problem:t?await this.runProblem(t):{step:`deploy`}}}default:return{state:`building`,detailsUrl:r}}}let n=await this.cloudflareBuild(e);if(n)return n;let r=await this.workflowRun(e);if(r?.status===`completed`&&r.conclusion===`cancelled`){let t=await this.head();if(t!==e)return this.deployStatus(t)}if(r?.status===`completed`&&r.conclusion!==`success`&&r.conclusion!==`skipped`)return{state:`failed`,detailsUrl:r.html_url,problem:await this.runProblem(r)};if(r)return{state:`building`,detailsUrl:r.html_url};if((await S(this.api,`/repos/${this.repo}/deployments?per_page=1`)).length>0)return{state:`building`};let i=await this.parentOf(e);return{state:i&&await this.cloudflareBuild(i)?`building`:`unknown`}}catch(e){if(e instanceof y)return{state:`unknown`};throw e}}async cloudflareBuild(e){let t=await x(this.api,`/repos/${this.repo}/commits/${e}/check-runs?per_page=50`,{allow:[403,404]});if(t.ok){let{check_runs:e=[]}=await t.json(),n=e.find(e=>P.test(`${e.app?.slug??``} ${e.name}`));if(n){let e=n.details_url??n.html_url??void 0;return n.status===`completed`?n.conclusion===`success`||n.conclusion===`neutral`||n.conclusion===`skipped`?{state:`live`,detailsUrl:e}:{state:`failed`,detailsUrl:e,problem:{step:`build`,detail:n.output?.title??void 0}}:{state:`building`,detailsUrl:e}}}let n=await x(this.api,`/repos/${this.repo}/commits/${e}/statuses?per_page=50`,{allow:[403,404]});if(!n.ok)return;let r=(await n.json()).find(e=>P.test(e.context));if(!r)return;let i=r.target_url??void 0;return r.state===`success`?{state:`live`,detailsUrl:i}:r.state===`pending`?{state:`building`,detailsUrl:i}:{state:`failed`,detailsUrl:i,problem:{step:`build`,detail:r.description??void 0}}}async parentOf(e){let t=await x(this.api,`/repos/${this.repo}/commits/${e}`,{allow:[403,404,422]});if(t.ok)return(await t.json()).parents?.[0]?.sha}async workflowRun(e){let t=await x(this.api,`/repos/${this.repo}/actions/runs?head_sha=${e}&per_page=20`,{allow:[403,404]});if(!t.ok)return;let{workflow_runs:n=[]}=await t.json(),r=n.filter(e=>!e.path?.endsWith(`/${s}.yml`));return r.find(e=>/deploy|pages/i.test(`${e.path??``} ${e.name??``}`))??r[0]}async runProblem(e){let t=await x(this.api,`/repos/${this.repo}/actions/runs/${e.id}/jobs?per_page=50`,{allow:[403,404]}),n=(t.ok?(await t.json()).jobs??[]:[]).find(e=>e.conclusion===`failure`);if(!n)return{step:e.conclusion===`startup_failure`?`not-started`:`host`,detail:e.conclusion??void 0};let r=n.steps?.find(e=>e.conclusion===`failure`);return r?{step:u(r.name)??(/deploy/i.test(n.name)?`deploy`:`build`),detail:`${n.name}: ${r.name}`}:{step:`not-started`,detail:n.name}}signOut(){this.ownerAccess.forget(),this.onSignOut()}},R={invalid:`invalid`,"no-access":`no-access`,"cant-publish":`cant-publish`,cancelled:`redirect-failed`,"not-installed":`not-installed`,"no-address":`no-address`,"wrong-address":`wrong-address`,"local-address":`local-address`,"not-owner":`not-owner`};function z(e){let t=R[String(e.problem)]??`unavailable`,n=typeof e.installUrl==`string`&&/^https:\/\//.test(e.installUrl)?e.installUrl:void 0;return new g(t,`The sign-in service said: ${String(e.problem??`no answer`)}.`,n)}function B(e){let t;try{t=new URL(e).hostname.toLowerCase()}catch{return!0}return t===`localhost`||t.endsWith(`.localhost`)||t===`0.0.0.0`||t===`[::1]`||/^127(\.\d{1,3}){3}$/.test(t)}function V(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}async function H(){let e=V(crypto.getRandomValues(new Uint8Array(32))),t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return{verifier:e,challenge:V(new Uint8Array(t))}}function U(){if(typeof window<`u`)return{href:()=>window.location.href,assign:e=>window.location.assign(e),replace:e=>window.history.replaceState(window.history.state,``,e)}}var W=`goodfellow_sign_in`,G=`goodfellow_sign_in_error`,K=class{url;fetcher;constructor(e,t){this.url=e.replace(/\/$/,``),this.fetcher=t}async answer(e,t){let n;try{n=await this.fetcher(`${this.url}${e}`,t)}catch(e){throw new g(`unavailable`,`Couldn't reach the sign-in service: ${e.message}`)}let r=await n.json().catch(()=>({}));if(!n.ok)throw z(r);return r}post(e,t){return this.answer(e,{method:`POST`,headers:{"content-type":`text/plain`},body:JSON.stringify(t)})}async postAnswer(e,t){let n;try{n=await this.fetcher(`${this.url}${e}`,{method:`POST`,headers:{"content-type":`text/plain`},body:JSON.stringify(t)})}catch(e){throw new g(`unavailable`,`Couldn't reach the sign-in service: ${e.message}`)}return{ok:n.ok,body:await n.json().catch(()=>({}))}}async health(){if((await this.answer(`/health`)).ok!==!0)throw new g(`unavailable`,`The sign-in service isn't set up.`)}async check(e,t){await this.answer(`/github/check?${new URLSearchParams({repo:e,purpose:t})}`)}startUrl(e){let t=new URLSearchParams({purpose:e.purpose,...e.repo&&{repo:e.repo},return:e.back,challenge:e.challenge,remember:e.remember?`1`:`0`,...e.install&&{install:`1`}});return`${this.url}/github/start?${t}`}session(e,t,n){return this.post(`/github/session`,{grant:e,verifier:t,...n&&{code:n}})}token(e,t){return this.post(`/github/token`,{session:e,...t&&{code:t}})}};function q(e,t,n,r){let i=t,a;async function o({refresh:t=!1}={}){return(t||Date.parse(i.expiresAt)-3e5<Date.now())&&(a??=e.token(i.session,r).finally(()=>{a=void 0}),i=await a,n(i)),i.token}return{current:()=>i,token:o,async codeToken(e){if(await o(e),!i.code)throw new g(`no-access`,`The sign-in service gave no token for the code repository.`);return i.code.token}}}var J=`main`;function Y(e=`https://github.com`){let t=new URLSearchParams({name:`Goodfellow site setup`,description:`Create a Goodfellow site. It can be deleted once the site is created.`,expires_in:`7`,administration:`write`,contents:`write`,workflows:`write`,pages:`write`,secrets:`write`}),n=new URLSearchParams({scopes:`repo,workflow`,description:`Goodfellow site setup`});return{fineGrained:`${e}/settings/personal-access-tokens/new?${t}`,classic:`${e}/settings/tokens/new?${n}`}}function X(e){let t=new Map;async function n(e,t){if(t.default_branch===J)return;let n=`/repos/${C(t.full_name)}`,r=await S(e,`${n}/git/ref/heads/${t.default_branch}`);await x(e,`${n}/git/refs`,{method:`POST`,body:{ref:`refs/heads/${J}`,sha:r.object.sha}}),await x(e,n,{method:`PATCH`,body:{default_branch:J}}),await x(e,`${n}/git/refs/heads/${t.default_branch}`,{method:`DELETE`})}async function r(e,t){try{return(await S(e,`/repos/${C(t.full_name)}/pages`,{method:`POST`,body:{build_type:`workflow`}})).html_url}catch(e){if(e instanceof y&&[403,404,409,422].includes(e.status))return;throw e}}async function i(e,t,n){try{return await x(e,`/repos/${C(t.full_name)}/pages`,{method:`PUT`,body:{cname:n}}),!0}catch(e){if(e instanceof y&&[400,403,404,409,422].includes(e.status))return!1;throw e}}async function a(t,n,r){let i=`/repos/${C(n.full_name)}`,a=[];for(let e of r.files){if(`delete`in e)continue;if(`content`in e){a.push({path:e.path,mode:`100644`,type:`blob`,content:e.content});continue}let n=await S(t,`${i}/git/blobs`,{method:`POST`,body:{content:_(e.bytes),encoding:`base64`}});a.push({path:e.path,mode:`100644`,type:`blob`,sha:n.sha})}try{let n=await S(t,`${i}/git/trees`,{method:`POST`,body:{tree:a}}),o=await S(t,`${i}/git/commits`,{method:`POST`,body:{message:r.message,tree:n.sha,parents:[],...e.author&&{author:{...e.author,date:new Date().toISOString()}}}});await x(t,`${i}/git/refs/heads/${J}`,{method:`PATCH`,body:{sha:o.sha,force:!0}})}catch(e){throw e instanceof y&&(e.status===403||e.status===404)?new f(`not-allowed`,`This sign-in can't write the site's files, or its build setup.`):e}}async function o(e,t){return(await x(e,`/repos/${C(t.full_name)}/rulesets`,{method:`POST`,body:{name:`Protect the published history`,target:`branch`,enforcement:`active`,conditions:{ref_name:{include:[`~DEFAULT_BRANCH`],exclude:[]}},rules:[{type:`non_fast_forward`},{type:`deletion`}]},allow:[403,404,422]})).ok}async function s(e){if(!e.private)return!0;let{newDeployKey:n,sealSecret:r}=await b(()=>import(`./deploy-keys-DAj2oX-N-DRd_HmOG.js`).then(e=>e.t),__vite__mapDeps([0,1]),import.meta.url);try{for(let{reader:i,read:a,secret:o}of e.links.reads){if(!o)continue;let s=e[i],c=e[a],l=t.get(s.toLowerCase()),u=t.get(c.toLowerCase());if(!l||!u)throw Error(`${s} and ${c} have to be created first.`);let d=await n(`goodfellow-${o.toLowerCase()}`);await x(u,`/repos/${C(c)}/keys`,{method:`POST`,body:{title:`${s}'s builds`,key:d.publicKey,read_only:!0}});let f=`/repos/${C(s)}/actions/secrets`,p=await S(l,`${f}/public-key`),m=await r(d.privateKey,h(p.key));await x(l,`${f}/${o}`,{method:`PUT`,body:{encrypted_value:_(m),key_id:p.key_id}})}return!0}catch(e){if(e instanceof y&&[403,404,422].includes(e.status))return!1;throw e}}return{user:e.user,owners:()=>e.owners(),isAvailable:(t,n)=>e.isAvailable(t,n),async createSite(c,l){let u=[];l?.(`repository`);let{repo:d,api:f,signInInstallUrl:p}=await e.create(c),m=async e=>(l?.(`connect`),s(e));await n(f,d);let h;return c.pages&&(l?.(`pages`),h=await r(f,d),h?c.domain&&(await i(f,d,c.domain)?h=`https://${c.domain}/`:u.push(`domain-unavailable`)):u.push(`pages-unavailable`)),t.set(d.full_name.toLowerCase(),f),c.link&&!await m(c.link)&&u.push(`connect-unavailable`),l?.(`files`),await a(f,d,c),l?.(`protection`),await o(f,d)||u.push(`protection-unavailable`),p&&u.push(`sign-in-not-installed`),{repo:d.full_name,webUrl:d.html_url,siteUrl:h,buildsUrl:`${d.html_url}/actions`,pagesUrl:c.pages?`${d.html_url}/settings/pages`:void 0,...p&&{signInInstallUrl:p},warnings:u}}}}async function he(e){let t=await S(e,`/user`);async function n(t,n){return(await x(e,`/repos/${C(`${t.path}/${n}`)}`,{allow:[404]})).status===404}return{user:{login:t.login,name:t.name??void 0,avatarUrl:t.avatar_url},async owners(){return[{path:t.login,name:t.name||t.login,kind:`personal`},...(await S(e,`/user/orgs?per_page=100`).catch(()=>[])).map(e=>({path:e.login,name:e.login,kind:`organization`}))]},isAvailable:n,async create(t){let r=t.owner.kind===`personal`?`/user/repos`:`/orgs/${encodeURIComponent(t.owner.path)}/repos`;if(!await n(t.owner,t.name))throw new f(`name-taken`,`There's already a repository called ${t.owner.path}/${t.name}.`);try{return{repo:await S(e,r,{method:`POST`,body:{name:t.name,private:t.private,description:t.description,auto_init:!0}}),api:e}}catch(e){throw e instanceof y&&e.status===422?new f(`name-invalid`,`GitHub can't use "${t.name}" as a repository name.`):e instanceof y&&(e.status===403||e.status===404)?new f(`not-allowed`,`This sign-in can't create repositories in ${t.owner.path}.`):e}}}}function ge(e,t,n,r){let i=r.session;async function a(t,n){let r=await e.postAnswer(t,{session:i,...n});if(typeof r.body.session==`string`&&(i=r.body.session),!r.ok)throw _e(r.body);return r.body}let{user:o}=r;return{user:{login:o.login,name:o.name,avatarUrl:o.avatarUrl},author:{name:o.name||o.login,email:o.email},async owners(){let e=await a(`/github/setup/owners`,{});return(e.owners??[]).map(({installed:t,...n})=>({...n,...!t&&e.installUrl&&{installUrl:e.installUrl}}))},async isAvailable(e,t){return(await a(`/github/setup/available`,{owner:e.path,name:t})).available===!0},async create(e){if(e.owner.installUrl)throw new f(`not-installed`,`Goodfellow isn't installed on ${e.owner.path}.`,e.owner.installUrl);let r=await a(`/github/setup/repository`,{owner:e.owner.path,name:e.name,private:e.private,description:e.description,...e.more&&{more:!0}});if(!r.repo||!r.token)throw new g(`unavailable`,`The sign-in service didn't answer.`);return{repo:r.repo,api:{apiUrl:t,token:r.token,fetch:n},...r.editInstallUrl&&{signInInstallUrl:r.editInstallUrl}}}}}function _e(e){switch(e.problem){case`name-taken`:return new f(`name-taken`,`There's already a repository with that name.`);case`name-invalid`:return new f(`name-invalid`,`GitHub can't use that as a repository name.`);case`not-allowed`:return new f(`not-allowed`,`This sign-in can't create repositories there.`);case`not-installed`:return new f(`not-installed`,`Goodfellow isn't installed there.`,e.installUrl);default:return z(e)}}function Z(e={}){let t=(e.apiUrl??`https://api.github.com`).replace(/\/$/,``),n=Y(e.webUrl),r=e.fetch??((e,t)=>globalThis.fetch(e,t)),i=e.location??U(),a=e.signIn,o=a&&i&&!B(i.href())?new K(a,r):void 0,s=v(`goodfellow:github:setup:pending`,e.storage);return{name:`GitHub`,canRedirect:o!==void 0,tokenLinks:[{url:n.fineGrained,label:`signIn.token.create`},{url:n.classic,label:`signIn.token.createBroad`,hint:`signIn.token.createBroadHint`}],async restore(){if(!i)return null;let e=new URL(i.href()),n=e.searchParams.get(W),a=e.searchParams.get(G);if(!n&&!a)return null;e.searchParams.delete(W),e.searchParams.delete(G),i.replace(e.toString());let c=s.load();if(s.clear(),a||!n||!c||!o)throw z({problem:a??`cancelled`});let l=await o.session(n,c);return X(ge(o,t,r,l))},async signInWithToken(e){let n=e.trim();if(!n)throw new g(`invalid`,`Paste a token to sign in.`);return X(await he({apiUrl:t,token:n,fetch:r}))},async startRedirect({install:e}={}){if(!o||!i)throw new g(`unavailable`,`Signing in with GitHub isn't available here.`);await o.health();let{verifier:t,challenge:n}=await H();s.save(t,!1),i.assign(o.startUrl({purpose:`setup`,back:i.href(),challenge:n,remember:!1,install:e}))}}}function Q(e){return e instanceof g&&e.problem!==`unavailable`}function $(e,t=`https://github.com`){let[n=``]=e.split(`/`),r=new URLSearchParams({name:`Goodfellow admin`,description:`Edit ${e} in its admin panel`,target_name:n,expires_in:`90`,contents:`write`,deployments:`read`,actions:`read`,statuses:`read`}),i=new URLSearchParams({scopes:`repo`,description:`Goodfellow admin for ${e}`}),a=new URLSearchParams({name:`Goodfellow owner`,description:`Manage the editors, domain and updates of ${e}`,target_name:n,expires_in:`1`,administration:`write`,pages:`write`,actions:`write`,variables:`write`});return{fineGrained:`${t}/settings/personal-access-tokens/new?${r}`,classic:`${t}/settings/tokens/new?${i}`,owner:`${t}/settings/personal-access-tokens/new?${a}`}}function ve(e){if(!/^[\w.-]+\/[\w.-]+$/.test(e.repo))throw Error(`github({ repo }) must look like "owner/name" (got "${e.repo}").`);if(e.code!==void 0&&!/^[\w.-]+\/[\w.-]+$/.test(e.code))throw Error(`github({ code }) must look like "owner/name" (got "${e.code}").`);let t=(e.apiUrl??`https://api.github.com`).replace(/\/$/,``),n=(e.webUrl??`https://github.com`).replace(/\/$/,``),r=t=>e.contentOnly&&e.code?{code:{repo:e.code,webUrl:n,...t&&{api:t}}}:{},i=$(e.repo,e.webUrl),a=v(`goodfellow:github:${e.repo}`,e.storage),o=v(`goodfellow:github:pending:${e.repo}`,e.storage),s=e.fetch??((e,t)=>globalThis.fetch(e,t)),c=e.location??U(),l=e.signIn,u=l&&c&&!B(c.href())?new K(l,s):void 0,d=()=>e.contentOnly?e.code:void 0;function f(e,t){a.save(e.type===`token`?e.token:JSON.stringify(e),t)}function p(){let e=a.load();if(e){try{let t=JSON.parse(e);if(t.type===`worker`||t.type===`token`)return t}catch{}return{type:`token`,token:e}}}async function m(t,n,{install:r}={}){if(!u||!c)throw new g(`unavailable`,`Signing in with GitHub isn't available here.`);r||await u.check(e.repo,t);let{verifier:i,challenge:a}=await H();o.save(JSON.stringify({verifier:i,purpose:t,remember:n}),!1),c.assign(u.startUrl({purpose:t,repo:e.repo,back:c.href(),challenge:a,remember:n,install:r}))}async function h(n,o){let c=q(u,n,e=>f({type:`worker`,session:e.session},o),e.code);f({type:`worker`,session:n.session},o);let l={apiUrl:t,token:c.token,fetch:s},d=await S(l,`/repos/${C(e.repo)}`),{user:p}=n;return new L({api:l,repo:e.repo,branch:e.branch??d.default_branch,...e.contentOnly&&{contentOnly:!0},...r({apiUrl:t,token:c.codeToken,fetch:s}),user:{login:p.login,name:p.name,avatarUrl:p.avatarUrl},author:{name:p.name||p.login,email:p.email},onSignOut:()=>{a.clear(),b(c.current())},ownerTokenLink:{url:i.owner,label:`owner.token.create`},ownerRedirect:e=>m(`owner`,!1,e)})}function _(e){x({apiUrl:t,token:e,fetch:s},`/installation/token`,{method:`DELETE`}).catch(()=>{})}function b(e){_(e.token),e.code&&_(e.code.token)}async function w(e,t,n){let r=u;try{let i=q(r,await r.session(t,n,d()),()=>{},d());e.useOwnerSignIn(i.token,()=>b(i.current()),d()?i.codeToken:void 0)}catch(t){e.ownerSignInFailed(t)}}async function T(){if(!c)return;let e=new URL(c.href()),t=e.searchParams.get(W),n=e.searchParams.get(G);if(!t&&!n)return;e.searchParams.delete(W),e.searchParams.delete(G),c.replace(e.toString());let r=o.load();o.clear();let i=r?JSON.parse(r):void 0;if(!i||!u)throw new g(`redirect-failed`,`Signing in with GitHub didn't finish in this tab.`);if(i.purpose===`owner`){let e=await E();if(!e)throw new g(`redirect-failed`,`Sign in again, then sign in as an owner.`);return n?e.ownerSignInFailed(z({problem:n})):t&&await w(e,t,i.verifier),e}if(n||!t)throw z({problem:n});return h(await u.session(t,i.verifier,d()),i.remember)}async function E(){let e=p();if(!e)return null;try{return e.type===`token`?await D(e.token):u?await h(await u.token(e.session,d()),a.remembered()):(a.clear(),null)}catch(e){throw Q(e)&&a.clear(),e}}async function D(n){let o={apiUrl:t,token:n,fetch:s},c=await S(o,`/user`),l;try{l=await S(o,`/repos/${C(e.repo)}`)}catch(t){throw t instanceof y&&(t.status===404||t.status===403)?new g(`no-access`,`The GitHub account ${c.login} can't see ${e.repo}.`):t}if(l.permissions?.push===!1)throw new g(`cant-publish`,`The GitHub account ${c.login} can see ${e.repo} but can't publish to it.`);return new L({api:o,repo:e.repo,branch:e.branch??l.default_branch,...e.contentOnly&&{contentOnly:!0},...r(o),user:{login:c.login,name:c.name??void 0,avatarUrl:c.avatar_url},onSignOut:()=>a.clear(),ownerTokenLink:{url:i.owner,label:`owner.token.create`},...u&&{ownerRedirect:e=>m(`owner`,!1,e)}})}function O({token:n}){let r={apiUrl:t,token:typeof n==`string`?n:()=>n(),fetch:s},a,o=()=>(a??=e.branch?Promise.resolve(e.branch):S(r,`/repos/${C(e.repo)}`).then(e=>e.default_branch),a.catch(()=>{a=void 0}),a),c=async(t,n)=>new L({api:r,repo:e.repo,branch:await o(),...e.contentOnly&&{contentOnly:!0},user:{login:n?.name??e.repo,...n&&{name:n.name}},onSignOut:()=>{},ownerTokenLink:{url:i.owner,label:`owner.token.create`},...t&&{revision:t},...n&&{author:n}});return{...e.contentOnly&&{contentOnly:!0},async revision(){return(await c()).revision()},at:c}}return{name:`GitHub`,source:ee(`@goodfellow-cms/github`,`github`,e,[`fetch`,`storage`,`location`]),canRedirect:u!==void 0,setup:()=>Z({...e.apiUrl&&{apiUrl:e.apiUrl},...e.webUrl&&{webUrl:e.webUrl},...e.fetch&&{fetch:e.fetch},...e.storage&&{storage:e.storage},...e.location&&{location:e.location},signIn:!1}),tokenLinks:[{url:i.fineGrained,label:`signIn.token.create`},{url:i.classic,label:`signIn.token.createBroad`,hint:`signIn.token.createBroadHint`}],async restore(){let e=await T();return e===void 0?E():e},async signInWithToken(e,t){let n=e.trim();if(!n)throw new g(`invalid`,`Paste a token to sign in.`);let r=await D(n);return f({type:`token`,token:n},t),r},startRedirect(e,t){return m(`edit`,e,t)},server:O}}export{L as GitHubBackend,ve as github,j as githubPagesRecords,Z as githubSetup,Y as githubSetupTokenLinks,$ as githubTokenLinks};
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import{n as e,r as t,t as n}from"./store-5raQS3us.js";import{a as r,c as i,d as a,f as o,i as s,m as c,o as l,p as u,r as d,t as f}from"./setup-host-w4Qxug91.js";import{n as p,o as m,r as h,s as ee,t as g}from"./git-eGyMXUIu.js";var te=class extends Error{problem;name=`ScheduledBuildsError`;constructor(e,t){super(t),this.problem=e}};async function _(e,t,n={}){let r=async r=>e.fetch(`${e.apiUrl}${t}`,{method:n.method??`GET`,headers:{authorization:`Bearer ${await e.token({refresh:r})}`,...n.body!==void 0&&{"content-type":`application/json`}},body:n.body===void 0?void 0:JSON.stringify(n.body),cache:`no-store`}),i=await r(!1);if(i.status===401&&e.canRefresh&&(i=await r(!0)),i.status===401)throw new p(`invalid`,`GitLab didn't accept the sign-in. It may have expired.`);if(!i.ok&&!n.allow?.includes(i.status)){let e=await i.json().catch(()=>({})),t=typeof e.message==`string`?e.message:JSON.stringify(e.message??e.error??``);throw new g(i.status,`GitLab answered ${i.status}: ${t||i.statusText}`)}return i}async function v(e,t,n){return await(await _(e,t,n)).json()}var y=30,b=40,ne=`member:`,x=`invitation:`,S=/^[^\s@]+@[^\s@]+\.[^\s@]+$/,C=/^[\w][\w.-]*$/;function w(e){return e>=b?`owner`:e>=y?`editor`:`viewer`}function T(e){return e===`owner`?b:y}function E(e){throw e instanceof g&&(e.status===401||e.status===403)?new a(`not-allowed`,`Changing editors on GitLab needs the Maintainer role in the project.`):e}function re(e,t,n,r){let i=`/projects/${encodeURIComponent(t)}`,o=`${i}/protected_branches/${encodeURIComponent(n)}`;async function s(t){let n=[];for(let r=1;r<=10;r++){let i=await v(e,`${t}${t.includes(`?`)?`&`:`?`}per_page=100&page=${r}`);if(n.push(...i),i.length<100)break}return n}return{invitesByEmail:!0,async list(){let[t,n]=await Promise.all([s(`${i}/members/all`),s(`${i}/members`)]),a=new Set(n.map(e=>e.id)),c=t.find(e=>e.username.toLowerCase()===r.toLowerCase()),l=(c?.access_level??0)>=b,u=l?await s(`${i}/invitations`).catch(()=>[]):[],d=await _(e,o,{allow:[404]}),f=d.ok?(await d.json()).push_access_levels??[]:[],p=!d.ok||f.some(e=>e.access_level!==null&&e.access_level<=y);return{editors:[...t.map(e=>({id:`${ne}${e.id}`,login:e.username,name:e.name,avatarUrl:e.avatar_url,role:w(e.access_level),...!a.has(e.id)&&{inherited:!0},...e.id===c?.id&&{self:!0}})),...u.map(e=>({id:`${x}${e.invite_email}`,email:e.invite_email,role:w(e.access_level),invited:!0}))],manage:l?`yes`:`no`,editorsCanPublish:p}},async invite(t,n){let r=t.trim().replace(/^@/,``);if(r.includes(`@`)){if(!S.test(r))throw new a(`invalid`,`That isn't an email address.`);let t=await v(e,`${i}/invitations`,{method:`POST`,body:{email:r,access_level:T(n)}}).catch(E);if(t.status!==`success`){let e=typeof t.message==`string`?t.message:Object.values(t.message??{})[0];throw/already/i.test(e??``)?new a(`already`,`They've already been invited.`):new a(`invalid`,`GitLab didn't accept the invitation: ${e??t.status}`)}return}if(!C.test(r))throw new a(`invalid`,`That isn't a GitLab username or email address.`);let[o]=await v(e,`/users?${new URLSearchParams({username:r})}`);if(!o)throw new a(`not-found`,`There's no GitLab account named ${r}.`);try{await _(e,`${i}/members`,{method:`POST`,body:{user_id:o.id,access_level:T(n)}})}catch(e){if(e instanceof g&&e.status===409)throw new a(`already`,`${r} already edits the site.`);E(e)}},async setRole(t,n){await _(e,t.id.startsWith(x)?`${i}/invitations/${encodeURIComponent(t.id.slice(11))}`:`${i}/members/${t.id.slice(7)}`,{method:`PUT`,body:{access_level:T(n)}}).catch(E)},async remove(t){await _(e,t.id.startsWith(x)?`${i}/invitations/${encodeURIComponent(t.id.slice(11))}`:`${i}/members/${t.id.slice(7)}`,{method:`DELETE`}).catch(E)},async letEditorsPublish(){let t=t=>_(e,`${i}/protected_branches`,{method:`POST`,body:{name:n,push_access_level:t,merge_access_level:t,allow_force_push:!1}});await _(e,o,{method:`DELETE`,allow:[404]}).catch(E);try{await t(y)}catch(e){await t(b).catch(()=>void 0),E(e)}}}}var ie=`35.185.44.232`,D=`2600:1901:0:7b8a::`;function O(e,{apex:t,www:n}){return t&&n?[e,`www.${e}`]:[e]}function k(e,t,n,r){let i=`${(e.split(`/`)[0]??``).toLowerCase()}.gitlab.io`,a=n.apex?[{type:`A`,name:t,value:ie,purpose:`site`},{type:`AAAA`,name:t,value:D,purpose:`site`,optional:!0}]:[{type:`CNAME`,name:t,value:i,purpose:`site`}],o=n.apex&&n.www?[{type:`CNAME`,name:`www.${t}`,value:i,purpose:`www`,optional:!0}]:[],s=O(t,n).flatMap(e=>{let n=r[e];if(!n)return[];let i=n.startsWith(`gitlab-pages-verification-code=`)?n:`gitlab-pages-verification-code=${n}`;return[{type:`TXT`,name:`_gitlab-pages-verification-code.${e}`,value:i,purpose:`verification`,optional:e!==t}]});return[...a,...o,...s]}function A(e,t){let n=`/projects/${encodeURIComponent(t)}/pages`,r=e=>`${n}/domains/${encodeURIComponent(e)}`;function i(e){throw e instanceof g&&(e.status===401||e.status===403)?new c(`not-allowed`,`Connecting a domain on GitLab needs the Maintainer role in the project.`):e}async function a(){let t=await _(e,n,{allow:[404]}).catch(i);return t.ok?await t.json():void 0}async function o(t){let n=await Promise.all(t.map(async t=>{let n=await _(e,r(t),{allow:[404]});return n.ok?[t,(await n.json()).verification_code??``]:[t,``]}));return Object.fromEntries(n)}async function s(t){let n=await v(e,r(t)).catch(i);if(n.verified)return n;let a=await _(e,`${r(t)}/verify`,{method:`PUT`,allow:[400,404,422]});return a.ok?await a.json():n}return{severalDomains:!0,async site(){let t=await a();if(!t)return;let r=(await v(e,`${n}/domains`).catch(()=>[])).map(e=>e.domain),i=(t.primary_domain&&r.includes(t.primary_domain)?t.primary_domain:void 0)??r.sort((e,t)=>e.length-t.length)[0];return{url:t.url,domain:i}},async connect(s,l){let u=await a();u&&u.is_unique_domain_enabled===!1&&await _(e,n,{method:`PATCH`,body:{pages_unique_domain_enabled:!0}}).catch(i);for(let t of O(s,l))try{await _(e,`${n}/domains`,{method:`POST`,body:{domain:t,auto_ssl_enabled:!0}})}catch(n){if(n instanceof g&&n.status===400){if(/taken/i.test(n.message)){if((await _(e,r(t),{allow:[404]})).ok)continue;throw new c(`taken`,`Another GitLab Pages site already uses this domain.`)}throw new c(`invalid`,`GitLab Pages doesn't accept this domain.`)}i(n)}return k(t,s,l,await o(O(s,l)))},async records(e,n){return k(t,e,n,await o(O(e,n)))},async status(t){let n=await s(t),i=await _(e,r(`www.${t}`),{allow:[404]});i.ok&&!(await i.json()).verified&&await s(`www.${t}`);let o=await a();return{verified:n.verified,certificate:n.certificate&&!n.certificate.expired?`ready`:`pending`,httpsOnly:o?.force_https===!0,primary:o?.primary_domain===void 0||o.primary_domain===t}},async secure(t,{primary:a=!0}={}){let o=await v(e,r(t)).catch(i);if(!o.verified||!o.certificate)throw new c(`not-ready`,`The domain's certificate isn't ready yet.`);if(!a){await _(e,n,{method:`PATCH`,body:{pages_https_only:!0}}).catch(i);return}try{await _(e,n,{method:`PATCH`,body:{pages_https_only:!0,pages_primary_domain:t}})}catch(t){t instanceof g&&t.status===400||i(t),await _(e,n,{method:`PATCH`,body:{pages_https_only:!0}}).catch(i)}},async disconnect(t){for(let n of[t,`www.${t}`])await _(e,r(n),{method:`DELETE`,allow:[404]}).catch(i)}}}var j=`Goodfellow: build the site for a scheduled change at `,M=`GOODFELLOW_SCHEDULED_CHANGE`;function N(e){throw e instanceof g&&(e.status===401||e.status===403)?new te(`not-allowed`,`Adding pipeline schedules on GitLab needs the Developer role, with permission to merge to the main branch.`):e}function ae(e){return`${e.getUTCMinutes()} ${e.getUTCHours()} ${e.getUTCDate()} ${e.getUTCMonth()+1} *`}function oe(e){return`${e.toISOString().slice(0,16)}Z`}function se(e,t,n,r,i=()=>new Date){let a=`/projects/${encodeURIComponent(t)}/pipeline_schedules`;return{async timing(){return await r()===void 0?`none`:`exact`},async sync(t){let r=i(),o=new Map;for(let e of[...t].filter(e=>e>r).sort((e,t)=>e.getTime()-t.getTime())){if(o.size>=50)break;o.set(oe(e),e)}let s=await v(e,`${a}?per_page=100`).catch(N),c=new Map;for(let e of s)e.description?.startsWith(`Goodfellow: build the site for a scheduled change at `)&&c.set(e.description.slice(53),e);for(let[t,n]of c)o.has(t)||await _(e,`${a}/${n.id}`,{method:`DELETE`,allow:[403,404]});for(let[t,r]of o){if(c.has(t))continue;let i=await v(e,a,{method:`POST`,body:{description:`${j}${t}`,ref:n,cron:ae(r),cron_timezone:`UTC`,active:!0}}).catch(N);await _(e,`${a}/${i.id}/variables`,{method:`POST`,body:{key:M,value:t,variable_type:`env_var`}}).catch(N)}}}}var P=`.gitlab-ci.yml`,F=`17 4 * * *`;function I(e){throw e instanceof g&&(e.status===401||e.status===403)?new l(`not-allowed`,`Setting up updates on GitLab needs the Maintainer role in the project.`):e}function L(e,t,n,a,o=`pages`){let s=`/projects/${encodeURIComponent(t)}`;async function c(){return v(e,`${s}/pipeline_schedules`)}async function u(){return(await c()).find(e=>(e.ref===n||e.ref===`refs/heads/${n}`)&&!e.description?.startsWith(`Goodfellow: build the site for a scheduled change at `))}return{async setup(){if(!(await a(P))?.includes(`update --publish`))return`missing`;try{let[t,r]=await Promise.all([v(e,s),c()]),i=r.some(e=>(e.ref===n||e.ref===`refs/heads/${n}`)&&(e.active||!e.description?.startsWith(`Goodfellow: build the site for a scheduled change at `)));return t.ci_push_repository_for_job_token_allowed&&i?`ready`:`needs-setup`}catch(e){if(e instanceof g&&e.status===403)return`needs-setup`;throw e}},async enable(){await _(e,s,{method:`PUT`,body:{ci_push_repository_for_job_token_allowed:!0}}).catch(I),await u().catch(I)||await _(e,`${s}/pipeline_schedules`,{method:`POST`,body:{description:`Rebuild the site and install Goodfellow's fixes each night`,ref:n,cron:F,cron_timezone:`UTC`,active:!0}}).catch(I)},async lastRun(){let t=await v(e,`${s}/pipelines?${new URLSearchParams({ref:n,per_page:`20`})}`);for(let n of t){if(n.source!==`schedule`&&n.source!==`api`)continue;let t={date:n.created_at,detailsUrl:n.web_url};if([`created`,`pending`,`running`,`waiting_for_resource`,`preparing`].includes(n.status))return{state:`running`,...t};let r=(await v(e,`${s}/pipelines/${n.id}/jobs?per_page=100`)).find(e=>e.name===o||e.name===`update`);if(!r)continue;let a=await _(e,`${s}/jobs/${r.id}/trace`,{allow:[403,404]}),c=a.ok?i(await a.text()):void 0;if(c)return{state:c.state,result:c,...t}}},async start(t){await _(e,`${s}/pipeline`,{method:`POST`,body:{ref:n,variables:[{key:`GOODFELLOW_UPDATE`,variable_type:`env_var`,value:t}]}}).catch(I)},nightly:{async supported(){return(await a(P))?.includes(`nightly`)??!1},async get(){try{let t=await u();return t?t.active?(await v(e,`${s}/pipeline_schedules/${t.id}`)).variables?.find(e=>e.key===`GOODFELLOW_NIGHTLY`)?.value===`always`?`always`:`changed`:`off`:void 0}catch(e){if(e instanceof g&&e.status===403)return;throw e}},async set(t){let n=await u().catch(I);if(!n)throw new l(`missing`,`The site has no nightly schedule yet: turn on updates first.`);let i=`${s}/pipeline_schedules/${n.id}`;if(await _(e,i,{method:`PUT`,body:{active:t!==`off`}}).catch(I),t===`always`){let t={key:r,value:`always`};(await _(e,`${i}/variables/GOODFELLOW_NIGHTLY`,{method:`PUT`,body:t,allow:[404]}).catch(I)).status===404&&await _(e,`${i}/variables`,{method:`POST`,body:t}).catch(I)}else t===`changed`&&await _(e,`${i}/variables/${r}`,{method:`DELETE`,allow:[404]}).catch(I)}},async rebuild(){await _(e,`${s}/pipeline`,{method:`POST`,body:{ref:n,variables:[{key:`GOODFELLOW_REBUILD`,variable_type:`env_var`,value:`true`}]}}).catch(I)}}}function R(e){return e instanceof g&&(e.status===403||e.status===404)}function z(e){let{api:t,project:n}=e,r,i=()=>(r??=v(t,`/projects/${encodeURIComponent(n)}`).then(e=>e.default_branch),r.catch(()=>{r=void 0}),r),a=async()=>e.open(await i()),o=async e=>{let t=await a();return t.readAt(e,await t.revision())},s=async()=>L(t,n,await i(),o,`update`);return{code:{repo:n,webUrl:`${e.webUrl}/${n}`,read:o,history:async(e,t)=>(await a()).history(e,t),readAt:async(e,t)=>(await a()).readAt(e,t)},async setup(){try{return await(await s()).setup()}catch(e){if(R(e))return`no-access`;throw e}},async enable(){await(await s()).enable?.()},async lastRun(){try{return await(await s()).lastRun()}catch(e){if(R(e))return;throw e}},async start(e){await(await s()).start(e)},async rebuild(){await(await s()).rebuild?.()}}}var B=100,V=50,H=RegExp(`\x1B\\[[\\d;]*[A-Za-z]`,`g`);function U(e){return e.name!==`rebuild`&&e.name!==`update`}function W(e,t){let n=`${t}/`;return[...e.keys()].filter(e=>e.startsWith(n)).sort()}var G=class r{user;pages;editors;updates;drafts;scheduledBuilds;contentOnly;options;api;project;branch;onSignOut;pinned;trees=new Map;blobs=new Map;constructor(e){if(this.options=e,this.api=e.api,this.project=encodeURIComponent(e.project),this.branch=e.branch,this.user=e.user,this.onSignOut=e.onSignOut,this.pinned=e.revision,this.pages=A(this.api,e.project),this.editors=re(this.api,e.project,this.branch,this.user.login),this.contentOnly=e.contentOnly===!0,!this.contentOnly)this.updates=L(this.api,e.project,this.branch,async e=>this.readAt(e,this.pinned??await this.revision()));else if(e.code){let t=e.code;this.updates=z({api:this.api,project:t.project,webUrl:t.webUrl,open:e=>new r({api:this.api,project:t.project,branch:e,user:this.user,onSignOut:()=>{}})})}this.drafts=u(this,this.draftHost()),this.scheduledBuilds=se(this.api,e.project,this.branch,async()=>this.readAt(`.gitlab-ci.yml`,this.pinned??await this.revision()))}async repositoryVisibility(){let{visibility:e}=await v(this.api,`/projects/${this.project}`);return e===`public`||e===`internal`?e:`private`}draftHost(){let e=`/projects/${this.project}`;return{liveBranch:this.branch,branchStore:e=>new r({...this.options,branch:e}),createBranch:async(e,t)=>{if((await _(this.api,this.repo(`/branches?${new URLSearchParams({branch:e,ref:t})}`),{method:`POST`,allow:[400]})).status===400)throw new o(`exists`,`There's already a draft called ${e}.`)},deleteBranch:async e=>{await _(this.api,this.repo(`/branches/${encodeURIComponent(e)}`),{method:`DELETE`,allow:[404]})},mergeBase:async e=>{let t=new URLSearchParams;t.append(`refs[]`,this.branch),t.append(`refs[]`,e);let n=await _(this.api,this.repo(`/merge_base?${t}`),{allow:[400,404]});if(!n.ok)throw new o(`not-found`,`There's no draft ${e}.`);return(await n.json()).id},listBranches:async e=>{let t=new URLSearchParams({search:`^${e}`,per_page:`100`});return(await v(this.api,this.repo(`/branches?${t}`))).map(e=>e.name).filter(t=>t.startsWith(e))},openReview:async({branch:t,title:n,description:r})=>{let i=await _(this.api,`${e}/merge_requests`,{method:`POST`,body:{source_branch:t,target_branch:this.branch,title:n,description:r,remove_source_branch:!0},allow:[403,404,409]});if(i.ok)return{url:(await i.json()).web_url};if(i.status!==409)throw new o(`no-reviews`,`This sign-in can't open merge requests on the site's project.`);let a=new URLSearchParams({source_branch:t,state:`opened`}),[s]=await v(this.api,`${e}/merge_requests?${a}`);if(!s)throw new g(409,`GitLab couldn't open the merge request.`);return{url:s.web_url}}}}repo(e){return`/projects/${this.project}/repository${e}`}async revision(){return this.pinned=await this.head(),this.pinned}async head(){return(await v(this.api,this.repo(`/branches/${encodeURIComponent(this.branch)}`))).commit.id}async listFolder(e,t){let n=[];for(let r=1;;r++){let i=new URLSearchParams({ref:e,path:t,recursive:`true`,per_page:String(B),page:String(r)}),a=await _(this.api,this.repo(`/tree?${i}`),{allow:[404]});if(a.status===404)return n;let o=await a.json();for(let e of o)e.type===`blob`&&n.push([e.path,e.id]);if(o.length<B)return n}}tree(t){let n=this.trees.get(t);return n||(n=Promise.all(e.map(e=>this.listFolder(t,e))).then(e=>new Map(e.flat())),n.catch(()=>this.trees.delete(t)),this.trees.set(t,n)),n}async currentTree(){return this.tree(this.pinned??await this.revision())}async read(e){return this.readFrom(await this.currentTree(),e)}readFrom(e,t){let n=e.get(t);if(!n)return Promise.resolve(void 0);let r=this.blobs.get(n);return r||(r=_(this.api,this.repo(`/blobs/${n}/raw`)).then(e=>e.text()),r.catch(()=>this.blobs.delete(n)),this.blobs.set(n,r)),r}async readFiles(e){let t=this.pinned??await this.revision();return this.readFilesFrom(t,await this.tree(t),e)}async readFilesFrom(e,t,n){let r=n.filter(e=>t.has(e)),i=r.filter(e=>!this.blobs.has(t.get(e)??``));for(let n=0;n<i.length;n+=V){let r=i.slice(n,n+V),a=await v(this.api,`/../graphql`,{method:`POST`,body:{query:`query ($project: ID!, $ref: String!, $paths: [String!]!) {
|
|
2
|
-
project(fullPath: $project) { repository { blobs(ref: $ref, paths: $paths) { nodes { path rawTextBlob } } } }
|
|
3
|
-
}`,variables:{project:decodeURIComponent(this.project),ref:e,paths:r}}});for(let e of a.data?.project?.repository?.blobs?.nodes??[]){let n=t.get(e.path);n&&typeof e.rawTextBlob==`string`&&this.blobs.set(n,Promise.resolve(e.rawTextBlob))}}let a=new Map;for(let e of r){let n=await this.readFrom(t,e);n!==void 0&&a.set(e,n)}return a}async readBytes(e){return this.bytesFrom(await this.currentTree(),e)}async bytesFrom(e,t){let n=e.get(t);if(!n)return;let r=await _(this.api,this.repo(`/blobs/${n}/raw`));return new Uint8Array(await r.arrayBuffer())}async list(e){return W(await this.currentTree(),e)}filesAt(e){return{read:async t=>this.readFrom(await this.tree(e),t),readFiles:async t=>this.readFilesFrom(e,await this.tree(e),t),readBytes:async t=>this.bytesFrom(await this.tree(e),t),list:async t=>W(await this.tree(e),t)}}async fileSizes(e){let t=await this.list(e),n=this.pinned??await this.revision(),r=new Map;for(let e=0;e<t.length;e+=V){let i=await v(this.api,`/../graphql`,{method:`POST`,body:{query:`query ($project: ID!, $ref: String!, $paths: [String!]!) {
|
|
4
|
-
project(fullPath: $project) { repository { blobs(ref: $ref, paths: $paths) { nodes { path size } } } }
|
|
5
|
-
}`,variables:{project:decodeURIComponent(this.project),ref:n,paths:t.slice(e,e+V)}}});for(let e of i.data?.project?.repository?.blobs?.nodes??[]){let t=Number(e.size);Number.isFinite(t)&&r.set(e.path,t)}}return r}async lastCommitFor(e,t){return(await v(this.api,this.repo(`/files/${encodeURIComponent(e)}?ref=${t}`))).last_commit_id}async existsAt(t,n,r){return e.some(e=>n.startsWith(`${e}/`))?t.has(n):this.lastCommitFor(n,r).then(()=>!0,e=>{if(e instanceof g&&e.status===404)return!1;throw e})}async write(e,{message:r,expectedRevision:i}){if(this.contentOnly&&t(e),await this.revision()!==i)throw new n;let a=await this.tree(i),o=(await Promise.all(e.map(async e=>{let t=await this.existsAt(a,e.path,i);if(`delete`in e)return t?{action:`delete`,file_path:e.path,last_commit_id:await this.lastCommitFor(e.path,i)}:void 0;let n=`bytes`in e?{content:m(e.bytes),encoding:`base64`}:{content:e.content};return t?{action:`update`,file_path:e.path,...n,last_commit_id:await this.lastCommitFor(e.path,i)}:{action:`create`,file_path:e.path,...n}}))).filter(e=>e!==void 0);if(o.length===0)return{revision:i};try{let e=await v(this.api,this.repo(`/commits`),{method:`POST`,body:{branch:this.branch,commit_message:r,actions:o,...this.options.author&&{author_name:this.options.author.name,author_email:this.options.author.email}}});return this.pinned=e.id,{revision:e.id}}catch(e){throw e instanceof g?e.status===403?new p(`cant-publish`,`This GitLab account can't publish to the site.`):e.status===400&&/already exists|changed since/i.test(e.message)||await this.revision()!==i?new n:e:e}}async history(e,{page:t=1,perPage:n=20}={}){let r=new URLSearchParams({ref_name:this.pinned??await this.revision(),path:e,per_page:String(n),page:String(t)});return(await v(this.api,this.repo(`/commits?${r}`))).map(e=>({revision:e.id,date:e.authored_date??e.committed_date??``,author:e.author_name||void 0,message:e.title}))}async readAt(e,t){let n=await _(this.api,this.repo(`/files/${encodeURIComponent(e)}/raw?${new URLSearchParams({ref:t})}`),{allow:[404]});return n.ok?n.text():void 0}async changedPaths(e,t){let n=await v(this.api,this.repo(`/compare?${new URLSearchParams({from:e,to:t,straight:`true`})}`));return[...new Set((n.diffs??[]).flatMap(e=>[e.old_path,e.new_path]))]}async deployStatus(e){try{let t=await this.statuses(e),n=t.filter(U);if(t.length>0&&n.length===0)return{state:`unknown`};if(n.length===0){if((await v(this.api,`/projects/${this.project}/pipelines?per_page=1`)).length>0)return{state:`building`};let{parent_ids:t=[]}=await v(this.api,this.repo(`/commits/${e}`));return{state:(t[0]?(await this.statuses(t[0])).filter(U):[]).length>0?`building`:`unknown`}}let r=n.find(e=>e.status===`failed`)??n.find(e=>e.status===`canceled`);if(r?.status===`canceled`){let t=await this.head();if(t!==e)return this.deployStatus(t)}if(r){let t=await this.jobProblem(e).catch(()=>void 0);return{state:`failed`,detailsUrl:r.target_url??void 0,...t&&{problem:t}}}return n.every(e=>e.status===`success`||e.status===`skipped`)?{state:`live`,detailsUrl:n[0]?.target_url??void 0}:{state:`building`,detailsUrl:n[0]?.target_url??void 0}}catch(e){if(e instanceof g)return{state:`unknown`};throw e}}statuses(e){return v(this.api,this.repo(`/commits/${e}/statuses`))}async jobProblem(e){let[t]=await v(this.api,`/projects/${this.project}/pipelines?${new URLSearchParams({sha:e,per_page:`1`})}`);if(!t)return;let n=(await v(this.api,`/projects/${this.project}/pipelines/${t.id}/jobs?per_page=100`)).find(e=>e.status===`failed`);if(!n)return;let r=n.failure_reason??``,i=`${n.name}: ${r}`;if(r===`ci_quota_exceeded`)return{step:`not-started`,detail:i};if(/runner_system|stuck_or_timeout|scheduler|api_failure|data_integrity|job_execution_timeout/.test(r))return{step:`host`,detail:i};if(n.name===`pages:deploy`)return{step:`deploy`,detail:i};let a=await _(this.api,`/projects/${this.project}/jobs/${n.id}/trace`,{allow:[403,404]}),o=a.ok?await a.text():``,c=s(o),l=o.split(`
|
|
6
|
-
`).map(e=>e.replace(H,``).replace(/^.*\r/,``)).filter(e=>e.startsWith(`$ `)).at(-1);return{step:c?`build`:(l?d(l):void 0)??`build`,detail:i,...c&&{cause:c}}}signOut(){this.onSignOut()}};function K(e){let t=``;for(let n of e)t+=String.fromCharCode(n);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}function q(e=32){return K(crypto.getRandomValues(new Uint8Array(e)))}async function J(e){let t=await crypto.subtle.digest(`SHA-256`,new TextEncoder().encode(e));return K(new Uint8Array(t))}function Y(e,t,n=Date.now()){return{type:`oauth`,access:e.access_token,refresh:e.refresh_token,expiresAt:n+(e.expires_in??7200)*1e3,verifier:t}}function X(e){let t=new URL(e);return`${t.origin}${t.pathname.replace(/\/?$/,`/`)}`}var Z=`main`;function ce(){return{href:()=>window.location.href,assign:e=>window.location.assign(e),replace:e=>window.history.replaceState(window.history.state,``,e)}}function Q(e={}){let t=(e.url??`https://gitlab.com`).replace(/\/$/,``),n=`${t}/api/v4`,r=e.fetch??((e,t)=>globalThis.fetch(e,t)),i=h(`goodfellow:gitlab-setup:pending`,e.storage),a=()=>e.location??ce();async function o(e){let n=await r(`${t}/oauth/token`,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams(e)});if(!n.ok)throw new p(`invalid`,`GitLab didn't accept the sign-in (${n.status}).`);return await n.json()}async function s(t){let i=t,s={apiUrl:n,token:async({refresh:t}={})=>{if(i.type===`token`)return i.token;if(t||i.expiresAt-6e4<Date.now()){let{verifier:t}=i;i=Y(await o({client_id:e.clientId??``,refresh_token:i.refresh,grant_type:`refresh_token`,redirect_uri:X(a().href()),code_verifier:t}),t)}return i.access},canRefresh:i.type===`oauth`,fetch:r},c=await v(s,`/user`);async function l(e,t){return(await _(s,`/projects/${encodeURIComponent(`${e.path}/${t}`)}`,{allow:[404]})).status===404}async function u(e){let t=e=>`/projects/${encodeURIComponent(e)}`;try{let n=new Map;for(let r of[`code`,`content`])n.set(r,(await v(s,t(e[r]))).id);for(let{reader:r,read:i}of e.links.reads)await _(s,`${t(e[i])}/job_token_scope/allowlist`,{method:`POST`,body:{target_project_id:n.get(r)}});e.links.updates&&await _(s,t(e[e.links.updates]),{method:`PUT`,body:{ci_push_repository_for_job_token_allowed:!0}});for(let n of e.links.nightly)await _(s,`${t(e[n])}/pipeline_schedules`,{method:`POST`,body:{description:n===e.links.updates?`Rebuild the site and install Goodfellow's fixes each night`:`Rebuild the site each night`,ref:Z,cron:F,cron_timezone:`UTC`,active:!0}});return!0}catch(e){if(e instanceof g&&[400,403,404].includes(e.status))return!1;throw e}}return{user:{login:c.username,name:c.name,avatarUrl:c.avatar_url},async owners(){let e=(await v(s,`/namespaces?per_page=100`)).map(e=>({path:e.full_path,name:e.kind===`user`?c.name??e.name:e.name,kind:e.kind===`user`?`personal`:`organization`,id:e.id}));return[...e.filter(e=>e.kind===`personal`),...e.filter(e=>e.kind!==`personal`)]},isAvailable:l,async createSite(e,t){if(t?.(`repository`),!await l(e.owner,e.name))throw new f(`name-taken`,`There's already a project called ${e.owner.path}/${e.name}.`);let n;try{n=await v(s,`/projects`,{method:`POST`,body:{name:e.name,path:e.name,namespace_id:e.owner.id,visibility:e.private?`private`:`public`,description:e.description,...e.pages&&{pages_access_level:e.private?`public`:`enabled`}}})}catch(t){throw t instanceof g&&t.status===400?new f(`name-invalid`,`GitLab can't use "${e.name}" as a project name.`):t instanceof g&&(t.status===403||t.status===404)?new f(`not-allowed`,`This sign-in can't create projects in ${e.owner.path}.`):t}let r=[];e.link&&(t?.(`connect`),await u(e.link)||r.push(`connect-unavailable`));let i;if(e.pages&&e.domain){t?.(`pages`);try{await _(s,`/projects/${n.id}/pages/domains`,{method:`POST`,body:{domain:e.domain,auto_ssl_enabled:!0}}),i=`https://${e.domain}/`}catch(e){if(!(e instanceof g)||![400,403,404,409,422].includes(e.status))throw e;r.push(`domain-unavailable`)}}return t?.(`files`),await _(s,`/projects/${n.id}/repository/commits`,{method:`POST`,body:{branch:Z,commit_message:e.message,actions:e.files.flatMap(e=>`delete`in e?[]:`content`in e?[{action:`create`,file_path:e.path,content:e.content}]:[{action:`create`,file_path:e.path,content:m(e.bytes),encoding:`base64`}])}}),{repo:n.path_with_namespace,webUrl:n.web_url,...i&&{siteUrl:i},buildsUrl:`${n.web_url}/-/pipelines`,pagesUrl:e.pages?`${n.web_url}/pages`:void 0,warnings:r}}}}return{name:`GitLab`,canRedirect:!!e.clientId,tokenLinks:[{url:`${t}/-/user_settings/personal_access_tokens?${new URLSearchParams({name:`Goodfellow site setup`,scopes:`api`})}`,label:`signIn.token.create`}],async restore(){let t=new URL(a().href()),n=t.searchParams.get(`code`),r=t.searchParams.get(`error`);if(!n&&!r)return null;let c=i.load();if(!c)return null;i.clear();let l=JSON.parse(c),u=t.searchParams.get(`state`);for(let e of[`code`,`state`,`error`,`error_description`])t.searchParams.delete(e);if(a().replace(t.toString()),r||!n||u!==l.state)throw new p(`redirect-failed`,`Signing in with GitLab was cancelled or didn't finish.`);return s(Y(await o({client_id:e.clientId??``,code:n,grant_type:`authorization_code`,redirect_uri:X(t.toString()),code_verifier:l.verifier}),l.verifier))},async signInWithToken(e){let t=e.trim();if(!t)throw new p(`invalid`,`Paste a token to sign in.`);return s({type:`token`,token:t})},async startRedirect(){if(!e.clientId)throw Error(`gitlabSetup({ clientId }) is needed to sign in with GitLab.`);let n={state:q(16),verifier:q(48)};i.save(JSON.stringify(n),!1);let r=new URLSearchParams({client_id:e.clientId,redirect_uri:X(a().href()),response_type:`code`,state:n.state,scope:`api`,code_challenge:await J(n.verifier),code_challenge_method:`S256`});a().assign(`${t}/oauth/authorize?${r}`)}}}var le=30;function $(){return{href:()=>window.location.href,assign:e=>window.location.assign(e),replace:e=>window.history.replaceState(window.history.state,``,e)}}function ue(e){let t=(e.url??`https://gitlab.com`).replace(/\/$/,``),n=`${t}/api/v4`,r=e.fetch??((e,t)=>globalThis.fetch(e,t)),i=h(`goodfellow:gitlab:${t}:${e.project}`,e.storage),a=h(`goodfellow:gitlab:pending:${e.project}`,e.storage),o=()=>e.location??$();async function s(e){let n=await r(`${t}/oauth/token`,{method:`POST`,headers:{"content-type":`application/x-www-form-urlencoded`},body:new URLSearchParams(e)});if(!n.ok)throw new p(`invalid`,`GitLab didn't accept the sign-in (${n.status}).`);return await n.json()}async function c(a,c){let l=a,u={apiUrl:n,token:async({refresh:t}={})=>{if(l.type===`token`)return l.token;if(t||l.expiresAt-6e4<Date.now()){let{verifier:t}=l;l=Y(await s({client_id:e.clientId??``,refresh_token:l.refresh,grant_type:`refresh_token`,redirect_uri:X(o().href()),code_verifier:t}),t),i.save(JSON.stringify(l),c)}return l.access},canRefresh:l.type===`oauth`,fetch:r},d=await v(u,`/user`),f;try{f=await v(u,`/projects/${encodeURIComponent(e.project)}`)}catch(t){throw t instanceof g&&(t.status===404||t.status===403)?new p(`no-access`,`The GitLab account ${d.username} can't see ${e.project}.`):t}if(Math.max(f.permissions?.project_access?.access_level??0,f.permissions?.group_access?.access_level??0)<le)throw new p(`cant-publish`,`The GitLab account ${d.username} can see ${e.project} but can't publish to it.`);return i.save(JSON.stringify(l),c),new G({api:u,project:e.project,branch:e.branch??f.default_branch,...e.contentOnly&&{contentOnly:!0},...e.contentOnly&&e.code&&{code:{project:e.code,webUrl:t}},user:{login:d.username,name:d.name,avatarUrl:d.avatar_url},onSignOut:()=>i.clear()})}async function l(){let t=new URL(o().href()),n=t.searchParams.get(`code`),r=t.searchParams.get(`state`),i=t.searchParams.get(`error`);if(!n&&!i)return null;let l=a.load();if(!l)return null;a.clear();let u=JSON.parse(l);for(let e of[`code`,`state`,`error`,`error_description`])t.searchParams.delete(e);if(t.hash=u.hash,o().replace(t.toString()),i||!n||r!==u.state)throw new p(`redirect-failed`,`Signing in with GitLab was cancelled or didn't finish.`);return c(Y(await s({client_id:e.clientId??``,code:n,grant_type:`authorization_code`,redirect_uri:X(t.toString()),code_verifier:u.verifier}),u.verifier),u.remember)}function u({token:t}){let i={apiUrl:n,token:async()=>typeof t==`string`?t:t(),canRefresh:!1,fetch:r},a,o=()=>(a??=e.branch?Promise.resolve(e.branch):v(i,`/projects/${encodeURIComponent(e.project)}`).then(e=>e.default_branch),a.catch(()=>{a=void 0}),a),s=async(t,n)=>new G({api:i,project:e.project,branch:await o(),...e.contentOnly&&{contentOnly:!0},user:{login:n?.name??e.project,...n&&{name:n.name}},onSignOut:()=>{},...t&&{revision:t},...n&&{author:n}});return{...e.contentOnly&&{contentOnly:!0},async revision(){return(await s()).revision()},at:s}}return{name:`GitLab`,source:ee(`@goodfellow-cms/gitlab`,`gitlab`,e,[`fetch`,`storage`,`location`]),canRedirect:!!e.clientId,setup:()=>Q({...e.url&&{url:e.url},...e.fetch&&{fetch:e.fetch},...e.storage&&{storage:e.storage},...e.location&&{location:e.location}}),redirectAddressesListed:!!e.clientId,tokenLinks:[{url:`${t}/-/user_settings/personal_access_tokens?${new URLSearchParams({name:`Goodfellow admin`,scopes:`api`})}`,label:`signIn.token.create`}],async restore(){let e=await l();if(e)return e;let t=i.load();if(!t)return null;try{return await c(JSON.parse(t),i.remembered())}catch(e){throw e instanceof p&&i.clear(),e}},async signInWithToken(e,t){let n=e.trim();if(!n)throw new p(`invalid`,`Paste a token to sign in.`);return c({type:`token`,token:n},t)},async startRedirect(n){if(!e.clientId)throw Error(`gitlab({ clientId }) is needed to sign in with GitLab.`);let r=q(48),i=q(16),s=new URL(o().href()),c={state:i,verifier:r,remember:n,hash:s.hash};a.save(JSON.stringify(c),!1);let l=new URLSearchParams({client_id:e.clientId,redirect_uri:X(s.toString()),response_type:`code`,state:i,scope:`api`,code_challenge:await J(r),code_challenge_method:`S256`});o().assign(`${t}/oauth/authorize?${l}`)},server:u}}export{G as GitLabBackend,ue as gitlab,k as gitlabPagesRecords,Q as gitlabSetup,X as redirectUri};
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./dist-C20K9oCc.js","./store-5raQS3us.js","./setup-host-w4Qxug91.js","./git-eGyMXUIu.js","./preload-helper-khBccGFq.js","./dist-cedgnWG_.js"])))=>i.map(i=>d[i]);
|
|
2
|
-
import{i as e}from"./store-5raQS3us.js";import{t}from"./preload-helper-khBccGFq.js";function n(e){if(e)try{let t=new URL(e.url),n=t.hostname===`localhost`||t.hostname===`127.0.0.1`;return(t.protocol===`https:`||t.protocol===`http:`&&n)&&t.pathname===`/`&&!t.search&&!t.hash?t.origin:void 0}catch{return}}var r=/^[ \t]*admin:[ \t]*\{[^\n]*\},?[ \t]*\n/m;function i(e){let t=r.exec(e)?.[0],n=t&&/url:\s*"([^"\\]+)"/.exec(t)?.[1];if(t&&n)return{url:n,.../checked:\s*true/.test(t)&&{checked:!0}}}function a(e,t,{start:n=!0,end:r=!0}={}){let i=0,a=e.length;for(;n&&i<a&&t.includes(e.charAt(i));)i++;for(;r&&a>i&&t.includes(e.charAt(a-1));)a--;return e.slice(i,a)}var o=`goodfellow:broker-connect`;function s(e){return e.startsWith(`.github/`)||e===`.gitlab-ci.yml`||e.startsWith(`.gitlab/`)}function c(t,n){let r={refused:[],confirm:[]};for(let i of t){let{path:t}=i;if(s(t)||t.startsWith(`/`)||t.split(`/`).includes(`..`))r.refused.push(t);else if(t.startsWith(`content/code/`))r.confirm.push({path:t,kind:`custom-code`});else if(!e(t))r.confirm.push({path:t,kind:`code`});else if(t===`content/site.json`&&`content`in i){let e;try{e=JSON.parse(i.content).url}catch{e=void 0}(e??void 0)!==(n??void 0)&&r.confirm.push({path:t,kind:`site-address`})}}return r}var l=class extends Error{problem;name=`BrokerRefusedError`;constructor(e,t){super(t),this.problem=e}},u=[`revision`,`read`,`readBytes`,`list`,`readFiles`,`fileSizes`,`write`,`changedPaths`],d={methods:[`read`,`readBytes`,`list`]},f={name:`draft`,data:[`name`],methods:[`changes`,`paths`,`publish`,`submitForReview`,`discard`],objects:{store:{methods:u}}},p={data:[`user`,`contentOnly`],methods:[...u,`deployStatus`,`history`,`readAt`,`repositoryVisibility`,`signOut`],sync:{filesAt:d},objects:{pages:{data:[`severalDomains`],methods:[`site`,`connect`,`records`,`status`,`secure`,`disconnect`]},editors:{methods:[`list`,`invite`,`setRole`,`remove`,`letEditorsPublish`]},ownerAccess:{data:[`tokenLink`,`active`,`problem`],methods:[`forget`,`startRedirect`,`requestToken`]},updates:{methods:[`setup`,`enable`,`lastRun`,`start`,`rebuild`],objects:{code:{data:[`repo`,`webUrl`],methods:[`read`,`history`,`readAt`]},nightly:{methods:[`supported`,`get`,`set`]}}},drafts:{methods:[`create`,`open`,`list`],returns:{create:f,open:f}},scheduledBuilds:{methods:[`timing`,`sync`]}}};function m(e){if(!(e instanceof Error))return{name:`Error`,message:String(e),fields:{}};let t={};for(let[n,r]of Object.entries(e))[`string`,`number`,`boolean`].includes(typeof r)&&(t[n]=r);return{name:e.name,message:e.message,fields:t}}function h(e){return e instanceof Error?{__error:m(e)}:e}function g(e,t,n={}){let r=new Map([[0,{target:t,shape:p,prefix:``}]]),i=1;function a(e,t,r,i){let o=e,s={};for(let e of t.data??[])o[e]!==void 0&&(s[e]=h(o[e]));let c=(t.methods??[]).filter(e=>typeof o[e]==`function`||n.extra?.[`${r}${e}`]!==void 0);for(let e of Object.keys(t.sync??{}))typeof o[e]==`function`&&c.push(e);let l={};for(let[e,n]of Object.entries(t.objects??{})){let t=o[e];typeof t==`object`&&t&&(l[e]=a(t,n,`${r}${e}.`,i))}return{handle:i,data:s,methods:c,objects:l}}let o=()=>a(t,p,``,0);function s(e,t){let n=r.get(e);if(!n)return;let i=n.target,a=n.shape,o=n.prefix;for(let e of t.slice(0,-1))if(a=a?.objects?.[e],i=i?.[e],o+=`${e}.`,!a||typeof i!=`object`||!i)return;let s=t.at(-1)??``;if((a?.methods?.includes(s)||Object.hasOwn(a?.sync??{},s))&&a)return{target:i,shape:a,method:s,name:`${o}${s}`}}async function c(e){let t=s(e.handle,e.path);if(!t)throw new l(`not-here`,`The broker doesn't offer that.`);let{target:o,shape:c,method:u,name:d}=t,f=Array.isArray(e.args)?e.args:[],p=n.extra?.[d];if(c.sync?.[u]){let t=c.sync[u],[r,i]=e.then??[``,[]];if(!t.methods?.includes(r))throw new l(`not-here`,`The broker doesn't offer that.`);await n.check?.({path:`${d}.${r}`,args:[...f,...i],target:o});let a=o[u].apply(o,f);return a[r].apply(a,i)}await n.check?.({path:d,args:f,target:o});let m=p?await p(...f):await o[u].apply(o,f),h=c.returns?.[u];if(h&&typeof m==`object`&&m){let e=i++,t=`${h.name??d}.`;return r.set(e,{target:m,shape:h,prefix:t}),{__object:a(m,h,t,e)}}return m}return e.onmessage=async t=>{let n=t.data;if(n?.type===`call`&&Array.isArray(n.path))try{let t=await c(n);e.postMessage({type:`answer`,id:n.id,ok:!0,value:t,state:o()})}catch(t){e.postMessage({type:`answer`,id:n.id,ok:!1,error:m(t),state:o()})}},e.postMessage({type:`state`,state:o()}),()=>{e.onmessage=null,r.clear()}}var _={anthropic:{name:`Claude`,keyUrl:`https://platform.claude.com/settings/keys`,needsKey:!0,models:[`claude-opus-5-5`,`claude-sonnet-5-5`,`claude-haiku-4-5`]},openai:{name:`OpenAI`,keyUrl:`https://platform.openai.com/api-keys`,needsKey:!0,baseUrl:`https://api.openai.com/v1`,structured:`json_schema`},gemini:{name:`Google Gemini`,keyUrl:`https://aistudio.google.com/apikey`,needsKey:!0,baseUrl:`https://generativelanguage.googleapis.com/v1beta/openai`,structured:`json_schema`},groq:{name:`Groq`,keyUrl:`https://console.groq.com/keys`,needsKey:!0,baseUrl:`https://api.groq.com/openai/v1`,structured:`json_object`},mistral:{name:`Mistral`,keyUrl:`https://console.mistral.ai/api-keys`,needsKey:!0,baseUrl:`https://api.mistral.ai/v1`,structured:`json_schema`},openrouter:{name:`OpenRouter`,keyUrl:`https://openrouter.ai/settings/keys`,needsKey:!0,baseUrl:`https://openrouter.ai/api/v1`,structured:`json_schema`},ovhcloud:{name:`OVHcloud AI Endpoints`,needsKey:!1,baseUrl:`https://oai.endpoints.kepler.ai.cloud.ovh.net/v1`,structured:`json_object`,models:[`gpt-oss-120b`]},custom:{name:`OpenAI-compatible`,needsKey:!1,structured:`json_object`},manual:{name:`Chat app`,needsKey:!1}};function v(e,t){let n=t?e.split(t).join(`[key]`):e;return n=n.replace(/\b(sk|gsk|AIza)[-_A-Za-z0-9]{12,}/g,`[key]`),n}var y=`https://api.anthropic.com`,b=10485760,x=[`content-type`,`accept`,`anthropic-version`,`anthropic-beta`];function S(e,t,n){return e===`anthropic`?t===`POST`&&n===`v1/messages`:t===`POST`&&n===`chat/completions`||t===`GET`&&n===`models`}function C(e,t){return Response.json({error:{message:t}},{status:e,headers:{"cache-control":`no-store`}})}function w(e,t={}){let n=t.fetch??((e,t)=>fetch(e,t)),r=Object.entries(e).flatMap(([e,t])=>t&&(typeof t==`string`||t.baseUrl)?[[e,t]]:[]),i=new Map(r);async function o(e,t,r){let o=t,s=i.get(o);if(!s)return C(404,`This site has no key for that service.`);if(!S(o,e.method,r))return C(404,`The AI assistant doesn't use that.`);let c=typeof s==`string`?s:s.key,l=o===`anthropic`?y:typeof s==`object`?s.baseUrl:_[o].baseUrl??``;if(!l)return C(404,`This site has no address for that service.`);let u=e.method===`GET`?void 0:await e.arrayBuffer();if(u&&u.byteLength>b)return C(413,`That request is too large.`);let d=new Headers;for(let t of x){let n=e.headers.get(t);n&&d.set(t,n)}c&&(o===`anthropic`?d.set(`x-api-key`,c):d.set(`authorization`,`Bearer ${c}`));let f=`${a(l,`/`,{start:!1})}/${r}${new URL(e.url).search}`,p;try{p=await n(f,{method:e.method,headers:d,body:u,signal:e.signal})}catch(e){if(e.name===`AbortError`)throw e;return C(502,`The AI service couldn't be reached.`)}if(!p.ok){let e=v(await p.text().catch(()=>``),c);return new Response(e,{status:p.status,headers:{"content-type":p.headers.get(`content-type`)??`text/plain`,"cache-control":`no-store`}})}return new Response(p.body,{status:p.status,headers:{"content-type":p.headers.get(`content-type`)??`application/json`,"cache-control":`no-store`}})}return{services:[...i.keys()],forward:o}}var T=new Set([`write`,`draft.store.write`]);function E(e,t){let n=c(e,t);if(n.refused.length>0)return{action:`refuse`,paths:n.refused};let r=new Map;for(let{path:e,kind:t}of n.confirm)r.set(t,[...r.get(t)??[],e]);let i=[...r].map(([e,t])=>({kind:e,paths:t}));return i.length>0?{action:`ask`,questions:i}:{action:`allow`}}function D(e){if(typeof e==`string`)return e;let t=e?.login;return typeof t==`string`?t:``}async function O(e,t){let{path:n,args:r,target:i}=e;return T.has(n)?E(r[0]??[],t):n===`draft.publish`?E(await i.changes(),t):n===`updates.start`?{action:`ask`,questions:[{kind:`update`,release:String(r[0])}]}:n===`editors.invite`||n===`editors.setRole`?{action:`ask`,questions:[{kind:`editors`,who:D(r[0]),role:String(r[1])}]}:n===`editors.letEditorsPublish`?{action:`ask`,questions:[{kind:`editors`,who:``}]}:{action:`allow`}}var k={title:`Sign in`,loading:`Loading…`,framed:`This page can't be shown inside another page. Open it on its own.`,noConfig:`This sign-in page isn't set up yet: it needs a broker.json beside it, naming the site it signs in to. See the token broker page in Goodfellow's documentation.`,signInTitle:`Sign in to edit {site}`,signInIntro:`This page keeps your sign-in and AI keys where the site's pages can't reach them, and shows the admin panel from here.`,signInRedirect:`Sign in with {host}`,signInToken:`Or sign in with an access token`,tokenLabel:`Access token`,remember:`Stay signed in on this device`,signInButton:`Sign in`,signingIn:`Signing in…`,signInError:`That didn't work: {message}`,noSiteAddress:`The site has no address yet, so there's no admin panel to show. Set its address in Site Settings first, or ask its owner to.`,badSiteAddress:`The site's address, {address}, isn't one this page can show the admin panel from.`,signedInAs:`Signed in as {name}`,aiKeys:`AI keys`,signOut:`Sign out`,adminFrame:`Admin panel`,confirmTitle:`Publish this?`,confirmIntro:`The admin panel asked to publish changes that need you to say so here, where nothing it runs can say so for you:`,confirmCode:`The site's code, which runs when the site is built:`,confirmCustomCode:`Code that runs on the site's pages:`,confirmSiteAddress:`A new Site address, which is where this page shows the admin panel from. Only publish it if you changed it yourself:`,confirmUpdate:`Installing Goodfellow {release}, which changes the site's packages.`,confirmEditors:`Giving {who} access to edit the site{role}.`,confirmEditorsPublish:`Letting the site's editors publish to it.`,confirmPublish:`Publish`,confirmAllow:`Allow`,cancel:`Cancel`,refusedWorkflow:`The token broker never changes the site's workflows, which run with its secrets: {paths}.`,declined:`You chose not to publish this.`,ownerTitle:`Owner token`,ownerIntro:`Create a token that can manage the site, then paste it here. This page keeps it for as long as it's open, and the admin panel never sees it.`,ownerCreate:`Create a token`,ownerLabel:`Owner token`,ownerUse:`Use this token`,aiTitle:`AI keys`,aiIntro:`The AI assistant asks these services through this page, with your keys, so the admin panel never sees them. Leave a service empty to not use it.`,aiRemember:`Remember these keys on this device`,aiSave:`Save`};function A(e,t={}){return k[e].replace(/\{(\w+)\}/g,(e,n)=>t[n]??e)}var j=`goodfellow:broker:route`,M=`goodfellow:broker:ai`,N=`goodfellow.config.tsx`,P=Object.keys(_).filter(e=>e!==`custom`&&e!==`manual`&&(e===`anthropic`||_[e].baseUrl));function F(e,t={},...n){let r=document.createElement(e);for(let[e,n]of Object.entries(t))r.setAttribute(e,n);return r.append(...n),r}function I(e){return e instanceof Error?e.message:String(e)}function L(e){let{repo:t,project:n}=e.options;return typeof t==`string`?t:typeof n==`string`?n:e.package}function R(){for(let e of[sessionStorage,localStorage])try{let t=e.getItem(M);if(t)return JSON.parse(t)}catch{}return{}}function z(e,t){B(),(t?localStorage:sessionStorage).setItem(M,JSON.stringify(e))}function B(){sessionStorage.removeItem(M),localStorage.removeItem(M)}async function V(e){let t=await e.revision(),r=JSON.parse(await e.read(`content/site.json`)??`{}`);if(typeof r.url!=`string`||!r.url)return{problem:`noSiteAddress`};let a;try{a=new URL(r.url.replace(/\/?$/,`/`))}catch{return{problem:`badSiteAddress`}}let o=a.hostname===`localhost`||a.hostname===`127.0.0.1`;if(a.protocol!==`https:`&&!(a.protocol===`http:`&&o))return{problem:`badSiteAddress`};let s=await e.readAt(N,t).catch(()=>void 0),c=s?i(s):void 0;return{url:`${(c?.checked?n(c):void 0)??a.origin}${a.pathname}admin/`,siteUrl:r.url}}async function H({root:e,config:t,hosts:n}){document.title=A(`title`);let r=(...t)=>e.replaceChildren(...t);if(window.top!==window){r(F(`p`,{class:`broker-note`},A(`framed`)));return}let i=new URLSearchParams(location.search).get(`site`),a=t?.sites.find(e=>!i||L(e)===i)??t?.sites[0],s=a&&Object.hasOwn(n,a.package)?n[a.package]:void 0,c=s&&(await s())[a?.export??``];if(!a||typeof c!=`function`){r(F(`p`,{class:`broker-note`},A(`noConfig`)));return}let u=c(a.options),d=()=>{location.hash&&sessionStorage.setItem(j,location.hash)};d(),window.addEventListener(`hashchange`,d),r(F(`p`,{class:`broker-note`},A(`loading`)));let f=null,p;try{f=await u.restore()}catch(e){p=e}f?await h(f):m(p);function m(e){let t=F(`form`,{class:`broker-sign-in`}),n=F(`input`,{type:`checkbox`,id:`broker-remember`}),i=F(`input`,{type:`password`,id:`broker-token`,autocomplete:`off`}),o=F(`p`,{class:`broker-error`,role:`alert`});e!==void 0&&(o.textContent=A(`signInError`,{message:I(e)}));let s=F(`button`,{type:`submit`},A(`signInButton`)),c=async e=>{s.disabled=!0,o.textContent=A(`signingIn`);try{await h(await e())}catch(e){o.textContent=A(`signInError`,{message:I(e)}),s.disabled=!1}};if(t.append(F(`h1`,{},A(`signInTitle`,{site:L(a)})),F(`p`,{},A(`signInIntro`)),o),u.canRedirect){let e=F(`button`,{type:`button`,class:`broker-primary`},A(`signInRedirect`,{host:u.name}));e.addEventListener(`click`,()=>void u.startRedirect(n.checked).catch(e=>{o.textContent=A(`signInError`,{message:I(e)})})),t.append(F(`div`,{},e))}if(u.tokenLinks){let e=F(`ul`,{});for(let t of u.tokenLinks)e.append(F(`li`,{},F(`a`,{href:t.url,target:`_blank`,rel:`noreferrer`},t.url)));t.append(F(`h2`,{},A(`signInToken`)),e,F(`label`,{for:`broker-token`},A(`tokenLabel`)),i,F(`label`,{class:`broker-check`},n,` ${A(`remember`)}`),F(`div`,{},s))}t.addEventListener(`submit`,e=>{e.preventDefault(),i.value.trim()&&c(()=>u.signInWithToken(i.value.trim(),n.checked))}),r(t)}async function h(e){let t=await V(e).catch(e=>({problem:`signInError`,error:e}));if(`problem`in t){r(F(`p`,{class:`broker-note`,role:`alert`},A(t.problem,{address:``,message:`error`in t?I(t.error):``})));return}let n=new URL(t.url).origin,i=sessionStorage.getItem(j)??``,a=F(`iframe`,{class:`broker-frame`,title:A(`adminFrame`),src:`${t.url}${i.startsWith(`#`)?i:``}`,sandbox:`allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads allow-modals`,allow:`clipboard-write`}),s=()=>{window.removeEventListener(`message`,p),f?.(),e.signOut(),B(),sessionStorage.removeItem(j),m()},c=F(`button`,{type:`button`},A(`aiKeys`));c.addEventListener(`click`,()=>S(()=>a.contentWindow?.location.replace(a.src)));let d=F(`button`,{type:`button`},A(`signOut`));d.addEventListener(`click`,s),r(F(`header`,{class:`broker-bar`},F(`span`,{},A(`signedInAs`,{name:e.user.name||e.user.login})),c,d),a);let f,p=r=>{if(r.source!==a.contentWindow||r.origin!==n||r.data?.type!==`goodfellow:broker-ready`)return;f?.();let i=new MessageChannel,c=new MessageChannel;f=g(i.port1,e,{async check(e){let n=await O(e,t.siteUrl);if(n.action===`refuse`)throw new l(`workflow`,A(`refusedWorkflow`,{paths:n.paths.join(`, `)}));if(n.action===`ask`&&!await b(n.questions))throw new l(`declined`,A(`declined`))},extra:{signOut:s,"ownerAccess.requestToken":()=>x(e)}}),c.port1.onmessage=e=>void v(c.port1,e.data);let d={hostName:u.name,redirectAddressesListed:u.canRedirect&&u.redirectAddressesListed===!0,aiServices:Object.keys(R())};a.contentWindow?.postMessage({type:o,account:d},n,[i.port2,c.port2])};window.addEventListener(`message`,p)}async function v(e,t){if(t?.type===`route`&&typeof t.hash==`string`){sessionStorage.setItem(j,t.hash);return}if(t?.type!==`ai`)return;let[n=``,...r]=t.path.split(`?`)[0]?.split(`/`)??[],i=t.path.includes(`?`)?t.path.slice(t.path.indexOf(`?`)):``,a=new Request(`https://broker.invalid/${r.join(`/`)}${i}`,{method:t.method,headers:t.headers,...t.body&&t.method!==`GET`&&{body:t.body}}),o=await w(R()).forward(a,n,r.join(`/`)),s=await o.arrayBuffer(),c={type:`ai`,id:t.id,status:o.status,headers:[...o.headers.entries()],body:s};e.postMessage(c,[s])}function y(e,t,n){return new Promise(r=>{let i=F(`dialog`,{class:`broker-dialog`},F(`h2`,{},e),...t),a=F(`div`,{class:`broker-actions`});for(let e of n){let t=F(`button`,{type:`button`,...e.primary&&{class:`broker-primary`}},e.label);t.addEventListener(`click`,()=>i.close(e.value?`yes`:`no`)),a.append(t)}i.append(a),i.addEventListener(`close`,()=>{i.remove(),r(i.returnValue===`yes`)}),document.body.append(i),i.showModal()})}function b(e){let t=[F(`p`,{},A(`confirmIntro`))],n=!1;for(let r of e)if(r.kind===`update`)t.push(F(`p`,{},A(`confirmUpdate`,{release:r.release})));else if(r.kind===`editors`)t.push(F(`p`,{},r.who?A(`confirmEditors`,{who:r.who,role:r.role?` (${r.role})`:``}):A(`confirmEditorsPublish`)));else{n=!0;let e=r.kind===`code`?`confirmCode`:r.kind===`custom-code`?`confirmCustomCode`:`confirmSiteAddress`;t.push(F(`p`,{},A(e)),F(`ul`,{},...r.paths.map(e=>F(`li`,{},F(`code`,{},e)))))}return y(A(`confirmTitle`),t,[{label:A(`cancel`),value:!1},{label:A(n?`confirmPublish`:`confirmAllow`),value:!0,primary:!0}])}async function x(e){let t=e.ownerAccess;if(!t)throw new l(`not-here`,`This site's host has no owner token.`);let n=F(`input`,{type:`password`,id:`broker-owner-token`,autocomplete:`off`}),r=F(`p`,{class:`broker-error`,role:`alert`});for(;;){if(!await y(A(`ownerTitle`),[F(`p`,{},A(`ownerIntro`)),F(`p`,{},F(`a`,{href:t.tokenLink.url,target:`_blank`,rel:`noreferrer`},A(`ownerCreate`))),F(`label`,{for:`broker-owner-token`},A(`ownerLabel`)),n,r],[{label:A(`cancel`),value:!1},{label:A(`ownerUse`),value:!0,primary:!0}]))throw new l(`declined`,A(`declined`));try{await t.applyToken(n.value.trim());return}catch(e){r.textContent=A(`signInError`,{message:I(e)})}}}async function S(e){let t=R(),n=new Map,r=P.map(e=>{let r=F(`input`,{type:`password`,id:`broker-ai-${e}`,autocomplete:`off`}),i=t[e];return typeof i==`string`&&(r.value=i),n.set(e,r),F(`div`,{},F(`label`,{for:`broker-ai-${e}`},_[e].name),r)}),i=F(`input`,{type:`checkbox`,id:`broker-ai-remember`});if(i.checked=localStorage.getItem(M)!==null,!await y(A(`aiTitle`),[F(`p`,{},A(`aiIntro`)),...r,F(`label`,{class:`broker-check`},i,` ${A(`aiRemember`)}`)],[{label:A(`cancel`),value:!1},{label:A(`aiSave`),value:!0,primary:!0}]))return;let a={};for(let[e,t]of n)t.value.trim()&&(a[e]=t.value.trim());z(a,i.checked),e()}}await H({root:document.getElementById(`broker`),config:await fetch(`./broker.json`,{cache:`no-store`}).then(e=>e.ok?e.json():void 0).catch(()=>void 0),hosts:{"@goodfellow-cms/github":()=>t(()=>import(`./dist-C20K9oCc.js`),__vite__mapDeps([0,1,2,3,4]),import.meta.url),"@goodfellow-cms/gitlab":()=>t(()=>import(`./dist-cedgnWG_.js`),__vite__mapDeps([5,1,2,3]),import.meta.url)}});
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{a as e,o as t}from"./store-5raQS3us.js";var n=class extends Error{problem;name=`DomainError`;constructor(e,t){super(t),this.problem=e}},r=`goodfellow-draft-`,i=/^[a-z0-9][a-z0-9-]{0,39}$/;function a(e){return i.test(e)}var o=class extends Error{name=`DraftError`;problem;constructor(e,t){super(t),this.problem=e}};function s(e){if(!a(e))throw new o(`not-found`,`"${e}" isn't a draft's name.`);return`${r}${e}`}function c(t,n){function i(r,i){let a=n.branchStore(i);async function o(){let e=await n.mergeBase(i);return a.changedPaths(e,await a.revision())}async function s(){let e=[];for(let t of await o())if(t.startsWith(`public/media/`)){let n=await a.readBytes(t);e.push(n?{path:t,bytes:n}:{path:t,delete:!0})}else{let n=await a.read(t);e.push(n===void 0?{path:t,delete:!0}:{path:t,content:n})}return e}return{name:r,store:a,changes:s,paths:o,async publish(r){let a=await n.mergeBase(i),o=await s(),c=o.length>0?await e(t,o,{message:r,expectedRevision:a}):{revision:await t.revision()};return await n.deleteBranch(i),c},async submitForReview({title:e,description:t=``}){return n.openReview({branch:i,title:e,description:t})},async discard(){await n.deleteBranch(i)}}}return{async create(e,r){let a=s(e);return await n.createBranch(a,r?.from??await t.revision()),i(e,a)},async open(e){let t=s(e);return await n.mergeBase(t),i(e,t)},async list(){return(await n.listBranches(r)).map(e=>e.slice(17)).filter(a).sort().reverse()}}}var l=class extends Error{problem;name=`EditorsError`;constructor(e,t){super(t),this.problem=e}};function u(e){let t=/^[\^~=v]*(\d+)\.(\d+)\.(\d+)$/.exec(e.trim());return t?[Number(t[1]),Number(t[2]),Number(t[3])]:void 0}function d(e,t){return e[0]-t[0]||e[1]-t[1]||e[2]-t[2]}function f(e,t){let n=u(e),r=u(t);return n&&r?d(n,r):0}function p(e){return u(e)?.join(`.`)}function m(e){try{let{dependencies:t={},devDependencies:n={}}=JSON.parse(e),r=t[`@goodfellow-cms/react`]??n[`@goodfellow-cms/react`];return r?p(r):void 0}catch{return}}var h=`goodfellow-update `;function g(e){let t=e.split(`
|
|
2
|
-
`);for(let e=t.length-1;e>=0;e--){let n=t[e]??``,r=n.indexOf(h);if(r!==-1)try{let e=JSON.parse(n.slice(r+18).trim());if([`up-to-date`,`updated`,`failed`].includes(e.state)&&typeof e.from==`string`)return e}catch{}}}var _=`GOODFELLOW_NIGHTLY`,v=[`changed`,`always`,`off`];function y(e){let t=e?.trim().toLowerCase();return v.includes(t)?t:`changed`}var b=class extends Error{problem;name=`UpdatesError`;constructor(e,t){super(t),this.problem=e}},x=`goodfellow-build-problem `;function S(e){let t=e.split(`
|
|
3
|
-
`);for(let e=t.length-1;e>=0;e--){let n=t[e]??``,r=n.indexOf(x);if(r!==-1)try{let e=JSON.parse(n.slice(r+25).trim());if((e.kind===`content`||e.kind===`code`)&&typeof e.message==`string`)return{kind:e.kind,message:e.message,...typeof e.file==`string`&&e.file&&{file:e.file}}}catch{}}}function C(e){let t=e.toLowerCase();if(/deploy-pages|deploy to |pages:deploy/.test(t))return`deploy`;if(/configure-pages|upload-pages-artifact|setup pages|set up pages/.test(t))return`pages`;if(/\b(npm (ci|install)|pnpm install|yarn( install)?|install packages)\b/.test(t))return`install`;if(/\bbuild\b/.test(t))return`build`}var w=`rebuild`;`${w}`;function T(e,t=`# `){let n=[];for(let r of e.split(`
|
|
4
|
-
`)){let e=``;for(let i of r.split(` `))e&&e.length+i.length+1>78-t.length?(n.push(e),e=i):e=e?`${e} ${i}`:i;n.push(e)}return n.map(e=>`${t}${e}`.trimEnd()).join(`
|
|
5
|
-
`)}`${T(`Drafts, from the admin panel's Add to draft and from Claude, are kept on branches named goodfellow-draft-…, which visitors never see, so Vercel doesn't build previews of them.`,` // `)}`,T(`The admin address's header rules, from the code's goodfellow.config.tsx: goodfellow admin and goodfellow broker, run in the code's folder, copy them here, since Vercel reads this file before the code is cloned.`,` // `),`${t}${t}`;var E=class extends Error{problem;link;name=`SetupError`;constructor(e,t,n){super(t),this.problem=e,this.link=n}};export{_ as a,g as c,l as d,o as f,S as i,y as l,n as m,w as n,b as o,c as p,C as r,f as s,E as t,m as u};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var e=`content`,t=`public/media`,n=`blocks/installed`,r=`components`,i=`hooks`,a=`content-repository`,o=class extends Error{name=`ConflictError`;constructor(e=`The site changed since it was loaded.`){super(e)}},s=[e,t,n,r,`lib`,i];function c(e){return e.startsWith(`/`)||e.includes(`\\`)||e.includes(`\0`)||e.split(`/`).some(e=>e===``||e===`.`||e===`..`)?!1:s.some(t=>e.startsWith(`${t}/`))}async function l(e,t,n){let r=n.expectedRevision,i=new Set(t.map(e=>e.path));for(let a=0;;a++)try{return await e.write(t,{...n,expectedRevision:r})}catch(t){if(!(t instanceof o)||!e.changedPaths||a===2)throw t;let s=await e.revision();if(s===r||(await e.changedPaths(n.expectedRevision,s)).some(e=>i.has(e)))throw t;r=s}}var u=[e,t];function d(e){return c(e)&&u.some(t=>e.startsWith(`${t}/`))}var f=class extends Error{name=`CodeChangeError`;constructor(e){super(`${e} is part of the site's code, which is kept in a repository of its own, not the content repository.`)}};function p(e){let t=e.find(e=>!d(e.path));if(t)throw new f(t.path)}export{l as a,d as i,s as n,a as o,p as r,o as t};
|