From 0c82d5f757f3145cfa93813144fed1484a15a778 Mon Sep 17 00:00:00 2001 From: Michiel de Jong Date: Fri, 2 Oct 2026 15:36:48 +0000 Subject: [PATCH] issue-tracker 0.3.0: Sync this table to GitHub (#177 item 14) On an issue-v1 table the app didn't make, the app offers "Sync this table to GitHub": it asks for the host's "Allow editing" when the row grant doesn't cover its row-extras, keeps a binding under the App (synced-table, repository, sync state, comments folder), and then syncs that table as its own: compare on open, review before send, the same conflict rules, bookkeeping on the rows. Existing rows stay local until Publish to GitHub, rows are never deleted, the table is never written, and a lapsed grant pauses the sync. The App now renders issue-v1 and declares its row extras from the first open, and Atomic's localId joins the row extras (the Bridge sets it on imported rows). Co-Authored-By: Claude Opus 5.5 --- apps/issue-tracker/0.3.0/ui.js | 9 + integrations/README.md | 16 +- integrations/catalog.json | 10 +- integrations/issue-tracker/README.md | 94 +++- integrations/issue-tracker/app/build.test.ts | 13 +- .../issue-tracker/app/controller.test.ts | 7 +- integrations/issue-tracker/app/controller.ts | 179 +++++++- integrations/issue-tracker/app/fakeStore.ts | 137 ++++++ integrations/issue-tracker/app/main.ts | 14 + integrations/issue-tracker/app/model.ts | 21 +- integrations/issue-tracker/app/package.json | 2 +- integrations/issue-tracker/app/store.ts | 35 ++ integrations/issue-tracker/app/sync.test.ts | 3 +- .../issue-tracker/app/syncTable.test.ts | 350 ++++++++++++++ integrations/issue-tracker/app/tracker.ts | 428 ++++++++++++++---- integrations/issue-tracker/app/views.test.ts | 37 ++ integrations/issue-tracker/app/views.ts | 106 ++++- .../issue-tracker/e2e/issue-tracker.spec.ts | 304 ++++++++++++- usertest/catalog.mjs | 2 +- 19 files changed, 1619 insertions(+), 148 deletions(-) create mode 100644 apps/issue-tracker/0.3.0/ui.js create mode 100644 integrations/issue-tracker/app/syncTable.test.ts diff --git a/apps/issue-tracker/0.3.0/ui.js b/apps/issue-tracker/0.3.0/ui.js new file mode 100644 index 000000000..4362d34f0 --- /dev/null +++ b/apps/issue-tracker/0.3.0/ui.js @@ -0,0 +1,9 @@ +var Er=Object.create;var Bt=Object.defineProperty;var Tr=Object.getOwnPropertyDescriptor;var Rr=Object.getOwnPropertyNames;var $r=Object.getPrototypeOf,Ar=Object.prototype.hasOwnProperty;var jr=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}};var Pr=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Rr(t))!Ar.call(e,s)&&s!==n&&Bt(e,s,{get:()=>t[s],enumerable:!(r=Tr(t,s))||r.enumerable});return e};var Or=(e,t,n)=>(n=e!=null?Er($r(e)):{},Pr(t||!e||!e.__esModule?Bt(n,"default",{value:e,enumerable:!0}):n,e));var Jt=jr((mo,qt)=>{"use strict";qt.exports=function(e,t){t||(t={}),typeof t=="function"&&(t={cmp:t});var n=typeof t.cycles=="boolean"?t.cycles:!1,r=t.cmp&&(function(o){return function(i){return function(a,c){var u={key:a,value:i[a]},f={key:c,value:i[c]};return o(u,f)}}})(t.cmp),s=[];return(function o(i){if(i&&i.toJSON&&typeof i.toJSON=="function"&&(i=i.toJSON()),i!==void 0){if(typeof i=="number")return isFinite(i)?""+i:"null";if(typeof i!="object")return JSON.stringify(i);var a,c;if(Array.isArray(i)){for(c="[",a=0;an.charCodeAt(0)<32||n.charCodeAt(0)===127))throw new Error("Expected an absolute identifier without whitespace or controls");let t=new URL(e);if(!["http:","https:"].includes(t.protocol)&&!(/^did:[a-z0-9]+:[A-Za-z0-9._:%+/=-]+(?:[?#][A-Za-z0-9._~:/?#[\]@!$&'()*+,;=%-]*)?$/.test(e)&&!/%(?![0-9a-fA-F]{2})/.test(e)))throw new Error(`Expected an HTTP(S) URL or DID: ${e}`)}var De=class{properties=new Map([[dt,j.RESOURCEARRAY]]);property(t,n){if(U(t),!Object.values(j).includes(n)||n===j.UNKNOWN)throw new Error(`Unsupported datatype: ${n}`);let r=this.properties.get(t);if(r&&r!==n)throw new Error(`Conflicting property: ${t}`);return this.properties.set(t,n),this}validate(t){U(t["@id"]),this.validateProperties(t,!0)}validateProperties(t,n){if(Object.getPrototypeOf(t)!==Object.prototype)throw new Error("Expected a plain JSON object");for(let[r,s]of Object.entries(t)){if(r==="@id"&&n)continue;U(r);let o=this.properties.get(r);if(!o)throw new Error(`Unknown property: ${r}`);if(typeof s=="number"&&!Number.isFinite(s))throw new Error("Expected a finite number");if(s==null)throw new Error(`Missing value for ${r}`);if(o===j.ATOMIC_URL)this.validateLink(s);else if(o===j.RESOURCEARRAY){if(!Array.isArray(s))throw new Error(`Expected a resource array: ${r}`);for(let i of s)this.validateLink(i)}else{if([j.FLOAT,j.INTEGER,j.TIMESTAMP].includes(o)&&typeof s!="number")throw new Error("Expected a number");if(o===j.BOOLEAN&&typeof s!="boolean")throw new Error("Expected a boolean");Vt(s,o)}}}validateLink(t){if(typeof t=="string")U(t);else if(t&&typeof t=="object"&&!Array.isArray(t))this.validateProperties(t,!1);else throw new Error("Expected a resource URL or nested resource")}};var _e=class e{schema;resources=new Map;constructor(t){this.schema=t}get(t){let n=this.resources.get(t);return n&&structuredClone(n)}put(t){this.schema.validate(t),this.resources.set(t["@id"],structuredClone(t))}patch(t,n){if(U(t),Object.hasOwn(n.set??{},"@id")||n.unset?.includes("@id"))throw new Error("A patch cannot change resource identity");let r={...this.get(t)??{"@id":t},...n.set};for(let s of n.unset??[])U(s),delete r[s];return this.put(r),structuredClone(r)}transaction(t){let n=this.resources;this.resources=new Map(n);try{t()}catch(r){throw this.resources=n,r}}apply(t){let n=new e(this.schema);n.resources=new Map(this.resources);for(let r of t)n.patch(r.subject,r.patch);this.resources=n.resources}delete(t){this.resources.delete(t)}all(t){return[...this.resources.values()].filter(n=>{let r=n["https://atomicdata.dev/properties/isA"];return!t||Array.isArray(r)&&r.includes(t)}).map(n=>structuredClone(n))}toJSONAD(){return JSON.stringify(this.all())}loadJSONAD(t){let n=JSON.parse(t),r=Array.isArray(n)?n:[n],s=new Map;for(let o of r){if(!o||typeof o!="object"||Array.isArray(o)||typeof o["@id"]!="string")throw new Error("Expected a named JSON-AD resource");let i=o;if(this.schema.validate(i),s.has(i["@id"]))throw new Error(`Duplicate subject: ${i["@id"]}`);s.set(i["@id"],structuredClone(i))}this.resources=s}};var be="https://raw.githubusercontent.com/localthought/devonian/main/vocab/",P={class:`${be}Identity.json`,scope:`${be}scope.json`,entity:`${be}entity.json`,localId:`${be}localId.json`,idType:`${be}idType.json`,resource:`${be}resource.json`},Ge=class{store;base;constructor(t,n){this.store=t,U(n);let r=new URL(n);if(!["http:","https:"].includes(r.protocol))throw new Error("Identity base must be an HTTP(S) URL");if(r.search||r.hash)throw new Error("Identity base URL cannot contain a query or fragment");this.base=n.replace(/\/$/,""),t.schema.property(P.scope,j.ATOMIC_URL).property(P.entity,j.STRING).property(P.localId,j.STRING).property(P.idType,j.STRING).property(P.resource,j.ATOMIC_URL)}key(t,n){if(U(t.scope),!t.entity||typeof n!="string"&&typeof n!="number"||typeof n=="number"&&!Number.isSafeInteger(n)||n==="")throw new Error("Expected an entity and a nonempty string or safe integer external ID");return encodeURIComponent(JSON.stringify([t.scope,t.entity,typeof n,n]))}subjectFor(t,n){return this.lookup(t,n)??`${this.base}/resources/${this.key(t,n)}`}lookup(t,n){return this.key(t,n),this.find(t).find(r=>r[P.localId]===String(n)&&r[P.idType]===typeof n)?.[P.resource]}externalId(t,n){let r=this.find(t).find(s=>s[P.resource]===n);if(r)return r[P.idType]==="number"?Number(r[P.localId]):r[P.localId]}bind(t,n,r){let s=this.key(t,n);U(r);let o=this.lookup(t,n),i=this.externalId(t,r);if(o!==void 0&&o!==r||i!==void 0&&i!==n)throw new Error("Conflicting identity mapping");o===r&&i===n||this.store.put({"@id":`${this.base}/identities/${s}`,[dt]:[P.class],[P.scope]:t.scope,[P.entity]:t.entity,[P.localId]:String(n),[P.idType]:typeof n,[P.resource]:r})}unbind(t,n){if(U(t.scope),U(n),!t.entity)throw new Error("Expected an entity");let r=this.find(t).find(o=>o[P.resource]===n);if(!r)return;let s=this.externalId(t,n);return this.store.delete(r["@id"]),s}find(t){let n=this.store.all(P.class).filter(o=>o[P.scope]===t.scope&&o[P.entity]===t.entity),r=new Set,s=new Set;for(let o of n){let i=o[P.localId],a=o[P.idType],c=o[P.resource];if(typeof i!="string"||!i||!["string","number"].includes(String(a))||typeof c!="string"||a==="number"&&(!Number.isSafeInteger(Number(i))||String(Number(i))!==i))throw new Error("Invalid identity mapping");let u=JSON.stringify([a,i]);if(r.has(u)||s.has(c))throw new Error("Conflicting identity mappings in snapshot");r.add(u),s.add(c)}return n}};var Ue=class{options;pending=Promise.resolve();constructor(t){if(this.options=t,U(t.scope),!t.entity)throw new Error("A lens requires an entity type");if(t.identities.store!==t.store)throw new Error("Lens and identity map must use the same store")}ingest(t){return this.enqueue(async()=>{let{connector:n,identities:r,store:s,read:o}=this.options,i=n.id(t),a=r.subjectFor(this.options,i),c=await o(t,a);return s.transaction(()=>{s.apply([...c.related??[],{subject:a,patch:c}]);for(let u of c.identities??[])r.bind(u.scope,u.id,u.subject);r.bind(this.options,i,a)}),a})}publish(t){return this.enqueue(async()=>{let{connector:n,identities:r,store:s,write:o}=this.options,i=s.get(t);if(!i)throw new Error(`Unknown resource: ${t}`);let a=r.externalId(this.options,t);if(a!==void 0){let m=await n.get(a);return await n.update(a,await o(i,m)),a}let c=JSON.stringify([this.options.scope,this.options.entity,t]),u=await n.create(await o(i,void 0),c),f=n.id(u);return r.bind(this.options,f,t),f})}ingestDelete(t){return this.enqueue(async()=>{let n=this.options.identities.lookup(this.options,t);n&&this.options.store.delete(n)})}delete(t){return this.enqueue(async()=>{let{connector:n,identities:r,store:s}=this.options,o=r.externalId(this.options,t);o!==void 0&&await n.delete(o),s.delete(t)})}enqueue(t){let n=this.pending.then(t);return this.pending=n.catch(()=>{}),n}};var ut=Or(Jt(),1),ye=(e,t)=>(0,ut.default)(e)===(0,ut.default)(t);function pt(e,t,n){let r={local:{},remote:{},createLocal:!1,createRemote:!1,deleteLocal:!1,deleteRemote:!1,conflicts:[]};if(ye(t,n))return t!==void 0&&(r.agreed=structuredClone(t)),r;if(t===null||n===null)return ye(t,e)&&n===null?r.deleteLocal=!0:ye(n,e)&&t===null?r.deleteRemote=!0:r.conflicts.push({property:"@record",base:e,local:t,remote:n}),r;if(e!==void 0&&(t===void 0||n===void 0))return r;r.createLocal=e===void 0&&t===void 0&&n!==void 0,r.createRemote=e===void 0&&n===void 0&&t!==void 0;let s=new Set([...Object.keys(e??{}),...Object.keys(t??{}),...Object.keys(n??{})]);for(let o of s){let i=e?.[o],a=t?.[o],c=n?.[o];ye(a,c)||(ye(a,i)?r.local[o]=structuredClone(c):ye(c,i)?r.remote[o]=structuredClone(a):r.conflicts.push({property:o,base:i,local:a,remote:c}))}return r}var Kt=["Todo","Doing","Blocked","Done"],ft={Doing:"atomic:doing",Blocked:"atomic:blocked"},Ir=Object.values(ft),Cr=e=>(typeof e=="string"?e:e.name).toLowerCase();function ze(e){if(!Number.isSafeInteger(e.number)||e.number<=0||typeof e.title!="string"||!(e.body===null||typeof e.body=="string")||!["open","closed"].includes(e.state)||!Array.isArray(e.labels))throw new Error("GitHub returned an invalid issue");let t=e.labels.map(Cr);return{title:e.title,body:e.body??"",status:e.state==="closed"?"Done":t.includes(ft.Blocked)?"Blocked":t.includes(ft.Doing)?"Doing":"Todo"}}function Wt(e){return{title:e.title,body:e.body,state:e.status==="Done"?"closed":"open"}}function Yt(e){let t=[];for(let r of e.labels){let s=typeof r=="string"?r:r?.name;if(typeof s!="string"||Ir.includes(s.toLowerCase()))continue;let o=typeof r=="object"?r.color:"",i=typeof o=="string"?o:"";t.push(/^[0-9a-f]{6}$/i.test(i)?{name:s,color:`#${i.toLowerCase()}`}:{name:s})}let n=Array.isArray(e.assignees)?e.assignees.map(r=>r?.login).filter(r=>typeof r=="string"):[];return{labels:t,assignees:n,...Number.isSafeInteger(e.comments)&&e.comments>=0?{commentCount:e.comments}:{}}}var Mr={Accept:"application/vnd.github+json","User-Agent":"Atomic-GitHub-Issues-Pilot","X-GitHub-Api-Version":"2022-11-28",Authorization:"secret:github","Content-Type":"application/json"};function we(e){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(e)||e.split("/").some(t=>t==="."||t===".."))throw new Error("Repository must be owner/name");return`https://api.github.com/repos/${e}/issues`}function q(e,t,n,r,s){return{operation:e,method:t,url:n,id:r,headers:Mr,...s===void 0?{}:{body:JSON.stringify(s)}}}var Hr="https://atomicdata.dev/properties/parent",mt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),gt=(e,t)=>`${e} +${t}`;function Fe(e,{known:t={},indexed:n=[],overlay:r=new Map}={}){let s=new Map,o={creates:0,saves:0},i=new Map,a=async m=>{if(!e.getMany)return;let g=m.filter(b=>!i.has(b));for(let b=0;b[]);for(let E of w)"error"in E&&E.error||i.set(E.subject,E)}},c=(m,g,b)=>{if(typeof g!="string"||!n.includes(m))return;let w=t[gt(m,g)]??=[];w.includes(b)||w.push(b)},u=async m=>{let g=i.get(m);i.delete(m);let b=g??await e.getResource(m),w=r.get(m);if(!w)return b;for(let[E,{stale:T,after:A}]of w){let _=b.get(E);!mt(_,A)&&T.some(H=>mt(H,_))?A===void 0?b.remove(E):b.set(E,A):w.delete(E)}return w.size||r.delete(m),b},f=m=>{let g={subject:m.subject,error:void 0,get:b=>m.get(b),set(b,w){let E=s.get(g)??new Map;return E.has(b)||E.set(b,m.get(b)),s.set(g,E),m.set(b,w),g},remove(b){let w=s.get(g)??new Map;return w.has(b)||w.set(b,m.get(b)),s.set(g,w),m.remove(b),g},async save(){let b=s.get(g);if(!b)return;await m.save(),o.saves++,i.delete(m.subject),s.delete(g);let w=r.get(m.subject)??new Map;for(let[E,T]of b){let A=m.get(E),_=w.get(E);w.set(E,{stale:_?[..._.stale,_.after]:[T],after:A}),c(E,A,m.subject)}r.set(m.subject,w)},getLoroDoc(){}};return g};return{writes:o,isLocalOnlyDrive:()=>!1,hasCompletedDriveSyncFor:()=>!0,getSaveState:m=>({kind:s.has(m)?"pending":"idle"}),async queryLocalDb({property:m,value:g}){let b=await e.query({property:m,value:String(g)}),w=[...b];await a([...b,...t[gt(m,String(g))]??[]]);for(let E of t[gt(m,String(g))]??[]){if(w.includes(E))continue;let T=await u(E).catch(()=>{});T&&mt(T.get(m),g)&&w.push(E)}for(let E of b)c(m,String(g),E);return{count:w.length,subjects:w}},async getResource(m){return f(await u(m))},async newResource({parent:m,isA:g,propVals:b={}}){let w=await e.newResource({parent:m,isA:g,propVals:b});o.creates++,m&&c(Hr,m,w.subject);for(let[E,T]of Object.entries(b))c(E,T,w.subject);return f(w)}}}var Xt=()=>({version:1,journal:{},known:{},stale:[]});function Nr(e){if(typeof e!="string"||!e)return Xt();let t=JSON.parse(e);if(t.version!==1)throw new Error("Unsupported sync state version");return{...Xt(),...t,journal:t.journal??{},known:t.known??{},stale:t.stale??[]}}var Lr=e=>Object.values(e?.records??{}).some(t=>t.pending&&(!t.pending.held||t.unconfirmed)),Be=class{constructor(t,n){this.resource=t;this.property=n;this.state=Nr(t.get(n))}resource;property;state;dirty=!1;chain=Promise.resolve();async saveSnapshot(t){this.state.snapshot=t,Lr(t)?await this.flush():this.dirty=!0}async saveJournal(){await this.flush()}get isDirty(){return this.dirty}async flushIfDirty(){this.dirty&&await this.flush()}flush(){let t=this.chain.then(async()=>{this.dirty=!1,this.resource.set(this.property,JSON.stringify(this.state)),await this.resource.save()});return this.chain=t.catch(()=>{}),t}};var Zt=e=>e!=null&&e!=="";function Dr(e){if(!e||typeof e.subject!="string"||!Array.isArray(e.requires)||!Array.isArray(e.recommends))throw new TypeError("a shared class needs subject, requires and recommends (import it from terms.mjs)")}function Qt({classes:e,lenses:t=[]}){if(!Array.isArray(e)||!e.length)throw new TypeError("createResolver needs at least one shared class");let n=new Map;for(let a of e)Dr(a),n.set(a.subject,a);let r=new Map;for(let a of t){if(!a||typeof a.from!="string"||typeof a.to!="string")throw new TypeError("a lens needs from and to class subjects");if(typeof a.read!="function")throw new TypeError(`the lens from ${a.from} needs a read function`);if(!n.has(a.to))throw new Error(`the lens from ${a.from} maps to ${a.to}, which this resolver does not render`);if(n.has(a.from))throw new Error(`${a.from} is a shared class this resolver renders; it needs no lens`);if(r.has(a.from))throw new Error(`two lenses map from ${a.from}`);r.set(a.from,a)}let s=a=>{if(n.has(a))return{kind:"shared",class:n.get(a)};let c=r.get(a);return c?{kind:"lens",class:n.get(c.to),lens:c}:null},o=a=>{let c=s(a);if(!c)throw new Error(`${a} is not a class this view renders, and no lens maps it`);return c},i=a=>[...a.requires,...a.recommends];return{classes:[...n.keys()],match:s,accepts:a=>s(a)!==null,read(a,c){let u=o(c),f=u.kind==="lens"?u.lens.read(a):a;if(!f||typeof f!="object")throw new TypeError(`the lens from ${c} returned no row`);let m={};for(let b of i(u.class))Zt(f[b])&&(m[b]=f[b]);let g=u.class.requires.filter(b=>!Zt(m[b]));return{class:u.class.subject,via:u.kind,values:m,missing:g,complete:g.length===0}},write(a,c,u={}){let f=o(c),m=new Set(i(f.class)),g=Object.keys(a).filter(b=>!m.has(b));if(g.length)throw new Error(`${g.join(", ")} ${g.length===1?"is":"are"} not a field of ${f.class.subject}`);if(f.kind==="shared")return{...a};if(typeof f.lens.write!="function")throw new Error(`the lens from ${c} is read-only`);return f.lens.write(a,u)}}}var Eo=Object.freeze({v1:"https://ontola.github.io/atomic-plugins/ontology/v1"}),To=Object.freeze({"atomic-calendar-day":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-day",datatype:"https://atomicdata.dev/datatypes/date"}),"atomic-calendar-end-day":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-end-day",datatype:"https://atomicdata.dev/datatypes/date"}),"atomic-calendar-all-day":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-all-day",datatype:"https://atomicdata.dev/datatypes/boolean"}),"atomic-calendar-start":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-start",datatype:"https://atomicdata.dev/datatypes/string"}),"atomic-calendar-end":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-end",datatype:"https://atomicdata.dev/datatypes/string"}),"atomic-calendar-location":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-location",datatype:"https://atomicdata.dev/datatypes/string"}),"atomic-calendar-notes":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-notes",datatype:"https://atomicdata.dev/datatypes/string"}),"atomic-calendar-recurrence":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-recurrence",datatype:"https://atomicdata.dev/datatypes/json"}),"work-start":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/work-start",datatype:"https://atomicdata.dev/datatypes/timestamp"}),"work-end":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/work-end",datatype:"https://atomicdata.dev/datatypes/timestamp"}),"work-project":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/work-project",datatype:"https://atomicdata.dev/datatypes/atomicURL",classtype:"https://ontola.github.io/atomic-plugins/ontology/classes/work-project-v1"}),"work-person":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/work-person",datatype:"https://atomicdata.dev/datatypes/atomicURL",classtype:"https://ontola.github.io/atomic-plugins/ontology/classes/work-person-v1"}),"work-billable":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/work-billable",datatype:"https://atomicdata.dev/datatypes/boolean"}),"bank-account":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/bank-account",datatype:"https://atomicdata.dev/datatypes/string"}),"bank-currency":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/bank-currency",datatype:"https://atomicdata.dev/datatypes/string"}),"bank-amount":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/bank-amount",datatype:"https://atomicdata.dev/datatypes/string"}),"bank-value-date":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/bank-value-date",datatype:"https://atomicdata.dev/datatypes/date"}),"bank-booking-date":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/bank-booking-date",datatype:"https://atomicdata.dev/datatypes/date"}),"bank-description":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/bank-description",datatype:"https://atomicdata.dev/datatypes/string"}),"bank-reference":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/bank-reference",datatype:"https://atomicdata.dev/datatypes/string"}),"money-category":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/money-category",datatype:"https://atomicdata.dev/datatypes/string"}),"money-note":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/properties/money-note",datatype:"https://atomicdata.dev/datatypes/string"})}),Ve=Object.freeze({"event-v1":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/classes/event-v1",requires:Object.freeze(["https://atomicdata.dev/properties/name","https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-day"]),recommends:Object.freeze(["https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-end-day","https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-all-day","https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-start","https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-end","https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-location","https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-notes","https://ontola.github.io/atomic-plugins/ontology/properties/atomic-calendar-recurrence"])}),"issue-v1":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/classes/issue-v1",requires:Object.freeze(["https://atomicdata.dev/properties/name"]),recommends:Object.freeze(["https://atomicdata.dev/task/v1/status","https://atomicdata.dev/task/v1/body","https://atomicdata.dev/task/v1/assignee","https://atomicdata.dev/task/v1/due-date"])}),"time-entry-v1":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/classes/time-entry-v1",requires:Object.freeze(["https://ontola.github.io/atomic-plugins/ontology/properties/work-start"]),recommends:Object.freeze(["https://atomicdata.dev/properties/name","https://ontola.github.io/atomic-plugins/ontology/properties/work-end","https://ontola.github.io/atomic-plugins/ontology/properties/work-project","https://ontola.github.io/atomic-plugins/ontology/properties/work-person","https://ontola.github.io/atomic-plugins/ontology/properties/work-billable"])}),"work-project-v1":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/classes/work-project-v1",requires:Object.freeze(["https://atomicdata.dev/properties/name"]),recommends:Object.freeze([])}),"work-person-v1":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/classes/work-person-v1",requires:Object.freeze(["https://atomicdata.dev/properties/name"]),recommends:Object.freeze([])}),"bank-transaction-v1":Object.freeze({subject:"https://ontola.github.io/atomic-plugins/ontology/classes/bank-transaction-v1",requires:Object.freeze(["https://ontola.github.io/atomic-plugins/ontology/properties/bank-account","https://ontola.github.io/atomic-plugins/ontology/properties/bank-currency","https://ontola.github.io/atomic-plugins/ontology/properties/bank-amount","https://ontola.github.io/atomic-plugins/ontology/properties/bank-value-date"]),recommends:Object.freeze(["https://atomicdata.dev/properties/name","https://ontola.github.io/atomic-plugins/ontology/properties/bank-booking-date","https://ontola.github.io/atomic-plugins/ontology/properties/bank-description","https://ontola.github.io/atomic-plugins/ontology/properties/bank-reference","https://ontola.github.io/atomic-plugins/ontology/properties/money-category","https://ontola.github.io/atomic-plugins/ontology/properties/money-note"])})});var J={title:"https://atomicdata.dev/properties/name",body:"https://atomicdata.dev/task/v1/body",status:"https://atomicdata.dev/task/v1/status"},Re="https://atomicdata.dev/task/v1/";function en(e){return{[J.body]:e.body,...e.title===void 0?{}:{[J.title]:e.title,[J.status]:[`${Re}${e.status.toLowerCase()}`]}}}function tn(e,t){if(t!=="issue")return{body:e[J.body]};let n={[`${Re}todo`]:"Todo",[`${Re}doing`]:"Doing",[`${Re}blocked`]:"Blocked",[`${Re}done`]:"Done"}[e[J.status]?.[0]];if(!n||e[J.status].length!==1)throw new Error("Unsupported task status");return{title:e[J.title],body:e[J.body],status:n}}var se=(e,t)=>JSON.stringify(e)===JSON.stringify(t),z=e=>structuredClone(e),qe=class{constructor({devonian:t,local:n,remote:r,base:s,snapshot:o,save:i,imported:a,uncertain:c}){this.api=t,this.uncertain=c,this.unsettled=new Map,this.imported=a,this.local=n,this.remote=r,this.save=i;let{AtomicSchema:u,AtomicStore:f,AtomicIdentityMap:m,Datatype:g}=t;if(this.store=new f(new u().property(J.title,g.STRING).property(J.body,g.MARKDOWN).property(J.status,g.RESOURCEARRAY)),this.identities=new m(this.store,s),this.binding={base:s,local:n.scope,remote:r.scope},o&&!se(o.binding,this.binding))throw new Error("State belongs to another connection");o?.graph&&this.store.loadJSONAD(o.graph),this.records=z(o?.records??{}),this.held=new Map}scope(t,n){return{scope:this[t].scope,entity:n}}id(t,n,r){return this.identities.externalId(this.scope(t,n),r)}context(t,n){if(n==="issue")return{};let r=n.slice(8),s=this.id(t,"issue",r);if(s===void 0)throw new Error("Issue must be mapped before comments");return{issueId:s}}async checkpoint(){await this.save({version:1,binding:this.binding,graph:this.store.toJSONAD(),records:z(this.records)})}properties(t){return en(t)}value(t,n){return tn(t,n)}lens(t,n,r,s){let o=this[t],i=this.context(t,n);return new this.api.AtomicLens({store:this.store,identities:this.identities,...this.scope(t,n),connector:{id:a=>a.id,get:a=>o.get(n,a,i),create:(a,c)=>o.create(n,a.value,c,s,i),update:(a,c)=>o.update(n,a,c.value,`${r}:${t}`,s,i),delete:async()=>{throw new Error("Deletion is outside issue sync")}},read:a=>({set:this.properties(a.value)}),write:(a,c)=>({...c,value:this.value(a,n)})})}async sync(){this.held.clear(),this.unsettled.clear();for(let[t,n]of Object.entries(this.records))n.pending?.held?delete n.pending:n.pending&&await this.attempt(t,n,!0);for(let[t,n,r]of await this.uncertainCreates())this.unsettled.set(t,{subject:t,entity:n,sent:r,candidates:[]});await this.syncEntity("issue");for(let[t,n]of Object.entries(this.records))n.entity==="issue"&&(this.id("local","issue",t)===void 0||this.id("remote","issue",t)===void 0||await this.syncEntity(`comment:${t}`));for(let t of this.unsettled.keys())this.held.delete(t)}async attempt(t,n,r=!1){try{await this.finish(t,n),delete n.unconfirmed,this.held.delete(t)}catch(s){if(s?.name!=="ReviewRequired")throw s;n.pending.held=!0,r&&(n.unconfirmed=!0),await this.checkpoint(),this.held.set(t,{subject:t,entity:n.entity,remoteId:this.id("remote",n.entity,t),before:z(n.pending.remote),after:z(n.pending.desired),key:s.proposal?.key,...n.unconfirmed?{unconfirmed:!0}:{}})}}async uncertainCreates(){if(!this.uncertain)return[];let t=[];for(let[n,r]of Object.entries(this.records)){if(this.id("local",r.entity,n)===void 0||this.id("remote",r.entity,n)!==void 0)continue;let s=await this.uncertain.sent(r.entity,n);s&&t.push([n,r.entity,s])}return t}candidate(t,n,r){return(n.value?.body??"")!==(r.body??"")?!1:t!=="issue"||n.value?.title===r.title}async landed(t,n){let r=this.records[t];if(!r)throw new Error(`Unknown record: ${t}`);let{entity:s}=r,o=await this.uncertain?.sent(s,t);if(!o||this.id("remote",s,t)!==void 0)throw new Error(`No uncertain create on ${t}`);let i=this.scope("remote",s);if(this.identities.lookup(i,n)!==void 0)throw new Error(`Already bound: ${s==="issue"?`#${n}`:`comment ${n}`} belongs to another record on this board`);let c=await this.remote.get(s,n,this.context("remote",s));return this.identities.bind(i,n,t),r.baseline=s==="issue"?{title:o.title,body:o.body??"",status:"Todo"}:{body:o.body??""},delete r.pending,delete r.unconfirmed,this.unsettled.delete(t),this.held.delete(t),await this.checkpoint(),c}async notArrived(t){let n=this.records[t];if(!n)throw new Error(`Unknown record: ${t}`);let{entity:r}=n,s=await this.uncertain?.sent(r,t);if(!s||this.id("remote",r,t)!==void 0)throw new Error(`No uncertain create on ${t}`);let o=this.scope("remote",r),a=(await this.remote.list(r,this.context("remote",r))).find(c=>this.identities.lookup(o,c.id)===void 0&&this.candidate(r,c,s));if(a)throw new Error(`It may have landed: ${r==="issue"?`#${a.id}`:`comment ${a.id}`} on GitHub matches what was sent`);await this.uncertain.forget(r,t),delete n.unconfirmed,this.unsettled.delete(t),await this.checkpoint()}async conflictRows(t){let n=this.records[t];if(!n)throw new Error(`Unknown record: ${t}`);if(n.pending)throw new Error(`Finish the saved operation on ${t} first`);let r={};for(let o of["local","remote"]){let i=this.id(o,n.entity,t);if(i===void 0)throw new Error(`Missing ${o} record: ${t}`);r[o]=await this[o].get(n.entity,i,this.context(o,n.entity))}let s=pt(n.baseline,r.local.value,r.remote.value);return{record:n,rows:r,decision:s}}async describeConflict(t){let{record:n,rows:r,decision:s}=await this.conflictRows(t);return s.conflicts.map(({property:o})=>({field:o,base:z(n.baseline?.[o]),local:z(r.local.value[o]),remote:z(r.remote.value[o])}))}async resolveConflict(t,n){if(typeof n=="string"&&n!=="local"&&n!=="remote")throw new Error("Keep either the local or the remote side");let r=typeof n=="object"&&n!==null?n:{},s=u=>typeof n=="string"?n:r[u],{record:o,rows:i,decision:a}=await this.conflictRows(t);for(let{property:u}of a.conflicts){let f=s(u);if(f===void 0&&typeof n!="string")throw new Error(`Choose a side for ${u}`);if(f!=="local"&&f!=="remote")throw new Error("Keep either the local or the remote side")}let c=z(o.baseline??{});for(let{property:u}of a.conflicts){let f=s(u)==="local"?"remote":"local",m=i[f].value[u];m===void 0?delete c[u]:c[u]=z(m)}return o.baseline=c,await this.checkpoint(),a.conflicts.map(u=>u.property)}async keepLocalOnly(t){let n=this.records[t];if(n?.entity!=="issue")throw new Error(`Unknown issue: ${t}`);let r=this.identities.unbind(this.scope("remote","issue"),t);delete n.pending,n.localOnly=!0;for(let[s,o]of Object.entries(this.records))o.entity===`comment:${t}`&&(this.identities.unbind(this.scope("remote",o.entity),s),delete o.pending);return await this.checkpoint(),r}async forget(t){if(this.records[t]?.entity!=="issue")throw new Error(`Unknown issue: ${t}`);let r=[];for(let[s,o]of Object.entries(this.records))if(!(s!==t&&o.entity!==`comment:${t}`)){for(let i of["remote","local"]){let a=this.identities.unbind(this.scope(i,o.entity),s);i==="local"&&a!==void 0&&r.push(a)}delete this.records[s]}return await this.checkpoint(),r}async syncEntity(t){let n={};for(let s of["remote","local"]){let o=await this[s].list(t,this.context(s,t));n[s]=new Map;for(let i of o){if(n[s].has(i.id))throw new Error("Duplicate external identity");n[s].set(i.id,i)}}for(let s of n.local.values()){if(s.remoteId===void 0)continue;let o=this.scope("remote",t),i=this.identities.subjectFor(o,s.remoteId);this.records[i]?.localOnly||(this.identities.bind(o,s.remoteId,i),this.identities.bind(this.scope("local",t),s.id,i),this.records[i]??={entity:t})}let r=[...this.unsettled.values()].filter(s=>s.entity===t);for(let s of["remote","local"])for(let o of n[s].values()){let i=this.identities.lookup(this.scope(s,t),o.id);if(!i&&s==="remote"){let a=r.filter(c=>this.candidate(t,o,c.sent));for(let c of a)c.candidates.push(z(o));if(a.length)continue}i||(i=await this.lens(s,t).ingest(o)),this.records[i]??={entity:t}}await this.checkpoint();for(let[s,o]of Object.entries(this.records)){if(o.entity!==t)continue;let i=!1;if(o.localOnly){if(this.id("remote",t,s)===void 0)continue;delete o.localOnly,i=!0}let a={};for(let m of["local","remote"]){let g=this.id(m,t,s);if(a[m]=g===void 0?void 0:n[m].get(g),g!==void 0&&!a[m])throw new Error(`Missing ${m} record: ${s}`)}let c=pt(o.baseline,a.local?.value,a.remote?.value);if(c.conflicts.length){let m=c.conflicts.map(b=>b.property),g=new Error(`Conflict on ${s}: ${m.join(", ")}`);throw Object.assign(g,{subject:s,entity:t,fields:m}),g}let u={...a.remote?.value??a.local?.value,...c.remote},f=a.remote?.metadata;if(a.remote&&!a.local&&o.baseline===void 0&&!i){this.store.patch(s,{set:this.properties(u)});let m=await this.lens("local",t,crypto.randomUUID(),f).publish(s);o.baseline=z(u),await this.checkpoint(),await this.imported?.({entity:t,subject:s,row:{id:m,...t==="issue"?{remoteId:a.remote.id}:{},value:z(u),...f?{metadata:z(f)}:{}},context:this.context("local",t)});continue}if(a.local&&a.remote&&se(a.local.value,a.remote.value)&&se(a.local.metadata,f)&&!i){o.baseline=z(u),await this.checkpoint();continue}o.pending={operation:crypto.randomUUID(),local:a.local?.value,remote:a.remote?.value,desired:u,metadata:f,...i?{relink:i}:{}},this.store.patch(s,{set:this.properties(u)}),await this.checkpoint(),await this.attempt(s,o)}}async finish(t,n){let{pending:r,entity:s}=n;for(let o of["local","remote"]){let i=this.id(o,s,t);if(i===void 0)continue;let a=await this[o].get(s,i,this.context(o,s));if(!se(a.value,r[o])&&!se(a.value,r.desired))throw new Error(`Conflict during saved operation on ${t}`)}for(let o of["remote","local"]){let i=this.id(o,s,t),a=i===void 0?void 0:await this[o].get(s,i,this.context(o,s));(!a||!se(a.value,r.desired)||o==="local"&&(r.relink||!se(a.metadata,r.metadata)))&&(await this.lens(o,s,r.operation,r.metadata).publish(t),await this.checkpoint())}for(let o of["local","remote"]){let i=await this[o].get(s,this.id(o,s,t),this.context(o,s));if(!se(i.value,r.desired))throw new Error(`Concurrent edit after write on ${t}`)}n.baseline=z(r.desired),delete n.pending,await this.checkpoint()}};var Io=Z.properties.commentsFolder??"https://atomicdata.dev/properties/commentsFolder";function nn(e,t){if(typeof t!="string"||!t)throw new Error("An Atomic drive is required");if(typeof e.isLocalOnlyDrive=="function"&&e.isLocalOnlyDrive(t))return{drive:t,kind:"local-only",ready:!0};let n=typeof e.hasCompletedDriveSyncFor=="function"&&e.hasCompletedDriveSyncFor(t)===!0;return{drive:t,kind:"synced",ready:n}}function rn(e,t){let n=nn(e,t);if(!n.ready)throw new Error(`Atomic drive has not finished syncing: ${t}`);return n}function ve(e,t,n,r){if(r==="offline")throw new Error("AtomicServer disconnected");if(nn(e,t).kind==="local-only")return;if(typeof e.getSaveState!="function")throw new Error(`Atomic write not acknowledged: ${n.subject}`);let s=e.getSaveState(n);if(s?.kind==="error")throw new Error(`Atomic write rejected: ${n.subject}: ${s.error??"unknown error"}`);if(s?.kind!=="idle")throw new Error(`Atomic write not acknowledged: ${n.subject}`)}var We=async e=>Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(e))),t=>t.toString(16).padStart(2,"0")).join(""),_r=(e,t)=>JSON.stringify(e)===JSON.stringify(t),Je=class{constructor(t,n,r){if(this.store=t,this.connection=n,this.scope=`https://github.com/${n.repository}`,!r)throw new Error("A browser integration-proxy transport is required");this.call=r}async request(t,n,r){let s=await this.call(t,n,await We(r??`${t}:${JSON.stringify(n)}`));if(s.status<200||s.status>=300)throw new Error(`GitHub ${t} returned ${s.status}`);return s.body?JSON.parse(s.body):void 0}row(t,n,r={}){if(t==="issue"){if(n.pull_request)throw new Error("Pull requests are excluded");return{id:n.number,value:ze(n),metadata:this.metadata(n,{number:n.number,...Yt(n)})}}if(!Number.isSafeInteger(n.id)||n.id<=0||typeof n.body!="string")throw new Error("Invalid GitHub comment");let s=`https://api.github.com/repos/${this.connection.repository}/issues/${r.issueId}`;if(n.issue_url!==s)throw new Error("Comment belongs to another issue");return{id:n.id,value:{body:n.body},metadata:this.metadata(n,{commentId:n.id})}}metadata(t,n){return{...n,...t.user?.login?{author:t.user.login}:{},...t.html_url?{url:t.html_url}:{},...t.created_at?{createdAt:t.created_at}:{},...t.updated_at?{updatedAt:t.updated_at}:{}}}async list(t,n={}){let r=[];for(let s=1;s<=100;s++){let o=await this.request(t==="issue"?"list_issues":"list_comments",{page:s,...t==="issue"?{}:{number:n.issueId}});if(!Array.isArray(o))throw new Error("Invalid GitHub page");for(let i of o)t==="issue"&&"pull_request"in i||r.push(this.row(t,i,n));if(o.length<100)return r}throw new Error("More than 10,000 records in one scan")}async get(t,n,r){let s=await this.request(t==="issue"?"get_issue":"get_comment",t==="issue"?{number:n}:{id:n}),o=this.row(t,s,r);if(o.id!==n)throw new Error("Provider returned another identity");return o}async create(t,n,r,s,o){let i=await this.request(t==="issue"?"create_issue":"create_comment",t==="issue"?{title:n.title,body:n.body}:{number:o.issueId,body:n.body},`${r}:create`),a=this.row(t,i,o);return t==="issue"&&n.status!=="Todo"&&await this.update(t,a.id,n,`${r}:initial-state`,s,o),{...a,value:n}}async update(t,n,r,s,o,i){if(t!=="issue"){await this.get(t,n,i),await this.request("update_comment",{id:n,body:r.body},`${s}:body`);return}if(!Kt.includes(r.status))throw new Error("Unsupported task status");if(await this.get(t,n,i),await this.request("update_issue",{number:n,...Wt(r)},`${s}:fields`),r.status==="Done")return;let a=await this.request("get_issue",{number:n}),c=new Set(a.labels.map(f=>(typeof f=="string"?f:f.name).toLowerCase())),u=[["Doing","atomic:doing","add_doing_label","remove_doing_label","doing","todo"],["Blocked","atomic:blocked","add_blocked_label","remove_blocked_label","blocked","unblocked"]];for(let[f,m,,g,,b]of u)r.status!==f&&c.has(m)&&await this.request(g,{number:n},`${s}:${b}`);for(let[f,m,g,,b]of u)r.status===f&&!c.has(m)&&await this.request(g,{number:n},`${s}:${b}`)}},Ke=class{constructor(t,n){this.store=t,this.config=n,this.connection=n.connection,this.scope=`https://atomicdata.dev/devonian-local/${encodeURIComponent(this.connection.table)}`}async subjects(t,n){rn(this.store,this.connection.drive);let r=await this.store.queryLocalDb({drive:this.connection.drive,property:t,value:n,limit:10001});if(!r||r.count>1e4||r.subjects.length!==r.count)throw new Error("Incomplete local database query");return r.subjects}async findByLocalId(t,n){let s=(await Promise.all((await this.subjects(V.properties.localId,n)).map(o=>this.resource(o)))).filter(o=>o.get(V.properties.parent)===t);if(s.length>1)throw new Error("Duplicate Atomic creation identity");return s[0]}async resource(t){let n=await this.store.getResource(t);if(n.error)throw n.error;return n.getLoroDoc(),n}row(t,n,r={}){let s=this.connection,o=n.get(V.properties.isA)??[];if(t==="issue"){if(!o.includes(s.rowClass)||n.get(V.properties.parent)!==s.table)throw new Error("Resource is not a row of this issue tracker")}else if(!o.includes(Z.classes.message)||n.get(Z.properties.about)!==r.issueId)throw new Error("Message belongs to another issue");let i=n.get(this.config.provenance);if(typeof i=="string"&&(i=JSON.parse(i)),t!=="issue"){let g=i?.commentId;return{id:n.subject,...Number.isSafeInteger(g)&&g>0?{remoteId:g}:{},value:{body:n.get(V.properties.description)??""},...i?{metadata:i}:{}}}let a=n.get(s.status)??[s.tags.Todo],c=Object.keys(s.tags).find(g=>s.tags[g]===a[0]);if(a.length!==1||!c)throw new Error("Choose exactly one Todo/Doing/Blocked/Done status");let u=n.get(V.properties.name),f=n.get(s.body)??"";if(typeof u!="string"||!u.trim()||typeof f!="string")throw new Error("Invalid Atomic issue");let m=n.get(s.number);if(m!==void 0&&(!Number.isSafeInteger(m)||m<=0))throw new Error("Invalid GitHub issue number");return{id:n.subject,remoteId:m,value:{title:u,body:f,status:c},...i?{metadata:i}:{}}}async list(t,n={}){let r=await this.subjects(t==="issue"?V.properties.parent:Z.properties.about,t==="issue"?this.connection.table:n.issueId),s=[];for(let o of r){let i=await this.resource(o);(i.get(V.properties.isA)??[]).includes(t==="issue"?this.connection.rowClass:Z.classes.message)&&s.push(this.row(t,i,n))}return s}async get(t,n,r){return this.row(t,await this.resource(n),r)}values(t,n,r,s){let o=this.connection;return{...t==="issue"?{[V.properties.name]:n.title,[o.body]:n.body,[o.status]:[o.tags[n.status]],...r?.number?{[o.number]:r.number}:{}}:{[V.properties.description]:n.body,[Z.properties.about]:s.issueId},...r?{[this.config.provenance]:r}:{}}}async create(t,n,r,s,o){let i=t==="issue"?this.connection.table:this.config.commentsFolder,a=`devonian:${await We(r)}`,c=await this.findByLocalId(i,a);if(c){ve(this.store,this.connection.drive,c);let f=await this.get(t,c.subject,o);if(!_r(f.value,n))throw new Error("Recovered Atomic create was edited; reconcile before retry");return f}let u=await this.store.newResource({parent:i,isA:[t==="issue"?this.connection.rowClass:Z.classes.message],propVals:{...this.values(t,n,s,o),[V.properties.localId]:a}});return ve(this.store,this.connection.drive,u,await u.save()),this.get(t,u.subject,o)}async update(t,n,r,s,o,i){let a=await this.resource(n);this.row(t,a,i);for(let[c,u]of Object.entries(this.values(t,r,o,i)))await a.set(c,u);ve(this.store,this.connection.drive,a,await a.save())}};var W={type:"integer",description:"Positive identifier or page number"},$e={type:"string",description:"Issue or comment field value"},sn=[["list_issues","List issues","list",{page:W},["page"]],["update_issue","Update an issue","update",{number:W,title:$e,body:$e,state:$e},["number","title","body","state"]],["add_doing_label","Mark an issue as doing","doing-add",{number:W},["number"]],["remove_doing_label","Remove the doing label","doing-remove",{number:W},["number"]],["add_blocked_label","Mark an issue as blocked","blocked-add",{number:W},["number"]],["remove_blocked_label","Remove the blocked label","blocked-remove",{number:W},["number"]],["list_comments","List issue comments","comments-list",{number:W,page:W},["number","page"]],["get_comment","Get an issue comment","comments-get",{id:W},["id"]],["create_comment","Create an issue comment","comments-create",{number:W,body:$e},["number","body"]],["update_comment","Update an issue comment","comments-update",{id:W,body:$e},["id","body"]]],_o=sn.map(([e,t,n,r,s])=>({name:e,title:t,description:`${t} in this connected repository. Writes require approval.`,operation:n,inputSchema:{type:"object",properties:r,required:[...s],additionalProperties:!1}}));function on(e,t,n){let r=sn.find(c=>c[0]===t);if(!r)return;let[,,s,o,i]=r;for(let c of i)if(!(c in n))throw new Error(`Missing ${c}`);for(let[c,u]of Object.entries(n)){if(!(c in o))throw new Error(`Unexpected ${c}`);if(["number","id","page"].includes(c)){if(!Number.isSafeInteger(u)||Number(u)<=0||c==="page"&&Number(u)>100)throw new Error(`Invalid ${c}`)}else if(typeof u!="string")throw new Error(`Invalid ${c}`)}let a=we(e);switch(t){case"list_issues":return q(s,"GET",`${a}?state=all&per_page=100&page=${n.page}&sort=created&direction=asc`,"action");case"list_comments":return q(s,"GET",`${a}/${n.number}/comments?per_page=100&page=${n.page}`,"action");case"get_comment":return q(s,"GET",`${a}/comments/${n.id}`,"action");case"create_comment":case"update_comment":if(!n.body.trim())throw new Error("Comment body cannot be empty");return q(s,t==="create_comment"?"POST":"PATCH",t==="create_comment"?`${a}/${n.number}/comments`:`${a}/comments/${n.id}`,"action",{body:n.body});case"add_doing_label":return q(s,"POST",`${a}/${n.number}/labels`,"action",{labels:["atomic:doing"]});case"remove_doing_label":return q(s,"DELETE",`${a}/${n.number}/labels/atomic%3Adoing`,"action");case"add_blocked_label":return q(s,"POST",`${a}/${n.number}/labels`,"action",{labels:["atomic:blocked"]});case"remove_blocked_label":return q(s,"DELETE",`${a}/${n.number}/labels/atomic%3Ablocked`,"action");case"update_issue":if(!["open","closed"].includes(String(n.state)))throw new Error("Invalid issue state");if(!n.title.trim()||n.title.length>256)throw new Error("Invalid issue title");return q(s,"PATCH",`${a}/${n.number}`,"action",{title:n.title,body:n.body,state:n.state})}}function an({repository:e,journal:t,save:n,dispatch:r}){if(typeof r!="function")throw new Error("proxyTransport needs a dispatch function");let s=we(e),o=Promise.resolve();return(i,a,c)=>{let u=async()=>{if(i==="get_issue"&&(!Number.isSafeInteger(a.number)||a.number<=0))throw new Error("Invalid issue number");if(i==="create_issue"&&(typeof a.title!="string"||!a.title.trim()||a.title.length>256||a.body!==void 0&&typeof a.body!="string"))throw new Error("Invalid issue title or body");let m=on(e,i,a)??(i==="get_issue"?q("get","GET",`${s}/${a.number}`,c):i==="create_issue"?q("create","POST",s,c,a):void 0);if(!m)throw new Error("Unsupported GitHub action");let g=m.method!=="GET",b=JSON.stringify({action:i,args:a}),w=t[c];if(g&&w){if(w.signature!==b)throw new Error("Operation identity reused with different arguments");if(w.receipt)return w.receipt;throw new Error(`Uncertain GitHub write (${i}). Inspect its outcome before retrying; it will not be resent.`)}g&&(t[c]={signature:b},await n());let E=new URL(m.url),T=await r(`${E.pathname}${E.search}`,{method:m.method,...m.body?{body:m.body}:{}}).catch(async A=>{throw A?.notSent?(g&&(delete t[c],await n()),A):new Error(`Proxy request failed (${A?.message??A}). Check CORS and reconnect; an uncertain write will not be resent.`)});return g&&T.status>=200&&T.status<300&&(t[c].receipt=T,await n()),T},f=o.then(u);return o=f.catch(()=>{}),f}}var ht=class extends Error{constructor(t){super(`Review required before writing to GitHub: ${t.key}`),this.name="ReviewRequired",this.proposal=t}};function Gr(e,t,n){return JSON.stringify([e,t??null,n])}function cn(e,t=new Set){let n=(r,s,o)=>{let i=Gr(r,s,o);if(!t.has(i))throw new ht({key:i,entity:r,id:s,value:o})};return{get scope(){return e.scope},list:(...r)=>e.list(...r),get:(...r)=>e.get(...r),create(r,s,...o){return n(r,void 0,s),e.create(r,s,...o)},update(r,s,o,...i){return n(r,s,o),e.update(r,s,o,...i)}}}var O="https://atomicdata.dev",F=`${O}/properties/parent`,ke=`${O}/properties/isA`,G=`${O}/properties/name`,Q=`${O}/properties/shortname`,ee=`${O}/properties/description`,Ur=`${O}/properties/datatype`,fn=`${O}/properties/recommends`,Ye=`${O}/properties/properties`,ln=`${O}/properties/classes`,dn=`${O}/properties/classtype`,zr=`${O}/properties/allowsOnly`,te=`${O}/properties/localId`,qo=`${O}/properties/color`,le=`${O}/properties/about`,Fr=`${O}/classes/Property`,Jo=`${O}/classes/SelectProperty`,Br=`${O}/classes/Class`,Ko=`${O}/classes/Tag`,Vr=`${O}/classes/Folder`,mn=`${O}/classes/Message`,qr=`${O}/ontology/server/property/default-ontology`,ce=Ve["issue-v1"].subject,xe=`${O}/task/v1`,je=`${xe}/status`,Pe=`${xe}/body`,Ae={string:`${O}/datatypes/string`,integer:`${O}/datatypes/integer`},de=["Todo","Doing","Blocked","Done"],Oe={Todo:`${xe}/todo`,Doing:`${xe}/doing`,Blocked:`${xe}/blocked`,Done:`${xe}/done`},Xe="github-issues:sync",yt="github-issues:comments",gn=[{key:"number",shortname:"github-issue-number",name:"GitHub issue number",datatype:Ae.integer,description:"The issue number in the bound GitHub repository."},{key:"provenance",shortname:"github-source",name:"GitHub source",datatype:Ae.string,description:"JSON text written by the GitHub issues app: the GitHub author, URL and timestamps. Not an Atomic authorship claim."},{key:"baseline",shortname:"github-sync-baseline",name:"GitHub sync baseline",datatype:Ae.string,description:"JSON text written by the GitHub issues app: the title, description and status (or comment text) it last agreed with GitHub. Edit it and sync can no longer tell which side changed."},{key:"repository",shortname:"github-repository",name:"GitHub repository",datatype:Ae.string,description:"The owner/name of the repository this app syncs with."},{key:"syncedTable",shortname:"synced-table",name:"Synced table",datatype:`${O}/datatypes/atomicURL`,description:"The table, not the app\u2019s own, that this sync binding keeps in step with one GitHub repository (on a binding under the app)."},{key:"syncState",shortname:"github-sync-state",name:"GitHub sync state",datatype:Ae.string,description:"JSON text: the sync checkpoint and write journal of the GitHub issues app. Edit it and sync can no longer tell what was already sent."}],Jr=["number","provenance","baseline"],Ie=e=>[...Jr.map(t=>e[t]),te],X=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[];async function Ze(e,t,n){for(let r of await e.query({property:te,value:n})){let s=await e.getResource(r);if(s.get(F)===t)return s}}async function wt(e,t){let n=new Map;for(let r of X(t.get(Ye))){let o=(await e.getResource(r)).get(Q);typeof o=="string"&&n.set(o,r)}return n}async function hn(e,t){let n=await wt(e,t),r={};for(let s of gn){let o=n.get(s.shortname);if(!o)return;r[s.key]=o}return r}async function Kr(e,t){let n=X(t.get(Ye)),r=await wt(e,t),s=[],o={};for(let i of gn){let a=r.get(i.shortname);a||(a=(await e.newResource({parent:t.subject,isA:[Fr],propVals:{[Q]:i.shortname,[G]:i.name,[ee]:i.description,[Ur]:i.datatype}})).subject,s.push(a)),o[i.key]=a}return s.length>0&&await t.set(Ye,[...n,...s]).save(),o}async function Wr(e,t){for(let n of X(t.get(Ye))){let r=await e.getResource(n);if(r.get(Q)!=="issue-status")continue;let s={};for(let o of X(r.get(zr))){let i=(await e.getResource(o)).get(Q);typeof i=="string"&&(s[i]=o)}return{status:n,tags:s}}}async function Qe(e,t,n){let r=(await e.getResource(t)).get(qr);if(typeof r=="string")return e.getResource(r);if(n&&n!==ce){let s=(await e.getResource(n)).get(F);if(typeof s=="string")return e.getResource(s)}throw new Error("This app has no ontology of its own to add fields to.")}async function un(e,t,n){for(let r of X(t.get(ke))){let s=await e.getResource(r).catch(()=>{});for(let o of X(s?.get(fn)??[]))if((await e.getResource(o).catch(()=>{}))?.get(Q)===n)return o}}function pn(e,t,n){if(!t)return!1;let r=X(e.get(t)??[]),s=n.filter(o=>!r.includes(o));return s.length?(e.set(t,[...r,...s]),!0):!1}async function ue(e){let t=await e.getApp(),n=await e.getData();if(!n?.table)throw new Error("This app has no table to sync into.");let r=(await e.getResource(n.table)).get(F)===t;return{app:t,table:n.table,own:r,...n.rowClass?{rowClass:n.rowClass}:{}}}var bt=new WeakMap;function vt(e,t){let n=bt.get(e);return n||(n=Yr(e,t),bt.set(e,n),n.catch(()=>bt.delete(e))),n}async function Yr(e,t){let n=await Qe(e,t.app,t.rowClass),r=await Kr(e,n),s=await e.getResource(t.app),o=pn(s,await un(e,s,"renders"),[ce]),i=pn(s,await un(e,s,"row-extras"),Ie(r));return(o||i)&&await s.save(),{ontology:n,properties:r}}async function bn(e,t){let n=await vt(e,t);if(t.own){let r=await e.getResource(t.table);r.get(dn)!==ce&&await r.set(dn,ce).save()}return n}async function yn(e){if(!(await e.getData())?.table)return;let n=await ue(e);n.own&&await bn(e,n)}async function wn(e){return Ie((await vt(e,await ue(e))).properties)}async function vn(e){let t=await ue(e),n=await Qe(e,t.app,t.rowClass).catch(()=>{}),r=n?await hn(e,n):void 0;return r?Ie(r):void 0}async function et(e,t,n,r){let s=o=>o?.get(F)===t.app&&o.get(n)===t.table;if(r){let o=await e.getResource(r).catch(()=>{});if(o&&s(o))return o}for(let o of await e.query({property:n,value:t.table})){let i=await e.getResource(o).catch(()=>{});if(i&&s(i))return i}}async function xt(e,t){if(!(await e.getData())?.table)return;let r=await ue(e),s=await Qe(e,r.app,r.rowClass).catch(()=>{});if(!s)return;let o=await wt(e,s),i;if(r.own)i=await Ze(e,r.app,Xe);else{let u=o.get("synced-table");if(!u)return;i=await et(e,r,u,t)}if(!i)return;let a=o.get("github-repository"),c=a?i.get(a):void 0;return{subject:i.subject,...typeof c=="string"&&c?{repository:c}:{}}}async function xn(e,t){let n=await ue(e);if(n.own)throw new Error("The app\u2019s own table needs no binding.");let{ontology:r,properties:s}=await vt(e,n),o=await et(e,n,s.syncedTable,t);if(o)return o.subject;let i=await Tn(e,r,s),a=(await e.getResource(n.table)).get(G);return(await e.newResource({parent:n.app,isA:[i],propVals:{[G]:`GitHub sync of ${typeof a=="string"&&a?a:"a table"}`,[te]:`${Xe} ${n.table}`,[s.syncedTable]:n.table}})).subject}async function kn(e,t){let n=await ue(e);if(n.own)return;let r=await Qe(e,n.app,n.rowClass),s=await hn(e,r);if(!s)return;let o=await et(e,n,s.syncedTable,t);if(!o)return;let i=o.get(s.repository);if(typeof i=="string"&&i)return;await(await Ze(e,o.subject,yt))?.destroy(),await o.destroy()}async function Sn(e){let t=await e.getData();return t?.table?(await e.getResource(t.table)).get(F)===await e.getApp():!0}async function En(e,t,n){let r=new Map(Object.entries(n.tags).map(([o,i])=>[i,o])),s=0;for(let o of await e.list()){let i=await e.get(o);if(i.get(F)!==t||X(i.get(ke)).includes(ce))continue;let a=X(i.get(n.status)??[]).map(u=>{let f=r.get(u),m=de.find(g=>g.toLowerCase()===f);return m?Oe[m]:u}),c=i.get(ee);i.set(ke,[ce]),a.length&&i.set(je,a),typeof c=="string"&&i.set(Pe,c),i.remove(n.status),i.remove(ee),await i.save(),s++}return s}async function Tn(e,t,n){let r=X(t.get(ln));for(let o of r)if((await e.getResource(o)).get(Q)==="github-issue-tracker-sync")return o;let s=await e.newResource({parent:t.subject,isA:[Br],propVals:{[Q]:"github-issue-tracker-sync",[G]:"GitHub issue tracker sync",[ee]:"Where the GitHub issues app keeps a table\u2019s bound repository and sync state: its own table\u2019s, or, with the synced table named, another table\u2019s.",[fn]:[G,n.repository,n.syncState,n.syncedTable]}});return await t.set(ln,[...r,s.subject]).save(),s.subject}async function Rn(e,t,n){let r=await ue(e),{app:s}=r,{ontology:o,properties:i}=await bn(e,r),a=r.own?await Wr(e,o):void 0,c=await Tn(e,o,i),u=r.own?await Ze(e,s,Xe):await et(e,r,i.syncedTable,n);if(!r.own&&!u)throw new Error("Choose \u201CSync this table to GitHub\u201D first.");let f=r.own?s:u.subject,m=await Ze(e,f,yt);m??=await e.newResource({parent:f,isA:[Vr],propVals:{[G]:"GitHub comments",[te]:yt,[ee]:r.own?"Comments on the GitHub issues in this app\u2019s table, as Messages about each row.":"Comments on the GitHub issues in the synced table, as Messages about each row."}});let g=u?.get(i.repository);if(typeof g=="string"&&g){if(t&&t!==g)throw new Error(r.own?`This app is bound to ${g}. Install another app for ${t}.`:`This table syncs with ${g}. It can\u2019t switch to ${t}.`);t=g}if(!t)throw new Error("Choose a GitHub repository first.");if(u?g!==t&&await u.set(i.repository,t).save():u=await e.newResource({parent:s,isA:[c],propVals:{[G]:`GitHub sync: ${t}`,[te]:Xe,[i.repository]:t}}),r.own){let b=await e.getResource(r.table),w=`${t} issues`;b.get(G)!==w&&await b.set(G,w).save()}return{repository:t,sync:u,...a?{legacy:a}:{},tracker:{app:s,table:r.table,rowClass:ce,properties:{status:je,body:Pe,...i},tags:Oe,commentsFolder:m.subject}}}var Se="github-issues",Xr=[/^No [a-z0-9-]+ connection .* is delegated to this app/,/^This host cannot reach the integration proxy/,/^This browser (has no WebCrypto|cannot make an Ed25519 key)/,/^The host returned no capability/,/^This app has no identity of its own yet/,/^The integration proxy refused (GET|POST|DELETE) \/connections/,/^Invalid (platform|proxy path|proxy method|proxy query|If-Match)/,/^A (GET )?proxy request/,/^(connectionId|publicKey|platform) is required/,/^Sign in/],$n=["unknown_connection","not_delegated","capability_scope","platform_mismatch","credential_refresh_failed"],Zr=[...$n,"missing_signature","unsupported_signature_version","invalid_agent","agent_key_mismatch","stale_timestamp","bad_signature","replayed","invalid_capability","capability_expired","capability_too_long","wrong_audience","capability_key_mismatch","not_owner","access_denied"];function An(e){let t=e.body,n=typeof t?.error=="string"?t.error:void 0;if(e.status<400||!n||!Zr.includes(n))return;let r=typeof t?.message=="string"?`: ${t.message}`:"";return Object.assign(new Error($n.includes(n)?`The integration proxy refused this connection (${n}${r}). Connect again.`:`The integration proxy refused the request (${n}${r}).`),{notSent:!0})}function jn(e,t){return async(n,{method:r,body:s})=>{let o=new URL(n,"https://api.github.com");if(o.origin!=="https://api.github.com"||!o.pathname.startsWith("/repos/")||o.hash)throw Object.assign(new Error(`Refusing a request outside /repos/: ${n}`),{notSent:!0});let i;try{i=await e.request({platform:Se,connectionId:t,path:o.pathname,method:r,...o.search?{query:Object.fromEntries(o.searchParams)}:{},...s===void 0?{}:{body:s}})}catch(c){let u=c instanceof Error?c.message:String(c);throw Object.assign(new Error(u),{notSent:Xr.some(f=>f.test(u))})}let a=An(i);if(a)throw a;return{status:i.status,body:typeof i.body=="string"?i.body:JSON.stringify(i.body??null)}}}var Qr=5;async function Pn(e,t){let n=[];for(let r=1;r<=Qr;r++){let s=await e.request({platform:Se,connectionId:t,path:"/user/repos",method:"GET",query:{per_page:"100",page:String(r),sort:"updated"}}),o=An(s);if(o)throw o;if(s.status<200||s.status>=300)throw new Error(`GitHub list_repositories returned ${s.status}`);let i=typeof s.body=="string"?JSON.parse(s.body):s.body;if(!Array.isArray(i))throw new Error("GitHub returned no repository list");for(let c of i)typeof c?.full_name=="string"&&n.push({fullName:c.full_name,hasIssues:c.has_issues!==!1,...Number.isSafeInteger(c.open_issues_count)?{openIssues:c.open_issues_count}:{},...typeof c.private=="boolean"?{private:c.private}:{}});let a=s.headers?.link;if(a!==void 0?!/rel="next"/.test(a):i.length<100)break}return n}var es="https://github-issues-app.invalid/bridge",kt=Ve["issue-v1"],ts=Qt({classes:[kt]}),ns=[...kt.requires,...kt.recommends],rs=new Map(de.map(e=>[Oe[e],e])),St=e=>Array.isArray(e)?e.map(St):e&&typeof e=="object"?Object.fromEntries(Object.keys(e).sort().map(t=>[t,St(e[t])])):e,Et=e=>JSON.stringify(St(e)),ss=e=>de.includes(e),Tt=class extends Ke{bound=()=>!1;onBaseline=()=>{};baselines=new Map;asIs=new Map;async subjects(t,n){let r=await super.subjects(t,n);if(t!==le)return r;let s=[];for(let o of r)(await this.store.getResource(o)).get(F)===this.config.commentsFolder&&s.push(o);return s}storedBaseline(t){let n=t.get(this.config.baseline),r;try{r=typeof n=="string"?JSON.parse(n):void 0}catch{r=void 0}return this.baselines.set(t.subject,r===void 0?void 0:Et(r)),r}row(t,n,r={}){let s=this.storedBaseline(n);if(t!=="issue"){let w=super.row(t,n,r);return this.onBaseline(t,n.subject,s),w}let o=this.connection,i=n.get(ke);if(!Array.isArray(i)||!i.includes(o.rowClass)||n.get(F)!==o.table)throw new Error("Resource is not a row of this issue tracker");let{values:a}=ts.read(Object.fromEntries(ns.map(w=>[w,n.get(w)])),o.rowClass),c=Array.isArray(a[je])?a[je].filter(w=>typeof w=="string"):[],u=c.length===0?"Todo":c.length===1?rs.get(c[0]):void 0;if(u)this.asIs.delete(n.subject);else{this.asIs.set(n.subject,c);let w=s?.status;u=ss(w)?w:"Todo"}let f=a[G],m=a[Pe]??"";if(typeof f!="string"||!f.trim()||typeof m!="string")throw new Error("Invalid Atomic issue");let g=n.get(o.number);if(g!==void 0&&(!Number.isSafeInteger(g)||g<=0))throw new Error("Invalid GitHub issue number");let b=n.get(this.config.provenance);return typeof b=="string"&&(b=JSON.parse(b)),this.onBaseline(t,n.subject,s),{id:n.subject,remoteId:g,value:{title:f,body:m,status:u},...b?{metadata:b}:{}}}localOnly(t,n){return n.get(this.connection.number)===void 0&&!this.bound("issue",t)&&!this.config.publish.has(t)}async issueRows(t){let n=[];for(let r of await this.subjects(F,this.connection.table)){let s=await this.resource(r),o=s.get(ke);if(!Array.isArray(o)||!o.includes(this.connection.rowClass))continue;let i=this.localOnly(r,s);i&&!t||n.push({id:r,r:s,localOnly:i})}return n}async list(t,n={}){return t!=="issue"?super.list(t,n):(await this.issueRows(!1)).map(({r})=>this.row(t,r,n))}async listAll(){let t=[];for(let{r:n,localOnly:r}of await this.issueRows(!0)){let s;try{s=this.row("issue",n)}catch{let o=n.get(G),i=n.get(Pe);s={id:n.subject,value:{title:typeof o=="string"?o:"",body:typeof i=="string"?i:"",status:"Todo"}}}t.push(r?{...s,localOnly:r}:s)}return t}values(t,n,r,s){let o=super.values(t,n,r,s),i=o,a=this.config.provenance;return i[a]!==void 0&&(i[a]=JSON.stringify(i[a])),i[this.config.baseline]=JSON.stringify(n),o}async update(t,n,r,s,o,i){let a=await this.resource(n),c=this.row(t,a,i),u=t==="issue"&&this.asIs.has(n)&&c.value.status===r.status;for(let[f,m]of Object.entries(this.values(t,r,o,i)))u&&f===this.connection.status||a.set(f,m);ve(this.store,this.connection.drive,a,await a.save()),this.baselines.set(n,Et(r))}},os={AtomicIdentityMap:Ge,AtomicLens:Ue,AtomicSchema:De,AtomicStore:_e,Datatype:j};function is(e,t){return{get scope(){return e.scope},list:(...n)=>e.list(...n),get:(...n)=>e.get(...n),async create(...n){let r=await e.create(...n);return t.value++,r},async update(...n){let r=await e.update(...n);return t.value++,r}}}var as=25,cs=1e4;function oe(e){let{store:t,repository:n,tracker:r,state:s}=e,o=Fe(t,{known:s.state.known,indexed:[F,le,te],...e.overlay?{overlay:e.overlay}:{}}),i=new Tt(o,{connection:{drive:r.app,table:r.table,rowClass:r.rowClass,body:r.properties.body,status:r.properties.status,number:r.properties.number,tags:r.tags},provenance:r.properties.provenance,baseline:r.properties.baseline,commentsFolder:r.commentsFolder,publish:new Set(s.state.publish??[])}),a=an({repository:n,journal:s.state.journal,save:()=>s.saveJournal(),dispatch:e.dispatch??jn(e.proxy,e.connectionId)}),c=new Je(void 0,{repository:n},a),u=s.state.journal,f=(k,$)=>We(`${JSON.stringify([c.scope,k,$])}:create`),m={async sent(k,$){let R=u[await f(k,$)];if(!R?.signature||R.receipt)return;let{args:I}=JSON.parse(R.signature);return k==="issue"?{title:I.title,body:I.body??""}:{body:I.body??""}},async forget(k,$){let R=await f(k,$);u[R]?.receipt||(delete u[R],await s.saveJournal())}},g={value:0},b=0,w=Date.now(),E=async({entity:k,row:$,context:R})=>{(++b>=as||Date.now()-w>=cs)&&(b=0,w=Date.now(),await s.flush());let I=e.onImported;I&&(k==="issue"?I({entity:k,row:Hn($,[])}):R.issueId&&I({entity:"comment",issue:R.issueId,comment:Mn($.id,$.value.body,$.metadata??{})}))},T={},A=new WeakMap,_=async k=>{for(let[$,R]of Object.entries(T)){if(R.baseline===void 0)continue;if(A.get(R)!==R.baseline){let C=H.id("local",R.entity,$);if(typeof C!="string")continue;let K=Et(R.baseline);if(i.baselines.get(C)!==K){let re=await o.getResource(C);re.set(r.properties.baseline,JSON.stringify(R.baseline)),await re.save(),o.writes.saves--,i.baselines.set(C,K)}A.set(R,R.baseline)}let I=k.records?.[$];I&&delete I.baseline}await s.saveSnapshot(k)},H=new qe({imported:E,devonian:os,local:i,remote:cn(is(c,g),e.approved??new Set),base:es,snapshot:s.state.snapshot,save:_,uncertain:m});T=H.records;let v=(k,$)=>H.identities.lookup(H.scope("local",k),$);return i.bound=(k,$)=>v(k,$)!==void 0,i.onBaseline=(k,$,R)=>{let I=v(k,$),C=I?T[I]:void 0;R===void 0||!C||(C.baseline=structuredClone(R),A.set(C,C.baseline))},{bridge:H,atomicStore:o,sent:g,local:i}}async function ls(e,t,n,r,s){let o={...t.writes},i=await On(t,r,s),a=Object.entries(e.records).filter(([c,u])=>e.id("local",u.entity,c)!==void 0&&e.id("remote",u.entity,c)!==void 0);return{issues:a.filter(([,c])=>c.entity==="issue").length,comments:a.filter(([,c])=>c.entity!=="issue").length,addedHere:o.creates,updatedHere:o.saves,sentToGitHub:n.value,held:[...e.held.values()].map(c=>{let u=e.id("local",c.entity,c.subject),f=typeof u=="string"?{...c,local:u}:c;if(c.entity==="issue")return f;let m=c.entity.slice(8),g=e.id("remote","issue",m);return g===void 0?f:{...f,issueNumber:g}}),uncertain:[...e.unsettled.values()].map(c=>{let u=e.id("local",c.entity,c.subject),f=c.entity==="issue"?void 0:e.id("remote","issue",c.entity.slice(8));return{subject:c.subject,entity:c.entity,sent:c.sent,candidates:c.candidates.map(ds),...typeof u=="string"?{local:u}:{},...typeof f=="number"?{issueNumber:f}:{}}}),rows:i}}function ds(e){let t=e.metadata??{},n=e.value,r={title:B(n.title),url:B(t.url),author:B(t.author),createdAt:B(t.createdAt)};return{id:Number(e.id),body:n.body??"",...Object.fromEntries(Object.entries(r).filter(([,s])=>s!==void 0))}}async function On(e,t,n){let r=await us(e,n),s=new Map,o=async a=>{if(!s.has(a)){let c=de.find(m=>Oe[m]===a),u=c?void 0:await e.getResource(a).catch(()=>{}),f=u?.get(G)??u?.get(Q);s.set(a,c??(typeof f=="string"&&f?f:a.split("/").pop()))}return s.get(a)},i=[];for(let a of await t.listAll()){let c=t.asIs.get(a.id);i.push({...Hn(a,r.get(a.id)??[]),...a.localOnly?{localOnly:!0}:{},...c?{statusAsIs:await Promise.all(c.map(o))}:{}})}return i}async function Rt(e){let{atomicStore:t,local:n}=oe(e);return On(t,n,e)}async function ie(e){let{bridge:t,atomicStore:n,sent:r,local:s}=oe(e);try{await t.sync()}catch(a){let c=a,u=/^Missing (local|remote) record: (.+)$/.exec(c?.message??"");if(u){let f=u[2],m=t.records[f]?.entity;c.missing={side:u[1],subject:f,entity:m},c.entity??=m,c.subject??=f}if(c?.subject&&c.entity){let f=t.id("local",c.entity,c.subject);typeof f=="string"&&(c.local=f)}throw await e.state.flush().catch(()=>{}),a}let o=e.state.state.publish??[],i=o.filter(a=>!s.bound("issue",a));return i.length!==o.length&&(e.state.state.publish=i),await e.state.flush(),ls(t,n,r,s,e)}async function In(e,t){let{bridge:n}=oe(e);return n.describeConflict(t)}async function Cn(e,t,n){let{bridge:r}=oe(e);try{return await r.resolveConflict(t,n)}finally{await e.state.flushIfDirty()}}var B=e=>typeof e=="string"?e:void 0;function Mn(e,t,n){return{subject:e,body:t??"",...B(n.author)?{author:B(n.author)}:{},...B(n.createdAt)?{createdAt:B(n.createdAt)}:{},...B(n.url)?{url:B(n.url)}:{}}}function Hn(e,t){let n=e.metadata??{},r=Array.isArray(n.labels)?n.labels.filter(o=>typeof o?.name=="string"):[],s={updatedAt:B(n.updatedAt),url:B(n.url),author:B(n.author)};return{subject:e.id,...e.remoteId===void 0?{}:{number:e.remoteId},title:e.value.title,status:e.value.status,body:e.value.body??"",labels:r,assignees:Array.isArray(n.assignees)?n.assignees.filter(o=>typeof o=="string"):[],...Object.fromEntries(Object.entries(s).filter(([,o])=>o!==void 0)),comments:t}}async function us(e,t){let{tracker:n}=t,r=new Map,{subjects:s}=await e.queryLocalDb({drive:n.app,property:F,value:n.commentsFolder});for(let o of s){let i=await e.getResource(o),a=i.get(le);if(typeof a!="string")continue;let c={};try{let m=i.get(n.properties.provenance);typeof m=="string"&&(c=JSON.parse(m))}catch{}let u=Mn(o,B(i.get(ee)),c),f=r.get(a)??[];f.push(u),r.set(a,f)}for(let o of r.values())o.sort((i,a)=>(i.createdAt??"\uFFFF").localeCompare(a.createdAt??"\uFFFF"));return r}async function Nn(e,t){let{bridge:n}=oe(e),r=n.id("local","issue",t);try{if(await n.keepLocalOnly(t),typeof r=="string"){let s=await e.store.getResource(r);s.get(e.tracker.properties.number)!==void 0&&await s.remove(e.tracker.properties.number).save()}}finally{await e.state.flush()}}async function Ln(e,t){let{bridge:n}=oe(e),r=[];try{r=await n.forget(t)}finally{await e.state.flush()}for(let s of r)await(await e.store.getResource(s).catch(()=>{}))?.destroy()}async function Dn(e,t,n){let{bridge:r,atomicStore:s}=oe(e),o;try{await r.landed(t,n),o=r.records[t]?.entity}finally{await e.state.flush()}let i=r.id("local","issue",t);if(o==="issue"&&typeof i=="string"){let a=await s.getResource(i);a.set(e.tracker.properties.number,n),await a.save()}}async function _n(e,t){let{bridge:n}=oe(e);try{await n.notArrived(t)}finally{await e.state.flush()}}var ps=[/^GitHub \S+ returned 401$/,/is delegated to this app/,/^The integration proxy refused this connection/],fs=[[/^Uncertain GitHub write/,"uncertain"],[/^Proxy request failed/,"uncertain"],[/^Operation identity reused/,"other"],[/^Missing (local|remote) record/,"missing"],[/^State belongs to another connection/,"other"],[/^Duplicate /,"other"],[/^Recovered Atomic create was edited/,"other"],[/^Conflict during saved operation/,"other"],[/^Concurrent edit after write/,"other"],[/^Choose exactly one Todo\/Doing\/Blocked\/Done status/,"other"],[/^Invalid Atomic issue/,"other"],[/^Atomic write (rejected|not acknowledged)/,"rejected"],[/may only write its own data/,"rejected"],[/^The integration proxy refused the request/,"other"]],nt="Syncing with GitHub is paused: this app may no longer edit this table\u2019s rows, or keep its GitHub issue numbers on them. Allow editing again to go on.",ms=e=>e.replace(/\.?$/,".");function Gn(e){let t=e,n=e instanceof Error?e.message:String(e);if(t?.subject&&Array.isArray(t.fields))return{kind:"conflict",message:n,subject:t.subject,fields:t.fields,...t.local?{local:t.local}:{}};if(ps.some(s=>s.test(n)))return{kind:"reconnect",message:n};let r=fs.find(([s])=>s.test(n));return r?{kind:"paused",message:n,reason:r[1],...t?.missing?{missing:{...t.missing,...t.local?{local:t.local}:{}}}:{}}:{kind:"failed",message:n}}var gs=250,hs=e=>de.includes(e)?e:void 0;function Un(e,t=()=>{},n=Date.now){let r={kind:"loading"},s=Promise.resolve(),o,i,a={},c,u,f,m=new Map,g=l=>(r=l,t(l),l),b=l=>{let p=s.then(l,l);return s=p.catch(()=>{}),p},w=async l=>{if(o)return o;let p=await Rn(e,l,u);c&&(u=p.sync.subject),f=Ie(p.tracker.properties);let h=new Be(p.sync,p.tracker.properties.syncState);if(o={tracker:p.tracker,sync:p.sync,state:h,overlay:new Map},a={...h.state.view},p.legacy&&h.state.migrated!=="issue-v1"){let y=$(o),{table:x,app:S}=p.tracker;await En({list:async()=>(await y.queryLocalDb({drive:S,property:F,value:x})).subjects,get:M=>y.getResource(M)},x,p.legacy),h.state.migrated="issue-v1",await h.flush()}return o},E=()=>!!e.proxy&&typeof e.rowAccess=="function"&&typeof e.requestRowAccess=="function",T=l=>g({kind:"other-table",canSync:E(),...l?{reason:l}:{}}),A=async()=>{if(!c)return!0;if(!e.rowAccess)return!1;let l=await e.rowAccess();if(l.status!=="granted")return!1;let p=f??await vn(e);return!!p&&p.every(h=>l.extras.includes(h))},_=async()=>await A().catch(()=>!1)?!1:(o=void 0,T(nt),!0),H=(l,p,h)=>({store:e,proxy:e.proxy,connectionId:p,repository:h,tracker:l.tracker,state:l.state,overlay:l.overlay,onImported:k}),v=0;function k(l){if(r.kind!=="ready"||!r.busy)return;let p=r,h=p.last?.result??tt(),y={...p.importing??{issues:0,comments:0}},x;l.entity==="issue"?(x=[...h.rows.filter(D=>D.subject!==l.row.subject),l.row],y.issues++):(x=h.rows.map(D=>D.subject===l.issue?{...D,comments:[...D.comments,l.comment]}:D),y.comments++);let S={...p,last:{at:p.last?.at??0,result:{...h,rows:x}},importing:y},M=n();if(M-vFe(e,{known:l.state.state.known,indexed:[F,le,te],overlay:l.overlay}),R=l=>r.kind==="ready"?r:l,I=(l,p)=>b(async()=>{if(r.kind!=="ready"||!e.proxy)return r;let h=r;if(await _())return r;g({...h,busy:l});try{let y=await w(h.repository);if(!h.last&&l==="syncing"){let D=await Rt(H(y,h.connectionId,h.repository)).catch(()=>[]);D.length&&r.kind==="ready"&&!r.last&&g({...r,last:{at:0,result:{...tt(),rows:D}}})}let x=await p(y,h);i=void 0;let S=R(h),M=(S.touched??[]).filter(D=>!(h.touched??[]).includes(D));for(let D of m.keys())M.includes(D)||m.delete(D);return g({kind:"ready",connectionId:h.connectionId,repository:h.repository,...x?{last:{at:n(),result:K(x)}}:S.last?{last:S.last}:{},...M.length?{touched:M}:{}})}catch(y){if(c&&await _())return r;let x=Gn(y);x.kind==="conflict"&&(i=x);let S=R(h),M=S.last;if(o)try{let D=await Rt(H(o,h.connectionId,h.repository));M={at:S.last?.at??0,result:K({...S.last?.result??tt(),rows:D})}}catch{}return g({kind:"ready",connectionId:h.connectionId,repository:h.repository,...M?{last:M}:{},...S.touched?.length?{touched:S.touched}:{},problem:x})}}),C=(l,p,h)=>l.some(y=>y.subject===p)?l.map(y=>y.subject===p?h(y):y):[...l,h(bs(p))],K=l=>{let p=l.rows;for(let[h,y]of m)p=C(p,h,y);return p===l.rows?l:{...l,rows:p}},re=(l,p)=>{if(r.kind!=="ready")return;let h=r,y=m.get(l);m.set(l,y?x=>p(y(x)):p),g({...h,last:{at:h.last?.at??0,result:{...h.last?.result??tt(),rows:C(h.last?.result.rows??[],l,p)}},touched:[...new Set([...h.touched??[],l])]})},he=async(l,p)=>{try{return await _()?!1:(await b(async()=>p(await w(l.repository))),!0)}catch(h){return c&&await _()||g({...R(l),problem:Gn(h)}),!1}},He=()=>{let l=r.kind==="ready"?r.problem:void 0,p=l?.kind==="paused"?l.missing:void 0;return p?.side==="remote"&&p.entity==="issue"?p.subject:void 0},Ne=l=>r.kind==="ready"&&!!r.last?.result.uncertain?.some(p=>p.subject===l);return{state:()=>r,foreign:()=>c,async load(){let l;if(await Sn(e))await yn(e).catch(()=>{}),l=await xt(e);else{let S=await e.getData(),M=(await e.getResource(S.table)).get(G);if(c=typeof M=="string"&&M?M:"This table",l=await xt(e,u),!l)return T();if(u=l.subject,!await A())return T(nt)}let p=e.proxy;if(!p||typeof p.connections!="function")return g({kind:"no-proxy"});let h=l?.repository,y=[];h&&(y=(await w(h)).state.state.stale);let x=(await p.connections({platform:Se})).find(S=>!y.includes(S.connectionId));return g(x?h?{kind:"ready",connectionId:x.connectionId,repository:h}:{kind:"choose-repository",connectionId:x.connectionId}:{kind:"not-connected"})},async start(){let l=await this.load();return l.kind==="choose-repository"?this.listRepositories():l.kind==="ready"?this.sync():l},async connect(){if(!e.proxy)return r;if(r.kind==="ready"&&r.problem?.kind==="reconnect"&&o)o.state.state.stale.push(r.connectionId),await o.state.flush();else if(r.kind!=="not-connected")return r;return g({kind:"connecting"}),await e.proxy.connect({platform:Se}),this.start()},async syncTable(){if(r.kind!=="other-table"||r.asking||!r.canSync)return r;g({...r,asking:!0});let l;try{if(f=await wn(e),!await A()){let p=await e.requestRowAccess();p.status!=="granted"?l=p.reason:await A()||(l="The grant doesn\u2019t cover the GitHub issue numbers, sources and baselines the app keeps on rows")}l||(u=await xn(e,u))}catch(p){l=p instanceof Error?p.message:String(p)}return l?T(`Not synced: ${ms(l)}`):this.start()},async notNow(){return c?(await kn(e,u),u=void 0,o=void 0,this.load()):r},async disconnect(){let l=e.proxy;return!l?.disconnect||r.kind!=="ready"?r:(await b(()=>l.disconnect({platform:Se})),this.load())},async listRepositories(){if(r.kind!=="choose-repository"||!e.proxy)return r;let{connectionId:l}=r;g({...r,listing:{kind:"loading"}});let p;try{p={kind:"listed",repositories:await Pn(e.proxy,l)}}catch(h){p={kind:"unavailable",message:h instanceof Error?h.message:String(h)}}return r.kind!=="choose-repository"?r:g({...r,listing:p})},async choose(l){if(r.kind!=="choose-repository"||r.settingUp)return r;let{connectionId:p,listing:h}=r,y=h?{listing:h}:{},x=l.trim();try{we(x)}catch{return g({kind:"choose-repository",connectionId:p,...y,error:"Enter the repository as owner/name, for example octocat/hello-world."})}g({kind:"choose-repository",connectionId:p,...y,settingUp:x});try{await w(x)}catch(S){return g({kind:"choose-repository",connectionId:p,...y,error:S instanceof Error?S.message:String(S)})}return g({kind:"ready",connectionId:p,repository:x}),this.sync()},sync(){return I("syncing",(l,p)=>ie(H(l,p.connectionId,p.repository)))},send(){let l=r.kind==="ready"?r.last?.result.held:[];return I("sending",(p,h)=>ie({...H(p,h.connectionId,h.repository),approved:new Set((l??[]).map(y=>y.key))}))},keep(l){return this.resolve(l)},async conflict(){let l=i;if(l?.kind!=="conflict"||r.kind!=="ready")return;let p=r;return b(async()=>{let h=await w(p.repository);return In(H(h,p.connectionId,p.repository),l.subject)})},resolve(l){let p=i;return p?.kind!=="conflict"?Promise.resolve(r):I("resolving",async(h,y)=>{let x=H(h,y.connectionId,y.repository);return await Cn(x,p.subject,l),ie(x)})},async edit(l,p){if(r.kind!=="ready")return r;let h=r;return re(l,x=>({...x,...p.title!==void 0?{title:p.title}:{},...p.body!==void 0?{body:p.body}:{},...p.status?{status:p.status}:{}})),await he(h,async x=>{let S=await $(x).getResource(l);p.title!==void 0&&S.set(G,p.title),p.body!==void 0&&S.set(x.tracker.properties.body,p.body);let M=hs(p.status);M&&S.set(x.tracker.properties.status,[x.tracker.tags[M]]),await S.save()})?this.sync():r},async comment(l,p){if(r.kind!=="ready"||!p.trim())return r;let h=r,y="";return await he(h,async S=>{y=(await $(S).newResource({parent:S.tracker.commentsFolder,isA:[mn],propVals:{[ee]:p,[le]:l}})).subject})?(re(l,S=>({...S,comments:[...S.comments,{subject:y,body:p}]})),this.sync()):r},async create(l){if(r.kind!=="ready")return{state:r};let p=r,h="";return await he(p,async x=>{h=(await $(x).newResource({parent:x.tracker.table,isA:[x.tracker.rowClass],propVals:{[G]:l.title,[x.tracker.properties.body]:l.body,[x.tracker.properties.status]:[x.tracker.tags[l.status]]}})).subject,x.state.state.publish=[...x.state.state.publish??[],h],await x.state.flush()})?(re(h,x=>({...x,...l})),{state:await this.sync(),subject:h}):{state:r}},async publish(l){return r.kind!=="ready"?r:await he(r,async y=>{let x=y.state.state.publish??[];x.includes(l)||(y.state.state.publish=[...x,l],await y.state.flush())})?this.sync():r},keepHereOnly(){let l=He();return l?I("resolving",async(p,h)=>{let y=H(p,h.connectionId,h.repository);return await Nn(y,l),ie(y)}):Promise.resolve(r)},removeFromBoard(){let l=He();return!l||c?Promise.resolve(r):I("resolving",async(p,h)=>{let y=H(p,h.connectionId,h.repository);return await Ln(y,l),ie(y)})},landed(l,p){return Ne(l)?I("resolving",async(h,y)=>{let x=H(h,y.connectionId,y.repository);return await Dn(x,l,p),ie(x)}):Promise.resolve(r)},sendAgain(l){return Ne(l)?I("resolving",async(p,h)=>{let y=H(p,h.connectionId,h.repository);return await _n(y,l),ie(y)}):Promise.resolve(r)},prefs:()=>({...a}),async savePrefs(l){if(a={...l},!o)return;let p=o;p.state.state.view={...l},await b(()=>p.state.flush())}}}function tt(){return{issues:0,comments:0,addedHere:0,updatedHere:0,sentToGitHub:0,held:[],uncertain:[],rows:[]}}function bs(e){return{subject:e,title:"",status:"Todo",body:"",labels:[],assignees:[],comments:[]}}var $t=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`,At="This Issue table wasn\u2019t made by this app and isn\u2019t synced with GitHub.",jt="Sync it to keep it and one GitHub repository in step: the repository\u2019s issues are added as rows, and edits made here are sent after you review them. Rows already here stay here until you publish them. The app asks you to allow it to edit this table\u2019s rows and to keep each issue\u2019s GitHub number, source and sync baseline on its row.";function zn(e){switch(e.kind){case"loading":return"Loading\u2026";case"no-proxy":return"This host cannot reach the integration proxy on behalf of an app, so this app cannot sync. Nothing was fetched.";case"other-table":return e.reason?`${At} ${e.reason}`:e.canSync?`${At} ${jt}`:At;case"not-connected":return"Not connected. Connect a GitHub account to sync one repository\u2019s issues and comments with this table.";case"connecting":return"Waiting for you to confirm the connection\u2026";case"choose-repository":return e.settingUp?`Setting up this table for ${e.settingUp}\u2026`:e.error??"Connected. Choose the repository to sync with this table.";case"ready":{if(e.busy==="syncing")return`Syncing with ${e.repository}\u2026`;if(e.busy==="sending")return`Sending approved changes to ${e.repository}\u2026`;if(e.busy==="resolving")return"Settling the conflict, then syncing\u2026";if(e.problem){let{kind:n,message:r}=e.problem;return n==="conflict"?`Sync paused: ${e.problem.fields.join(", ")} changed both here and on GitHub since the last sync. Keep one side to continue. (${r})`:n==="reconnect"?`GitHub no longer accepts this connection. Your issues are still here. Reconnect to continue. (${r})`:n==="paused"?`Sync paused: ${r}. Nothing is resent automatically; check the issue on GitHub before syncing again.`:`Sync failed: ${r}`}if(!e.last)return`Bound to ${e.repository}. Sync imports its issues and comments into this table. Nothing is sent to GitHub without your review.`;let t=e.last.result;return`Last synced ${new Date(e.last.at).toLocaleString()}: ${$t(t.issues,"issue")} and ${$t(t.comments,"comment")} in sync with ${e.repository}; ${t.addedHere} added and ${t.updatedHere} updated here, ${t.sentToGitHub} sent to GitHub.`+(t.held.length?` ${$t(t.held.length,"change")} waiting for your review before ${t.held.length===1?"it is":"they are"} sent to GitHub.`:"")}}}function Fn(e){let t=ys(e);return e.unconfirmed?`${t}. GitHub did not confirm the last attempt, so it may already be there: check GitHub before sending again`:t}function ys(e){if(e.entity!=="issue"){let s=e.issueNumber?`#${e.issueNumber}`:"a new issue";return e.remoteId===void 0?`Add a comment on ${s}: \u201C${e.after.body}\u201D`:`Edit comment ${e.remoteId} on ${s} to \u201C${e.after.body}\u201D`}if(e.remoteId===void 0)return`Create issue \u201C${e.after.title}\u201D (${e.after.status})`;let t=s=>s==="Doing"?"atomic:doing":s==="Blocked"?"atomic:blocked":void 0,n=[],r=e.before;if(r?.title!==e.after.title&&n.push(`title \u201C${r?.title??""}\u201D \u2192 \u201C${e.after.title}\u201D`),r?.body!==e.after.body&&n.push("description"),r?.status!==e.after.status){let s=t(e.after.status),o=t(r?.status),i=e.after.status==="Done"?"close it":r?.status==="Done"?`reopen it${s?` with the ${s} label`:""}`:s&&o?`${o} label \u2192 ${s}`:s?`add the ${s} label`:`remove the ${o??"atomic:doing"} label`;n.push(`status ${r?.status??"?"} \u2192 ${e.after.status} (${i})`)}return`Update #${e.remoteId}: ${n.join("; ")||"no visible change"}`}var rt=["Todo","Doing","Blocked","Done"];function st(e,t){let n=typeof e=="string"?Date.parse(e):e;if(n===void 0||Number.isNaN(n))return"";let r=Math.max(0,Math.round((t-n)/6e4));if(r<1)return"just now";if(r<60)return`${r} min ago`;let s=Math.round(r/60);if(s<24)return`${s} h ago`;let o=Math.round(s/24);return o<30?o===1?"yesterday":`${o} days ago`:new Date(n).toLocaleDateString()}function Bn(e,t){let n=e?Date.parse(e):NaN;if(Number.isNaN(n))return"";let r=Math.max(0,Math.floor((t-n)/6e4));return r<1?"now":r<60?`${r}m`:r<1440?`${Math.floor(r/60)}h`:r<1440*14?`${Math.floor(r/1440)}d`:`${Math.floor(r/10080)}w`}function Vn(e,t){switch(e.kind){case"loading":return{state:"idle",text:"Loading\u2026"};case"no-proxy":case"other-table":return;case"not-connected":return{state:"idle",text:"Not connected"};case"connecting":return{state:"syncing",text:"Connecting\u2026"};case"choose-repository":return e.settingUp?{state:"syncing",text:"Setting up\u2026"}:{state:"synced",text:"Connected"};case"ready":{if(e.busy==="syncing"&&!e.last)return{state:"syncing",text:"Importing\u2026"};if(e.busy==="sending")return{state:"syncing",text:"Sending\u2026"};if(e.busy)return{state:"syncing",text:"Syncing\u2026"};let n=e.problem;return n?.kind==="reconnect"?{state:"reauth",text:"Reconnect needed"}:n?.kind==="conflict"||n?.kind==="paused"?{state:"paused",text:"Sync paused"}:n?.kind==="failed"?{state:"error",text:"Sync failed"}:e.last?.at?{state:"synced",text:`Synced ${st(e.last.at,t)}`}:{state:"idle",text:"Not synced yet"}}}}var Pt=(e,t,n=`${t}s`)=>`${e} ${e===1?t:n}`,ws=e=>(e.last?.result.held??[]).filter(t=>t.unconfirmed);function qn(e,t=!1,n=!0){if(e.kind!=="ready")return;let r=e.problem,s=a=>{let c=e.last?.result.rows.find(u=>u.subject===a);return c?.number?`#${c.number}`:"An issue"};if(r?.kind==="conflict")return{tone:"warn",icon:"warn",title:"Sync paused.",text:`${s(r.local)} was changed both here and on GitHub since the last sync (${r.fields.join(", ")}). Nothing is sent or fetched until you choose.`,actions:[{label:"Review conflict",action:"review-conflict",primary:!0}],problem:r};if(r?.kind==="reconnect")return{tone:"neg",icon:"plug",title:"GitHub no longer accepts this connection.",text:"Your issues are still here. Changes you make are kept and sent after you reconnect.",actions:[{label:"Reconnect GitHub",action:"reconnect",primary:!0}],details:r.message,problem:r};if(r?.kind==="paused"){if(r.reason==="uncertain")return{tone:"warn",icon:"info",title:"A change was sent to GitHub, but no answer came back.",text:"It may or may not have arrived. Check GitHub, then sync: the app reads GitHub back first, and it never sends a new issue twice.",actions:[{label:"Check on GitHub",action:"open-github"},{label:"Sync now",action:"sync",primary:!0}],details:r.message,problem:r};if(r.reason==="missing"){let a=r.missing?.side==="remote"&&r.missing.entity==="issue",c=s(r.missing?.local);return a&&t&&n?{tone:"warn",icon:"ghost",title:`Remove ${c==="An issue"?"this issue":c} from this board?`,text:"Its row and its comments are deleted from this table. Nothing on GitHub changes.",actions:[{label:"Cancel",action:"cancel-remove"},{label:"Remove",action:"confirm-remove",danger:!0}],details:r.message,problem:r}:a?{tone:"warn",icon:"ghost",title:`${c} is on this board but no longer on GitHub.`,text:n?"It may have been deleted or moved to another repository. Nothing on GitHub will change.":"It may have been deleted or moved to another repository. Nothing on GitHub will change. To remove it here, delete its row in the table.",actions:[{label:"Keep here only",action:"keep-here"},...n?[{label:"Remove from board",action:"remove",danger:!0}]:[]],details:r.message,problem:r}:{tone:"warn",icon:"ghost",title:r.missing?.side==="local"?"A synced record was deleted from this table.":"A comment on this board is no longer on GitHub.",text:"Sync is paused so nothing is deleted on the other side. Check GitHub and the table before syncing again.",actions:[{label:"Check on GitHub",action:"open-github"},{label:"Sync now",action:"sync"}],details:r.message,problem:r}}return r.reason==="rejected"?{tone:"neg",icon:"lock",title:"Atomic Server refused to save a change.",text:"You may not have write rights on this table. Ask the drive owner for access, then try again.",actions:[{label:"Try again",action:"sync",primary:!0}],details:r.message,problem:r}:{tone:"warn",icon:"warn",title:"Sync paused.",text:"Something needs a look before syncing again. Nothing is resent automatically.",actions:[{label:"Sync now",action:"sync"}],details:r.message,problem:r}}let[o]=e.last?.result.uncertain??[];if(o&&!e.busy)return xs(o);let i=ws(e);if(i.length&&!e.busy)return{tone:"warn",icon:"info",title:`${Pt(i.length,"change")} sent to GitHub got no answer.`,text:"GitHub does not show it yet, so it probably did not arrive. Check GitHub, then send it again if it is missing.",actions:[{label:"Check on GitHub",action:"open-github"},{label:"Send again",action:"send",primary:!0}]};if(e.busy==="syncing"&&!e.last)return{tone:"info",icon:"info",title:"First import running.",text:"You can look around; moving cards is available once it finishes.",actions:[]}}var vs=3;function xs(e){let t=e.entity==="issue",n=t?`\u201C${e.sent.title??""}\u201D`:`Your comment on ${e.issueNumber?`#${e.issueNumber}`:"an issue"}`,r=u=>t?`#${u}`:`comment ${u}`,s=t?"the same title and description":"the same text",o=`${n} was sent to GitHub, but no answer came back.`,i=e.candidates.slice(0,vs),[a]=e.candidates;if(!a)return{tone:"warn",icon:"info",title:o,text:`GitHub shows no ${t?"issue":"comment"} with ${s}, so it probably did not arrive. Check GitHub; if it is not there, send it again. You review it before it goes.`,actions:[{label:"Check on GitHub",action:"open-github"},{label:"Send again",action:"send-again",subject:e.subject,primary:!0}]};let c=e.candidates.length===1?`GitHub has ${r(a.id)} with ${s}${a.author?`, by ${a.author}`:""}. If that is it, link it here; nothing is sent again.`:`GitHub has ${e.candidates.length} ${t?"issues":"comments"} with ${s}. Check them on GitHub, then choose the one it became; nothing is sent again.`;return{tone:"warn",icon:"info",title:o,text:c,actions:[...e.candidates.length===1?[{label:`Check ${r(a.id)} on GitHub`,action:"open-github",...a.url?{url:a.url}:{}}]:[{label:"Check on GitHub",action:"open-github"}],...i.map((u,f)=>({label:`It landed as ${r(u.id)}`,action:"landed",subject:e.subject,id:u.id,...f===0?{primary:!0}:{}}))]}}function Jn(e){let t=e.last?.result.held.length??0,n=t?` \xB7 ${Pt(t,"change")} waiting to send`:e.touched?.length?` \xB7 ${Pt(e.touched.length,"change")} saving`:"";if(e.busy==="syncing"&&!e.last)return"Importing\u2026";if(e.busy==="syncing")return`Checking GitHub for changes${n}`;if(e.busy==="sending")return`Sending to GitHub${n}`;if(e.busy==="resolving")return"Settling the conflict\u2026";let r=e.last?.at?new Date(e.last.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"";return e.problem?.kind==="conflict"||e.problem?.kind==="paused"?`Paused${r?` at ${r}`:""}${n}`:e.last?.at?`Last sync ${r}${n}`:`Not synced yet${n}`}function ot(e){let t=new Map,n=e.last?.result.held??[],r=e.last?.result.rows??[],s=new Map;for(let i of r)for(let a of i.comments)s.set(a.subject,i.subject);for(let i of n){let a=i.local&&s.has(i.local)?s.get(i.local):i.local;a&&t.set(a,e.busy==="sending"?"sending":"waiting")}for(let i of e.touched??[])t.set(i,e.busy==="sending"?"sending":"waiting");for(let i of e.last?.result.uncertain??[]){let a=i.local&&s.has(i.local)?s.get(i.local):i.local;a&&t.set(a,"unconfirmed")}let o=e.problem;return o?.kind==="conflict"&&o.local&&t.set(s.get(o.local)??o.local,"conflict"),t}function Kn(e){let t=new Set;for(let n of e.last?.result.held??[])n.entity!=="issue"&&n.local&&t.add(n.local);return t}var Ce={waiting:"Waiting to send",sending:"Sending",conflict:"Changed on both sides",unconfirmed:"Sent, but GitHub did not answer"};function it(e,{search:t,label:n}){if(n&&!e.labels.some(o=>o.name===n))return!1;let r=t.toLowerCase().split(/\s+/).filter(Boolean),s=[e.title.toLowerCase(),...e.labels.map(o=>o.name.toLowerCase())];return r.every(o=>{let i=o.replace(/^#/,"");return/^\d+$/.test(i)&&e.number!==void 0&&String(e.number)===i?!0:s.some(a=>a.includes(o))})}var Ot=e=>!!(e.search.trim()||e.label);function Wn(e){return[...new Set(e.flatMap(t=>t.labels.map(n=>n.name)))].sort((t,n)=>t.localeCompare(n))}var ks=(e,t)=>(e.number??-1)-(t.number??-1),Ss=(e,t)=>(t.updatedAt??"\uFFFF").localeCompare(e.updatedAt??"\uFFFF");function It(e,t,n=!1){let r=e.filter(s=>it(s,t));return rt.map(s=>{let o=r.filter(a=>a.status===s).sort(s==="Done"?Ss:ks),i=s==="Done"&&!n?20:1/0;return{status:s,total:o.length,rows:o.slice(0,i),hidden:Math.max(0,o.length-i)}})}function Yn(e,t){if(Ot(t))return`${e.filter(s=>it(s,t)).length} of ${e.length} shown`;let n=e.filter(r=>r.status==="Done").length;return`${e.length-n} open \xB7 ${n} done`}function Ct(e,t){return t??(e==="s"||e==="m"?"list":"board")}function Xn(e){return e==="xl"?"docked":e==="s"?"sheet":"drawer"}function pe(e){return e.kind==="ready"&&!!e.last&&e.last.at>0}var Mt={1:"Todo",2:"Doing",3:"Blocked",4:"Done"},Zn=[["J / K or arrows","Move focus between issues"],["Enter","Open the focused issue"],["Esc","Close the panel"],["1 / 2 / 3 / 4","Set status to Todo / Doing / Blocked / Done"],["C","Comment on the open issue"],["N","New issue"],["B","Switch between board and list"],["/","Search"],["G then S","Sync now"],["?","Show this list"]];function Ht(e){let t=e;return!t||typeof t.tagName!="string"?!1:t.tagName==="INPUT"||t.tagName==="TEXTAREA"||t.tagName==="SELECT"||t.isContentEditable===!0}var Qn=`.pl-app{display:flex;flex-direction:column}.app-body{flex:1;min-height:0}.toolbar{display:flex;align-items:center;gap:8px;padding:12px 16px 4px;flex-wrap:wrap}.tb-count{margin-left:auto;font-size:12.5px;color:var(--pl-muted);font-variant-numeric:tabular-nums}.tb-menu{position:relative}.board{display:grid;grid-template-columns:repeat(4,minmax(220px,1fr));gap:12px;padding:8px 16px 20px;overflow-x:auto;scroll-snap-type:x mandatory;align-items:start}.col{scroll-snap-align:start;background:var(--pl-sunken);border-radius:var(--pl-radius);padding:6px;display:grid;gap:6px;min-height:96px}.col.drop{box-shadow:inset 0 0 0 2px var(--pl-accent)}.col-head{display:flex;align-items:center;gap:8px;padding:4px 4px 2px 8px}.col-head h2{margin:0;font-size:13px;font-weight:600}.count{font-size:12px;color:var(--pl-muted);font-variant-numeric:tabular-nums}.col-head .icon-btn{margin-left:auto}.cards,.rows,.comments,.srcs,.repos{list-style:none;margin:0;padding:0;display:grid;gap:6px}.card{background:var(--pl-surface);border:1px solid var(--pl-hairline);border-radius:8px;position:relative}.card:hover{border-color:var(--pl-border)}.card.is-selected{border-color:var(--pl-accent);box-shadow:0 0 0 1px var(--pl-accent)}.card.dragging{opacity:.5}.card.flash{animation:pl-flash 1.5s ease-out}@keyframes pl-flash{0%{background:var(--pl-accent-soft)}}@media(prefers-reduced-motion:reduce){.card.flash{animation:none}}.card-hit{all:unset;box-sizing:border-box;display:grid;gap:6px;width:100%;padding:9px 11px 10px;cursor:pointer;border-radius:8px}.card-hit:focus-visible{outline:2px solid var(--pl-accent);outline-offset:2px}.card-top{display:flex;align-items:center;gap:6px;min-height:14px}.ref{font:12px/1 ui-monospace,SF Mono,Menlo,Consolas,monospace;color:var(--pl-muted);font-variant-numeric:tabular-nums}.card-title{font-weight:500;line-height:1.35;display:-webkit-box;-webkit-line-clamp:3;-webkit-box-orient:vertical;overflow:hidden;text-wrap:pretty;overflow-wrap:anywhere}.card-foot,.row-foot{display:flex;align-items:center;gap:8px}.card .chip{background:var(--pl-bg);box-shadow:inset 0 0 0 1px var(--pl-hairline)}.cmt{margin-left:auto;display:inline-flex;align-items:center;gap:3px;font-size:12px;color:var(--pl-muted);font-variant-numeric:tabular-nums}.sync-mark{margin-left:auto;display:inline-flex;width:10px;height:10px;border-radius:50%;flex:none}.sync-mark.waiting{border:1.5px solid var(--pl-muted)}.sync-mark.sending{border:1.5px solid color-mix(in srgb,var(--pl-accent) 25%,transparent);border-top-color:var(--pl-accent);animation:pl-spin 1s linear infinite}.sync-mark.conflict{width:auto;height:auto;border-radius:0;color:color-mix(in srgb,var(--pl-warn) 75%,var(--pl-text))}.card-menu{position:absolute;top:4px;right:4px;opacity:0}.card:hover .card-menu,.card:focus-within .card-menu,.card-menu[aria-expanded=true]{opacity:1}.card .menu{top:32px;right:4px}.show-more{border:0;background:none;color:var(--pl-muted);font-size:12.5px;padding:6px 8px;text-align:left;cursor:pointer;border-radius:6px}.show-more:hover{background:var(--pl-surface);color:var(--pl-text)}.card.skel{padding:11px;display:grid;gap:8px}.sk{display:block;height:9px;border-radius:5px;background:var(--pl-sunken)}.split{display:grid;grid-template-columns:minmax(0,1fr) clamp(400px,36vw,440px);align-items:start}.split-main{min-width:0}.detail{background:var(--pl-surface);display:flex;flex-direction:column}.detail.docked{border-left:1px solid var(--pl-hairline);margin-top:8px;position:sticky;top:0;max-height:100vh;min-height:calc(100vh - 100px);overflow:auto}.detail .d-foot{margin-top:auto}.scrim{position:fixed;inset:0;z-index:20;background:color-mix(in srgb,var(--pl-text) 25%,transparent)}.detail.drawer{position:fixed;top:0;right:0;bottom:0;z-index:21;width:min(440px,calc(100% - 48px));overflow:auto;border-left:1px solid var(--pl-hairline);box-shadow:var(--t-box-shadow-intense, none)}.pl-app[data-size=m] .detail.drawer{width:calc(100% - 48px)}.detail.sheet{position:fixed;inset:0;z-index:21;overflow:auto}.d-bar{display:flex;align-items:center;gap:6px;padding:8px 8px 8px 16px;border-bottom:1px solid var(--pl-hairline);min-height:48px;position:sticky;top:0;background:var(--pl-surface);z-index:1}.detail.sheet .d-bar{padding-left:4px}.d-body{padding:16px;display:grid;gap:14px;align-content:start;flex:1}.pl-app .d-title{font:600 18px/1.3 var(--pl-font);resize:none;field-sizing:content;width:100%;border:1px solid transparent;border-radius:6px;padding:4px 6px;margin:0 0 0 -7px;background:transparent;text-wrap:balance;overflow:hidden}textarea.d-title:hover{border-color:var(--pl-hairline)}textarea.d-title:focus{border-color:var(--pl-accent);outline:none}.d-title.ro{margin-left:0;padding:0}.d-props{display:grid;grid-template-columns:64px 1fr;gap:10px 12px;align-items:center}.d-k{font-size:12.5px;color:var(--pl-muted)}.status-seg button{padding:0 9px}.d-h{margin:6px 0 -4px;font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--pl-muted);display:flex;gap:6px;align-items:baseline}.tabs{display:flex;gap:2px;border-bottom:1px solid var(--pl-hairline)}.tabs button{border:0;background:none;padding:6px 10px;cursor:pointer;color:var(--pl-muted);border-bottom:2px solid transparent;margin-bottom:-1px;font-size:13px}.tabs button[aria-selected=true]{color:var(--pl-text);border-bottom-color:var(--pl-accent)}.md{font-size:14px;line-height:1.55;max-width:65ch;overflow-wrap:anywhere}.md p{margin:0 0 8px}.md ul,.md ol{margin:0 0 8px;padding-left:20px}.md pre{background:var(--pl-sunken);padding:8px 10px;border-radius:6px;overflow:auto;margin:0 0 8px}.md pre code{background:none;padding:0}.md blockquote{margin:0 0 8px;padding-left:10px;border-left:3px solid var(--pl-hairline);color:var(--pl-muted)}.md h3,.md h4,.md h5,.md h6{margin:8px 0 4px;font-size:14px}.md-empty{color:var(--pl-muted);font-style:italic}.editor{width:100%;min-height:140px;resize:vertical;border:1px solid var(--pl-hairline);border-radius:8px;padding:8px 10px;background:var(--pl-surface);font:13px/1.5 ui-monospace,SF Mono,Menlo,Consolas,monospace}.editor:focus{border-color:var(--pl-accent);outline:none}.row-actions{display:flex;gap:8px;justify-content:flex-end}.comments{gap:12px}.comments li{display:grid;grid-template-columns:28px 1fr;gap:10px}.comments p{margin:0}.comments li.pending{opacity:.8}.c-meta{font-size:12.5px;color:var(--pl-muted);margin-bottom:2px!important}.c-meta b{color:var(--pl-text);font-weight:600}.pend{color:var(--pl-accent-ink)}.avatar{width:28px;height:28px;border-radius:50%;display:grid;place-items:center;font-size:10.5px;font-weight:600;background:var(--pl-sunken);color:var(--pl-muted);text-transform:uppercase}.avatar.me{background:var(--pl-accent-soft);color:var(--pl-accent-ink)}.composer{display:grid;gap:6px}.composer textarea{width:100%;resize:vertical;min-height:56px;border:1px solid var(--pl-hairline);border-radius:8px;padding:8px 10px;background:var(--pl-surface)}.composer textarea:focus{border-color:var(--pl-accent);outline:none}.cmp-row{display:flex;align-items:center;gap:8px;justify-content:space-between}.d-foot{padding:10px 16px;border-top:1px solid var(--pl-hairline);font-size:12px;color:var(--pl-muted);display:flex;flex-wrap:wrap;gap:4px;align-items:center}.d-actions{padding:10px 16px;border-top:1px solid var(--pl-hairline);display:flex;gap:8px;align-items:center;flex-wrap:wrap;justify-content:flex-end;position:sticky;bottom:0;background:var(--pl-surface)}.d-actions .hint{flex-basis:100%;text-align:right;margin:0}.ro-note{margin:0;display:flex;gap:8px;align-items:flex-start;padding:8px 10px;border-radius:8px;background:var(--pl-sunken);font-size:12.5px;color:var(--pl-muted)}.cf{border:1px solid var(--pl-hairline);border-radius:var(--pl-radius);padding:8px 10px 10px;margin:0;display:grid;gap:6px}.cf legend{font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--pl-muted);padding:0 4px}.cf-opt{display:grid;grid-template-columns:18px 1fr;gap:2px 8px;padding:8px;border-radius:7px;cursor:pointer}.cf-opt:has(input:checked){background:var(--pl-accent-soft)}.cf-opt input{grid-row:span 2;margin:3px 0 0;accent-color:var(--pl-accent)}.cf-src{font-size:12px;color:var(--pl-muted)}.cf-val{display:block;overflow-wrap:anywhere;white-space:pre-wrap}.cf-val .glyph{vertical-align:-2px;margin-right:4px}.cf-val ins{text-decoration:none;background:color-mix(in srgb,var(--pl-pos) 18%,transparent);border-radius:3px;padding:0 2px}.review{display:grid;gap:8px;margin:0;padding:0 0 0 18px}.list{padding:4px 0 24px;display:grid;gap:4px}.group-head{all:unset;box-sizing:border-box;display:flex;align-items:center;gap:8px;width:100%;padding:10px 16px;font-weight:600;font-size:13px;cursor:pointer;min-height:44px}.group-head[aria-expanded=false]>svg:first-child{transform:rotate(-90deg)}.group-head:focus-visible{outline:2px solid var(--pl-accent);outline-offset:-2px}.rows{gap:0;background:var(--pl-surface);border-block:1px solid var(--pl-hairline)}.row{display:grid;grid-template-columns:44px 1fr;border-bottom:1px solid var(--pl-hairline);position:relative}.row:last-child{border-bottom:0}.row.is-selected{background:var(--pl-accent-soft)}.glyph-btn{border:0;background:none;display:grid;place-items:start center;padding-top:14px;cursor:pointer;min-height:44px}.row .menu{top:40px;left:8px}.row-hit{all:unset;box-sizing:border-box;display:grid;gap:4px;padding:11px 16px 11px 0;cursor:pointer;min-width:0}.row-hit:focus-visible{outline:2px solid var(--pl-accent);outline-offset:-2px}.row-line{display:flex;align-items:center;gap:6px}.row-line .sync-mark{margin-left:0}.when{margin-left:auto;font-size:12px;color:var(--pl-muted);font-variant-numeric:tabular-nums}.row-title{font-weight:500;line-height:1.35;overflow-wrap:anywhere}.center-wrap{display:grid;justify-items:center;padding:28px 16px 36px}.onboard{width:100%;max-width:560px;display:grid;gap:14px}.onboard h2{margin:0;font-size:20px;font-weight:600;text-wrap:balance}.lede{margin:0;color:var(--pl-muted)}.fine{margin:0;font-size:12.5px;color:var(--pl-muted)}.srcs{gap:8px}.src{display:flex;align-items:center;gap:12px;padding:12px 14px;border:1px solid var(--pl-hairline);border-radius:var(--pl-radius);background:var(--pl-surface);flex-wrap:wrap}.src-text{display:grid;gap:2px;flex:1 1 260px}.src-text span{color:var(--pl-muted);font-size:13px}.src-text .effect{color:var(--pl-text);font-size:12.5px}.src.disabled{background:transparent}.src.disabled b,.src.disabled .effect{color:var(--pl-muted)}.repos{gap:0;border:1px solid var(--pl-hairline);border-radius:var(--pl-radius);background:var(--pl-surface);overflow:hidden;max-height:320px;overflow-y:auto}.repo{display:grid;grid-template-columns:18px 1fr auto;gap:10px;align-items:center;padding:10px 12px;cursor:pointer}.repos>li+li{border-top:1px solid var(--pl-hairline)}.repo:has(input:checked){background:var(--pl-accent-soft)}.repo.disabled{color:var(--pl-muted);cursor:default}.repo input{margin:0;accent-color:var(--pl-accent)}.effects{padding:12px 14px;border-radius:var(--pl-radius);background:var(--pl-sunken)}.effects h3{margin:0 0 6px;font-size:13px}.effects ul{margin:0;padding-left:18px;display:grid;gap:4px;font-size:13px}.actions-row{display:flex;justify-content:flex-end;gap:8px;flex-wrap:wrap;align-items:center}.field-error{margin:0;color:var(--pl-neg);font-size:12.5px}.typed{display:flex;gap:8px;flex-wrap:wrap}.typed .search{flex:1 1 240px}.empties{padding:8px 16px 20px}.empty-cell{border:1px dashed var(--pl-hairline);border-radius:var(--pl-radius)}.overlay{position:fixed;inset:0;z-index:40;display:grid;place-items:center;background:color-mix(in srgb,var(--pl-text) 25%,transparent);padding:16px}.dialog{background:var(--pl-surface);border-radius:var(--pl-radius);border:1px solid var(--pl-hairline);padding:16px;width:min(440px,100%);max-height:100%;overflow:auto;display:grid;gap:12px}.dialog h2{margin:0;font-size:16px}.keys{display:grid;grid-template-columns:auto 1fr;gap:6px 14px;margin:0;font-size:13px}.keys dt{white-space:nowrap}.keys dd{margin:0;color:var(--pl-muted)}.pill-wrap{position:relative;display:inline-flex}.pill-wrap .popover{top:calc(100% + 8px);right:0}.conn-menu{position:relative}.conn-menu .menu{right:0;top:calc(100% + 4px)}.label-menu .menu{left:0;top:calc(100% + 4px);max-height:280px;overflow:auto}.pl-app[data-size=s] .d-props{grid-template-columns:56px 1fr}.pl-app[data-size=s] .pl-header{gap:8px;padding:8px 12px} +`;var er=Qn;function d(e,t=null,...n){let r=document.createElement(e);for(let[s,o]of Object.entries(t??{}))o==null||o===!1||(s.startsWith("on")&&typeof o=="function"?r.addEventListener(s.slice(2),o):s==="class"?r.className=String(o):s in r&&typeof o!="string"?r[s]=o:r.setAttribute(s,o===!0?"":String(o)));return tr(r,n),r}function tr(e,t){for(let n of t)n==null||n===!1||(Array.isArray(n)?tr(e,n):e.appendChild(typeof n=="string"||typeof n=="number"?document.createTextNode(String(n)):n))}var Y=(e,t=1.6)=>``,Ts={mark:'',synced:'',syncing:'',paused:'',reauth:Y("M5.5 1.5v3.5M10.5 1.5v3.5M3.5 5h9v2.5a4.5 4.5 0 0 1-9 0zM8 12v3",1.8),error:'',idle:'',plus:Y("M8 3v10M3 8h10"),more:'',board:'',list:'',search:'',chevron:Y("m4 6 4 4 4-4",1.8),comment:Y("M2.5 3.5h11v7h-6l-3 2.5v-2.5h-2z",1.3),close:Y("m4 4 8 8M12 4l-8 8"),back:Y("M10 3 5 8l5 5"),external:Y("M6 3H3v10h10v-3M9 3h4v4M13 3 7 9",1.5),info:'',warn:'',plug:Y("M5.5 2v3.5M10.5 2v3.5M3.5 5.5h9V8a4.5 4.5 0 0 1-9 0zM8 12.5V15",1.5),ghost:Y("M3.5 14V7a4.5 4.5 0 0 1 9 0v7l-1.5-1.2L9.5 14 8 12.8 6.5 14 5 12.8z",1.4),lock:'',inbox:Y("M3 13.5 5.5 5h13l2.5 8.5V19H3z M3 13.5h5l1 2.5h6l1-2.5h5",1.4),filter:Y("M4 5h16l-6 7.5V19l-4-2v-4.5z",1.4),server:'',todo:'',doing:'',blocked:'',done:''},Rs={inbox:24,filter:24,server:24,todo:14,doing:14,blocked:14,done:14};function N(e,t=16,n){let r=Rs[e]??16,s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(t)),s.setAttribute("height",String(t)),s.setAttribute("viewBox",`0 0 ${r} ${r}`),s.setAttribute("aria-hidden","true"),n&&s.setAttribute("class",n),s.innerHTML=Ts[e],s}var $s={idle:"idle",synced:"synced",syncing:"syncing",paused:"paused",reauth:"reauth",error:"error"};function Nt(e,t,n){let r=[N($s[e],12),d("span",null,t)];return n?d("button",{type:"button",class:"pl-pill","data-state":e,"aria-haspopup":"dialog",onclick:n},d("span",{role:"status",class:"pill-status"},r)):d("span",{class:"pl-pill","data-state":e,role:"status"},r)}function nr(e,...t){return d("header",{class:"pl-header"},d("span",{class:"pl-mark","aria-hidden":"true"},N("mark")),d("h1",{class:"pl-name"},e),...t)}function rr(e,t){return d("span",{class:"src-chip"},d("b",null,e),d("span",{class:"mono"},t))}function Lt(e,t=[],n){let r=[];e.filter(o=>o!=null&&o!==!1&&o!=="").forEach((o,i)=>{i&&r.push(d("span",{class:"dot-sep","aria-hidden":"true"},"\xB7")),r.push(...Array.isArray(o)?o:[o])});let s=d("div",{class:"pl-conn"},r,d("span",{class:"spacer"}),...t);if(n!==void 0){let o=d("span",{class:`progress${n===!0?" indeterminate":""}`,"aria-hidden":"true"});n!==!0&&o.style.setProperty("--p",`${Math.round(n*100)}%`),s.append(o)}return s}function sr(e){let t=d("div",{class:"pl-banner","data-tone":e.tone,...e.alert?{role:"alert"}:{}},d("span",{class:"b-icon"},N(e.icon)),d("p",{class:"b-text"},d("b",null,e.title)," ",e.text),e.actions?.length?d("div",{class:"b-actions"},e.actions):null);return e.details?d("div",{class:"banner-wrap"},t,d("details",{class:"b-details"},d("summary",null,"Details"),d("code",null,e.details))):t}function Me(e,t,n,r,s=!1){return d("div",{class:`pl-empty${s?" tall":""}`},d("span",{class:"e-icon","aria-hidden":"true"},N(e,24)),d("p",null,d("b",null,t),n),r??null)}function L(e,t,{kind:n="",sm:r=!1,iconName:s,...o}={}){return d("button",{type:"button",class:["btn",n,r?"sm":""].filter(Boolean).join(" "),onclick:t,...o},s?N(s,14):null,Array.isArray(e)?e:d("span",null,e))}function Ee(e,t,n,{sm:r=!1,...s}={}){return d("button",{type:"button",class:`icon-btn${r?" sm":""}`,"aria-label":t,title:t,onclick:n,...s},N(e,r?14:16))}function Dt(e,t,n,r,{mode:s="pressed",disabled:o=!1,cls:i=""}={}){let a=d("div",{class:`seg ${i}`.trim(),role:s==="radio"?"radiogroup":"group","aria-label":e});for(let c of t){let u=c.value===n;a.append(d("button",{type:"button",...s==="radio"?{role:"radio","aria-checked":String(u),tabindex:u?0:-1}:{"aria-pressed":String(u)},...c.title?{"aria-label":c.title,title:c.title}:{},"data-value":c.value,disabled:o,onclick:()=>r(c.value)},c.iconName?N(c.iconName,14):null,c.label))}return s==="radio"&&a.addEventListener("keydown",c=>{let u=c,f=u.key==="ArrowRight"||u.key==="ArrowDown"?1:u.key==="ArrowLeft"||u.key==="ArrowUp"?-1:0;if(!f)return;u.preventDefault();let m=Math.max(0,t.findIndex(b=>b.value===n)),g=t[(m+f+t.length)%t.length];r(g.value)}),a}function _t(e,t,n,r=!1){let s=d("input",{type:"search",placeholder:e,"aria-label":e,autocomplete:"off",oninput:o=>n(o.target.value)});return s.value=t,{input:s,field:d("label",{class:`search${r?" wide":""}`},N("search",14),s,d("kbd",{"aria-hidden":"true"},"/"))}}function Gt(e,t){let n=d("i",{"aria-hidden":"true"});return t&&/^#[0-9a-f]{6}$/i.test(t)&&(n.style.background=t),d("span",{class:"chip"},n,e)}function fe(e,t=14){return N(e,t,`glyph g-${e}`)}function or(){let e=d("div",{class:"sr","aria-live":"polite"});return{region:e,say(t){e.textContent="",setTimeout(()=>{e.textContent=t},30)}}}var ir=`html,body{margin:0;background:var(--t-color-bg-body)}.pl-app{--pl-bg: var(--t-color-bg-body);--pl-surface: var(--t-color-bg);--pl-sunken: var(--t-color-bg-1);--pl-border: var(--t-color-bg-2);--pl-hairline: color-mix(in srgb, var(--t-color-bg-2) 55%, var(--t-color-bg));--pl-text: var(--t-color-text);--pl-muted: var(--t-color-text-light);--pl-accent: var(--t-color-main);--pl-accent-soft: var(--t-color-main-selected-bg);--pl-accent-ink: var(--t-color-main-selected-fg);--pl-on-accent: var(--t-color-bg);--pl-neg: var(--t-color-alert);--pl-warn: var(--t-color-warning);--pl-radius: var(--t-radius, 9px);--pl-font: var(--t-font-family, system-ui, sans-serif);--pl-pos: var(--t-color-success, #2f8f5b);background:var(--pl-bg);color:var(--pl-text);font:14px/1.45 var(--pl-font);position:relative;min-height:100vh;box-sizing:border-box}.pl-app[data-pl-scheme=dark]{--pl-pos: var(--t-color-success, #5cc48a)}.pl-app *,.pl-app *:before,.pl-app *:after{box-sizing:border-box}.pl-app button,.pl-app input,.pl-app textarea{font:inherit;color:inherit}.pl-app :focus-visible{outline:2px solid var(--pl-accent);outline-offset:2px}.pl-app [hidden]{display:none!important}.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}.spacer{flex:1 1 auto}.mono{font-family:ui-monospace,SF Mono,Menlo,Consolas,monospace;font-size:.92em}.muted{color:var(--pl-muted)}.small{font-size:12.5px}.pl-app a{color:var(--pl-accent);text-decoration:none;display:inline-flex;align-items:center;gap:3px}.pl-app a:hover{text-decoration:underline}.pl-app code{font-family:ui-monospace,SF Mono,Menlo,Consolas,monospace;font-size:.9em;background:var(--pl-sunken);padding:1px 5px;border-radius:4px}@keyframes pl-spin{to{transform:rotate(360deg)}}.pl-spin{animation:pl-spin 1s linear infinite;transform-origin:50% 50%;transform-box:fill-box}@keyframes pl-slide{0%{transform:translate(-100%)}to{transform:translate(340%)}}@media(prefers-reduced-motion:reduce){.pl-spin,.progress.indeterminate:after,.sync-mark.sending{animation:none!important}}.pl-header{display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--pl-surface);border-bottom:1px solid var(--pl-hairline);min-height:52px}.pl-mark{width:28px;height:28px;border-radius:8px;display:grid;place-items:center;background:var(--pl-accent-soft);color:var(--pl-accent);flex:none}.pl-name{font-weight:600;font-size:15px;margin:0}.src-chip{display:inline-flex;align-items:center;gap:6px;padding:3px 10px;border-radius:999px;background:var(--pl-sunken);font-size:12.5px;white-space:nowrap;min-width:0;overflow:hidden;text-overflow:ellipsis}.src-chip b{font-weight:600}.pl-pill{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;border:1px solid var(--pl-hairline);font-size:12.5px;white-space:nowrap;background:var(--pl-surface);cursor:default}button.pl-pill{cursor:pointer}.pl-pill[data-state=synced] svg{color:var(--pl-pos)}.pl-pill[data-state=idle] svg{color:var(--pl-muted)}.pl-pill[data-state=syncing]{color:var(--pl-accent-ink);background:var(--pl-accent-soft);border-color:transparent}.pl-pill[data-state=syncing] svg{color:var(--pl-accent)}.pl-pill[data-state=paused]{border-color:color-mix(in srgb,var(--pl-warn) 60%,transparent);background:color-mix(in srgb,var(--pl-warn) 12%,var(--pl-surface))}.pl-pill[data-state=paused] svg{color:var(--pl-warn)}.pl-pill[data-state=reauth],.pl-pill[data-state=error]{border-color:color-mix(in srgb,var(--pl-neg) 60%,transparent);background:color-mix(in srgb,var(--pl-neg) 10%,var(--pl-surface))}.pl-pill[data-state=reauth] svg,.pl-pill[data-state=error] svg{color:var(--pl-neg)}.btn{display:inline-flex;align-items:center;justify-content:center;gap:6px;height:32px;padding:0 12px;border-radius:8px;border:1px solid var(--pl-border);background:var(--pl-surface);cursor:pointer;white-space:nowrap;font-weight:500}.btn.sm{height:28px;padding:0 10px;font-size:13px}.btn.primary{background:var(--pl-accent);border-color:var(--pl-accent);color:var(--pl-on-accent)}.btn:disabled{opacity:.45;cursor:not-allowed}.btn.ghost{border-color:transparent;background:transparent}.btn.ghost:hover:not(:disabled){background:var(--pl-sunken)}.btn.danger{color:var(--pl-neg);border-color:color-mix(in srgb,var(--pl-neg) 55%,transparent)}.btn.icon-only{width:32px;padding:0}.icon-btn{display:inline-grid;place-items:center;width:32px;height:32px;border-radius:8px;border:0;background:transparent;color:var(--pl-muted);cursor:pointer;flex:none}.icon-btn.sm{width:26px;height:26px}.icon-btn:hover{background:var(--pl-sunken);color:var(--pl-text)}.link-btn{border:0;background:none;color:var(--pl-accent);cursor:pointer;font-weight:500;padding:4px 6px;border-radius:6px}.link-btn:disabled{color:var(--pl-muted);cursor:default}.pl-conn{position:relative;display:flex;align-items:center;gap:8px;padding:6px 12px 6px 16px;font-size:12.5px;color:var(--pl-muted);background:var(--pl-surface);border-bottom:1px solid var(--pl-hairline);min-height:38px;flex-wrap:wrap}.pl-conn .acct{color:var(--pl-text);font-weight:500}.dot-sep{opacity:.6}.progress{position:absolute;left:0;right:0;bottom:-1px;height:2px;overflow:hidden}.progress:after{content:"";position:absolute;left:0;top:0;bottom:0;width:var(--p, 30%);background:var(--pl-accent)}.progress.indeterminate:after{width:30%;animation:pl-slide 1.4s ease-in-out infinite}.pl-banner{display:flex;align-items:flex-start;flex-wrap:wrap;gap:10px 12px;margin:12px 16px 0;padding:10px 12px;border-radius:var(--pl-radius);border:1px solid;font-size:13.5px}.pl-banner[data-tone=warn]{border-color:color-mix(in srgb,var(--pl-warn) 55%,transparent);background:color-mix(in srgb,var(--pl-warn) 10%,var(--pl-surface))}.pl-banner[data-tone=warn] .b-icon{color:color-mix(in srgb,var(--pl-warn) 70%,var(--pl-text))}.pl-banner[data-tone=neg]{border-color:color-mix(in srgb,var(--pl-neg) 50%,transparent);background:color-mix(in srgb,var(--pl-neg) 8%,var(--pl-surface))}.pl-banner[data-tone=neg] .b-icon{color:var(--pl-neg)}.pl-banner[data-tone=info]{border-color:transparent;background:var(--pl-accent-soft);color:var(--pl-accent-ink)}.b-icon{flex:none;padding-top:1px;display:inline-flex}.b-text{flex:1 1 260px;min-width:0;margin:0}.b-actions{display:flex;gap:8px;flex-wrap:wrap}.b-details{margin:6px 16px 0;font-size:12.5px;color:var(--pl-muted)}.b-details code{display:block;margin-top:4px;white-space:pre-wrap;word-break:break-all}.seg{display:inline-flex;padding:2px;border-radius:9px;background:var(--pl-sunken);gap:2px}.seg button{display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 10px;border:0;border-radius:7px;background:transparent;cursor:pointer;color:var(--pl-muted);font-size:13px}.seg button[aria-pressed=true],.seg button[aria-checked=true]{background:var(--pl-surface);color:var(--pl-text);box-shadow:0 0 0 1px var(--pl-hairline)}.seg button:disabled{cursor:not-allowed;opacity:.6}.search{display:inline-flex;align-items:center;gap:6px;height:32px;padding:0 8px 0 10px;border:1px solid var(--pl-hairline);border-radius:8px;background:var(--pl-surface);color:var(--pl-muted);flex:0 1 260px;min-width:120px}.search.wide{flex:none;width:100%}.search input{border:0;outline:0;background:transparent;min-width:0;flex:1;color:var(--pl-text)}.search input::-webkit-search-cancel-button{display:none}.search:focus-within{border-color:var(--pl-accent)}kbd{font:11px/1 ui-monospace,Menlo,monospace;padding:3px 5px;border:1px solid var(--pl-hairline);border-radius:4px;color:var(--pl-muted)}.chips{display:flex;flex-wrap:wrap;gap:4px;align-items:center;min-width:0}.chip{display:inline-flex;align-items:center;gap:5px;height:20px;padding:0 7px;border-radius:999px;background:var(--pl-sunken);font-size:11.5px;white-space:nowrap}.chip i{width:8px;height:8px;border-radius:50%;flex:none;background:var(--pl-muted)}.chip.more{color:var(--pl-muted)}.glyph{flex:none}.g-todo{color:var(--pl-muted)}.g-doing{color:var(--pl-warn)}.g-blocked{color:var(--pl-neg)}.g-done{color:var(--pl-accent)}.pl-empty{display:grid;justify-items:center;gap:12px;text-align:center;padding:40px 20px}.pl-empty.tall{padding:72px 24px}.pl-empty p{margin:0;max-width:42ch;color:var(--pl-muted)}.pl-empty p b{color:var(--pl-text);font-weight:600;display:block}.e-icon{width:52px;height:52px;border-radius:14px;display:grid;place-items:center;background:var(--pl-sunken);color:var(--pl-muted)}.popover{position:absolute;z-index:30;width:min(320px,calc(100vw - 32px));padding:12px;border-radius:var(--pl-radius);border:1px solid var(--pl-hairline);background:var(--pl-surface);box-shadow:var( --t-box-shadow-intense, 0 10px 24px -12px color-mix(in srgb, var(--pl-text) 35%, transparent) );display:grid;gap:8px;justify-items:start}.popover p{margin:0;font-size:13px}.menu{position:absolute;z-index:30;min-width:180px;padding:4px;border-radius:8px;border:1px solid var(--pl-hairline);background:var(--pl-surface);box-shadow:var( --t-box-shadow-intense, 0 10px 24px -12px color-mix(in srgb, var(--pl-text) 35%, transparent) );display:grid}.menu button{all:unset;box-sizing:border-box;display:flex;align-items:center;gap:8px;padding:7px 10px;border-radius:6px;cursor:pointer;font-size:13px}.menu button:hover,.menu button:focus-visible{background:var(--pl-sunken);outline:none}.menu button[aria-checked=true]{font-weight:600}.menu button:disabled{color:var(--pl-muted);cursor:default}.pl-app[data-size=s] :is(.btn,.icon-btn,.seg button,.link-btn,.menu button){min-height:44px}.pl-app[data-size=s] .icon-btn{min-width:44px} +`;var ar=ir;function js(e){return e<600?"s":e<720?"m":e<1e3?"l":"xl"}function Ps(e){let t=e.trim(),n,r=t.match(/^#([0-9a-f]{3}|[0-9a-f]{6})$/i)?.[1];if(r){let a=r.length===3?r.split("").map(c=>c+c).join(""):r;n=[0,2,4].map(c=>parseInt(a.slice(c,c+2),16))}else{let a=t.match(/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i);a&&(n=[a[1],a[2],a[3]].map(Number))}if(!n)return;let[s,o,i]=n.map(a=>{let c=a/255;return c<=.03928?c/12.92:((c+.055)/1.055)**2.4});return .2126*s+.7152*o+.0722*i}function cr(e,t){let n=e.ownerDocument,r="pl-app-styles";if(n.getElementById(r))return;let s=n.createElement("style");s.id=r,s.textContent=ar+t,n.head.append(s)}function lr(e,t,n={}){let r=e.ownerDocument.defaultView,s=()=>{let m=n.getTheme?.().colorScheme;if(m){e.dataset.plScheme=m;return}let g=r?.getComputedStyle(e.ownerDocument.documentElement).getPropertyValue("--t-color-bg"),b=g?Ps(g):void 0;e.dataset.plScheme=b!==void 0&&b<.4?"dark":"light"},o,i=()=>{let m=e.getBoundingClientRect().width||r?.innerWidth||0,g=js(m);e.dataset.size=g,g!==o&&(o=g,t(g,m))};s(),i();let a=m=>{m.data?.type==="__atomic_style"&&setTimeout(s,0)};r?.addEventListener("message",a);let c=n.onThemeChange?.(({colorScheme:m})=>{m?e.dataset.plScheme=m:s()}),u=r?.ResizeObserver,f=u?new u(i):void 0;return f?.observe(e),f||r?.addEventListener("resize",i),()=>{r?.removeEventListener("message",a),c?.(),f?.disconnect(),r?.removeEventListener("resize",i)}}var Os=/^https?:\/\/[^\s<>"']+$/i;function me(e){let t=[],n=/(`[^`]+`)|(\*\*[^*]+\*\*)|(\*[^*\s][^*]*\*|_[^_\s][^_]*_)|(\[[^\]]+\]\([^)\s]+\))/g,r=0,s;for(;s=n.exec(e);){s.index>r&&t.push(document.createTextNode(e.slice(r,s.index)));let o=s[0],i,a;if(s[1])i=document.createElement("code"),i.textContent=o.slice(1,-1);else if(s[2])i=a=document.createElement("strong"),a.append(...me(o.slice(2,-2)));else if(s[3])i=a=document.createElement("em"),a.append(...me(o.slice(1,-1)));else{let[,c,u]=o.match(/^\[([^\]]+)\]\(([^)\s]+)\)$/);if(Os.test(u)){let f=document.createElement("a");f.href=u,f.target="_blank",f.rel="noopener noreferrer",f.append(...me(c)),i=f}else i=document.createTextNode(o)}t.push(i),r=s.index+o.length}return r{let n=document.createElement(e);return n.append(...t),n};function at(e){let t=document.createDocumentFragment(),n=e.replace(/\r\n?/g,` +`).split(` +`),r=0,s=i=>{if(!i.length)return;let a=ae("p");i.forEach((c,u)=>{u&&a.append(ae("br")),a.append(...me(c))}),t.append(a),i.length=0},o=[];for(;r/.test(i)){s(o);let u=[];for(;r/.test(n[r]);)u.push(n[r++].replace(/^\s*>\s?/,""));let f=ae("blockquote");f.append(at(u.join(` +`))),t.append(f);continue}i.trim()?o.push(i):s(o),r++}return s(o),t}var ge={Todo:"todo",Doing:"doing",Blocked:"blocked",Done:"done"},ne=e=>e.number!==void 0?`#${e.number}`:e.localOnly?"Local":"New",pr=e=>e.statusAsIs?`Status here: ${e.statusAsIs.join(", ")||"none"} (not synced with GitHub)`:void 0,fr=e=>`https://github.com/${e}`;function Is(e,t,n){let r=[d("span",{class:"sr"},"GitHub "),"Issues"],s=e.kind==="ready"?e.repository:e.kind==="choose-repository"?"choose a repository":void 0,o=t.size==="s",i=Vn(e,t.now),a=null;if(i){let u=i.state==="error",f=u&&t.retryIn!==void 0?`Sync failed \xB7 retrying in ${Math.max(1,Math.round(t.retryIn/60))} min`:o&&i.state==="synced"&&i.text.startsWith("Synced ")?i.text.slice(7):i.text;a=u?d("span",{class:"pill-wrap"},Nt("error",f,()=>n.setUi({menu:t.menu==="pill"?void 0:"pill"})),t.menu==="pill"&&e.kind==="ready"?Cs(e,t,n):null):Nt(i.state,f)}let c=e.kind==="ready"?o?d("button",{type:"button",class:"btn primary icon-only","aria-label":"New issue",title:"New issue (N)","data-key":"new-issue",onclick:()=>n.open({kind:"new"},"new-issue")},N("plus",14)):L("New issue",()=>n.open({kind:"new"},"new-issue"),{kind:"primary",iconName:"plus","data-key":"new-issue"}):null;return nr(r,s&&!o?rr("GitHub",s):null,d("span",{class:"spacer"}),a,c)}function Cs(e,t,n){let r=e.problem?.kind==="failed"?e.problem.message:"Unknown error";return d("div",{class:"popover",role:"dialog","aria-label":"Sync failed"},d("p",null,d("b",null,"GitHub or the host did not answer. "),r),d("p",{class:"muted"},t.retryIn!==void 0?"Retrying automatically while this app is open: 4 min, then 8, up to once an hour.":"Sync runs when this app opens and on Sync now."),L("Retry now",()=>{n.setUi({menu:void 0},!1),n.sync()},{kind:"primary",sm:!0}))}function Ms(e,t,n){let r=e.problem?0:e.last?.result.held.length??0,s=!!e.busy,o=t.menu==="conn",i=e.busy==="syncing"||e.busy==="sending"?!0:void 0,a=Lt([t.size==="s"?d("span",{class:"mono acct"},e.repository):d("span",{class:"acct"},"GitHub"),t.size==="s"&&!r?null:d("span",null,Jn(e))],[r&&!e.last?.result.held.some(c=>c.unconfirmed)?d("button",{type:"button",class:"link-btn","data-key":"review",disabled:s,onclick:()=>n.open({kind:"review"},"review")},"Review and send"):null,d("button",{type:"button",class:"link-btn","data-key":"sync-now",disabled:s,onclick:()=>n.sync()},"Sync now"),d("span",{class:"conn-menu"},Ee("more","Connection menu",()=>n.setUi({menu:o?void 0:"conn"}),{sm:!0,"aria-haspopup":"menu","aria-expanded":String(o)}),o?Ut("Connection",[{label:"Open repository on GitHub",run:()=>n.openGitHub(fr(e.repository))},{label:"Reconnect GitHub",run:()=>n.connect(),disabled:e.problem?.kind!=="reconnect"},{label:"Disconnect GitHub",run:()=>n.disconnect(),disabled:!t.canDisconnect},{label:"Change repository: install another app",run:()=>{},disabled:!0},{label:"Keyboard shortcuts",run:()=>n.setUi({help:!0,menu:void 0})}],n):null)],i);return a.title=zn(e),a}function Ut(e,t,n){let r=d("div",{class:"menu",role:"menu","aria-label":e},t.map(s=>d("button",{type:"button",role:s.checked===void 0?"menuitem":"menuitemradio",...s.checked===void 0?{}:{"aria-checked":String(s.checked)},disabled:!!s.disabled,onclick:()=>{n.setUi({menu:void 0},!1),s.run()}},s.glyph?fe(s.glyph):null,s.label)));return r.addEventListener("keydown",s=>{let o=s,i=[...r.querySelectorAll("button:not(:disabled)")],a=i.indexOf(o.target);if(o.key==="ArrowDown"||o.key==="ArrowUp"){o.preventDefault(),o.stopPropagation();let c=o.key==="ArrowDown"?1:-1;i[(a+c+i.length)%i.length]?.focus()}}),r}function Hs(e,t,n){let r=qn(e,t.confirmRemove,t.table===void 0);if(!r||e.kind!=="ready")return null;let s=({action:o,subject:i,id:a,url:c})=>{o==="reconnect"?n.connect():o==="landed"&&i&&a!==void 0?n.landed(i,a):o==="send-again"&&i?n.sendAgain(i):o==="review-conflict"?n.open({kind:"conflict",choices:{}},"banner-action"):o==="send"?n.send():o==="sync"?n.sync():o==="keep-here"?n.keepHereOnly():o==="remove"?n.setUi({confirmRemove:!0}):o==="cancel-remove"?n.setUi({confirmRemove:!1}):o==="confirm-remove"?n.removeFromBoard():n.openGitHub(c??`${fr(e.repository)}/issues`)};return sr({tone:r.tone,icon:r.icon,title:r.title,text:r.text,alert:t.alert&&!!r.problem,...r.details?{details:r.details}:{},actions:r.actions.map((o,i)=>L(o.label,()=>s(o),{kind:o.primary?"primary":o.danger?"danger":"",sm:!0,disabled:!!e.busy&&o.action!=="open-github",...i===r.actions.length-1?{"data-key":"banner-action"}:{}}))})}function Ns(e,t,n){let r=t.table??"This table",s=e.reason===nt;return Me(s?"paused":"inbox",s?`Syncing ${r} with GitHub is paused.`:`${r} isn\u2019t synced with GitHub.`,s?"This app may no longer edit this table\u2019s rows, or keep its GitHub issue numbers on them. Allow editing again to go on. Nothing is sent or written while it is paused.":e.reason??(e.canSync?jt:"This Atomic Server can\u2019t let an app edit another table\u2019s rows, so it can\u2019t be synced from here. Nothing was changed."),e.canSync?L(e.asking?"Waiting for you to allow editing\u2026":s?"Allow editing again":"Sync this table to GitHub",()=>n.syncTable(),{kind:"primary",disabled:!!e.asking,"data-key":"sync-table"}):void 0,!0)}function mr(e,t){return e.table===void 0?null:L("Not now",()=>t.notNow(),{kind:"ghost","data-key":"not-now"})}function Ls(){return Me("server","This Atomic Server can\u2019t reach GitHub or Jira for apps.","Ask its admin to update Atomic Server. Nothing was fetched.",void 0,!0)}function Ds(e,t,n){let r=e.kind==="connecting",s=(o,i,a,c,u=!1)=>d("li",{class:`src${u?" disabled":""}`},d("div",{class:"src-text"},d("b",null,o),d("span",null,i),d("span",{class:"effect"},a)),c);return d("div",{class:"center-wrap"},d("div",{class:"onboard"},d("h2",null,t.table===void 0?"Bring your issues into this drive":`Sync ${t.table} with GitHub`),d("p",{class:"lede"},t.table===void 0?"Pick where your issues live today. They stay there; this board mirrors them into an Atomic table you can link, search and query.":"The repository\u2019s issues are added to this table as rows; the rows already here stay here until you publish them. Nothing is sent to GitHub until you review it."),d("ul",{class:"srcs"},s("GitHub Issues","One repository\u2019s issues and comments.","Two-way: status, title, description and comments are sent back to GitHub after you review them.",L(r?"Waiting\u2026":"Connect",()=>n.connect(),{kind:"primary","aria-label":"Connect GitHub Issues","data-key":"connect-github",disabled:r})),s("Jira","One Jira Cloud project.","Read-only for now: nothing is sent back to Jira.",d("span",{class:"muted small"},"Not available on this server yet"),!0),s("Todoist","One Todoist project\u2019s tasks.","Read-only: nothing is sent back to Todoist.",d("span",{class:"muted small"},"Not available in this app yet"),!0)),d("p",{class:"fine"},r?"Confirm the connection in the bar Atomic Server shows above this app.":"Connecting opens a confirmation bar from Atomic Server, then your provider\u2019s sign-in. This app never sees your password or token."),r?null:mr(t,n)))}function _s(e){return e.hasIssues?e.openIssues===void 0?"":e.openIssues===0?"no open issues":`about ${e.openIssues} open ${e.openIssues===1?"issue":"issues"}`:"issues disabled"}function Gs(e,t,n){let r=e.listing,s=r?.kind==="listed"?r.repositories:void 0,i=!s||s.length===0?t.typedRepo.trim():t.repoChoice,a=!!e.settingUp,c;if(!r||r.kind==="loading")c=d("p",{class:"lede"},"Loading the repositories this connection can see\u2026");else if(s&&s.length){let f=t.repoFilter.toLowerCase(),m=s.filter(b=>b.fullName.toLowerCase().includes(f)),{field:g}=_t(`Filter ${s.length} ${s.length===1?"repository":"repositories"}`,t.repoFilter,b=>n.setUi({repoFilter:b}),!0);g.dataset.key="repo-filter",g.querySelector("input").dataset.key="repo-filter-input",g.querySelector("kbd")?.remove(),c=[g,d("ul",{class:"repos",role:"radiogroup","aria-label":"Repositories"},m.map(b=>d("li",null,d("label",{class:`repo${b.hasIssues?"":" disabled"}`},d("input",{type:"radio",name:"repository",value:b.fullName,checked:t.repoChoice===b.fullName,disabled:!b.hasIssues||a,"data-key":`repo:${b.fullName}`,onchange:()=>n.setUi({repoChoice:b.fullName})}),d("span",{class:"mono"},b.fullName),d("span",{class:"muted small"},_s(b)))))),m.length?null:d("p",{class:"fine"},"No repository matches this filter.")]}else{let f=d("input",{name:"repository",autocomplete:"off",spellcheck:"false",placeholder:"octocat/hello-world","aria-label":"Repository (owner/name)","data-key":"typed-repo",disabled:a,oninput:m=>n.setUi({typedRepo:m.target.value},!1),onkeydown:m=>{m.key==="Enter"&&n.choose(m.target.value)}});f.value=t.typedRepo,c=[d("p",{class:"lede"},r.kind==="unavailable"?"This connection could not list your repositories here, so type the one to import.":"This connection sees no repositories. Type the one to import."),d("div",{class:"typed"},d("label",{class:"search"},d("span",{class:"sr"},"Repository (owner/name)"),f)),r.kind==="unavailable"?d("details",{class:"b-details",style:"margin:0"},d("summary",null,"Details"),d("code",null,r.message)):null]}let u=i||"repository";return d("div",{class:"center-wrap"},d("div",{class:"onboard"},d("h2",null,t.table===void 0?"Which repository?":`Which repository should ${t.table} sync with?`),c,e.error?d("p",{class:"field-error",role:"alert"},e.error):null,d("div",{class:"effects"},d("h3",null,"What this board will do on GitHub"),d("ul",null,d("li",null,"Moving a card to ",d("b",null,"Done")," closes the issue. Moving it back reopens it."),d("li",null,"Moving a card to ",d("b",null,"Doing")," adds the ",d("code",null,"atomic:doing")," label; leaving Doing removes it. Other labels are never touched."),d("li",null,"Moving a card to ",d("b",null,"Blocked")," adds the ",d("code",null,"atomic:blocked")," label the same way."),d("li",null,"Title, description and comment edits are sent to GitHub after you review and send them. A card made in this app becomes a new issue the same way; a row added to the table elsewhere stays here until you choose Publish to GitHub on it."),d("li",null,t.table===void 0?"Nothing is ever deleted on GitHub. One app syncs one repository.":"Nothing is ever deleted, on GitHub or in this table. This table syncs with one repository, and never switches."))),d("div",{class:"actions-row"},a?null:mr(t,n),L(a?`Setting up ${e.settingUp}\u2026`:`Import ${u}`,()=>i&&n.choose(i),{kind:"primary",disabled:a||!i,"data-key":"import"}))))}function gr(e){return e?e==="conflict"||e==="unconfirmed"?d("span",{class:`sync-mark conflict ${e}`,title:Ce[e]},N("warn",14),d("span",{class:"sr"},Ce[e])):d("span",{class:`sync-mark ${e}`,title:Ce[e]},d("span",{class:"sr"},Ce[e])):null}function hr(e,t){if(!e.labels.length)return null;let n=e.labels.slice(0,t),r=e.labels.length-n.length;return d("span",{class:"chips"},n.map(s=>Gt(s.name,s.color)),r>0?d("span",{class:"chip more",title:e.labels.slice(t).map(s=>s.name).join(", ")},`+${r}`):null)}function br(e){let t=e.comments.length;return t?d("span",{class:"cmt",title:`${t} ${t===1?"comment":"comments"}`},N("comment",13),d("span",{"aria-hidden":"true"},String(t)),d("span",{class:"sr"},`${t} ${t===1?"comment":"comments"}`)):null}function yr(e,t,n){return Ut(`Move ${ne(e)} to`,rt.map(r=>({label:r,glyph:ge[r],checked:e.status===r&&!e.statusAsIs,disabled:!n||e.status===r&&!e.statusAsIs,run:()=>t.move(e.subject,r,"menu")})),t)}function Us(e,t,n,r,s){let o=pe(t)&&!t.busy,i=`move:${e.subject}`,a=n.menu===i,c=n.panel?.kind==="issue"&&n.panel.subject===e.subject;return d("li",{class:`card${c?" is-selected":""}${n.flash.has(e.subject)?" flash":""}`,"data-subject":e.subject,draggable:o?"true":"false",ondragstart:f=>{let m=f;m.dataTransfer?.setData("text/plain",e.subject),m.dataTransfer&&(m.dataTransfer.effectAllowed="move"),m.currentTarget.classList.add("dragging")},ondragend:f=>f.currentTarget.classList.remove("dragging")},d("button",{type:"button",class:"card-hit","data-key":`card:${e.subject}`,"data-issue":e.subject,onclick:()=>s.open({kind:"issue",subject:e.subject},`card:${e.subject}`),onfocus:()=>s.setUi({focus:e.subject},!1)},d("span",{class:"card-top"},d("span",{class:"ref"},ne(e)),d("span",{class:"sr"},`Status: ${e.status}.`),e.statusAsIs?d("span",{class:"muted small",title:pr(e)},"\u2260"):null,gr(r.get(e.subject))),d("span",{class:"card-title"},e.title),e.labels.length||e.comments.length?d("span",{class:"card-foot"},hr(e,3),br(e)):null),Ee("more",`Move ${ne(e)} to\u2026`,()=>s.setUi({menu:a?void 0:i}),{sm:!0,class:"icon-btn sm card-menu","aria-haspopup":"menu","aria-expanded":String(a),"data-key":`cardmenu:${e.subject}`}),a?yr(e,s,o):null)}function dr(){return d("li",{class:"card skel","aria-hidden":"true"},d("span",{class:"sk",style:"width:22%"}),d("span",{class:"sk",style:"width:86%"}),d("span",{class:"sk",style:"width:54%"}))}function zs(e,t,n){let r=e.last?.result.rows??[],s=e.busy==="syncing"&&(!e.last||!!e.importing),o={search:t.search,label:t.label},i=It(r,o,t.allDone),a=ot(e),c=pe(e)&&!e.busy;return d("div",{class:"board","data-scroll":"board"},i.map(u=>d("section",{class:"col","aria-labelledby":`col-${u.status}`,"data-status":u.status,ondragover:m=>{c&&(m.preventDefault(),m.currentTarget.classList.add("drop"))},ondragleave:m=>m.currentTarget.classList.remove("drop"),ondrop:m=>{let g=m;g.preventDefault(),g.currentTarget.classList.remove("drop");let b=g.dataTransfer?.getData("text/plain");b&&c&&n.move(b,u.status,"drag")}},d("header",{class:"col-head"},fe(ge[u.status]),d("h2",{id:`col-${u.status}`},u.status),d("span",{class:"count"},s&&!r.length?"\u2026":String(u.total)),Ee("plus",`New issue in ${u.status}`,()=>{n.setDrafts({newStatus:u.status},!1),n.open({kind:"new"},`colnew:${u.status}`)},{sm:!0,"data-key":`colnew:${u.status}`})),d("ul",{class:"cards",role:"list","aria-labelledby":`col-${u.status}`},u.rows.map(m=>Us(m,e,t,a,n)),s?[dr(),dr()]:null),u.hidden?d("button",{type:"button",class:"show-more","data-key":"show-more",onclick:()=>n.setUi({allDone:!0})},`Show ${u.hidden} more`):u.status==="Done"&&t.allDone&&u.total>20?d("button",{type:"button",class:"show-more","data-key":"show-more",onclick:()=>n.setUi({allDone:!1})},"Show fewer"):null)))}var Fs=["Doing","Blocked","Todo","Done"];function Bs(e,t,n){let r=e.last?.result.rows??[],s={search:t.search,label:t.label},o=It(r,s,t.allDone),i=ot(e),a=pe(e)&&!e.busy;return d("div",{class:"list"},Fs.map(c=>{let u=o.find(g=>g.status===c),f=t.groups[c]??c!=="Done",m=`group-${c}`;return d("section",{class:"group"},d("button",{type:"button",class:"group-head",id:m,"aria-expanded":String(f),"data-key":m,onclick:()=>n.setUi({groups:{...t.groups,[c]:!f}})},N("chevron",12),fe(ge[c]),d("span",null,c),d("span",{class:"count"},String(u.total))),f?d("ul",{class:"rows",role:"list","aria-labelledby":m},u.rows.map(g=>{let b=`status:${g.subject}`,w=t.menu===b,E=t.panel?.kind==="issue"&&t.panel.subject===g.subject;return d("li",{class:`row${E?" is-selected":""}`,"data-subject":g.subject},d("button",{type:"button",class:"glyph-btn","aria-label":`Status: ${g.status}. Change status of ${ne(g)}`,"aria-haspopup":"menu","aria-expanded":String(w),"data-key":`glyph:${g.subject}`,onclick:()=>n.setUi({menu:w?void 0:b})},fe(ge[g.status],16)),d("button",{type:"button",class:"row-hit","data-key":`card:${g.subject}`,"data-issue":g.subject,onclick:()=>n.open({kind:"issue",subject:g.subject},`card:${g.subject}`),onfocus:()=>n.setUi({focus:g.subject},!1)},d("span",{class:"row-line"},d("span",{class:"ref"},ne(g)),gr(i.get(g.subject)),d("span",{class:"when"},Bn(g.updatedAt,t.now))),d("span",{class:"row-title"},g.title),g.labels.length||g.comments.length?d("span",{class:"row-foot"},hr(g,2),br(g)):null),w?yr(g,n,a):null)})):null,f&&u.hidden?d("button",{type:"button",class:"show-more",style:"margin:4px 12px","data-key":"show-more",onclick:()=>n.setUi({allDone:!0})},`Show ${u.hidden} more`):null)}))}function Vs(e,t,n,r){let s=e.last?.result.rows??[],o=Wn(s),i=t.size==="s",{field:a,input:c}=_t("Search issues",t.search,f=>r.setUi({search:f}));c.dataset.key="search",c.id="issue-search";let u=t.menu==="label";return d("div",{class:"toolbar"},Dt("Layout",[{value:"board",label:i?[]:"Board",iconName:"board",title:"Board"},{value:"list",label:i?[]:"List",iconName:"list",title:"List"}],n,f=>r.setUi({layout:f})),a,i?null:d("span",{class:"tb-menu label-menu"},d("button",{type:"button",class:"btn ghost","aria-haspopup":"menu","aria-expanded":String(u),"data-key":"label-filter",disabled:!o.length&&!t.label,onclick:()=>r.setUi({menu:u?void 0:"label"})},t.label?`Label: ${t.label}`:"Label",N("chevron",10)),u?Ut("Filter by label",[{label:"Any label",checked:!t.label,run:()=>r.setUi({label:void 0})},...o.map(f=>({label:f,checked:t.label===f,run:()=>r.setUi({label:f})}))],r):null),i?null:d("span",{class:"tb-count"},e.busy==="syncing"&&!e.last?"Importing\u2026":e.busy&&e.importing?qs(e.importing):Yn(s,{search:t.search,label:t.label})))}function qs(e){let t=(n,r)=>`${n} ${r}${n===1?"":"s"}`;return`Importing\u2026 ${t(e.issues,"issue")}${e.comments?`, ${t(e.comments,"comment")}`:""} so far`}function Js(e,t,n){let r=e.last?.result.rows??[];if(!e.last)return null;let s={search:t.search,label:t.label};if(!r.length)return Me("inbox",`No issues in ${e.repository} yet.`,"Create one here and it goes to GitHub once you review and send it.",L("New issue",()=>n.open({kind:"new"},"empty-new"),{kind:"primary",iconName:"plus","data-key":"empty-new"}),!0);if(Ot(s)&&!r.some(o=>it(o,s))){let o=[t.search.trim()?`\u201C${t.search.trim()}\u201D`:"",t.label?`label ${t.label}`:""].filter(Boolean).join(" with ");return Me("filter",`No issues match ${o}.`,`${r.length} ${r.length===1?"issue is":"issues are"} hidden by these filters.`,L("Clear filters",()=>n.setUi({search:"",label:void 0}),{"data-key":"clear-filters"}),!0)}return null}function Ks(e){return(e??"?").replace(/[^a-z0-9]/gi,"").slice(0,2)||"?"}function ct(e,t,n){let r=()=>n.open(void 0);return d("div",{class:"d-bar"},t==="sheet"?Ee("back","Back to issues",r,{"data-key":"detail-close"}):null,d("span",{class:"ref"},e),d("span",{class:"spacer"}),t==="sheet"?null:Ee("close","Close",r,{"data-key":"detail-close"}))}function wr(e,t,n){return Dt("Status",rt.map(r=>({value:r,label:[fe(ge[r]),r]})),e,t,{mode:"radio",disabled:n,cls:"status-seg"})}function Ws(e,t,n,r,s){let o=n.drafts,i=pe(t),a=Kn(t),c=ot(t),u=!1,f=d("textarea",{class:"d-title",rows:1,"aria-label":"Title","data-key":"detail-title",oninput:v=>s.setDrafts({title:v.target.value},!1),onkeydown:v=>{let k=v,$=k.target;if(k.key==="Enter"){k.preventDefault();let R=$.value.trim();u=!0,R&&R!==e.title?s.saveTitle(e.subject,R):s.setDrafts({title:void 0}),$.blur()}else k.key==="Escape"&&$.value!==e.title&&(k.preventDefault(),k.stopPropagation(),$.value=e.title,s.setDrafts({title:void 0}))},onblur:v=>{let k=v.target.value.trim();!u&&k&&k!==e.title&&s.saveTitle(e.subject,k),u=!1}});f.value=o.title??e.title;let m=d("div",{class:"tabs",role:"tablist","aria-label":"Description"},["write","preview"].map(v=>d("button",{type:"button",role:"tab","aria-selected":String(o.tab===v),"data-key":`tab:${v}`,onclick:()=>s.setDrafts({tab:v,...v==="write"&&o.body===void 0?{body:e.body}:{}})},v==="write"?"Write":"Preview"))),g;if(o.tab==="write"){let v=d("textarea",{class:"editor","aria-label":"Description (Markdown)","data-key":"detail-body",oninput:k=>s.setDrafts({body:k.target.value},!1)});v.value=o.body??e.body,g=[v,d("div",{class:"row-actions"},L("Cancel",()=>s.setDrafts({tab:"preview",body:void 0}),{sm:!0}),L("Save description",()=>s.saveBody(e.subject,v.value),{sm:!0,kind:"primary","data-key":"save-body"}))]}else{let v=d("div",{class:"md"});e.body.trim()?v.append(at(e.body)):v.append(d("p",{class:"md-empty"},"No description.")),g=v}let b=d("ul",{class:"comments"},e.comments.map(v=>{let k=a.has(v.subject)||!v.author;return d("li",{class:k?"pending":""},d("span",{class:`avatar${v.author?"":" me"}`,"aria-hidden":"true"},v.author?Ks(v.author):"You".slice(0,2)),d("div",null,d("p",{class:"c-meta"},v.author?[d("b",null,v.author)," on GitHub",v.createdAt?` \xB7 ${st(v.createdAt,n.now)}`:""]:[d("b",null,"You")," \xB7 ",d("span",{class:"pend"},t.busy==="sending"?"Sending":"Waiting to send")]),d("div",{class:"md"},at(v.body))))})),w=d("textarea",{placeholder:"Add a comment\u2026 (Markdown)","aria-label":"Add a comment","data-key":"composer",rows:3,oninput:v=>{let k=v.target.value;s.setDrafts({comment:k},!1),E.disabled=!k.trim()},onkeydown:v=>{let k=v;k.key==="Enter"&&(k.metaKey||k.ctrlKey)&&(k.preventDefault(),s.comment(e.subject,k.target.value))}});w.value=o.comment;let E=L("Comment",()=>s.comment(e.subject,w.value),{kind:"primary",sm:!0,disabled:!o.comment.trim(),"data-key":"comment"}),T=e.number!==void 0,A=c.get(e.subject),_=d("div",{class:"d-body"},f,d("div",{class:"d-props"},d("span",{class:"d-k"},"Status"),wr(e.status,v=>v!==e.status&&s.move(e.subject,v,"menu"),!i||!!t.busy),d("span",{class:"d-k"},"Labels"),d("span",{class:"chips"},e.labels.map(v=>Gt(v.name,v.color)),d("span",{class:"muted small"},e.labels.length?"Labels are edited on GitHub":"None \xB7 edited on GitHub")),e.assignees.length?d("span",{class:"d-k"},"Assignees"):null,e.assignees.length?d("span",{class:"small"},e.assignees.join(", ")):null),e.statusAsIs?d("p",{class:"ro-note"},N("info",14),`${pr(e)}.`):null,e.localOnly?d("div",{class:"ro-note"},N("info",14),d("span",null,`Only in this table. It becomes an issue in ${t.repository} once you publish it and then review and send it.`),L("Publish to GitHub",()=>s.publish(e.subject),{sm:!0,kind:"primary",disabled:!!t.busy,"data-key":"publish"})):null,A?d("p",{class:"ro-note"},N(A==="conflict"?"warn":"info",14),A==="conflict"?"Changed here and on GitHub; review the conflict to resume sync.":"Changes to this issue are waiting to send. Review and send them from the bar above."):null,d("h3",{class:"d-h"},"Description"),m,g,d("h3",{class:"d-h"},"Comments",d("span",{class:"count"},String(e.comments.length))),e.comments.length?b:d("p",{class:"muted small",style:"margin:0"},"No comments yet."),d("div",{class:"composer"},w,d("div",{class:"cmp-row"},d("span",{class:"muted small"},T?"Sent to GitHub after you review it":"Sent once the issue is on GitHub"),E))),H=d("div",{class:"d-foot"},d("span",{class:"mono"},T?`${t.repository}#${e.number}`:e.localOnly?"Only in this table":`${t.repository} \xB7 not on GitHub yet`),t.last?.at?` \xB7 synced ${st(t.last.at,n.now)}`:"",e.url?[" \xB7 ",d("a",{href:e.url,target:"_blank",rel:"noopener noreferrer"},"Open on GitHub",N("external",12))]:null);return[ct(T?`#${e.number}`:"New issue",r,s),_,H]}function Ys(e,t,n,r){let s=t.drafts,o=d("textarea",{class:"d-title",rows:1,placeholder:"Title","aria-label":"Title","data-key":"new-title",oninput:a=>r.setDrafts({newTitle:a.target.value}),onkeydown:a=>{let c=a;c.key==="Enter"&&(c.preventDefault(),s.newTitle.trim()&&r.create())}});o.value=s.newTitle;let i=d("textarea",{class:"editor",placeholder:"Description (Markdown)","aria-label":"Description (Markdown)","data-key":"new-body",oninput:a=>r.setDrafts({newBody:a.target.value},!1)});return i.value=s.newBody,[ct("New issue",n,r),d("div",{class:"d-body"},o,d("div",{class:"d-props"},d("span",{class:"d-k"},"Status"),wr(s.newStatus,a=>r.setDrafts({newStatus:a}),!1)),d("h3",{class:"d-h"},"Description"),i,d("p",{class:"ro-note"},N("info",14),`Created in this table first. It becomes an issue in ${e.repository} once you review and send it.`)),d("div",{class:"d-actions"},L("Cancel",()=>r.open(void 0)),L("Create issue",()=>r.create(),{kind:"primary",disabled:!s.newTitle.trim()||!!e.busy,"data-key":"create"}))]}function Xs(e,t,n){let r=e.last?.result.held??[],s=r.length;return[ct("Waiting to send",t,n),d("section",{class:"d-body","aria-label":"Changes to send to GitHub"},d("h2",{class:"d-title ro"},s?`Send ${s} ${s===1?"change":"changes"} to GitHub?`:"Nothing is waiting"),d("p",{class:"muted small",style:"margin:0"},"Nothing reaches GitHub until you send it. A change edited after this review is held again."),s?d("ol",{class:"review"},r.map(o=>d("li",null,Fn(o)))):null),d("div",{class:"d-actions"},L("Not now",()=>n.open(void 0)),L(`Send ${s} ${s===1?"change":"changes"} to GitHub`,()=>n.send(),{kind:"primary",disabled:!s||!!e.busy,"data-key":"send"}))]}var ur={title:"Title",body:"Description",status:"Status"};function Zs(e,t,n){if(e==="status"&&typeof t=="string"&&t in ge)return d("span",{class:"cf-val"},fe(ge[t]),t);let r=typeof t=="string"?t:JSON.stringify(t??""),s=typeof n=="string"?n:"",o=0;for(;ou.subject===s?.local),i=t.fields??[],a=i.filter(u=>!t.choices[u.field]),c;return s?t.error?c=d("p",{class:"field-error"},t.error):t.fields?c=[d("p",{class:"muted small",style:"margin:0"},"Pick which version to keep for each field. Nothing is sent or saved until you apply."),i.map(u=>d("fieldset",{class:"cf"},d("legend",null,ur[u.field]??u.field),["local","remote"].map(f=>d("label",{class:"cf-opt"},d("input",{type:"radio",name:`cf-${u.field}`,value:f,checked:t.choices[u.field]===f,"data-key":`cf:${u.field}:${f}`,onchange:()=>r.open({...t,choices:{...t.choices,[u.field]:f}})}),d("span",{class:"cf-src"},f==="local"?"Here":"On GitHub"),Zs(u.field,u[f],f==="local"?u.remote:u.local))))),d("p",{class:"muted small",style:"margin:0"},"Other fields and comments did not conflict and will sync normally. Keeping \u201CHere\u201D for a field becomes a change you review before it is sent.")]:c=d("p",{class:"muted"},"Reading both versions\u2026"):c=d("p",null,"This conflict is settled."),[ct("Conflict",n,r),d("div",{class:"d-body"},d("h2",{class:"d-title ro"},o?`${ne(o)} ${o.title}`:"Changed on both sides"),c),d("div",{class:"d-actions"},L("Apply and resume sync",()=>r.resolve(),{kind:"primary",disabled:!s||!t.fields||a.length>0||!!e.busy,"data-key":"apply"}),a.length&&t.fields?d("p",{class:"hint muted small"},`Choose ${a.map(u=>ur[u.field]??u.field).join(" and ")} first`):null)]}function eo(e,t,n,r){let s=t.panel;if(!s)return null;let o,i="Issue";if(s.kind==="issue"){let a=e.last?.result.rows.find(c=>c.subject===s.subject);if(!a)return null;o=Ws(a,e,t,n,r),i=`${ne(a)} ${a.title}`}else s.kind==="new"?(o=Ys(e,t,n,r),i="New issue"):s.kind==="review"?(o=Xs(e,n,r),i="Changes to send"):(o=Qs(e,s,n,r),i="Conflict review");return d("aside",{class:`detail ${n}`,"aria-label":i,...n==="docked"?{}:{role:"dialog","aria-modal":"true"},"data-panel":s.kind},o)}function to(e){return d("div",{class:"overlay",onclick:t=>{t.target===t.currentTarget&&e.setUi({help:!1})}},d("div",{class:"dialog",role:"dialog","aria-modal":"true","aria-labelledby":"help-title"},d("h2",{id:"help-title"},"Keyboard shortcuts"),d("dl",{class:"keys"},Zn.map(([t,n])=>[d("dt",null,d("kbd",null,t)),d("dd",null,n)])),d("div",{class:"actions-row"},L("Close",()=>e.setUi({help:!1}),{"data-key":"help-close"}))))}function vr(e,t,n,r,s){let o=Is(e,t,s);if(e.kind==="no-proxy")return[o,Ls()];if(e.kind==="other-table")return[o,Ns(e,t,s)];if(e.kind==="loading")return[o,d("p",{class:"lede",style:"padding:24px 16px"},"Loading\u2026")];if(e.kind==="not-connected"||e.kind==="connecting")return[o,Ds(e,t,s)];if(e.kind==="choose-repository")return[o,Lt([d("span",{class:"acct"},"GitHub"),"connected"]),Gs(e,t,s)];let i=d("div",{class:"split-main"},Hs(e,t,s),Vs(e,t,n,s),Js(e,t,s)??(n==="board"?zs(e,t,s):Bs(e,t,s))),a=eo(e,t,r,s),c=a&&r==="docked"?d("div",{class:"split app-body"},i,a):d("div",{class:"app-body"},i),u=[o,Ms(e,t,s),c];return a&&r!=="docked"&&u.push(d("div",{class:"scrim","aria-hidden":"true",onclick:()=>s.open(void 0)}),a),t.help&&u.push(to(s)),u}var xr=240,no=3600,zt=()=>({tab:"preview",comment:"",newTitle:"",newBody:"",newStatus:"Todo"});async function zi({root:e,store:t}){cr(e,er),e.classList.add("pl-app");let n=e.ownerDocument,r=n.defaultView,s=or(),o={size:"xl",search:"",allDone:!1,groups:{},help:!1,drafts:zt(),repoFilter:"",typedRepo:"",alert:!1,canDisconnect:typeof t.proxy?.disconnect=="function",flash:new Set,now:Date.now()},i,a=!1,c,u=xr,f,m,g,b=!1,w=()=>{o.now=Date.now(),f?o.retryIn=Math.max(0,(f-o.now)/1e3):delete o.retryIn;let l=v.state(),p=n.activeElement,h=p&&e.contains(p)?p.dataset.key:void 0,y=p,x=h&&typeof y?.selectionStart=="number"?[y.selectionStart,y.selectionEnd??y.selectionStart]:void 0,S=[...e.querySelectorAll(".board, .detail, .repos")].map(Te=>[Te.className.split(" ")[0],Te.scrollLeft,Te.scrollTop]),M=Ct(o.size,o.layout),D=Xn(o.size);e.replaceChildren(...vr(l,o,M,D,C),s.region);for(let[Te,kr,Sr]of S){let lt=e.querySelector(`.${Te}`);lt&&(lt.scrollLeft=kr,lt.scrollTop=Sr)}if(!h)return;let Le=E(h);if(Le&&(Le.focus({preventScroll:!0}),x&&"setSelectionRange"in Le))try{Le.setSelectionRange(x[0],x[1])}catch{}};function E(l){let p=l.replace(/["\\]/g,"\\$&");return e.querySelector(`[data-key="${p}"]`)}let T=l=>{l&&E(l)?.focus()},A=l=>{if(!(l.kind==="ready"&&l.problem?.kind==="failed")){c&&clearTimeout(c),c=void 0,f=void 0,l.kind==="ready"&&!l.problem&&!l.busy&&(u=xr);return}c||(f=Date.now()+u*1e3,c=setTimeout(()=>{c=void 0,f=void 0,u=Math.min(no,u*2),v.sync()},u*1e3))},_=l=>{if(l.kind!=="ready"||l.busy||!l.last)return;let p=new Map(l.last.result.rows.map(h=>[h.subject,[h.title,h.status,h.body,h.comments.length,h.updatedAt].join(` +`)]));if(o.flash=new Set,g){let h=new Set(l.touched??[]);for(let[y,x]of p){let S=g.get(y);S!==void 0&&S!==x&&!h.has(y)&&o.flash.add(y)}}g=p},v=Un(t,l=>{let p=v.foreign();if(p===void 0?delete o.table:o.table=p,l.kind==="ready"){if(!b){b=!0;let h=v.prefs();h.layout&&(o.layout=h.layout),h.search&&(o.search=h.search),h.label&&(o.label=h.label)}(l.problem?.kind!=="paused"||!l.problem.missing)&&(o.confirmRemove=!1),o.alert=a&&!!l.problem,o.panel?.kind==="conflict"&&l.problem?.kind!=="conflict"&&!l.busy&&(o.panel=void 0)}_(l),A(l),w()}),k=()=>{m&&clearTimeout(m),m=setTimeout(()=>{v.state().kind==="ready"&&v.savePrefs({...o.layout?{layout:o.layout}:{},...o.search?{search:o.search}:{},...o.label?{label:o.label}:{}})},800)},$=async l=>{if(/^https?:/i.test(l)){if(t.openExternal){await t.openExternal(l).catch(()=>{});return}try{r.open(l,"_blank","noopener")}catch{}}};e.addEventListener("click",l=>{let p=l.target.closest?.("a[href]");if(!p||!t.openExternal)return;let h=p.href;/^https?:/i.test(h)&&(l.preventDefault(),$(h))});let R=()=>{let l=v.state();return l.kind==="ready"?l:void 0},I=l=>R()?.last?.result.rows.find(p=>p.subject===l),C={connect:()=>{v.connect()},listRepositories:()=>{v.listRepositories()},choose:l=>{v.choose(l)},sync:()=>{v.sync()},send:()=>{o.panel?.kind==="review"&&(o.panel=void 0),v.send().then(()=>T(i??"sync-now"))},move(l,p,h){let y=R(),x=I(l);!y||!x||x.status===p&&!x.statusAsIs||!pe(y)||(s.say(`Moved ${ne(x)} to ${p}`),h==="key"&&(o.focus=l),v.edit(l,{status:p}))},open(l,p){l&&p&&(i=p);let h=l?.kind!==o.panel?.kind||l?.kind==="issue"&&o.panel?.kind==="issue"&&l.subject!==o.panel.subject;if(h&&(o.drafts={...zt(),newStatus:o.drafts.newStatus,...l?.kind==="new"?{newTitle:o.drafts.newTitle,newBody:o.drafts.newBody}:{}}),o.panel=l,o.menu=void 0,w(),!l){T(i),i=void 0,o.drafts.newStatus="Todo";return}l.kind==="conflict"&&!l.fields&&!l.error&&v.conflict().then(y=>{o.panel?.kind==="conflict"&&(o.panel=y?{...o.panel,fields:y}:{...o.panel,error:"This conflict is already settled."},w())}).catch(y=>{o.panel?.kind==="conflict"&&(o.panel={...o.panel,error:y instanceof Error?y.message:String(y)},w())}),!(!h||o.size==="xl")&&T(l.kind==="new"?"new-title":"detail-close")},saveTitle(l,p){o.drafts.title=void 0,v.edit(l,{title:p})},saveBody(l,p){o.drafts={...o.drafts,body:void 0,tab:"preview"},v.edit(l,{body:p})},comment(l,p){p.trim()&&(o.drafts.comment="",s.say("Comment added; waiting to send"),v.comment(l,p))},create(){let l=o.drafts;if(!l.newTitle.trim())return;let p={title:l.newTitle.trim(),body:l.newBody,status:l.newStatus};o.drafts=zt(),v.create(p).then(({subject:h})=>{h&&o.panel?.kind==="new"&&(o.panel={kind:"issue",subject:h},i=`card:${h}`,w())})},resolve(){let l=o.panel;l?.kind==="conflict"&&v.resolve(l.choices)},setUi(l,p=!0){let h="layout"in l||"search"in l||"label"in l;Object.assign(o,l),"label"in l&&l.label===void 0&&delete o.label,h&&k(),p&&w()},setDrafts(l,p=!0){o.drafts={...o.drafts,...l},p&&w()},openGitHub(l){$(l)},focusSearch(){T("search")},disconnect(){v.disconnect()},keepHereOnly(){v.keepHereOnly()},removeFromBoard(){o.confirmRemove=!1,v.removeFromBoard()},landed(l,p){v.landed(l,p)},sendAgain(l){v.sendAgain(l)},publish(l){s.say("Publishing to GitHub after your review"),v.publish(l)},syncTable(){s.say("Asking you to allow this app to edit this table"),v.syncTable()},notNow(){v.notNow()}},K,re=()=>[...e.querySelectorAll("[data-issue]")].filter(l=>!l.closest(".detail")),he=()=>n.activeElement?.closest("[data-subject]")?.dataset.subject??(o.panel?.kind==="issue"?o.panel.subject:void 0),He=()=>{let l=o.menu??"";o.menu=void 0,w(),T(l.startsWith("move:")?`cardmenu:${l.slice(5)}`:l.startsWith("status:")?`glyph:${l.slice(7)}`:l==="label"?"label-filter":void 0)},Ne=l=>{let p=e.querySelector(".detail"),h=p?[...p.querySelectorAll('button:not(:disabled), textarea, input:not(:disabled), a[href], [tabindex="0"]')]:[];if(!h.length)return;let y=h[0],x=h[h.length-1];!p.contains(n.activeElement)||l.shiftKey&&n.activeElement===y?(l.preventDefault(),(l.shiftKey?x:y).focus()):!l.shiftKey&&n.activeElement===x&&(l.preventDefault(),y.focus())},Ft=l=>{let p=l.key;if(K&&p.toLowerCase()==="s")return clearTimeout(K),K=void 0,C.sync(),!0;if(p==="g"||p==="G")return K=setTimeout(()=>K=void 0,1e3),!1;if(p==="/")C.focusSearch();else if(p==="?")C.setUi({help:!0}),T("help-close");else if(p==="b"||p==="B"){let h=Ct(o.size,o.layout);C.setUi({layout:h==="board"?"list":"board"})}else if(p==="n"||p==="N")C.open({kind:"new"},"new-issue");else if(p==="c"||p==="C"){if(o.panel?.kind!=="issue")return!1;T("composer")}else if(["j","k","J","K","ArrowDown","ArrowUp"].includes(p)){if(o.panel&&o.size!=="xl")return!1;let h=re();if(!h.length)return!1;let y=h.indexOf(n.activeElement),x=p==="j"||p==="J"||p==="ArrowDown",S=y<0?x?0:h.length-1:Math.min(h.length-1,Math.max(0,y+(x?1:-1)));h[S].focus()}else if(p in Mt){let h=he();if(!h)return!1;C.move(h,Mt[p],"key")}else return!1;return!0};n.addEventListener("keydown",l=>{if(!(l.defaultPrevented||l.metaKey||l.ctrlKey||l.altKey)){if(l.key==="Escape"){if(o.menu)He();else if(o.help)C.setUi({help:!1});else if(o.panel)C.open(void 0);else return;l.preventDefault();return}if(l.key==="Tab"&&o.panel&&o.size!=="xl"){Ne(l);return}Ht(l.target)||o.help||!R()||o.menu&&(l.key==="ArrowDown"||l.key==="ArrowUp")||Ft(l)&&l.preventDefault()}}),n.addEventListener("click",l=>{!o.menu||l.target.closest?.(".menu, .popover, [aria-haspopup]")||(o.menu=void 0,w())}),lr(e,l=>{o.size=l,w()},{...t.getTheme?{getTheme:()=>t.getTheme()}:{},...t.onThemeChange?{onThemeChange:l=>t.onThemeChange(l)}:{}}),setInterval(()=>{Ht(n.activeElement)||w()},3e4),w();try{await v.start()}catch(l){let p=l instanceof Error?l.message:String(l),h=n.createElement("p");h.className="field-error",h.style.padding="16px",h.textContent=`Could not load: ${p}`,e.append(h)}finally{a=!0}}export{zi as view}; diff --git a/integrations/README.md b/integrations/README.md index 448388ef3..640723cb4 100644 --- a/integrations/README.md +++ b/integrations/README.md @@ -343,11 +343,13 @@ a drive app whose rows are a shared class (`event-v1`, `issue-v1`, `time-entry-v1`, ...) is offered by the host's "+ Add view" on any table of that class. On such a table it can offer "Sync this table to ". Calendar 0.3.0 does this for Google Calendar -([`calendar/README.md`](calendar/README.md#syncing-a-table-the-app-didnt-make)); -issue-tracker and timesheets can follow the same pattern. What the pinned -host (`a12b74a`) allows, read from `server/src/plugins/app_row_grant.rs`, +([`calendar/README.md`](calendar/README.md#syncing-a-table-the-app-didnt-make)), +and issue-tracker 0.3.0 for GitHub +([`issue-tracker/README.md`](issue-tracker/README.md#syncing-a-table-the-app-didnt-make)); +timesheets can follow the same pattern. What the pinned host (`a12b74a`) +allows, read from `server/src/plugins/app_row_grant.rs`, `server/src/handlers/app_write.rs` and the page's `AppPage/hostStore.ts`, -and checked by the calendar e2e: +and checked by the calendar and issue-tracker e2es: | Write | Allowed | | ------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | @@ -391,6 +393,12 @@ The pattern, as calendar implements it: is paused and offer to allow editing again; don't fail on the first write. A provider deletion can't delete the row: offer "keep as local" and tell the person to delete the row in the table. +7. **List everything the app writes on rows.** The grant checks every + property a row write sends, not only the provider's. Issue-tracker's + Bridge sets Atomic's `localId` on each row it imports (so a create a + reload interrupted is found again, not made twice), so issue-tracker + 0.3.0 lists `localId` in `row-extras` too. A property under another app, + or on the never-list (`parent`, `isA`, rights, `classtype`), can't be one. What this does not give, at the pin: edits made while the app is closed are found only on its next open (the app can't read `/changes` or receive diff --git a/integrations/catalog.json b/integrations/catalog.json index edf5a5c96..f7d3d83b3 100644 --- a/integrations/catalog.json +++ b/integrations/catalog.json @@ -365,15 +365,15 @@ "https://atomicdata.dev/properties/name": "GitHub issues", "https://atomicdata.dev/properties/emoji": "🐙", "https://atomicdata.dev/properties/description": "A drive app that keeps one GitHub repository's issues on a board, two-way, with every change to GitHub reviewed before it is sent.", - "https://atomicdata.dev/integrations/properties/capabilities": "Imports one repository's issues and comments into the app's table, shown as a board (Todo, Doing, Blocked, Done) or a list, with search and a label filter. The rows are of the shared Issue class (issue-v1: title, task/v1 status and body), so other views of that class can read them. Title, description (Markdown), status and comments sync both ways; Doing and Blocked are the atomic:doing and atomic:blocked labels on GitHub. A change bound for GitHub waits in Review and send until you approve exactly that change. A field changed on both sides pauses sync until you pick a side. An issue gone from GitHub can be kept here only or removed from the board.", + "https://atomicdata.dev/integrations/properties/capabilities": "Imports one repository's issues and comments into the app's table, shown as a board (Todo, Doing, Blocked, Done) or a list, with search and a label filter. The rows are of the shared Issue class (issue-v1: title, task/v1 status and body), so other views of that class can read them. Title, description (Markdown), status and comments sync both ways; Doing and Blocked are the atomic:doing and atomic:blocked labels on GitHub. A change bound for GitHub waits in Review and send until you approve exactly that change. A field changed on both sides pauses sync until you pick a side. An issue gone from GitHub can be kept here only or removed from the board. Added as a view of another Issue table, it offers Sync this table to GitHub: once you allow it to edit that table's rows (the host's Allow editing, which then also covers the GitHub issue number, source, sync baseline and import key the app keeps on each row), it imports one repository into that table and syncs it the same way; the repository choice and sync state are kept under the app, and the table's own rows stay local until you publish them.", "https://atomicdata.dev/integrations/properties/events": "Install from Drive apps, connect GitHub through the host's consent bar and choose a repository. It syncs when opened, on Sync now and after each edit made in the app; nothing runs while the app is closed.", - "https://atomicdata.dev/integrations/properties/limitation": "One repository per app, synced with the app's own table only: offered on another Issue table, it shows a notice and syncs nothing. A row added to the table outside the app stays local until you choose Publish to GitHub on it. A status other than exactly one of Todo, Doing, Blocked and Done is shown as it is and not synced. Labels and assignees are shown read-only; milestones and pull requests are not synced, and deletions are never sent to GitHub. One syncing view per app is assumed: two tabs or devices are not guarded. A new issue or comment whose send got no answer is never sent twice: you link it to the issue it became on GitHub, or send it again once GitHub shows no match. Waits for the stable ontology domain. Mock-tested only: not yet verified against live GitHub or the real integration proxy.", + "https://atomicdata.dev/integrations/properties/limitation": "One repository per table: the app's own table, and each other Issue table it was asked to sync. On a table that isn't the app's own, rows are never deleted (Allow editing doesn't cover it, so Remove from board isn't offered there), the table itself is never written, and syncing pauses when the grant is taken back. A row added to the table outside the app stays local until you choose Publish to GitHub on it. A status other than exactly one of Todo, Doing, Blocked and Done is shown as it is and not synced. Labels and assignees are shown read-only; milestones and pull requests are not synced, and deletions are never sent to GitHub. One syncing view per app is assumed: two tabs or devices are not guarded. A new issue or comment whose send got no answer is never sent twice: you link it to the issue it became on GitHub, or send it again once GitHub shows no match. Waits for the stable ontology domain. Mock-tested only: not yet verified against live GitHub or the real integration proxy.", "https://atomicdata.dev/integrations/properties/keywords": "github issues board kanban tracker two-way review drive app devonian", - "https://atomicdata.dev/integrations/properties/version": "0.2.0", + "https://atomicdata.dev/integrations/properties/version": "0.3.0", "https://atomicdata.dev/integrations/properties/app-row-name": "Issue", "https://atomicdata.dev/integrations/properties/app-row-name-plural": "Issues", - "https://atomicdata.dev/integrations/properties/app-module": "https://ontola.github.io/atomic-plugins/apps/issue-tracker/0.2.0/ui.js", - "https://atomicdata.dev/integrations/properties/app-module-integrity": "sha384-Oy8HoxJRzRTf+5CIJJrWPEDdnFx/HrS+tq7OsA8vJAWfQclMxNPGGvKHRYXSutel" + "https://atomicdata.dev/integrations/properties/app-module": "https://ontola.github.io/atomic-plugins/apps/issue-tracker/0.3.0/ui.js", + "https://atomicdata.dev/integrations/properties/app-module-integrity": "sha384-V1/cSNb1t/cfotBhNY423Jx+7992gxY5Yvw4HRxTc5IFXpKBwMbaAisdn5CB9oqR" }, { "https://atomicdata.dev/properties/localId": "open-cloud-mesh", diff --git a/integrations/issue-tracker/README.md b/integrations/issue-tracker/README.md index d0f1a77f1..de9354478 100644 --- a/integrations/issue-tracker/README.md +++ b/integrations/issue-tracker/README.md @@ -82,11 +82,13 @@ states end to end, is still to be built. ## Drive app (`app/`) An iframe drive app, the same shape as `pets/app/` and `notion/app/`: one -ES module (`app/build.mjs` -> `dist/ui.js`, minified, 154,931 bytes for -0.2.0) whose `view({ root, store })` runs in the host's null-origin frame. It +ES module (`app/build.mjs` -> `dist/ui.js`, minified, 160,628 bytes for +0.3.0) whose `view({ root, store })` runs in the host's null-origin frame. It hosts the Devonian bridge from `devonian/github-issues/` for **one repository -per app install**, two-way for issue title, body (Markdown), -Todo/Doing/Blocked/Done status and comments. +per table**: the app's own table, and each other Issue table it was asked +to sync (since 0.3.0, see [Syncing a table the app didn't +make](#syncing-a-table-the-app-didnt-make)), two-way for issue title, body +(Markdown), Todo/Doing/Blocked/Done status and comments. **Flow.** The first screen offers GitHub Issues (Jira and Todoist are shown as not available). "Connect" asks the host for a connection @@ -128,7 +130,10 @@ its published GitHub Pages subject: issue number, GitHub source (JSON: url, author, labels, assignees, timestamps) and GitHub sync baseline (JSON: the title, body and status the app last agreed with GitHub). They are declared as the App's `row-extras` - (atomic-server #1849). A comment's Message carries its own baseline; + (atomic-server #1849), and so is Atomic's `localId` (since 0.3.0), which + the Bridge sets on each row it imports so that a create a reload + interrupted is found again instead of made twice. A comment's Message + carries its own baseline; - one Message per comment (`about` its row) in a "GitHub comments" folder under the app; - one sync resource holding the bound repository and the sync state as JSON @@ -137,13 +142,13 @@ its published GitHub Pages subject: preferences. **The shared class.** On first open the app adds `issue-v1` to its App's -`renders` (so the host's "+ Add view" offers it on any table of that class) -and sets its own table's `classtype` to `issue-v1`, through the frame store -(#177 spike S2; a catalog Install cannot do this yet, #177 H2). The table is -then an ordinary `issue-v1` table that other views of the class can read. -Opened as a view on an Issue table it did not make, the app shows a notice -and writes nothing: syncing an existing table ("Sync this table to GitHub", -#177 item 14) is not built. +`renders` (so the host's "+ Add view" offers it on any table of that class), +lists its row extras in `row-extras`, and sets its own table's `classtype` +to `issue-v1`, through the frame store (#177 spike S2; a catalog Install +cannot do this yet, #177 H2). Since 0.3.0 that happens on the first open +itself, before a repository is chosen; 0.2.0 did it only once one was. The +table is then an ordinary `issue-v1` table that other views of the class can +read. **Baselines on the rows (#177 decision 7).** The Bridge still keeps a baseline per record in memory. At each checkpoint, a baseline that differs @@ -341,6 +346,55 @@ folder as a sandbox package. `syncables` is not used: the Bridge's GitHub port already pages GitHub, and bundling the GitHub OpenAPI document for syncables would only add size. +### Syncing a table the app didn't make + +Since 0.3.0 (#177 §6.2 item 14), on the pattern calendar 0.3.0 set for +Google Calendar (#272). Opened as a view on an Issue table it did not make, +the app shows that the table isn't synced and offers **Sync this table to +GitHub**. Nothing is written before that is pressed. Pressing it: + +1. makes sure the App declares its row extras (number, source, baseline and + `localId`), then compares `store.rowAccess()`'s `extras` with them. When + there is no grant, or it doesn't cover them (for example "Allow editing" + chosen in Add view before the app ever declared its extras), it calls + `store.requestRowAccess()`, and the host shows its own "Allow editing" / + "Not now" bar. "Not now" leaves the table unsynced and says why; +2. makes a **binding** under the App: a resource of the app's sync class + with `synced-table` (a new app Property, an `atomicURL`, the table's + subject) and `localId` `github-issues:sync `, so AtomicServer keeps + one per table. The app finds it with `store.query` on `synced-table` and + accepts only one whose parent is the App; +3. goes on as on the app's own table: connect (if needed), choose the + repository, import. The repository, the sync state and a "GitHub + comments" folder for that table's comments are kept on and under the + binding. "Not now" on those two screens removes a binding that has no + repository yet. + +From then on it is the same sync as on the app's own table: compare on +open and on "Sync now", every change bound for GitHub held for review, the +same conflict rules, the baselines and issue numbers on the rows. Rows that +were in the table before stay local until "Publish to GitHub" on each +(#177 Q6). What differs from the app's own table: + +- the table itself is never written: no rename after the repository, no + `classtype` change. A row grant never covers the table; +- rows are never deleted: a grant doesn't cover `destroy`, so for an issue + gone from GitHub only "Keep here only" is offered, and the banner says to + delete the row in the table; +- the grant is checked on every open, before every pass and before every + edit made in the app. Once it lapses (the view removed, the person who + gave it loses write access, the app's key changes, or someone revokes it + in the tab's menu), the app says syncing is paused and offers "Allow + editing again"; it sends nothing to GitHub and writes nothing meanwhile. + A row write the host refuses mid-pass for that reason shows the same + pause; +- the binding keeps its repository for good, like the app's own sync + resource: the table can't switch repositories. + +Not verified: what an uninstall does with a binding; two tabs syncing the +same table (not guarded, as on the app's own table). Edits made in the +table while the app is closed are found only on its next open (#177 H6). + ## Mock data for user testing The mock proxy's github-issues fixture has a second, opt-in scenario for @@ -412,12 +466,22 @@ local until "Publish to GitHub", its reviewed create, and moving it to Blocked, which adds `atomic:blocked` on GitHub; then Disconnect GitHub and connecting again through the host's "Use existing connection" with no reload, after which the app syncs by itself (the unit tests also cover the -repository-picker case). The e2e reads `issue-v1` from its published GitHub +repository-picker case). A second e2e test (0.3.0) makes an `issue-v1` +table by hand with one row, adds GitHub issues to it as a Read-only view, +presses "Sync this table to GitHub", allows editing in the host's bar, +connects, imports a repository of its own (seeded through the mock's +`createIssue` driver), checks the rows, the untouched table and the binding +under the App, and sends a status edit made in the table after review. The +e2e reads `issue-v1` from its published GitHub Pages subject, so it needs network access to `ontola.github.io`; its `beforeAll` checks Pages serves the class first (`node ontology-kit/served.mjs classes/issue-v1`). The 0.1.x in-place -rewrite, a status shown as it is and the "other table" notice are unit-tested -only (`app/controller.test.ts`). +rewrite and a status shown as it is are unit-tested only +(`app/controller.test.ts`), and so are, for another table +(`app/syncTable.test.ts`, against a fake host that enforces the pinned +row-grant scope): "Not now" in the host's bar, a grant from before the +extras were declared, Publish to GitHub, reopening, a revoked grant and +"Allow editing again", "Not now" before a repository, and no row deletion. These check `adapter.ts`'s pagination, PR exclusion and mapping, the generic event-to-JavaScript starter (`automation.test.ts`), the Todoist projection, and diff --git a/integrations/issue-tracker/app/build.test.ts b/integrations/issue-tracker/app/build.test.ts index edd5fe2ac..fdce3726f 100644 --- a/integrations/issue-tracker/app/build.test.ts +++ b/integrations/issue-tracker/app/build.test.ts @@ -20,14 +20,17 @@ describe('GitHub issues drive-app bundle', async () => { expect(Object.keys(mod)).toEqual(['view']); expect(typeof mod.view).toBe('function'); // Stored as a string property on a resource; keep an eye on the size. - // Measured 154,931 bytes (151.3 KiB) on 2026-10-01 for 0.2.0, with the - // JS and the embedded stylesheets minified: the shared issue-v1 class, - // the bundled ontology-kit terms and resolver, Blocked, Publish to - // GitHub and baselines on the rows (#177 item 6). Earlier: 137,315 bytes + // Measured 160,628 bytes (156.9 KiB) on 2026-10-02 for 0.3.0, with the + // JS and the embedded stylesheets minified: 0.2.0 plus "Sync this table + // to GitHub" on another issue-v1 table (#177 item 14: the row grant, + // the binding under the App and its setup copy). Earlier: 154,931 bytes + // on 2026-10-01 for 0.2.0 (the shared issue-v1 class, the bundled + // ontology-kit terms and resolver, Blocked, Publish to GitHub and + // baselines on the rows, #177 item 6); 137,315 bytes // on 2026-10-01 after resolving uncertain creates (#156); 125,472 bytes // on 2026-09-24 for the designed board/list/detail UI (#89). The limit is // the latest plus 10%, rounded up to the next KiB. - expect(bytes).toBeLessThan(167 * 1024); + expect(bytes).toBeLessThan(173 * 1024); }); it('has no storage or network access of its own', () => { diff --git a/integrations/issue-tracker/app/controller.test.ts b/integrations/issue-tracker/app/controller.test.ts index ce5992f12..efd056eb3 100644 --- a/integrations/issue-tracker/app/controller.test.ts +++ b/integrations/issue-tracker/app/controller.test.ts @@ -24,6 +24,7 @@ import { DESCRIPTION, IS_A, ISSUE_V1, + LOCAL_ID, NAME, PARENT, PROPERTIES, @@ -542,6 +543,8 @@ group( property(store, 'github-issue-number'), property(store, 'github-source'), property(store, 'github-sync-baseline'), + // The Bridge's create-recovery key on imported rows (since 0.3.0). + LOCAL_ID, ]); expect(store.resources.get(TABLE)![CLASSTYPE]).toBe(ISSUE_V1); // Idempotent: a second open writes neither again. @@ -672,14 +675,14 @@ group( ]); }); - it('only shows a notice on an Issue table it did not make', async () => { + it('writes nothing on an Issue table it did not make before it is asked to sync it', async () => { const store = fakeStore({ table: 'did:ad:someone-elses-table' }); store.resources.set('did:ad:someone-elses-table', { [PARENT]: 'did:ad:drive', [CLASSTYPE]: ISSUE_V1, }); const state = await createController(store).start(); - expect(state.kind).toBe('other-table'); + expect(state).toEqual({ kind: 'other-table', canSync: true }); expect(store.writes).toEqual([]); }); }, diff --git a/integrations/issue-tracker/app/controller.ts b/integrations/issue-tracker/app/controller.ts index 44b9482ab..8a0ba0504 100644 --- a/integrations/issue-tracker/app/controller.ts +++ b/integrations/issue-tracker/app/controller.ts @@ -30,10 +30,16 @@ import { NAME, PARENT, STATUSES, - boundRepository, + adoptOwnTable, + bindTable, + binding, + declareRowExtras, migrateRows, provision, + rowExtras, + rowExtrasNow, showsOwnTable, + unbindTable, type Tracker, } from './tracker.js'; import { listRepositories, PLATFORM, type Repository } from './transport.js'; @@ -92,10 +98,19 @@ export type ViewState = | { kind: 'no-proxy' } /** * Shown on an Issue table the app did not make (it is offered there - * because it renders `issue-v1`). Syncing such a table with GitHub is - * not built yet (#177 H4, item 14). + * because it renders `issue-v1`) that isn't synced, or whose sync is + * paused because the row grant lapsed. "Sync this table to GitHub" (#177 + * §6.2 item 14) is offered when the host can ask for "Allow editing" and + * reach the proxy (`canSync`). */ - | { kind: 'other-table' } + | { + kind: 'other-table'; + canSync: boolean; + /** Waiting for the person to answer the host's "Allow editing" bar. */ + asking?: boolean; + /** Why the last "Sync this table" stopped, or why syncing is paused. */ + reason?: string; + } | { kind: 'not-connected' } | { kind: 'connecting' } | { @@ -135,7 +150,25 @@ export interface IssueInput { export interface Controller { state(): ViewState; + /** + * The name of the table shown when it is not the app's own (it was added + * as a view of it); undefined on the app's own table. Known after `load`. + */ + foreign(): string | undefined; load(): Promise; + /** + * "Sync this table to GitHub", on a table the app didn't make: asks for + * "Allow editing" (covering the app's row extras) when the grant doesn't + * cover them, keeps the choice as a binding under the App, then goes on + * as on the app's own table: connect, choose a repository, import. + */ + syncTable(): Promise; + /** + * "Not now" on a table the app didn't make, before a repository was + * chosen: back to not synced. The grant stays; the host's tab menu takes + * it back. + */ + notNow(): Promise; /** * `load`, then the step that state needs: the repository list for the * picker, or the first sync once a repository is bound. The view's open @@ -221,6 +254,12 @@ const PAUSED: [RegExp, PausedReason][] = [ [/^The integration proxy refused the request/, 'other'], ]; +/** The `other-table` state on a table that is bound but whose grant lapsed. */ +export const PAUSED_NOTE = + 'Syncing with GitHub is paused: this app may no longer edit this table’s rows, or keep its GitHub issue numbers on them. Allow editing again to go on.'; + +const sentence = (text: string) => text.replace(/\.?$/, '.'); + export function classify(error: unknown): Problem { const e = error as PassError; const message = error instanceof Error ? error.message : String(error); @@ -285,6 +324,12 @@ export function createController( let session: Session | undefined; let conflict: Problem | undefined; let prefs: ViewPrefs = {}; + /** The name of the table shown, when it is not the app's own. */ + let foreign: string | undefined; + /** The binding of that table, once known (the host's query can lag). */ + let hint: string | undefined; + /** The row extras a grant must cover, once the session knows them. */ + let extras: string[] | undefined; /** Optimistic changes per touched row, re-applied until a pass has seen it. */ const changes = new Map IssueRow>(); @@ -304,7 +349,9 @@ export function createController( const open = async (repository?: string): Promise => { if (session) return session; - const provisioned = await provision(store, repository); + const provisioned = await provision(store, repository, hint); + if (foreign) hint = provisioned.sync.subject; + extras = rowExtras(provisioned.tracker.properties); const state = new SyncState( provisioned.sync, provisioned.tracker.properties.syncState, @@ -345,6 +392,42 @@ export function createController( return session; }; + const canSync = () => + !!store.proxy && + typeof store.rowAccess === 'function' && + typeof store.requestRowAccess === 'function'; + + /** The `other-table` state, with the offer to sync or the reason it stopped. */ + const other = (reason?: string) => + set({ + kind: 'other-table', + canSync: canSync(), + ...(reason ? { reason } : {}), + }); + + /** + * Whether the person's grant on the table the app is a view of covers its + * rows and every row extra. Always true on the app's own table. + */ + const covered = async (): Promise => { + if (!foreign) return true; + if (!store.rowAccess) return false; + const access = await store.rowAccess(); + if (access.status !== 'granted') return false; + const wanted = extras ?? (await rowExtrasNow(store)); + + return !!wanted && wanted.every(extra => access.extras.includes(extra)); + }; + + /** The grant lapsed since the view opened: say so instead of failing on a write. */ + const lapsed = async (): Promise => { + if (await covered().catch(() => false)) return false; + session = undefined; + other(PAUSED_NOTE); + + return true; + }; + const passOptions = ( s: Session, connectionId: string, @@ -426,6 +509,7 @@ export function createController( serial(async () => { if (current.kind !== 'ready' || !store.proxy) return current; const ready = current; + if (await lapsed()) return current; set({ ...ready, busy }); try { @@ -466,6 +550,8 @@ export function createController( ...(touched.length ? { touched } : {}), }); } catch (error) { + // A row write refused because the grant lapsed during the pass. + if (foreign && (await lapsed())) return current; const problem = classify(error); if (problem.kind === 'conflict') conflict = problem; const after = latest(ready); @@ -544,10 +630,12 @@ export function createController( work: (s: Session) => Promise, ): Promise => { try { + if (await lapsed()) return false; await serial(async () => work(await open(ready.repository))); return true; } catch (error) { + if (foreign && (await lapsed())) return false; set({ ...latest(ready), problem: classify(error) }); return false; @@ -569,13 +657,34 @@ export function createController( const controller: Controller = { state: () => current, + foreign: () => foreign, async load() { - if (!(await showsOwnTable(store))) return set({ kind: 'other-table' }); + let bound: Awaited>; + + if (!(await showsOwnTable(store))) { + const data = await store.getData(); + const name = (await store.getResource(data!.table)).get(NAME); + foreign = typeof name === 'string' && name ? name : 'This table'; + // Not synced until "Sync this table" made a binding; paused when the + // grant no longer covers the rows and the app's row extras. + bound = await binding(store, hint); + if (!bound) return other(); + hint = bound.subject; + if (!(await covered())) return other(PAUSED_NOTE); + } else { + // Renders issue-v1 and declares the row extras from the first open, + // so "+ Add view" offers the app on other Issue tables. `provision` + // does it again and reports a refusal; here it only must not stop + // the view from opening. + await adoptOwnTable(store).catch(() => {}); + bound = await binding(store); + } + const proxy = store.proxy; if (!proxy || typeof proxy.connections !== 'function') return set({ kind: 'no-proxy' }); - const repository = await boundRepository(store); + const repository = bound?.repository; let stale: string[] = []; if (repository) { @@ -630,6 +739,44 @@ export function createController( return this.start(); }, + async syncTable() { + if (current.kind !== 'other-table' || current.asking || !current.canSync) + return current; + set({ ...current, asking: true }); + let reason: string | undefined; + + try { + // The extras first: a grant covers what the App declared when given. + extras = await declareRowExtras(store); + + if (!(await covered())) { + const answer = await store.requestRowAccess!(); + if (answer.status !== 'granted') reason = answer.reason; + // The host grants what the App declares now; check it covers them. + else if (!(await covered())) + reason = + 'The grant doesn’t cover the GitHub issue numbers, sources and baselines the app keeps on rows'; + } + + if (!reason) hint = await bindTable(store, hint); + } catch (error) { + reason = error instanceof Error ? error.message : String(error); + } + + if (reason) return other(`Not synced: ${sentence(reason)}`); + + return this.start(); + }, + + async notNow() { + if (!foreign) return current; + await unbindTable(store, hint); + hint = undefined; + session = undefined; + + return this.load(); + }, + async disconnect() { const proxy = store.proxy; if (!proxy?.disconnect || current.kind !== 'ready') return current; @@ -850,7 +997,9 @@ export function createController( removeFromBoard() { const gone = missingIssue(); - if (!gone) return Promise.resolve(current); + // A row grant never deletes a row (atomic-server#1740): on a table the + // app didn't make, the person deletes it in the table. + if (!gone || foreign) return Promise.resolve(current); return run('resolving', async (s, ready) => { const options = passOptions(s, ready.connectionId, ready.repository); @@ -924,6 +1073,14 @@ function blankRow(subject: string): IssueRow { const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? one : many}`; +/** What the `other-table` state says first. */ +export const OTHER_NOTE = + 'This Issue table wasn’t made by this app and isn’t synced with GitHub.'; + +/** The `other-table` state's offer, when the host can do it (`canSync`). */ +export const SYNC_NOTE = + 'Sync it to keep it and one GitHub repository in step: the repository’s issues are added as rows, and edits made here are sent after you review them. Rows already here stay here until you publish them. The app asks you to allow it to edit this table’s rows and to keep each issue’s GitHub number, source and sync baseline on its row.'; + export function describe(state: ViewState): string { switch (state.kind) { case 'loading': @@ -931,7 +1088,11 @@ export function describe(state: ViewState): string { case 'no-proxy': return 'This host cannot reach the integration proxy on behalf of an app, so this app cannot sync. Nothing was fetched.'; case 'other-table': - return 'This is an Issue table this app did not make. Syncing it with GitHub is not built yet; open the app itself to sync its own table.'; + return state.reason + ? `${OTHER_NOTE} ${state.reason}` + : state.canSync + ? `${OTHER_NOTE} ${SYNC_NOTE}` + : OTHER_NOTE; case 'not-connected': return 'Not connected. Connect a GitHub account to sync one repository’s issues and comments with this table.'; case 'connecting': diff --git a/integrations/issue-tracker/app/fakeStore.ts b/integrations/issue-tracker/app/fakeStore.ts index d56647db4..195431038 100644 --- a/integrations/issue-tracker/app/fakeStore.ts +++ b/integrations/issue-tracker/app/fakeStore.ts @@ -10,6 +10,14 @@ * switched on: `lagReads` (a read after an app write returns the old values * that many times) and `hideFromQuery` (a `query` leaves out resources the * app created until that many queries later). Test-only; not bundled. + * + * On a `table` that isn't the app's own (an `issue-v1` table the app is a + * view of) writes follow the pinned host's row grant (atomic-server + * `app_row_grant.rs`, #1740 and #1849): none on its rows without a grant; + * with one, only `issue-v1`'s `requires` and `recommends` plus the + * `row-extras` the App declared when it was granted, on rows of exactly + * that class; never the table itself, never `destroy`. `rowAccess()` and + * `requestRowAccess()` answer as view-client.js does. */ import { githubTracker } from '../fixtures/github-issues/scenario.mjs'; import type { @@ -24,11 +32,14 @@ import { CLASSTYPE, DEFAULT_ONTOLOGY, IS_A, + ISSUE_V1, NAME, PARENT, PROPERTIES, RECOMMENDS, SHORTNAME, + TASK_BODY, + TASK_STATUS, } from './tracker.js'; export const APP = 'did:ad:app'; @@ -40,6 +51,15 @@ export const APP_CLASS = 'did:ad:plugin-class-app'; export const RENDERS = 'did:ad:plugin-renders'; export const ROW_EXTRAS = 'did:ad:plugin-row-extras'; +/** `issue-v1`'s `requires` and `recommends` (ontology-kit/source.json). */ +const ISSUE_COLUMNS = [ + NAME, + TASK_STATUS, + TASK_BODY, + 'https://atomicdata.dev/task/v1/assignee', + 'https://atomicdata.dev/task/v1/due-date', +]; + export interface FakeStore extends PluginStore { readonly resources: Map>; readonly writes: { op: 'create' | 'save'; subject: string }[]; @@ -66,6 +86,12 @@ export interface FakeStore extends PluginStore { setScheme(scheme: ColorScheme): void; /** A person editing a row in the data-browser: no app write, no lag. */ edit(subject: string, props: Record): void; + /** The live row grant on another `table`: the extras it covers, or none. */ + readonly grant: { extras: string[] } | undefined; + /** Someone takes the grant back in the host's tab menu. */ + revokeGrant(): void; + /** How many times the host asked the person ("Allow editing"). */ + readonly asked: number; } export function fakeStore({ @@ -74,6 +100,8 @@ export function fakeStore({ relay = true, hostApis = true, table = TABLE, + grant: initialGrant = 'none', + answer: answerWith = 'allow', }: { /** The table the app is shown on; another one is a view on someone's table. */ table?: string; @@ -87,6 +115,14 @@ export function fakeStore({ relay?: boolean; /** The host calls of atomic-server pin 007869464 (getMany, openExternal, …). */ hostApis?: boolean; + /** + * The grant on another `table` before the app opens: none, or "Allow + * editing" from Add view before the app declared its row extras + * (`columns`, covering none of them). + */ + grant?: 'none' | 'columns'; + /** What the person answers when the app asks with `requestRowAccess()`. */ + answer?: 'allow' | 'deny'; } = {}): FakeStore { // As `createApp` lays it out at the pin. const resources = new Map>([ @@ -117,6 +153,52 @@ export function fakeStore({ const calls: HostProxyRequest[] = []; const github = githubTracker(); let next = 0; + let grant: { extras: string[] } | undefined = + initialGrant === 'columns' ? { extras: [] } : undefined; + let asked = 0; + const foreign = table !== TABLE; + + /** The App's `row-extras` now. */ + const declared = () => { + const value = resources.get(APP)![ROW_EXTRAS]; + + return Array.isArray(value) + ? value.filter((v): v is string => typeof v === 'string') + : []; + }; + + /** Refuses a write the pinned host's row grant would refuse. */ + const checkGrant = ( + subject: string, + parent: JSONValue, + isA: JSONValue, + written: string[], + op: 'create' | 'save' | 'destroy', + ) => { + if (!foreign) return; + if (subject === table) + throw new Error('This app may only write its own data.'); + if (parent !== table) return; + if (!grant) + throw new Error( + 'This app is a view of this table but may not edit its rows.', + ); + if (op === 'destroy') + throw new Error('Letting an app edit rows does not let it delete them'); + if (!Array.isArray(isA) || isA.length !== 1 || isA[0] !== ISSUE_V1) + throw new Error('This app may only edit rows of the table’s row class'); + const live = declared(); + const allowed = new Set([ + ...ISSUE_COLUMNS, + ...grant.extras.filter(extra => live.includes(extra)), + ]); + + for (const property of written) + if (!allowed.has(property)) + throw new Error( + `This app may edit this table's columns and the row data it was allowed to keep, not ${property}`, + ); + }; const wrap = ( subject: string, @@ -125,6 +207,8 @@ export function fakeStore({ const props = structuredClone(stored); /** Removed since the last save; `save` sends them, as view-client.js does. */ const removed = new Set(); + /** Set since the last save: what view-client.js sends. */ + const changed = new Set(); return { subject, @@ -135,17 +219,27 @@ export function fakeStore({ set(property, value) { props[property] = value; removed.delete(property); + changed.add(property); return this; }, remove(property) { delete props[property]; removed.add(property); + changed.delete(property); return this; }, async save() { const before = resources.get(subject) ?? {}; + checkGrant( + subject, + before[PARENT], + before[IS_A], + [...changed, ...removed], + 'save', + ); + changed.clear(); if (fake.lagReads) stale.set(subject, { props: structuredClone(before), @@ -162,6 +256,8 @@ export function fakeStore({ return this; }, async destroy() { + const before = resources.get(subject) ?? {}; + checkGrant(subject, before[PARENT], before[IS_A], [], 'destroy'); resources.delete(subject); }, }; @@ -310,6 +406,7 @@ export function fakeStore({ return out; }, async newResource({ parent, isA = [], propVals = {} } = {}) { + checkGrant('', parent ?? APP, isA, Object.keys(propVals), 'create'); const subject = `did:ad:new-${++next}`; const stored = { ...structuredClone(propVals), @@ -323,6 +420,46 @@ export function fakeStore({ return wrap(subject, stored); }, subscribe: () => () => {}, + get grant() { + return grant; + }, + revokeGrant: () => { + grant = undefined; + }, + get asked() { + return asked; + }, + async rowAccess() { + if (!foreign) return { status: 'unavailable' as const }; + + return grant + ? { + status: 'granted' as const, + grantedBy: 'did:ad:agent-person', + grantedAt: 1, + via: 'request', + extras: grant.extras, + } + : { status: 'none' as const }; + }, + async requestRowAccess() { + if (!foreign) + return { + status: 'denied' as const, + reason: 'This app is not shown as a table view here', + }; + const live = declared(); + // As the host's rowAccessQuestion: no question when the grant covers the list. + if (grant && live.every(extra => grant!.extras.includes(extra))) + return { status: 'granted' as const }; + asked++; + if (answerWith === 'deny') + return { status: 'denied' as const, reason: 'The person said no' }; + // A new grant, for the list as the App declares it now. + grant = { extras: live }; + + return { status: 'granted' as const }; + }, counts, opened, disconnected: [], diff --git a/integrations/issue-tracker/app/main.ts b/integrations/issue-tracker/app/main.ts index 4a1be11b0..1c7d6b358 100644 --- a/integrations/issue-tracker/app/main.ts +++ b/integrations/issue-tracker/app/main.ts @@ -190,6 +190,11 @@ export async function view({ root, store }: ViewArgs): Promise { }; const onState = (state: ViewState) => { + // A table the app didn't make: its name, for the setup screens. + const table = controller.foreign(); + if (table === undefined) delete ui.table; + else ui.table = table; + if (state.kind === 'ready') { // The saved layout and filters, once, when the app first shows its // board: on open, or after connecting with no reload. @@ -441,6 +446,15 @@ export async function view({ root, store }: ViewArgs): Promise { live.say('Publishing to GitHub after your review'); void controller.publish(subject); }, + + syncTable() { + live.say('Asking you to allow this app to edit this table'); + void controller.syncTable(); + }, + + notNow() { + void controller.notNow(); + }, }; // ---------------------------------------------------------- keyboard diff --git a/integrations/issue-tracker/app/model.ts b/integrations/issue-tracker/app/model.ts index ab03414ae..e8b195a38 100644 --- a/integrations/issue-tracker/app/model.ts +++ b/integrations/issue-tracker/app/model.ts @@ -132,6 +132,11 @@ export const unconfirmed = (state: Ready): Held[] => export function bannerFor( state: ViewState, confirmingRemove = false, + /** + * False on a table the app didn't make: a row grant never deletes a row + * (atomic-server#1740), so "Remove from board" isn't offered there. + */ + own = true, ): BannerModel | undefined { if (state.kind !== 'ready') return undefined; const p = state.problem; @@ -187,7 +192,7 @@ export function bannerFor( p.missing?.side === 'remote' && p.missing.entity === 'issue'; const name = ref(p.missing?.local); - if (issue && confirmingRemove) + if (issue && confirmingRemove && own) return { tone: 'warn', icon: 'ghost', @@ -206,10 +211,20 @@ export function bannerFor( tone: 'warn', icon: 'ghost', title: `${name} is on this board but no longer on GitHub.`, - text: 'It may have been deleted or moved to another repository. Nothing on GitHub will change.', + text: own + ? 'It may have been deleted or moved to another repository. Nothing on GitHub will change.' + : 'It may have been deleted or moved to another repository. Nothing on GitHub will change. To remove it here, delete its row in the table.', actions: [ { label: 'Keep here only', action: 'keep-here' }, - { label: 'Remove from board', action: 'remove', danger: true }, + ...(own + ? [ + { + label: 'Remove from board', + action: 'remove' as const, + danger: true, + }, + ] + : []), ], details: p.message, problem: p, diff --git a/integrations/issue-tracker/app/package.json b/integrations/issue-tracker/app/package.json index 295806367..bf2e03e77 100644 --- a/integrations/issue-tracker/app/package.json +++ b/integrations/issue-tracker/app/package.json @@ -1,7 +1,7 @@ { "name": "@atomic-integrations/issue-tracker-app", "private": true, - "version": "0.2.0", + "version": "0.3.0", "type": "module", "description": "GitHub issues drive app: bundles the npm devonian package into app/dist/ui.js. Not a certified sandbox package (no atomicCertification); it lives in app/ so certify.mjs does not treat issue-tracker as one.", "dependencies": { diff --git a/integrations/issue-tracker/app/store.ts b/integrations/issue-tracker/app/store.ts index e4665abe6..124effc0f 100644 --- a/integrations/issue-tracker/app/store.ts +++ b/integrations/issue-tracker/app/store.ts @@ -94,6 +94,28 @@ export interface HostProxy { /** Whether the host is drawn light or dark (`store.getTheme()`). */ export type ColorScheme = 'light' | 'dark'; +/** + * What `store.rowAccess()` answers (atomic-server#1740, #1849): whether this + * app may edit the rows of the table it is a view of, and which of its + * declared `row-extras` that grant covers. + */ +export type RowAccess = + | { + status: 'granted'; + grantedBy: string; + grantedAt: number; + via: string; + extras: string[]; + } + | { status: 'none' } + /** Not shown as a table's view. */ + | { status: 'unavailable' }; + +/** What `store.requestRowAccess()` answers once the person chose. */ +export type RowAccessAnswer = + | { status: 'granted' } + | { status: 'denied'; reason: string }; + export interface PluginStore { getApp(): Promise; getData(): Promise; @@ -127,6 +149,19 @@ export interface PluginStore { onThemeChange?( handler: (theme: { colorScheme?: ColorScheme }) => void, ): () => void; + /* + * Since atomic-server pin a12b74a (#1740, #1849), feature-detected: "Sync + * this table to GitHub" on a table the app didn't make needs both. + */ + /** Whether this app may edit the rows of the table it is a view of. */ + rowAccess?(): Promise; + /** + * Asks the person, in the host's own bar ("Allow editing" / "Not now"), + * to let this app edit the table's rows and keep its `row-extras` on them. + * Answered straight away when a live grant already covers every extra the + * App declares now. + */ + requestRowAccess?(): Promise; } export interface ViewArgs { diff --git a/integrations/issue-tracker/app/sync.test.ts b/integrations/issue-tracker/app/sync.test.ts index 34d8508df..f553f7834 100644 --- a/integrations/issue-tracker/app/sync.test.ts +++ b/integrations/issue-tracker/app/sync.test.ts @@ -617,7 +617,8 @@ group('frame store adapter', () => { const listed = store.resources.get('did:ad:ontology')?.[ PROPERTIES ] as string[]; - expect(listed.length).toBe(5); + // Number, source, baseline, repository, sync state, synced table. + expect(listed.length).toBe(6); }); }); diff --git a/integrations/issue-tracker/app/syncTable.test.ts b/integrations/issue-tracker/app/syncTable.test.ts new file mode 100644 index 000000000..8fdf11c54 --- /dev/null +++ b/integrations/issue-tracker/app/syncTable.test.ts @@ -0,0 +1,350 @@ +// @wc-ignore-file +/** + * "Sync this table to GitHub" (#177 §6.2 item 14) on an `issue-v1` table the + * app is a view of, not its own. The fake store enforces the pinned host's + * row grant (atomic-server `app_row_grant.rs`): no row write without "Allow + * editing", only `issue-v1`'s columns and the App's declared `row-extras`, + * never the table, never a delete. The repository, sync state and comments + * live on a binding under the App. + */ +import { describe as group, expect, it } from 'vitest'; +import { SEEDED_REPOSITORY } from '../fixtures/github-issues/scenario.mjs'; +import { + createController, + describe, + describeHeld, + PAUSED_NOTE, + SYNC_NOTE, + type ViewState, +} from './controller.js'; +import { bannerFor } from './model.js'; +import { + APP, + fakeStore, + RENDERS, + ROW_EXTRAS, + type FakeStore, +} from './fakeStore.js'; +import { + CLASSTYPE, + IS_A, + ISSUE_V1, + LOCAL_ID, + NAME, + PARENT, + SHORTNAME, + TASK_STATUS, + TASK_TAGS, +} from './tracker.js'; + +const TEAM = 'did:ad:team-table'; +const HAND = 'did:ad:hand-1'; + +type Ready = Extract; + +const ready = (state: ViewState): Ready => { + if (state.kind !== 'ready') + throw new Error(`Expected ready, got ${JSON.stringify(state)}`); + + return state; +}; + +const property = (store: FakeStore, shortname: string) => + [...store.resources.entries()].find( + ([, props]) => props[SHORTNAME] === shortname, + )![0]; + +/** An `issue-v1` table someone made, with one row of their own. */ +function teamTable(options: Parameters[0] = {}): FakeStore { + const store = fakeStore({ table: TEAM, ...options }); + store.resources.set(TEAM, { + [PARENT]: 'did:ad:drive', + [NAME]: 'Team issues', + [CLASSTYPE]: ISSUE_V1, + }); + store.resources.set(HAND, { + [PARENT]: TEAM, + [IS_A]: [ISSUE_V1], + [NAME]: 'Plan the offsite', + [TASK_STATUS]: [TASK_TAGS.Todo], + }); + + return store; +} + +const rowsOf = (store: FakeStore) => + [...store.resources].filter(([, p]) => p[PARENT] === TEAM); + +/** Bindings under the App naming the table. */ +const bindingsOf = (store: FakeStore) => + [...store.resources].filter( + ([, p]) => p[PARENT] === APP && p[property(store, 'synced-table')] === TEAM, + ); + +const tableWrites = (store: FakeStore) => + store.writes.filter( + w => + w.subject === TEAM || store.resources.get(w.subject)?.[PARENT] === TEAM, + ); + +const githubWrites = (store: FakeStore) => + store.calls.filter(c => (c.method ?? 'GET') !== 'GET'); + +async function synced(store = teamTable()) { + const controller = createController(store); + await controller.start(); + const chosen = await controller.syncTable(); + expect(chosen.kind).toBe('choose-repository'); + const state = ready(await controller.choose(SEEDED_REPOSITORY)); + if (state.problem) throw new Error(state.problem.message); + + return { store, controller, state }; +} + +group('Sync this table to GitHub (#177 §6.2 item 14)', () => { + it('offers it on a table that isn’t synced, and writes nothing before it is pressed', async () => { + const store = teamTable(); + const controller = createController(store); + const state = await controller.start(); + expect(state).toEqual({ kind: 'other-table', canSync: true }); + expect(describe(state)).toContain(SYNC_NOTE); + expect(controller.foreign()).toBe('Team issues'); + expect(store.asked).toBe(0); + expect(store.calls).toEqual([]); + expect(store.writes).toEqual([]); + }); + + it('is not offered on a host without the row grant or the proxy relay', async () => { + for (const store of [ + Object.assign(teamTable(), { requestRowAccess: undefined }), + teamTable({ relay: false }), + ]) { + const controller = createController(store); + expect(await controller.start()).toEqual({ + kind: 'other-table', + canSync: false, + }); + expect((await controller.syncTable()).kind).toBe('other-table'); + expect(store.writes).toEqual([]); + } + }); + + it('asks for Allow editing with the row extras, binds the table under the App, and imports into it', async () => { + const { store, state } = await synced(); + expect(store.asked).toBe(1); + // The grant covers what the App declares: three GitHub extras and localId. + expect([...store.grant!.extras].sort()).toEqual( + [ + property(store, 'github-issue-number'), + property(store, 'github-source'), + property(store, 'github-sync-baseline'), + LOCAL_ID, + ].sort(), + ); + // One binding, under the App, with the repository; the table is untouched. + const bindings = bindingsOf(store); + expect(bindings).toHaveLength(1); + expect(bindings[0][1][property(store, 'github-repository')]).toBe( + SEEDED_REPOSITORY, + ); + expect(store.resources.get(TEAM)).toEqual({ + [PARENT]: 'did:ad:drive', + [NAME]: 'Team issues', + [CLASSTYPE]: ISSUE_V1, + }); + expect(store.writes.filter(w => w.subject === TEAM)).toEqual([]); + // GitHub's two issues became rows of the table, with the extras. + const imported = rowsOf(store).filter(([s]) => s !== HAND); + expect(imported).toHaveLength(2); + + for (const [, row] of imported) { + expect(row[IS_A]).toEqual([ISSUE_V1]); + expect(row[property(store, 'github-issue-number')]).toEqual( + expect.any(Number), + ); + expect(row[property(store, 'github-sync-baseline')]).toEqual( + expect.any(String), + ); + } + + // #1's comment is a Message in a folder under the binding. + const comment = state.last!.result.rows.find(r => r.number === 1)! + .comments[0].subject; + const parentOf = (s: string) => store.resources.get(s)?.[PARENT]; + expect(parentOf(parentOf(comment) as string)).toBe(bindings[0][0]); + // The row that was already there stays local only, untouched. + expect(store.resources.get(HAND)).toEqual({ + [PARENT]: TEAM, + [IS_A]: [ISSUE_V1], + [NAME]: 'Plan the offsite', + [TASK_STATUS]: [TASK_TAGS.Todo], + }); + expect(state.last!.result.rows.find(r => r.subject === HAND)).toMatchObject( + { localOnly: true }, + ); + expect(githubWrites(store)).toEqual([]); + }); + + it('asks again when Add view’s grant came before the App declared its extras', async () => { + const { store } = await synced(teamTable({ grant: 'columns' })); + expect(store.asked).toBe(1); + expect(store.grant!.extras).toHaveLength(4); + }); + + it('stays not synced, with the reason, when the person says Not now to the host', async () => { + const store = teamTable({ answer: 'deny' }); + const controller = createController(store); + await controller.start(); + expect(await controller.syncTable()).toEqual({ + kind: 'other-table', + canSync: true, + reason: 'Not synced: The person said no.', + }); + expect(bindingsOf(store)).toEqual([]); + expect(store.calls).toEqual([]); + expect(tableWrites(store)).toEqual([]); + }); + + it('sends a status edit made in the table after review, and moves the row’s baseline', async () => { + const { store, controller, state } = await synced(); + const first = state.last!.result.rows.find(r => r.number === 1)!.subject; + // The person closes #1 in the host's table: their own commit. + store.edit(first, { [TASK_STATUS]: [TASK_TAGS.Done] }); + const held = ready(await controller.sync()); + expect(held.last!.result.held.map(describeHeld)).toEqual([ + 'Update #1: status Todo → Done (close it)', + ]); + expect(githubWrites(store)).toEqual([]); + const sent = ready(await controller.send()); + expect(sent.problem).toBeUndefined(); + expect(sent.last!.result.sentToGitHub).toBe(1); + expect(store.github.snapshot(SEEDED_REPOSITORY).issues[0].state).toBe( + 'closed', + ); + const baseline = JSON.parse( + store.resources.get(first)![ + property(store, 'github-sync-baseline') + ] as string, + ); + expect(baseline.status).toBe('Done'); + }); + + it('publishes a row that was already there only when asked, after review', async () => { + const { store, controller } = await synced(); + expect(ready(await controller.sync()).last!.result.held).toEqual([]); + await controller.publish(HAND); + const held = ready(controller.state()); + expect(held.last!.result.held.map(describeHeld)).toEqual([ + 'Create issue “Plan the offsite” (Todo)', + ]); + ready(await controller.send()); + expect(store.github.snapshot(SEEDED_REPOSITORY).issues[2].title).toBe( + 'Plan the offsite', + ); + // The next pass writes the issue number onto the row (a row extra). + await controller.sync(); + expect( + store.resources.get(HAND)![property(store, 'github-issue-number')], + ).toBe(3); + }); + + it('opens straight into the sync next time, without asking again', async () => { + const { store } = await synced(); + const again = createController(store); + const state = ready(await again.start()); + expect(state.repository).toBe(SEEDED_REPOSITORY); + expect(state.problem).toBeUndefined(); + expect(state.last!.result.addedHere).toBe(0); + expect(store.asked).toBe(1); + }); + + it('pauses, without a request to GitHub, once the grant is taken back', async () => { + const { store, controller } = await synced(); + store.revokeGrant(); + const calls = store.calls.length; + expect(await controller.sync()).toEqual({ + kind: 'other-table', + canSync: true, + reason: PAUSED_NOTE, + }); + const reopened = createController(store); + expect(await reopened.start()).toMatchObject({ + kind: 'other-table', + reason: PAUSED_NOTE, + }); + expect(store.calls.length).toBe(calls); + // Allowing editing again goes on with the same repository and binding. + const resumed = ready(await reopened.syncTable()); + expect(store.asked).toBe(2); + expect(resumed.repository).toBe(SEEDED_REPOSITORY); + expect(resumed.problem).toBeUndefined(); + expect(bindingsOf(store)).toHaveLength(1); + }); + + it('Not now before a repository is chosen goes back to not synced', async () => { + const store = teamTable(); + const controller = createController(store); + await controller.start(); + expect((await controller.syncTable()).kind).toBe('choose-repository'); + expect(bindingsOf(store)).toHaveLength(1); + expect(await controller.notNow()).toEqual({ + kind: 'other-table', + canSync: true, + }); + expect(bindingsOf(store)).toEqual([]); + }); + + it('never deletes a row of the table: Remove from board is not offered or done there', async () => { + const { store, controller, state } = await synced(); + const row = state.last!.result.rows.find(r => r.number === 1)!.subject; + // GitHub stops returning #1 (deleted or transferred). + const request = store.proxy!.request.bind(store.proxy); + + store.proxy!.request = async r => { + if (/\/issues\/1(\/|$)/.test(r.path)) + return { status: 404, headers: {}, body: {} }; + const response = await request(r); + if (/\/issues$/.test(r.path) && Array.isArray(response.body)) + return { + ...response, + body: (response.body as { number: number }[]).filter( + i => i.number !== 1, + ), + }; + + return response; + }; + + const paused = ready(await controller.sync()); + expect(paused.problem).toMatchObject({ kind: 'paused', reason: 'missing' }); + const banner = bannerFor(paused, false, false)!; + expect(banner.actions.map(a => a.label)).toEqual(['Keep here only']); + expect(banner.text).toContain('delete its row in the table'); + await controller.removeFromBoard(); + expect(store.resources.has(row)).toBe(true); + // Keep here only just takes the issue number off the row: allowed. + expect(ready(await controller.keepHereOnly()).problem).toBeUndefined(); + expect( + store.resources.get(row)![property(store, 'github-issue-number')], + ).toBeUndefined(); + }); + + it('renders issue-v1 and declares its row extras from the first open, before connecting', async () => { + const store = fakeStore({ connected: false }); + expect((await createController(store).start()).kind).toBe('not-connected'); + const app = store.resources.get(APP)!; + expect(app[RENDERS]).toContain(ISSUE_V1); + expect(app[ROW_EXTRAS]).toContain(LOCAL_ID); + }); + + it('leaves the app’s own table as it was: no binding, no grant asked', async () => { + const store = fakeStore(); + const controller = createController(store); + expect((await controller.start()).kind).toBe('choose-repository'); + expect(controller.foreign()).toBeUndefined(); + expect(await controller.syncTable()).toMatchObject({ + kind: 'choose-repository', + }); + expect(store.asked).toBe(0); + }); +}); diff --git a/integrations/issue-tracker/app/tracker.ts b/integrations/issue-tracker/app/tracker.ts index 8589d79b3..b6a0d71cd 100644 --- a/integrations/issue-tracker/app/tracker.ts +++ b/integrations/issue-tracker/app/tracker.ts @@ -18,6 +18,13 @@ * per-record baselines, write journal, view preferences). * - One folder under the app for the GitHub comments (Messages `about` a * row), also found by `localId`. + * - Since 0.3.0 (#177 §6.2 item 14), per table the app is a view of and + * was asked to sync ("Sync this table to GitHub"): a binding under the + * app, of the same class as the sync resource, whose `synced-table` names + * that table, with its own repository, sync state and comments folder. + * A row grant never writes the table itself, so nothing about the sync + * is kept there; per-row bookkeeping is on the rows, as on the app's own + * table. * * On first open (`provision`) the app also makes itself a view of * `issue-v1`: it adds the class to its App's `renders` and sets its own @@ -98,6 +105,8 @@ export interface Tracker { baseline: string; repository: string; syncState: string; + /** On a binding: the table, not the app's own, it syncs. */ + syncedTable: string; }; tags: Record; commentsFolder: string; @@ -150,6 +159,14 @@ const PROPERTY_SPECS: PropertySpec[] = [ datatype: datatypes.string, description: 'The owner/name of the repository this app syncs with.', }, + { + key: 'syncedTable', + shortname: 'synced-table', + name: 'Synced table', + datatype: `${A}/datatypes/atomicURL`, + description: + 'The table, not the app’s own, that this sync binding keeps in step with one GitHub repository (on a binding under the app).', + }, { key: 'syncState', shortname: 'github-sync-state', @@ -163,6 +180,17 @@ const PROPERTY_SPECS: PropertySpec[] = [ /** The provider extras kept on rows, declared as the App's `row-extras`. */ const ROW_EXTRAS: OwnProperty[] = ['number', 'provenance', 'baseline']; +/** + * Everything the app writes on rows beyond `issue-v1`'s own columns, as the + * App declares it in `row-extras`: the provider extras, and Atomic's + * `localId`, which the Bridge sets on each row it imports so a create a + * reload interrupted is found again instead of made twice. A row grant on + * another table covers only what is listed here (atomic-server#1849). + */ +export const rowExtras = ( + properties: Record, +): string[] => [...ROW_EXTRAS.map(key => properties[key]), LOCAL_ID]; + const asList = (value: JSONValue): string[] => Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') @@ -185,19 +213,46 @@ export async function findByLocalId( return undefined; } -async function ensureProperties( +/** The app's own properties its ontology already lists, by shortname. */ +async function listedProperties( store: PluginStore, ontology: PluginResource, -): Promise> { - const listed = asList(ontology.get(PROPERTIES)); +): Promise> { const byShortname = new Map(); - for (const subject of listed) { + for (const subject of asList(ontology.get(PROPERTIES))) { const property = await store.getResource(subject); const shortname = property.get(SHORTNAME); if (typeof shortname === 'string') byShortname.set(shortname, subject); } + return byShortname; +} + +/** The app's own properties, without creating any; undefined when one is missing. */ +async function existingProperties( + store: PluginStore, + ontology: PluginResource, +): Promise | undefined> { + const byShortname = await listedProperties(store, ontology); + const out = {} as Record; + + for (const spec of PROPERTY_SPECS) { + const subject = byShortname.get(spec.shortname); + if (!subject) return undefined; + out[spec.key] = subject; + } + + return out; +} + +async function ensureProperties( + store: PluginStore, + ontology: PluginResource, +): Promise> { + const listed = asList(ontology.get(PROPERTIES)); + const byShortname = await listedProperties(store, ontology); + const created: string[] = []; const out = {} as Record; @@ -307,29 +362,64 @@ function include( return true; } -/** The table shown is not this app's own (it was added as a view there). */ -export class OtherTable extends Error { - constructor() { - super( - 'This is another Issue table. Syncing a table this app did not make with GitHub is not built yet.', - ); - this.name = 'OtherTable'; - } +/** The table shown, and whether it is the app's own or one it is a view of. */ +export interface Where { + app: string; + table: string; + own: boolean; + rowClass?: string; +} + +export async function where(store: PluginStore): Promise { + const app = await store.getApp(); + const data = await store.getData(); + if (!data?.table) throw new Error('This app has no table to sync into.'); + const own = (await store.getResource(data.table)).get(PARENT) === app; + + return { + app, + table: data.table, + own, + ...(data.rowClass ? { rowClass: data.rowClass } : {}), + }; } /** - * Makes this app a view of `issue-v1` (#177 §5, item 3): `renders` lists - * the class, `row-extras` lists the app's row extras, and its own table's - * `classtype` is the class. Idempotent. Throws `OtherTable` when the table - * shown is not the app's own; `renders` and `row-extras` are set first. + * Makes this app a view of `issue-v1` (#177 §5, item 3): its own properties + * exist, `renders` lists the class and `row-extras` lists what it keeps on + * rows (`rowExtras`). Only the app's own subtree is written, so this runs + * on any table, and must run before the app asks for a row grant there: a + * grant covers the extras declared when it was given. Idempotent. */ -async function adopt( - store: PluginStore, - app: string, - table: string, - extras: string[], -): Promise { - const resource = await store.getResource(app); +interface Declared { + ontology: PluginResource; + properties: Record; +} + +/** + * One `declare` per view (per host `store`). The host's reads can lag the + * app's own saves (frameStore.ts), so a second run could read the ontology + * without the properties the first one made and make them again; the same + * `ontology` object is reused instead, as `provision` always did. + */ +const declaredBy = new WeakMap>(); + +function declare(store: PluginStore, at: Where): Promise { + let pending = declaredBy.get(store); + + if (!pending) { + pending = declareNow(store, at); + declaredBy.set(store, pending); + pending.catch(() => declaredBy.delete(store)); + } + + return pending; +} + +async function declareNow(store: PluginStore, at: Where): Promise { + const ontology = await appOntology(store, at.app, at.rowClass); + const properties = await ensureProperties(store, ontology); + const resource = await store.getResource(at.app); const renders = include( resource, await appProperty(store, resource, 'renders'), @@ -338,13 +428,198 @@ async function adopt( const declared = include( resource, await appProperty(store, resource, 'row-extras'), - extras, + rowExtras(properties), ); if (renders || declared) await resource.save(); - const own = await store.getResource(table); - if (own.get(PARENT) !== app) throw new OtherTable(); - if (own.get(CLASSTYPE) !== ISSUE_V1) - await own.set(CLASSTYPE, ISSUE_V1).save(); + + return { ontology, properties }; +} + +/** + * `declare`, then, on the app's own table, sets its `classtype` to + * `issue-v1`. A table the app is a view of is never written. + */ +async function adopt( + store: PluginStore, + at: Where, +): ReturnType { + const declared = await declare(store, at); + + if (at.own) { + const own = await store.getResource(at.table); + if (own.get(CLASSTYPE) !== ISSUE_V1) + await own.set(CLASSTYPE, ISSUE_V1).save(); + } + + return declared; +} + +/** + * On every open of the app's own table, before a repository is chosen too: + * `adopt`, so the App renders `issue-v1` and declares its row extras from + * the start and the host's "+ Add view" offers it on other Issue tables + * (#177 item 14). Writes nothing on a table the app is a view of. + */ +export async function adoptOwnTable(store: PluginStore): Promise { + const data = await store.getData(); + if (!data?.table) return; + const at = await where(store); + if (at.own) await adopt(store, at); +} + +/** + * What the app keeps on rows (`rowExtras`), declared on the App first when + * missing. For checking a row grant's `extras` before asking for one. + */ +export async function declareRowExtras(store: PluginStore): Promise { + return rowExtras((await declare(store, await where(store))).properties); +} + +/** + * What the app keeps on rows, as far as its ontology has the properties; + * undefined when one is missing (then no grant can cover them yet). Writes + * nothing. + */ +export async function rowExtrasNow( + store: PluginStore, +): Promise { + const at = await where(store); + const ontology = await appOntology(store, at.app, at.rowClass).catch( + () => undefined, + ); + const properties = ontology + ? await existingProperties(store, ontology) + : undefined; + + return properties ? rowExtras(properties) : undefined; +} + +/** + * The binding of the table shown, when it is one the app is a view of: a + * resource under the App whose `synced-table` names that table. `hint` is + * a subject the caller already knows (the host's `query` can miss a + * resource the page has not synced yet). Only one under the App counts: + * anyone can make a resource that names the table. + */ +async function findBinding( + store: PluginStore, + at: Where, + syncedTable: string, + hint?: string, +): Promise { + const ours = (r: PluginResource | undefined) => + r?.get(PARENT) === at.app && r.get(syncedTable) === at.table; + + if (hint) { + const known = await store.getResource(hint).catch(() => undefined); + if (known && ours(known)) return known; + } + + for (const subject of await store.query({ + property: syncedTable, + value: at.table, + })) { + const found = await store.getResource(subject).catch(() => undefined); + if (found && ours(found)) return found; + } + + return undefined; +} + +/** What `binding` reports about the sync of the table shown. */ +export interface Binding { + /** The sync resource (own table) or binding (another table). */ + subject: string; + repository?: string; +} + +/** + * The sync resource of the app's own table, or the binding of a table it is + * a view of; undefined when there is none yet, which on another table means + * "not synced". Writes nothing. + */ +export async function binding( + store: PluginStore, + hint?: string, +): Promise { + const data = await store.getData(); + if (!data?.table) return undefined; + const at = await where(store); + const ontology = await appOntology(store, at.app, at.rowClass).catch( + () => undefined, + ); + if (!ontology) return undefined; + const byShortname = await listedProperties(store, ontology); + let sync: PluginResource | undefined; + + if (at.own) sync = await findByLocalId(store, at.app, SYNC_LOCAL_ID); + else { + const syncedTable = byShortname.get('synced-table'); + if (!syncedTable) return undefined; + sync = await findBinding(store, at, syncedTable, hint); + } + + if (!sync) return undefined; + const property = byShortname.get('github-repository'); + const value = property ? sync.get(property) : undefined; + + return { + subject: sync.subject, + ...(typeof value === 'string' && value ? { repository: value } : {}), + }; +} + +/** + * "Sync this table to GitHub" on a table the app is a view of: makes its + * binding under the App when missing, with no repository yet (`provision` + * adds it). Writes only the app's own subtree. Returns its subject. + */ +export async function bindTable( + store: PluginStore, + hint?: string, +): Promise { + const at = await where(store); + if (at.own) throw new Error('The app’s own table needs no binding.'); + const { ontology, properties } = await declare(store, at); + const found = await findBinding(store, at, properties.syncedTable, hint); + if (found) return found.subject; + const syncClass = await ensureClass(store, ontology, properties); + const name = (await store.getResource(at.table)).get(NAME); + const made = await store.newResource({ + parent: at.app, + isA: [syncClass], + propVals: { + [NAME]: `GitHub sync of ${typeof name === 'string' && name ? name : 'a table'}`, + // AtomicServer keeps a localId unique per parent: one binding per table. + [LOCAL_ID]: `${SYNC_LOCAL_ID} ${at.table}`, + [properties.syncedTable]: at.table, + }, + }); + + return made.subject; +} + +/** + * "Not now" before a repository was chosen: the table goes back to not + * synced. A binding that already names a repository is kept. + */ +export async function unbindTable( + store: PluginStore, + hint?: string, +): Promise { + const at = await where(store); + if (at.own) return; + const ontology = await appOntology(store, at.app, at.rowClass); + const properties = await existingProperties(store, ontology); + if (!properties) return; + const found = await findBinding(store, at, properties.syncedTable, hint); + if (!found) return; + const repository = found.get(properties.repository); + if (typeof repository === 'string' && repository) return; + // Its comments folder, if any, goes first. + const comments = await findByLocalId(store, found.subject, COMMENTS_LOCAL_ID); + await comments?.destroy(); + await found.destroy(); } /** Whether the table shown is the app's own, not one it was added to as a view. */ @@ -413,7 +688,7 @@ export async function migrateRows( async function ensureClass( store: PluginStore, ontology: PluginResource, - recommends: string[], + properties: Record, ): Promise { const classes = asList(ontology.get(CLASSES)); @@ -429,8 +704,13 @@ async function ensureClass( [SHORTNAME]: 'github-issue-tracker-sync', [NAME]: 'GitHub issue tracker sync', [DESCRIPTION]: - 'Where the GitHub issues app keeps its bound repository and sync state.', - [RECOMMENDS]: recommends, + 'Where the GitHub issues app keeps a table’s bound repository and sync state: its own table’s, or, with the synced table named, another table’s.', + [RECOMMENDS]: [ + NAME, + properties.repository, + properties.syncState, + properties.syncedTable, + ], }, }); await ontology.set(CLASSES, [...classes, klass.subject]).save(); @@ -441,80 +721,66 @@ async function ensureClass( /** The bound repository, or undefined before one was chosen. */ export async function boundRepository( store: PluginStore, + hint?: string, ): Promise { - const app = await store.getApp(); - const sync = await findByLocalId(store, app, SYNC_LOCAL_ID); - if (!sync) return undefined; - const data = await store.getData(); - const ontology = await appOntology(store, app, data?.rowClass).catch( - () => undefined, - ); - if (!ontology) return undefined; - - for (const subject of asList(ontology.get(PROPERTIES))) { - const property = await store.getResource(subject); - if (property.get(SHORTNAME) !== 'github-repository') continue; - const value = sync.get(subject); - - return typeof value === 'string' && value ? value : undefined; - } - - return undefined; + return (await binding(store, hint))?.repository; } /** * Creates (or finds) everything above and binds `repository` on first use. - * A later call with another repository throws: one app, one repository. + * A later call with another repository throws: one table, one repository. + * On a table the app is a view of, the binding must exist (`bindTable`; + * `hint` is its subject when known): the repository, sync state and + * comments folder are kept there, and the table is never written. */ export async function provision( store: PluginStore, repository?: string, + hint?: string, ): Promise<{ tracker: Tracker; sync: PluginResource; repository: string; legacy?: Legacy; }> { - const app = await store.getApp(); - const data = await store.getData(); - if (!data?.table) throw new Error('This app has no table to sync into.'); - const ontology = await appOntology(store, app, data.rowClass); - const properties = await ensureProperties(store, ontology); - await adopt( - store, - app, - data.table, - ROW_EXTRAS.map(key => properties[key]), - ); - const legacy = await legacyStatus(store, ontology); + const at = await where(store); + const { app } = at; + const { ontology, properties } = await adopt(store, at); + const legacy = at.own ? await legacyStatus(store, ontology) : undefined; // The same `ontology` object: a fresh read could lag the save above, and // the host's `save` sends every property it holds, stale ones included. - const syncClass = await ensureClass(store, ontology, [ - NAME, - properties.repository, - properties.syncState, - ]); - - let comments = await findByLocalId(store, app, COMMENTS_LOCAL_ID); + const syncClass = await ensureClass(store, ontology, properties); + + let sync = at.own + ? await findByLocalId(store, app, SYNC_LOCAL_ID) + : await findBinding(store, at, properties.syncedTable, hint); + if (!at.own && !sync) + throw new Error('Choose “Sync this table to GitHub” first.'); + // Another table's comments go in a folder under its binding, so the two + // syncs never list each other's. + const commentsParent = at.own ? app : sync!.subject; + let comments = await findByLocalId(store, commentsParent, COMMENTS_LOCAL_ID); comments ??= await store.newResource({ - parent: app, + parent: commentsParent, isA: [FOLDER], propVals: { [NAME]: 'GitHub comments', [LOCAL_ID]: COMMENTS_LOCAL_ID, - [DESCRIPTION]: - 'Comments on the GitHub issues in this app’s table, as Messages about each row.', + [DESCRIPTION]: at.own + ? 'Comments on the GitHub issues in this app’s table, as Messages about each row.' + : 'Comments on the GitHub issues in the synced table, as Messages about each row.', }, }); - let sync = await findByLocalId(store, app, SYNC_LOCAL_ID); const bound = sync?.get(properties.repository); if (typeof bound === 'string' && bound) { if (repository && repository !== bound) throw new Error( - `This app is bound to ${bound}. Install another app for ${repository}.`, + at.own + ? `This app is bound to ${bound}. Install another app for ${repository}.` + : `This table syncs with ${bound}. It can’t switch to ${repository}.`, ); repository = bound; } @@ -531,11 +797,17 @@ export async function provision( [properties.repository]: repository, }, }); + } else if (bound !== repository) { + await sync.set(properties.repository, repository).save(); } - const table = await store.getResource(data.table); - const tableName = `${repository} issues`; - if (table.get(NAME) !== tableName) await table.set(NAME, tableName).save(); + // The app's own table is named after its repository; a table it is a + // view of keeps the name the person gave it (a grant never writes it). + if (at.own) { + const table = await store.getResource(at.table); + const tableName = `${repository} issues`; + if (table.get(NAME) !== tableName) await table.set(NAME, tableName).save(); + } return { repository, @@ -543,7 +815,7 @@ export async function provision( ...(legacy ? { legacy } : {}), tracker: { app, - table: data.table, + table: at.table, rowClass: ISSUE_V1, properties: { status: TASK_STATUS, body: TASK_BODY, ...properties }, tags: TASK_TAGS, diff --git a/integrations/issue-tracker/app/views.test.ts b/integrations/issue-tracker/app/views.test.ts index 3f48b317f..dc06d6ba3 100644 --- a/integrations/issue-tracker/app/views.test.ts +++ b/integrations/issue-tracker/app/views.test.ts @@ -9,6 +9,7 @@ import { SEEDED_REPOSITORY } from '../fixtures/github-issues/scenario.mjs'; import { createController } from './controller.js'; import { fakeStore, type FakeStore } from './fakeStore.js'; import { view } from './main.js'; +import { ISSUE_V1 } from './tracker.js'; const wait = (ms = 0) => new Promise(r => setTimeout(r, ms)); @@ -120,6 +121,42 @@ describe('first run', () => { }); }); +describe('an Issue table the app didn’t make (#177 item 14)', () => { + const teamStore = () => { + const store = fakeStore({ table: 'did:ad:team', connected: false }); + store.resources.set('did:ad:team', { + 'https://atomicdata.dev/properties/parent': 'did:ad:drive', + 'https://atomicdata.dev/properties/name': 'Team issues', + 'https://atomicdata.dev/properties/classtype': ISSUE_V1, + }); + + return store; + }; + + it('offers Sync this table, asks the host, then sets up with the table’s name and Not now', async () => { + const { root, store } = await mount({ store: teamStore(), bind: false }); + expect(root.textContent).toContain('Team issues isn’t synced with GitHub.'); + const sync = q(root, '[data-key=sync-table]'); + expect(sync.textContent).toBe('Sync this table to GitHub'); + sync.click(); + await settle(root); + expect(store.asked).toBe(1); + expect(q(root, 'h2').textContent).toBe('Sync Team issues with GitHub'); + q(root, '[data-key=not-now]').click(); + await settle(root); + expect(q(root, '[data-key=sync-table]')).not.toBeNull(); + }); + + it('has no Sync button on a host without the row grant', async () => { + const store = Object.assign(teamStore(), { requestRowAccess: undefined }); + const { root } = await mount({ store, bind: false }); + expect(root.textContent).toContain( + 'can’t let an app edit another table’s rows', + ); + expect(root.querySelectorAll('.pl-empty button')).toHaveLength(0); + }); +}); + describe('board and list', () => { it('defaults to the board at 1000 px and the list at 380 px', async () => { expect( diff --git a/integrations/issue-tracker/app/views.ts b/integrations/issue-tracker/app/views.ts index 3a22ca881..bf03b2d7b 100644 --- a/integrations/issue-tracker/app/views.ts +++ b/integrations/issue-tracker/app/views.ts @@ -7,6 +7,8 @@ import { describe, describeHeld, + PAUSED_NOTE, + SYNC_NOTE, type Ready, type RepositoryListing, type ViewState, @@ -101,6 +103,11 @@ export interface Ui { canDisconnect?: boolean; /** Asking to confirm "Remove from board" (state 13). */ confirmRemove?: boolean; + /** + * The name of the table shown when the app didn't make it (`controller + * .foreign()`); absent on the app's own table. + */ + table?: string; /** Rows to highlight after new data arrived. */ flash: Set; /** Seconds until the automatic retry after a transient failure. */ @@ -132,6 +139,10 @@ export interface Actions { sendAgain(subject: string): void; /** "Publish to GitHub" for a local-only row (#177 Q6). */ publish(subject: string): void; + /** "Sync this table to GitHub" on a table the app didn't make (#177 item 14). */ + syncTable(): void; + /** Back to not synced, before a repository was chosen there. */ + notNow(): void; } const GLYPH: Record = { @@ -400,7 +411,7 @@ function bannerNode( ui: Ui, actions: Actions, ): HTMLElement | null { - const model = bannerFor(state, ui.confirmRemove); + const model = bannerFor(state, ui.confirmRemove, ui.table === undefined); if (!model || state.kind !== 'ready') return null; const run = ({ @@ -447,6 +458,58 @@ function bannerNode( // ---------------------------------------------------------------- setup +/** + * An Issue table the app didn't make, not synced (or paused): the offer to + * sync it, or why it can't be synced from here. + */ +function otherTable( + state: Extract, + ui: Ui, + actions: Actions, +): HTMLElement { + const name = ui.table ?? 'This table'; + const paused = state.reason === PAUSED_NOTE; + + return empty( + paused ? 'paused' : 'inbox', + paused + ? `Syncing ${name} with GitHub is paused.` + : `${name} isn’t synced with GitHub.`, + paused + ? 'This app may no longer edit this table’s rows, or keep its GitHub issue numbers on them. Allow editing again to go on. Nothing is sent or written while it is paused.' + : (state.reason ?? + (state.canSync + ? SYNC_NOTE + : 'This Atomic Server can’t let an app edit another table’s rows, so it can’t be synced from here. Nothing was changed.')), + state.canSync + ? button( + state.asking + ? 'Waiting for you to allow editing…' + : paused + ? 'Allow editing again' + : 'Sync this table to GitHub', + () => actions.syncTable(), + { + kind: 'primary', + disabled: !!state.asking, + 'data-key': 'sync-table', + }, + ) + : undefined, + true, + ); +} + +/** "Not now" on the setup screens of a table the app didn't make. */ +function notNow(ui: Ui, actions: Actions): HTMLElement | null { + return ui.table === undefined + ? null + : button('Not now', () => actions.notNow(), { + kind: 'ghost', + 'data-key': 'not-now', + }); +} + function noProxy(): HTMLElement { return empty( 'server', @@ -457,7 +520,7 @@ function noProxy(): HTMLElement { ); } -function sources(state: ViewState, actions: Actions): HTMLElement { +function sources(state: ViewState, ui: Ui, actions: Actions): HTMLElement { const connecting = state.kind === 'connecting'; const row = ( name: string, @@ -485,11 +548,19 @@ function sources(state: ViewState, actions: Actions): HTMLElement { h( 'div', { class: 'onboard' }, - h('h2', null, 'Bring your issues into this drive'), + h( + 'h2', + null, + ui.table === undefined + ? 'Bring your issues into this drive' + : `Sync ${ui.table} with GitHub`, + ), h( 'p', { class: 'lede' }, - 'Pick where your issues live today. They stay there; this board mirrors them into an Atomic table you can link, search and query.', + ui.table === undefined + ? 'Pick where your issues live today. They stay there; this board mirrors them into an Atomic table you can link, search and query.' + : 'The repository’s issues are added to this table as rows; the rows already here stay here until you publish them. Nothing is sent to GitHub until you review it.', ), h( 'ul', @@ -531,6 +602,7 @@ function sources(state: ViewState, actions: Actions): HTMLElement { ? 'Confirm the connection in the bar Atomic Server shows above this app.' : 'Connecting opens a confirmation bar from Atomic Server, then your provider’s sign-in. This app never sees your password or token.', ), + connecting ? null : notNow(ui, actions), ), ); } @@ -661,7 +733,13 @@ function chooseRepository( h( 'div', { class: 'onboard' }, - h('h2', null, 'Which repository?'), + h( + 'h2', + null, + ui.table === undefined + ? 'Which repository?' + : `Which repository should ${ui.table} sync with?`, + ), body, state.error ? h('p', { class: 'field-error', role: 'alert' }, state.error) @@ -706,13 +784,16 @@ function chooseRepository( h( 'li', null, - 'Nothing is ever deleted on GitHub. One app syncs one repository.', + ui.table === undefined + ? 'Nothing is ever deleted on GitHub. One app syncs one repository.' + : 'Nothing is ever deleted, on GitHub or in this table. This table syncs with one repository, and never switches.', ), ), ), h( 'div', { class: 'actions-row' }, + busy ? null : notNow(ui, actions), button( busy ? `Setting up ${state.settingUp}…` : `Import ${target}`, () => choice && actions.choose(choice), @@ -1972,23 +2053,14 @@ export function page( if (state.kind === 'no-proxy') return [top, noProxy()]; if (state.kind === 'other-table') - return [ - top, - empty( - 'inbox', - 'This Issue table was not made by this app.', - 'Syncing an existing table with GitHub is not built yet. Open the GitHub issues app itself to see and sync its own table. Nothing was changed here.', - undefined, - true, - ), - ]; + return [top, otherTable(state, ui, actions)]; if (state.kind === 'loading') return [ top, h('p', { class: 'lede', style: 'padding:24px 16px' }, 'Loading…'), ]; if (state.kind === 'not-connected' || state.kind === 'connecting') - return [top, sources(state, actions)]; + return [top, sources(state, ui, actions)]; if (state.kind === 'choose-repository') return [ top, diff --git a/integrations/issue-tracker/e2e/issue-tracker.spec.ts b/integrations/issue-tracker/e2e/issue-tracker.spec.ts index 9bb2e9303..43faf4732 100644 --- a/integrations/issue-tracker/e2e/issue-tracker.spec.ts +++ b/integrations/issue-tracker/e2e/issue-tracker.spec.ts @@ -26,6 +26,12 @@ * existing connection", with no reload: the app syncs again by itself * (#196 user test; it used to stop at an unsynced board). * + * A second test (#177 item 14, since 0.3.0): an `issue-v1` table the person + * made by hand, "+ Add view" → GitHub issues (Read-only), "Sync this table + * to GitHub", the host's "Allow editing" bar, connect, choose a repository + * of its own (seeded with the fixture's `createIssue` driver), import into + * that table, and a status edit made in the table sent after review. + * * The rows are of the shared class at its published GitHub Pages subject, * which the pinned server and the browser fetch from Pages themselves, as * in production (ontology-kit/README.md, "Plugin e2e tests and the @@ -48,8 +54,10 @@ import { before } from '../../../browser/e2e/tests/test-utils'; const APP_FRAME = 'iframe[title="App"]'; /** The catalog's version of this app (integrations/catalog.json). */ -const VERSION = '0.2.0'; +const VERSION = '0.3.0'; const REPOSITORY = 'atomic-fixture/tracker'; +/** Seeded by the item 14 test itself, through the fixture's createIssue driver. */ +const TEAM_REPOSITORY = 'atomic-fixture/team-board'; const NAME = 'https://atomicdata.dev/properties/name'; const CLASSTYPE = 'https://atomicdata.dev/properties/classtype'; const PARENT = 'https://atomicdata.dev/properties/parent'; @@ -351,9 +359,13 @@ test.describe('GitHub issues drive app', () => { // The connection lives at the proxy, owned by the signed-in user and // delegated to this app; the page keeps nothing credential-like. - const connections = await proxyConnections('github-issues'); + // Only this test's agent's: the other test connects its own, in parallel. + const me = await signedInAgent(page); + const mine = async () => + (await proxyConnections('github-issues')).filter(c => c.owner === me); + const connections = await mine(); expect(connections).toHaveLength(1); - expect(connections[0].owner).toBe(await signedInAgent(page)); + expect(connections[0].owner).toBe(me); expect(connections[0].delegations).toHaveLength(1); expect(await page.evaluate(() => Object.keys(localStorage))).not.toEqual( expect.arrayContaining([ @@ -368,9 +380,7 @@ test.describe('GitHub issues drive app', () => { await app.getByRole('button', { name: 'Connection menu' }).click(); await app.getByRole('menuitem', { name: 'Disconnect GitHub' }).click(); await expect(status).toContainText('Not connected', { timeout: 30_000 }); - expect((await proxyConnections('github-issues'))[0].delegations).toEqual( - [], - ); + expect((await mine())[0].delegations).toEqual([]); await app.getByRole('button', { name: 'Connect GitHub' }).click(); await consent .getByRole('button', { name: 'Use existing connection' }) @@ -389,10 +399,202 @@ test.describe('GitHub issues drive app', () => { ); await expect(status).toContainText('Synced'); expect(page.url()).toBe(appUrl); - const again = await proxyConnections('github-issues'); + const again = await mine(); expect(again).toHaveLength(1); expect(again[0].delegations).toHaveLength(1); }); + + test('syncs a hand-made issue-v1 table with GitHub after Allow editing, and sends a reviewed status edit (#177 item 14)', async ({ + page, + }) => { + test.skip( + !process.env.ATOMIC_MOCK_INTEGRATION_PROXY || + !process.env.INTEGRATION_PROXY_URL, + 'Run with the documented mock integration-proxy server configuration', + ); + test.setTimeout(300_000); + const issueV1 = ( + (await import('../../../ontology-kit/terms.mjs' as string)) as { + classes: Record; + } + ).classes['issue-v1'].subject; + // A repository of its own, so the other test's edits can't race this one. + for (const title of ['Book the venue', 'Write the agenda']) + await fixture('createIssue', [TEAM_REPOSITORY, { title, body: '' }]); + + await installFromCatalog(page); + const app = page.frameLocator(APP_FRAME); + await expect(app.getByRole('status')).toContainText('Not connected', { + timeout: 45_000, + }); + const appSubject = new URL(page.url()).searchParams.get('subject')!; + // The first open makes the App a view of issue-v1, before connecting. + await expect + .poll( + async () => + page.evaluate( + async ({ subject, wanted }) => { + const store = window.store!; + const resource = await store.fetchResourceFromServer(subject, { + noWebSocket: true, + }); + + return Object.values(resource.getPropVals()).some( + v => Array.isArray(v) && v.includes(wanted), + ); + }, + { subject: appSubject, wanted: issueV1 }, + ), + { timeout: 30_000 }, + ) + .toBe(true); + + // A table the person made, of the shared class, with one row of theirs. + const table = await page.evaluate( + async ({ klass, name, classtype, task }) => { + const store = window.store!; + const made = await store.newResource({ + parent: store.getDrive(), + isA: ['https://atomicdata.dev/classes/Table'], + propVals: { [name]: 'Team issues', [classtype]: klass }, + }); + await made.save(); + const row = await store.newResource({ + parent: made.subject, + isA: [klass], + propVals: { + [name]: 'Plan the offsite', + [`${task}/status`]: [`${task}/todo`], + }, + }); + await row.save(); + + return made.subject; + }, + { klass: issueV1, name: NAME, classtype: CLASSTYPE, task: TASK }, + ); + await page.goto( + `${new URL(page.url()).origin}/app/show?subject=${encodeURIComponent(table)}`, + ); + await page + .getByRole('main') + .getByRole('button', { name: 'Add view' }) + .click(); + await page + .getByRole('menuitem', { name: 'GitHub issues' }) + .click({ timeout: 60_000 }); + // Read-only first: the sync asks for itself. + await page + .locator('dialog[open]') + .getByRole('button', { name: 'Read-only' }) + .click(); + await expect( + app.getByText('Team issues isn’t synced with GitHub.'), + ).toBeVisible({ timeout: 45_000 }); + await app + .getByRole('button', { name: 'Sync this table to GitHub' }) + .click(); + // The host's own bar asks, outside the frame. + const ask = page.getByRole('group', { name: 'Let this app edit rows' }); + await expect(ask).toBeVisible({ timeout: 30_000 }); + await ask.getByRole('button', { name: 'Allow editing' }).click(); + + // No connection yet: connect as on the app's own page. Coming back from + // the proxy reloads the page, and the app goes on. + await expect( + app.getByRole('heading', { name: 'Sync Team issues with GitHub' }), + ).toBeVisible({ timeout: 45_000 }); + await app.getByRole('button', { name: 'Connect GitHub' }).click(); + const consent = page.getByRole('group', { name: 'Connect an account' }); + await consent.getByRole('button', { name: 'Connect', exact: true }).click(); + await page + .getByRole('button', { + name: 'Use LocalThought to sync GitHub Issues with this destination', + exact: true, + }) + .click(); + await expect(page).not.toHaveURL(/connection_code=|integration_state=/); + await expect( + app.getByRole('heading', { + name: 'Which repository should Team issues sync with?', + }), + ).toBeVisible({ timeout: 45_000 }); + await app.getByRole('radio', { name: new RegExp(TEAM_REPOSITORY) }).check(); + await app + .getByRole('button', { name: `Import ${TEAM_REPOSITORY}` }) + .click(); + const bar = app.locator('.pl-conn'); + await expect(bar).toHaveAttribute( + 'title', + /2 issues and 0 comments in sync with atomic-fixture\/team-board/, + { timeout: 60_000 }, + ); + + // GitHub's issues are rows of that table now, with the app's extras; the + // person's own row is as it was; the table kept its name and class. + const issueRows = async () => + (await rowsUnder(page, table)).filter(r => + (r[IS_A] as unknown[] | undefined)?.includes(issueV1), + ); + const rows = await issueRows(); + expect(rows).toHaveLength(3); + expect(rows.map(r => r['github-issue-number']).sort()).toEqual([ + 1, + 2, + undefined, + ]); + + for (const row of rows.filter(r => r[NAME] !== 'Plan the offsite')) { + expect(row[IS_A]).toEqual([issueV1]); + expect(row['github-sync-baseline']).toEqual(expect.any(String)); + } + + expect(rows.find(r => r[NAME] === 'Plan the offsite')).not.toHaveProperty( + 'github-issue-number', + ); + const after = await page.evaluate( + async ({ subject, name, classtype }) => { + const t = await window.store!.fetchResourceFromServer(subject, { + noWebSocket: true, + }); + + return { name: t.get(name), classtype: t.get(classtype) }; + }, + { subject: table, name: NAME, classtype: CLASSTYPE }, + ); + expect(after).toEqual({ name: 'Team issues', classtype: issueV1 }); + // The repository choice is kept under the App, naming the table. + expect(await bindingFor(page, appSubject, table)).toBe(TEAM_REPOSITORY); + + // A status edit made in the table, as the signed-in person, is reviewed + // and then sent. + const first = rows.find(r => r['github-issue-number'] === 1)! + .subject as string; + await setStatus(page, first, 'done'); + await app.getByRole('button', { name: 'Sync now' }).click(); + await app + .getByRole('button', { name: 'Review and send' }) + .click({ timeout: 30_000 }); + const review = app.getByRole('region', { + name: 'Changes to send to GitHub', + }); + await expect(review).toContainText( + 'Update #1: status Todo → Done (close it)', + ); + expect((await teamIssue(1)).state).toBe('open'); + await app.getByRole('button', { name: 'Send 1 change to GitHub' }).click(); + await expect(bar).toHaveAttribute('title', /1 sent to GitHub/, { + timeout: 30_000, + }); + expect((await teamIssue(1)).state).toBe('closed'); + await expect + .poll(async () => { + const row = (await issueRows()).find(r => r.subject === first); + + return JSON.parse(String(row?.['github-sync-baseline'] ?? '{}')).status; + }) + .toBe('Done'); + }); }); /** A card (board) or row (list) by its "#n" reference. */ @@ -465,6 +667,94 @@ async function github( return issue; } +/** An issue of `TEAM_REPOSITORY`, as the mock's github-issues fixture has it. */ +async function teamIssue(number: number): Promise> { + const { issues } = (await fixture('snapshot', [TEAM_REPOSITORY])) as { + issues: { number: number }[]; + }; + const issue = issues.find(i => i.number === number); + if (!issue) throw new Error(`No issue #${number}`); + + return issue; +} + +/** + * The resources under `table`, read from the server, with `subject`. The + * app's own properties are keyed by shortname; atomicdata.dev terms keep + * their URL. + */ +async function rowsUnder( + page: Page, + table: string, +): Promise[]> { + return page.evaluate(async (subject: string) => { + const store = window.store!; + const collection = await ( + await store.getResource(subject) + ).getChildrenCollection(500); + const out: Record[] = []; + + for (const member of await collection.getAllMembers()) { + const row = await store.fetchResourceFromServer(member, { + noWebSocket: true, + }); + const named: Record = { subject: member }; + + for (const [property, value] of Object.entries(row.getPropVals())) { + const shortname = property.startsWith('https://atomicdata.dev/') + ? undefined + : (await store.getResource(property)).get( + 'https://atomicdata.dev/properties/shortname', + ); + named[typeof shortname === 'string' ? shortname : property] = value; + } + + out.push(named); + } + + return out; + }, table); +} + +/** + * The repository on the App's binding for `table`: a child of the App whose + * `synced-table` names it. + */ +async function bindingFor( + page: Page, + app: string, + table: string, +): Promise { + return page.evaluate( + async ({ appSubject, tableSubject }) => { + const store = window.store!; + const children = await ( + await store.getResource(appSubject) + ).getChildrenCollection(500); + + for (const member of await children.getAllMembers()) { + const child = await store.fetchResourceFromServer(member, { + noWebSocket: true, + }); + const named: Record = {}; + + for (const [property, value] of Object.entries(child.getPropVals())) { + const shortname = (await store.getResource(property)).get( + 'https://atomicdata.dev/properties/shortname', + ); + named[String(shortname)] = value; + } + + if (named['synced-table'] === tableSubject) + return named['github-repository']; + } + + return undefined; + }, + { appSubject: app, tableSubject: table }, + ); +} + /** One github-issues fixture driver on the mock proxy. */ async function fixture(name: string, args: unknown[]): Promise { const response = await fetch( diff --git a/usertest/catalog.mjs b/usertest/catalog.mjs index 499ccb218..ab025ef9d 100755 --- a/usertest/catalog.mjs +++ b/usertest/catalog.mjs @@ -60,7 +60,7 @@ const I = 'https://atomicdata.dev/integrations/properties/'; /** Drive apps built here. `base` is the catalog entry whose copy they reuse. */ const VERSIONS = { calendar: 'usertest-10', - 'issue-tracker': 'usertest-6', + 'issue-tracker': 'usertest-7', money: 'usertest-2', notion: 'usertest-4', timesheets: 'usertest-5',