From de77259e52d42c799e10416d0162255045091bd7 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 29 Sep 2026 12:29:38 +0000 Subject: [PATCH 1/6] docs: design proposal for domain bundles of views, reflectors, importers and lenses Records Michiel's decisions (catalog lists bundles, bundles per domain, built-in views on the same contract as plugin views, inline only for host-compiled bundles) and proposes the catalog shape, repo layout, atomic-server requirements and order of work. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01L5aQY5QYngBKqaPkmCFZWM --- docs/design/bundles.md | 291 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 291 insertions(+) create mode 100644 docs/design/bundles.md diff --git a/docs/design/bundles.md b/docs/design/bundles.md new file mode 100644 index 000000000..1882fd662 --- /dev/null +++ b/docs/design/bundles.md @@ -0,0 +1,291 @@ +# Bundles: organising plugins by what they do + +Status: **proposal, not reviewed. Nothing here is implemented.** It builds on +the decisions recorded in +[#177](https://github.com/ontola/atomic-plugins/issues/177) (shared row +classes, "option 4") and on the placements of +[`server-plugin-routes.md`](server-plugin-routes.md) (#88). Where it changes an +earlier decision, it says so. Facts about the host were taken from #177 §1.1, +which checked them at atomic-server `2567fc30b`. They were not re-checked +against the current `.atomic-server-ref`. + +Decided by Michiel (2026-09-29): + +1. **The catalog lists bundles.** A bundle is the unit a person finds, + installs and removes. +2. **A bundle holds parts of several kinds.** The kinds include reflectors + (keeping a native table of a row class in sync with a remote dataset) and + custom views (ways to show tables of a row class). +3. **Bundles are per domain, not per provider.** The Calendar bundle holds + the event views and every reflector that fills an event table (Google + Calendar now, CalDAV later). It is not a "Google" bundle. +4. **Built-in table views work the same way as plugin views.** The only + difference is that they may run in the host page without an iframe. This + **amends #177 decision 7 (Q3)**, which kept the built-in Calendar, Issues + and Timer views as they were and left their evolution for later. + +Everything below these four points is proposed. + +Contents: + +1. [Terms](#1-terms) +2. [The domain bundles](#2-the-domain-bundles) +3. [Catalog shape](#3-catalog-shape) +4. [Built-in views as a bundle](#4-built-in-views-as-a-bundle) +5. [Repository layout](#5-repository-layout) +6. [Host requirements (atomic-server)](#6-host-requirements-atomic-server) +7. [Order of work](#7-order-of-work) +8. [Open questions](#8-open-questions) + +--- + +## 1. Terms + +- **Row class.** The `classtype` of a table. A part says which row classes it + works on by exact subject: one of the #177 shared classes + (`event-v1`, `issue-v1`, `time-entry-v1`, `bank-transaction-v1`, …) or a + class the bundle defines itself. +- **Bundle.** One catalog entry: a domain name, card copy, a version, and a + list of parts. It installs and uninstalls as a whole. A part can't be + installed without its bundle. Whether a person can switch single parts off + is open (§8, Q3). +- **Part.** One piece of code with one kind. The kinds: + +| Kind | What it does | Declares | Placement (#88) | Exists today as | +| ------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | --------------- | --------------------------------------------------------------------------------- | +| **view** | Shows (and, with "Allow editing", edits) any table whose row class it renders, including hand-made tables and tables no reflector filled | `renders`: row classes, exact subjects | A | Drive apps and their `renders` list; offered through "+ Add view" (`appsForClass`) | +| **reflector** | Keeps a native table of a row class in sync with a linked dataset behind a remote API, one or both ways | `rowClass`, `platform`, `direction` (`read` or `two-way`), provider extras | A, later B | The "sync part" of #177 §3 | +| **importer** | Turns a file the person hands over into rows of a row class, once per upload. Nothing is kept in sync afterwards | `rowClass`, `accepts` (file types and size limits) | B | Sandbox plugins with `accepts`/`destination` (`money/`, `willow-drop/`) | +| **lens** | Maps rows of one class onto another, both ways, so a view of the target class works on a table of the source class | `from`, `to` | A (open, Q14) | Devonian `AtomicLens`; the resolver's lens hooks in `ontology-kit/` | + +Importers are a separate kind from reflectors on purpose. A reflector +promises that the table and the remote dataset stay in step, and a person +should be able to trust that word. An importer makes no such promise. + +Lenses were not in the first sketch of this idea. They are included because +#177 decision 5 makes a lens the only way a view reaches a table of another +class. A view without the lens that makes it reachable is often useless. + +## 2. The domain bundles + +A mapping of what exists today onto domain bundles. "Declared" means catalog +copy or code without host evidence, as in [READINESS.md](../integrations/READINESS.md). + +| Bundle | Row class(es) | Views | Reflectors | Importers | Lenses (planned) | Folder today | Catalog entries today | +| ------------ | ---------------------------------- | --------------------------------------------------------------------- | -------------------------------------------------------- | ---------------------------------------- | -------------------------------------------- | ------------------------------------------------- | ---------------------------------------- | +| **Calendar** | `event-v1` | `calendar/app/`; built-in Calendar | Google Calendar (`calendar/devonian/google-calendar/`) | – | – | `calendar/` | `devonian-google-calendar` | +| **Issues** | `issue-v1` | `issue-tracker/app/`; built-in Issues | GitHub (`issue-tracker/devonian/github-issues/`), Todoist (read) | – | Issue Tracker template → `issue-v1` | `issue-tracker/` | `devonian-todoist` (GitHub has none) | +| **Time** | `time-entry-v1` (+ `work-project-v1`, `work-person-v1`) | `timesheets/app/`; built-in Timer | Clockify (`timesheets/devonian/clockify/`), read | – | Time tracker template → `time-entry-v1` | `timesheets/` | `timesheets` | +| **Money** | `bank-transaction-v1` | `money/app/` | Moneybird (declared only) | MT940 and camt.053 (`money/plugin.ts`) | – | `money/` | `money`, `moneybird` | +| **Tables** | Per data source (no shared class) | Built-in table view | Notion (`notion/app/`, `notion/plugin.ts`) | – | – | `notion/` | `notion` | +| **Pets** | Its own `Pet` class | `pets/app/` | Mock `pets` platform | – | – | `pets/` | `pets` | +| **Willow** | Its own entry class | – | – | Willow drop (`willow-drop/`) | – | `willow-drop/` | `willow-drop` | + +Notes: + +- The folders are already mostly domain-shaped. The bundle only makes that + explicit, and adds the built-in views to each domain. +- **Notion has no domain.** A Notion data source can be anything, so its + reflector writes a per-source class. "Tables" is a placeholder name for a + bundle of generic reflectors whose only view is the built-in table view. + Q2 asks whether that is the right home. +- **Pets stays a demo bundle.** It exists to exercise the drive-app path end + to end, and its catalog card still describes the static sandbox demo + (READINESS.md). +- **Server protocol packages are not domain bundles.** `atproto/`, + `nextgraph/`, `open-cloud-mesh/`, `solid/` and `willow/` are protocol + endpoints (placements C, D, E), not table sync or views. Q1 asks whether + they get a part kind of their own (`route`) or stay outside this model. +- A bundle may list a reflector with no host entry point yet, as today's + catalog lists `devonian-todoist`. The bundle's card must then say which + parts work, per the "declared, not verified" rule. + +## 3. Catalog shape + +Proposed: `PluginCatalogEntry` is replaced by `Bundle`, whose `parts` are +nested resources. The card fields (`experimental`, `enabled`, `limitation`, +`keywords`, `capabilities`, `requires`) move to the bundle. Each part keeps +what is specific to it. Property subjects are abbreviated here. + +```jsonc +{ + "@id": "https://atomicdata.dev/integrations/bundles/calendar", + "isA": ["https://atomicdata.dev/integrations/classes/Bundle"], + "shortname": "calendar", + "name": "Calendar", + "version": "0.1.0", + "experimental": true, + "enabled": false, // uses the github.io ontology base (#177 decision 4) + "limitation": ["Single, non-recurring events only."], + "parts": [ + { + "kind": "view", + "shortname": "calendar-view", + "renders": ["/classes/event-v1"], + "app-module": "https://ontola.github.io/atomic-plugins/apps/calendar/0.1.0/ui.js", + "app-module-integrity": "sha384-…" + }, + { + "kind": "reflector", + "shortname": "google-calendar", + "rowClass": "/classes/event-v1", + "platform": "google-calendar", + "direction": "two-way", + "runs-in": "calendar-view" // placement A: runs inside that view's module + } + ] +} +``` + +- **One published module per bundle version, or per part.** Today a drive + app is one `apps///ui.js`, and the calendar app already holds + both the view and the Google sync. Proposed: a reflector that runs in a + view's module names it with `runs-in` and has no module of its own. A + reflector that must also run in the background (B, once H11 exists) gets + its own sandbox bundle. Q4 asks whether to split them further. +- **Versioning.** The bundle has one version. `apps.mjs`' rule that a + published file on `main` is never changed stays unchanged; paths become + `apps///.js` for bundles with more than one module. +- **Host impact now:** none. At the pin the host reads only `shortname`, + `enabled`, `experimental` and `requires-api-plugins` from the catalog + (READINESS.md). The check that `version` equals the package's + (`integrations/README.md`, "Version and catalog entry") and + `catalog-requires.mjs` move from entries to bundles. + +## 4. Built-in views as a bundle + +**Proposal:** the data browser ships a bundle of its own, `builtin`, whose +views are the built-in Calendar, Issues, Timer and table views. They are +offered, listed and matched by the same code path as plugin views. The only +difference is a trust level that lets them skip the iframe. + +### 4.1 Same contract + +- Each built-in view declares `renders`, and "+ Add view" offers it through + `appsForClass`, just as it offers plugin views. The generic table view + renders every class. +- Each implements `view({ root, store })` against the same `store` API a + drive app gets from `hostStore.ts`. The host calls it in the page instead + of posting messages to a frame. +- Each is bound by the same grants: row edits only after "Allow editing" + (#1788), only the class's `requires`/`recommends`, never `destroy`, never + `parent`, `isA`, rights, the table or its views. + +The benefit is that the built-in views become the reference implementation +of the plugin view API. Anything they need, plugin views can have too. It +also becomes a policy question, not a rewrite, to move a built-in view into +an iframe or to vet a plugin view into the trusted set. + +### 4.2 The "inline" trust level + +- A part may run without an iframe only if it is in a bundle **compiled + into the host build**. A remote catalog entry cannot request it. A + catalog, even this repository's, is data fetched at runtime (Settings → + Integration can point it elsewhere), and one edit to it must never be + able to put third-party code into the host page. +- "Inline" grants **no extra capability**. It removes the isolation, not a + permission. Without the iframe, the grants above are kept by the view + calling only the `store` API, which is enforced by code review, not by + the browser. The server-side checks (the row grant in + `app_row_grant.rs`, `refuseOutsideApp`) apply in both cases if the + in-page `store` goes through the same path. That was not checked; see + H-B3. + +### 4.3 What changes in matching + +This is the costly part. Today the built-in views recognise tables by +shortname: Calendar by the `calendarFields` shortnames, Timer by the `work-*` +terms `timeTrackingSchema` mints **per drive**, Issues by the task/v1 +subjects (#177 §1.1, §2). Declaring `renders` with the shared classes means: + +- **Calendar and Issues** can render `event-v1` and `issue-v1` directly. + Those classes reuse the same shortnames and task/v1 subjects (#177 §2.2, + §2.3). +- **Timer** can't. `time-entry-v1`'s `work-*` properties are new subjects, + not the per-drive ones (#177 §2.4). Existing Time tracker tables need a + lens (§3.1 of #177) or a migration, or Timer keeps its old match as a + second path during a transition. +- **Tables made from the templates** keep their own classes until H3 (#177 + §7: templates use the shared classes). Without H3 or a lens, switching a + built-in view to strict matching would stop offering it on tables it is + offered on today. So the switch must wait for H3 plus lenses, or keep + the shortname match as a fallback for the built-in bundle only. #177 + decision 5 (strict matching) is about plugin views, so a built-in + fallback doesn't break it, but it is a difference between the two that + this design is meant to remove. Q5. + +## 5. Repository layout + +Proposed: keep `integrations//`, one folder per domain bundle, and +rename only where the folder name is a provider or doesn't name the domain: + +| Today | Proposed | +| ---------------------------- | ------------------------------------------------- | +| `integrations/calendar/` | unchanged | +| `integrations/issue-tracker/` | `integrations/issues/` | +| `integrations/timesheets/` | `integrations/time/` | +| `integrations/money/` | unchanged | +| `integrations/notion/` | `integrations/tables/notion/` (Q2) | +| `integrations/willow-drop/` | `integrations/willow/` next to the protocol scaffold, or unchanged (Q1) | + +Inside a bundle folder, parts get a subfolder per kind only when a bundle +has more than one part of that kind, for example +`issues/reflectors/github/` and `issues/reflectors/todoist/`. The existing +convention that a Devonian lens for a platform lives at +`/devonian//` stays. Renames are a separate PR per +bundle, after the catalog change, because `lanes.json`, CI paths and the +e2e specs name these folders. + +## 6. Host requirements (atomic-server) + +Nothing here is assumed to happen. H2 and H3 are #177's numbers. + +1. **H-B1: install a bundle from the catalog.** `installCatalogApp` installs + every part of a bundle, and uninstall removes them together. Supersedes + the per-app install of [#94](https://github.com/ontola/atomic-plugins/issues/94); + includes #177's H2 (the catalog declares `rowClass` and `renders`). +2. **H-B2: a view registry that built-in views register in.** `appsForClass` + (or its successor) lists built-in and installed views from one registry, + by `renders`. `TableViewTabs` renders both kinds from it. +3. **H-B3: an in-page `store`.** The `hostStore.ts` operations, callable + directly by an inline view, going through the same grant checks as the + frame path. Whether those checks are all in the frame message handler or + partly shared with the server was not checked. +4. **H-B4: the inline trust level.** Honoured only for bundles compiled into + the host build (§4.2). +5. **#177 H3: templates use the shared classes.** A prerequisite for the + built-in views to match strictly (§4.3). + +## 7. Order of work + +1. Review this document and answer §8. +2. **No host change:** restructure `catalog.json` into bundles (§3), update + `catalog-requires.mjs`, the version check and READINESS.md to read + bundles, one PR. Host behaviour at the pin is unchanged. +3. **No host change:** folder renames (§5), one PR per bundle. +4. **No host change:** the Time tracker and Issue Tracker template lenses + (#177 §3.1), once Q14 is decided. +5. **atomic-server:** H-B2 and H-B3 first, with the table view as the first + built-in view on the new path, since it renders every class and so + doesn't depend on §4.3. +6. **atomic-server:** H-B1 and H-B4, then Calendar and Issues on the new + path, then Timer after H3 or its lens. + +## 8. Open questions + +1. **Server protocol packages** (`atproto`, `nextgraph`, `open-cloud-mesh`, + `solid`, `willow`): do they become bundles with a `route` part kind, or + stay a separate catalog class until the #88 placements C–E exist? +2. **Notion:** a "Tables" bundle of generic reflectors, a Notion bundle as + the one provider-shaped exception, or should Notion reflect into the + domain bundles when a data source matches a shared class (for example a + Notion task database → `issue-v1`)? +3. **Parts on and off:** can a person switch off a single part, say the + Todoist reflector in the Issues bundle, or only the whole bundle? +4. **Modules:** one module per bundle version, or one per part (§3)? +5. **Built-in fallback:** may built-in views keep shortname matching until + H3 and the lenses land (§4.3), or should they switch only when strict + matching loses no table? +6. **Third-party bundles in a domain:** if someone publishes a second + Calendar view, is that part added to the Calendar bundle (one bundle per + domain across publishers) or a separate bundle in the same domain? From 2244c1d9d164cb34f26915690820e1a272c373dd Mon Sep 17 00:00:00 2001 From: Michiel de Jong Date: Thu, 1 Oct 2026 14:50:10 +0000 Subject: [PATCH 2/6] moneybird 0.1.0: publish the drive app, install it from the catalog (#102) apps.mjs gets an APP_FOLDERS map for drive apps that do not live at integrations//app/: Moneybird builds from integrations/money/moneybird/ and records its version in a private package.json there, never in the Bank statements importer's integrations/money/package.json. Tests cover the mapping, the version file and write for a mapped app. apps/moneybird/0.1.0/ui.js is written by `apps.mjs write moneybird` (9,866 bytes minified, within build.test.ts's dated 11,000 limit). The catalog entry gets version, app-module, integrity and Contact/Contacts row names, and stays enabled: false. It drops requires-api-plugins (the host hides such entries from Drive apps) and platform, both fields of the removed LocalThought flow. moneybird.spec.ts now installs from the catalog card instead of replacing a New app's source. Catalog copy: the Moneybird and Todoist `events` no longer say "Connect through LocalThought"; that flow was removed from atomic-server. Co-Authored-By: Claude Opus 5.5 --- apps/moneybird/0.1.0/ui.js | 1 + integrations/READINESS.md | 2 +- integrations/README.md | 6 +- integrations/catalog.json | 13 ++-- integrations/lanes.json | 2 +- integrations/money/README.md | 19 +++-- integrations/money/e2e/moneybird.spec.ts | 77 +++++++++---------- integrations/money/moneybird/package.json | 7 ++ integrations/tooling/apps.mjs | 45 ++++++++--- integrations/tooling/apps.test.mjs | 91 +++++++++++++++++++++++ 10 files changed, 194 insertions(+), 69 deletions(-) create mode 100644 apps/moneybird/0.1.0/ui.js create mode 100644 integrations/money/moneybird/package.json diff --git a/apps/moneybird/0.1.0/ui.js b/apps/moneybird/0.1.0/ui.js new file mode 100644 index 000000000..3426c8bdd --- /dev/null +++ b/apps/moneybird/0.1.0/ui.js @@ -0,0 +1 @@ +var v="https://moneybird.com/api/v2";var w=class extends Error{constructor(e,n){super(e);this.status=n}status},Z=/^\d{1,20}$/;function P(t){let o=typeof t=="number"?String(t):t;return typeof o=="string"&&Z.test(o)?o:void 0}function O(t,o){if(t.status===401||t.status===403)throw new w(`Moneybird refused ${o} (${t.status}); reconnect Moneybird.`,t.status);if(t.status!==200)throw new w(`Moneybird answered ${t.status} for ${o}.`,t.status);if(!Array.isArray(t.body))throw new w(`Moneybird sent no list for ${o}.`);return t.body}async function _(t){return O(await t("/administrations.json"),"administrations").flatMap(e=>{if(!e||typeof e!="object")return[];let n=e,c=P(n.id);return c?[{id:c,name:typeof n.name=="string"&&n.name?n.name:c,...typeof n.currency=="string"?{currency:n.currency}:{}}]:[]})}function B(t){if(t)for(let o of t.split(",")){let e=o.match(/^\s*<([^>]*)>\s*;(.*)$/);if(e&&/(^|;)\s*rel="?next"?\s*(;|$)/i.test(e[2]))return e[1]}}async function D(t,o,{pageSize:e=100,maxPages:n=200}={}){if(!P(o))throw new w("Choose a Moneybird administration first.");let c=`/${o}/contacts.json`,y=new Map,r=`${c}?per_page=${e}&include_archived=true`;for(let i=1;r;i++){if(i>n)throw new w(`Stopped after ${n} pages of contacts; the provider kept sending a next page.`);let a=await t(r),m=O(a,`contacts page ${i}`);for(let p of m){if(!p||typeof p!="object")continue;let l=P(p.id);l&&y.set(l,{...p,id:l})}let d=B(a.headers?.link);r=d===void 0?void 0:z(d,c)}return[...y.values()]}function z(t,o){let e;try{e=new URL(t,`${v}/`)}catch{throw new w("Moneybird sent an unreadable next-page link.")}let n=new URL(v);if(e.origin!==n.origin||e.pathname!==`${n.pathname}${o}`)throw new w(`Refusing a next-page link outside ${o}: ${e.href}`);return`${o}${e.search}`}var E="https://atomicdata.dev/datatypes/",b=(t,o,e)=>({key:t,shortname:`moneybird-${t.replace(/_/g,"-")}`,name:o,description:e,datatype:`${E}string`}),T=[b("id","Moneybird ID","Moneybird contact identifier, as sent."),b("administration_id","Administration ID","Moneybird administration the contact belongs to."),b("company_name","Company name","Company name; may be empty."),b("firstname","First name","First name; may be empty."),b("lastname","Last name","Last name; may be empty."),b("email","E-mail","Primary e-mail address."),b("city","City","City of the primary address."),b("country","Country","ISO 3166-1 alpha-2 country code."),b("customer_id","Customer ID","The customer number shown in Moneybird."),{key:"archived",shortname:"moneybird-archived",name:"Archived",description:"Archived in Moneybird.",datatype:`${E}boolean`},b("updated_at","Updated in Moneybird","Moneybird updated_at, the exact ISO 8601 string it sent."),{key:"version",shortname:"moneybird-version",name:"Version",description:"Moneybird record version; changes with every edit there.",datatype:`${E}integer`}],V=(t,o)=>`moneybird:${o}:contact:${t.id}`;function j(t){let o=typeof t.company_name=="string"?t.company_name.trim():"";return o||[t.firstname,t.lastname].filter(n=>typeof n=="string"&&n.trim()!=="").join(" ")||`Contact ${t.id}`}function G(t){let o={};for(let e of T){let n=t[e.key];n!=null&&(e.datatype.endsWith("boolean")?typeof n=="boolean"&&(o[e.shortname]=n):e.datatype.endsWith("integer")?typeof n=="number"&&Number.isSafeInteger(n)&&(o[e.shortname]=n):(typeof n=="string"||typeof n=="number")&&(o[e.shortname]=String(n)))}return o}var I="moneybird",f="https://atomicdata.dev",J=`${f}/properties/parent`,st=`${f}/properties/isA`,x=`${f}/properties/name`,F=`${f}/properties/shortname`,Q=`${f}/properties/description`,tt=`${f}/properties/datatype`,U=`${f}/properties/recommends`,H=`${f}/properties/properties`,nt=`${f}/classes/Property`,W={shortname:"moneybird-source-id",name:"Moneybird source",description:"Import identity: moneybird::contact:. Stable across reads.",datatype:`${f}/datatypes/string`},R={shortname:"moneybird-administration",name:"Moneybird administration",description:"The Moneybird administration this app imports from.",datatype:`${f}/datatypes/string`};function L(t,o){return async e=>{if(!e.startsWith("/"))throw new Error(`Refusing a Moneybird path: ${e}`);let n=await t.request({platform:o.platform,connectionId:o.connectionId,path:e,method:"GET"});return{status:n.status,headers:n.headers??{},body:n.body}}}var Y=t=>Array.isArray(t)?t.filter(o=>typeof o=="string"):[];async function $(t,o){let e=await t.getData();if(!e?.rowClass)throw new Error("This app has no table with a row class to import into.");let c=(await t.getResource(e.rowClass)).get(J);if(typeof c!="string")throw new Error("The row class has no parent ontology to add fields to.");let y=await t.getResource(c),r=Y(y.get(H)),i=new Map;for(let d of r){let p=(await t.getResource(d)).get(F);typeof p=="string"&&i.set(p,d)}let a=[],m=new Map;for(let d of o){let p=i.get(d.shortname);p||(p=(await t.newResource({parent:c,isA:[nt],propVals:{[F]:d.shortname,[x]:d.name,[Q]:d.description,[tt]:d.datatype}})).subject,a.push(p)),m.set(d.shortname,p)}return a.length>0&&await y.set(H,[...r,...a]).save(),m}async function q(t,o,e,n=D){let c=await t.getData();if(!c?.rowClass)throw new Error("This app has no table with a row class to import into.");let y=await n(o,e),r=await $(t,[W,...T]),i=await t.getResource(c.rowClass),a=Y(i.get(U)),m=[x,...r.values()],d=[...a,...m.filter(s=>!a.includes(s))];(d.length!==a.length||i.get(x)!=="Contact")&&await i.set(U,d).set(x,"Contact").save();let p=await t.getResource(c.table);p.get(x)!=="Moneybird contacts"&&await p.set(x,"Moneybird contacts").save();let l=r.get(W.shortname),C=new Map;for(let s of await t.query({property:J,value:c.table})){let h=await t.getResource(s),u=h.get(l);typeof u=="string"&&C.set(u,h)}let g={total:y.length,added:0,updated:0,unchanged:0};for(let s of y){let h=V(s,e),u={[x]:j(s),[l]:h};for(let[S,M]of Object.entries(G(s)))u[r.get(S)]=M;let k=C.get(h);if(!k){await t.newResource({parent:c.table,isA:[c.rowClass],propVals:u}),g.added++;continue}let N=Object.entries(u).filter(([S,M])=>k.get(S)!==M);if(N.length===0){g.unchanged++;continue}for(let[S,M]of N)k.set(S,M);await k.save(),g.updated++}return g}function K(t){switch(t.kind){case"loading":return"Loading\u2026";case"no-relay":return"This host cannot reach the integration proxy for apps yet.";case"disconnected":return"Not connected. Connect Moneybird to import your contacts (read-only).";case"connecting":return"Waiting for you to confirm the connection\u2026";case"choosing":return t.administrations.length?"Choose the Moneybird administration to import contacts from.":"This Moneybird account has no administrations to import from.";case"syncing":return"Importing contacts\u2026";case"synced":{let o=t.summary;return`Last synced ${t.at.toLocaleTimeString()}: ${o.total} contacts (${o.added} added, ${o.updated} updated, ${o.unchanged} unchanged).`}case"error":return`Refresh failed: ${t.message} Contacts imported earlier are kept.`}}var A=t=>t instanceof Error?t.message:String(t);function X(t,o){let e={kind:"loading"},n=r=>{e=r,o(e)},c=async()=>{let r=(await $(t,[R])).get(R.shortname),i=(await t.getResource(await t.getApp())).get(r);return typeof i=="string"&&i?i:void 0},y=async r=>{let i=await _(L(t.proxy,r));n({kind:"choosing",connection:r,administrations:i})};return{state:()=>e,async load(){let r=t.proxy;if(!r)return n({kind:"no-relay"}),{};let[i]=await r.connections({platform:I});if(!i)return n({kind:"disconnected"}),{};try{let a=await c();return a?{syncing:this.sync(i,a)}:(await y(i),{})}catch(a){return n({kind:"error",connection:i,message:A(a)}),{}}},async connect(){let r=t.proxy;if(!r)return n({kind:"no-relay"});n({kind:"connecting"});try{await r.connect({platform:I}),n({kind:"disconnected"})}catch(i){n({kind:"error",message:A(i)})}},async select(r){if(e.kind!=="choosing")return;let{connection:i}=e;try{let a=(await $(t,[R])).get(R.shortname);await(await t.getResource(await t.getApp())).set(a,r).save()}catch(a){return n({kind:"error",connection:i,message:A(a)})}await this.sync(i,r)},async change(){if(!("connection"in e)||!e.connection)return;let{connection:r}=e;try{await y(r)}catch(i){n({kind:"error",connection:r,message:A(i)})}},async sync(r="connection"in e?e.connection:void 0,i="administration"in e?e.administration:void 0){let a=t.proxy;if(!a)return n({kind:"no-relay"});if(!(!r||!i||e.kind==="syncing")){n({kind:"syncing",connection:r,administration:i});try{let m=await q(t,L(a,r),i);n({kind:"synced",connection:r,administration:i,at:new Date,summary:m})}catch(m){n({kind:"error",connection:r,administration:i,message:A(m)})}}}}}async function mt({root:t,store:o}){let e=t.ownerDocument,n=(s,h="")=>{let u=e.createElement(s);return u.textContent=h,u},c=n("h1","Moneybird"),y=n("p");y.setAttribute("role","status");let r=n("button","Connect Moneybird"),i=n("label","Administration "),a=n("select");i.append(a);let m=n("button","Import contacts"),d=n("button","Sync now"),p=n("button","Change administration");for(let s of[r,m,d,p])s.type="button";let l=n("div");l.append(i,m),t.style.fontFamily="system-ui, sans-serif",t.style.padding="1rem",t.replaceChildren(c,y,r,l,d,p);let C=s=>{y.textContent=K(s),r.hidden=!(s.kind==="disconnected"||s.kind==="error"&&!s.connection),l.hidden=s.kind!=="choosing",s.kind==="choosing"&&(a.replaceChildren(...s.administrations.map(u=>{let k=n("option",u.name);return k.value=u.id,k})),m.disabled=s.administrations.length===0);let h=s.kind==="synced"||s.kind==="syncing"||s.kind==="error"&&!!s.administration;d.hidden=!h,d.disabled=s.kind==="syncing",p.hidden=!h,p.disabled=s.kind==="syncing"},g=X(o,C);C(g.state()),r.addEventListener("click",()=>{g.connect()}),m.addEventListener("click",()=>{g.select(a.value)}),d.addEventListener("click",()=>{g.sync()}),p.addEventListener("click",()=>{g.change()}),await g.load().catch(s=>{y.textContent=`Could not load: ${s instanceof Error?s.message:String(s)}`})}export{mt as view}; diff --git a/integrations/READINESS.md b/integrations/READINESS.md index af25f2e32..d9df81708 100644 --- a/integrations/READINESS.md +++ b/integrations/READINESS.md @@ -87,7 +87,7 @@ read from the atomic-server source at the pin. | Google Calendar (`calendar`) | Drive app `calendar/app/`: iframe, `calendar/adapter.ts` through `app/relay.ts` over `store.proxy`. The #89 UI (agenda, week, drawer, review sheet; Month hands off to the table's Calendar view, which spans all-day ranges because rows use the host's `atomic-calendar-*` field names) | Published (`calendar` 0.1.4 on GitHub Pages; 0.1.0 wrote `day`/`all-day` and no end day; 0.1.4 removed the adapter's unused sandbox manifest and credential placeholder, and the relay enforces the declared scope of `app/operations.ts`) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | One calendar's single non-recurring events in (≤ 25,000 per scan); reviewed edits of five fields out with If-Match and `sendUpdates=none`; no creates or deletes in Google | Unit; **Host E2E** (`calendar` lane: catalog install, connect, import, refresh after a Google-side edit, review and send, 412 conflict, lost response, links/Month/Disconnect through the host, the host Calendar view spanning a three-day all-day event and placing a timed one, responsive and theme). Historical: live import (2026-09-09, proxy v39) through the retired LocalThought snapshot importer. No live run of the drive app | [#101](https://github.com/ontola/atomic-plugins/issues/101) live verification | | Todoist (`devonian-todoist`) | Library only: `issue-tracker/todoist.ts` projection | None. Its host hook was removed in `f3efedf65` | Declared: read-only, active tasks and projects | Unit. Recorded-fixture tests skip until a recording exists | [#99](https://github.com/ontola/atomic-plugins/issues/99), [#46](https://github.com/ontola/atomic-plugins/issues/46) | | GitHub issues (`issue-tracker`) | Drive app `issue-tracker/app/`: iframe, the Devonian bridge from `issue-tracker/devonian/github-issues/` (npm `devonian` 0.8.0) over `store.proxy`. The #89 board/list UI. The lens's sandbox `plugin.ts` has no host | Published (`issue-tracker` 0.1.1 on GitHub Pages; #206) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | Two-way for one repository: title, body, Todo/Doing/Done status, comments. Every GitHub write is held for review before send. An issue gone from GitHub: "Keep here only" or "Remove from board". An uncertain create has no in-app way out yet | Unit (incl. state 13); **Host E2E** (`issue-tracker` lane: catalog install, connect, repository picker, import, reload, reviewed status update, conflict review, keyboard move, comment). Opt-in lens `*.live.test.ts` (need `GITHUB_TOKEN`; not run in CI). Historical: live GitHub read (2026-09-09, proxy v38) via the retired server flow. No live run of the drive app | [#156](https://github.com/ontola/atomic-plugins/issues/156) "It landed", [#100](https://github.com/ontola/atomic-plugins/issues/100) | -| Moneybird (`moneybird`) | Drive app `money/moneybird/`: iframe, own Moneybird reader over `store.proxy.request` (contacts only) | None. The catalog entry is `enabled: false` with no `app-module` yet; the host E2E installs test-side (`New app` + source) | Read-only. Contacts of one administration into a typed table | Unit; **Host E2E** on a SYNTHETIC fixture (`money` lane, `moneybird.spec.ts`: connect, choose an administration, 5 typed rows, failed refresh keeps rows, resync). Nothing verified against real Moneybird | [#102](https://github.com/ontola/atomic-plugins/issues/102) (a real recording needs a Moneybird account) | +| Moneybird (`moneybird`) | Drive app `money/moneybird/`: iframe, own Moneybird reader over `store.proxy.request` (contacts only) | Catalog Drive apps install of `apps/moneybird/0.1.0/ui.js`; the entry stays `enabled: false`, so only the lanes' dev-server offers it | Read-only. Contacts of one administration into a typed table | Unit; **Host E2E** on a SYNTHETIC fixture (`money` lane, `moneybird.spec.ts`: catalog install, connect, choose an administration, 5 typed rows, failed refresh keeps rows, resync). Nothing verified against real Moneybird | [#102](https://github.com/ontola/atomic-plugins/issues/102) (a real recording needs a Moneybird account) | `integrations/localthought/` is shared tooling, not a user-facing plugin: the shared mock proxy every E2E lane uses (`mock-proxy.mjs`, which speaks diff --git a/integrations/README.md b/integrations/README.md index 0ba83dde8..958e90c55 100644 --- a/integrations/README.md +++ b/integrations/README.md @@ -214,7 +214,11 @@ supported client reads the v1 URL any more. A drive app (an `integrations//app/` whose `build.mjs` builds one ES module exporting `view({ root, store })`) is installable from the catalog when -its entry carries: +its entry carries the properties below. An app that lives elsewhere, such as +Moneybird in `integrations/money/moneybird/` beside the Bank statements +importer, is listed in `apps.mjs`'s `APP_FOLDERS` map: its `build.mjs` and a +`private` `package.json` holding its version are in that folder, and the +enclosing plugin's `package.json` is not read for it. | Catalog property | Meaning | | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- | diff --git a/integrations/catalog.json b/integrations/catalog.json index b04b9884f..c25aab2db 100644 --- a/integrations/catalog.json +++ b/integrations/catalog.json @@ -185,7 +185,7 @@ "https://atomicdata.dev/properties/emoji": "✅", "https://atomicdata.dev/properties/description": "Bring your Todoist projects and tasks into a local issue tracker.", "https://atomicdata.dev/integrations/properties/capabilities": "Imports active tasks and projects. Tasks open in the Issues view with their title, due day and priority. Todoist lists active tasks only, so a task shows as closed only when Todoist itself reports it checked.", - "https://atomicdata.dev/integrations/properties/events": "Connect through LocalThought, then Sync now (and every five minutes while the folder is open) to pull the latest tasks.", + "https://atomicdata.dev/integrations/properties/events": "None at this version: no host runs the Todoist lens. Its host hook, with the LocalThought connect flow it used, was removed from atomic-server (f3efedf65, c707ca4ed), and no drive app wraps the lens yet. A drive app would connect Todoist through the host's consent bar and the integration proxy, like the other drive apps; that is planned, not built.", "https://atomicdata.dev/integrations/properties/limitation": "Read only: the proxy's Todoist access is data:read, so closing, editing or creating a task here is not sent to Todoist. A task that stops appearing is never assumed completed. The lens can check such a task by id and mark it completed, deleted, unavailable or unconfirmed, with when it was last seen, but no host runs that check yet, and nothing has been verified against a live Todoist account.", "https://atomicdata.dev/integrations/properties/keywords": "todoist tasks todo projects devonian lens local tracker issues", "https://atomicdata.dev/integrations/properties/requires-api-plugins": true, @@ -224,11 +224,14 @@ "https://atomicdata.dev/properties/emoji": "🐦", "https://atomicdata.dev/properties/description": "Import the contacts of one Moneybird administration, read-only.", "https://atomicdata.dev/integrations/properties/capabilities": "Imports the contacts of one administration (archived ones included) into a typed table: name, company, e-mail, city, country, customer ID, archived, version. Invoices, financial mutations, ledger accounts and the other collections are not imported yet.", - "https://atomicdata.dev/integrations/properties/events": "Connect through LocalThought, pick an administration, then contacts refresh whenever the app is opened, or on Sync now.", + "https://atomicdata.dev/integrations/properties/events": "Install from Drive apps, connect Moneybird through the host's consent bar and choose an administration. Contacts refresh whenever the app is opened and on Sync now. Nothing runs while the app is closed.", "https://atomicdata.dev/integrations/properties/limitation": "Read-only: nothing is written back to Moneybird. Contacts only. One administration per app. Tested against a synthetic fixture, not a real Moneybird account.", - "https://atomicdata.dev/integrations/properties/keywords": "moneybird bookkeeping accounting invoices contacts ledger finance administration localthought", - "https://atomicdata.dev/integrations/properties/requires-api-plugins": true, - "https://atomicdata.dev/integrations/properties/platform": "moneybird" + "https://atomicdata.dev/integrations/properties/keywords": "moneybird bookkeeping accounting invoices contacts ledger finance administration drive app", + "https://atomicdata.dev/integrations/properties/version": "0.1.0", + "https://atomicdata.dev/integrations/properties/app-row-name": "Contact", + "https://atomicdata.dev/integrations/properties/app-row-name-plural": "Contacts", + "https://atomicdata.dev/integrations/properties/app-module": "https://ontola.github.io/atomic-plugins/apps/moneybird/0.1.0/ui.js", + "https://atomicdata.dev/integrations/properties/app-module-integrity": "sha384-yc2fJ42WEWVdgEEJuhhnL4Tf3fGLwiPzNq2EluOcSXQVDfu4QyWK5jrAEf+NzKIy" }, { "https://atomicdata.dev/properties/localId": "timesheets", diff --git a/integrations/lanes.json b/integrations/lanes.json index e8ae2e530..ca7d28048 100644 --- a/integrations/lanes.json +++ b/integrations/lanes.json @@ -101,7 +101,7 @@ "index": 3, "platforms": ["moneybird"], "tiers": ["e2e"], - "note": "e2e drives the Bank statements importer through the host's generic file entry point (atomic-server#1653: manifest accepts/destination, PluginPage Import tab): publish, discover, set up, MT940 and camt.053 import, reload, reimport, local edit, conflict and refused files. A second test installs the Money drive app (integrations/money/app/) test-side as an app rendering the Bank transaction class, adds it through the table's Add view as a read-only view, imports an MT940 from inside the app through the host's review (store.importer.run, atomic-server#1774), and saves a category after the host's Allow editing (atomic-server#1788). The pin includes that change (atomic-server#1691); against an older host, publishing the bundle fails on the unknown manifest field. Host bug atomic-server#1846, fixed at pin 1432e244a (atomic-server#1847, atomic-plugins #179): at pin 2567fc30b Add view read the drive's apps once on mount, so when the app's save synced in after navigating, 'New app' never appeared and the second test failed. No typecheck/unit tier: money has an atomicCertification block, so the unsharded certification step in shared-checks already runs exactly its typecheck (tsconfig.json) and unit (vitest.config.ts) on every integrations/** change, plus bundle reproducibility. moneybird.spec.ts drives the read-only Moneybird contacts drive app (integrations/money/moneybird/, #102) through the host relay against the SYNTHETIC moneybird fixture in integrations/money/fixtures/moneybird/ (hand-written from the public OpenAPI document; not a recording, which needs a Moneybird account).", + "note": "e2e drives the Bank statements importer through the host's generic file entry point (atomic-server#1653: manifest accepts/destination, PluginPage Import tab): publish, discover, set up, MT940 and camt.053 import, reload, reimport, local edit, conflict and refused files. A second test installs the Money drive app (integrations/money/app/) test-side as an app rendering the Bank transaction class, adds it through the table's Add view as a read-only view, imports an MT940 from inside the app through the host's review (store.importer.run, atomic-server#1774), and saves a category after the host's Allow editing (atomic-server#1788). The pin includes that change (atomic-server#1691); against an older host, publishing the bundle fails on the unknown manifest field. Host bug atomic-server#1846, fixed at pin 1432e244a (atomic-server#1847, atomic-plugins #179): at pin 2567fc30b Add view read the drive's apps once on mount, so when the app's save synced in after navigating, 'New app' never appeared and the second test failed. No typecheck/unit tier: money has an atomicCertification block, so the unsharded certification step in shared-checks already runs exactly its typecheck (tsconfig.json) and unit (vitest.config.ts) on every integrations/** change, plus bundle reproducibility. moneybird.spec.ts installs the read-only Moneybird contacts drive app (integrations/money/moneybird/, #102) from the catalog's Drive apps section, as the committed apps/moneybird//ui.js (apps.mjs APP_FOLDERS maps it there), and drives it through the host relay against the SYNTHETIC moneybird fixture in integrations/money/fixtures/moneybird/ (hand-written from the public OpenAPI document; not a recording, which needs a Moneybird account).", "e2e": [ "integrations/money/e2e/money.spec.ts", "integrations/money/e2e/moneybird.spec.ts" diff --git a/integrations/money/README.md b/integrations/money/README.md index f5a22e41a..1f724f159 100644 --- a/integrations/money/README.md +++ b/integrations/money/README.md @@ -307,13 +307,18 @@ administration on page 2 with 503; both are test behaviour, not claims about Moneybird. **A real recording needs someone with a Moneybird test administration and API token**; the steps are in `scenario.mjs`'s header. -**Install.** Test-side only: `e2e/moneybird.spec.ts` creates a `New app` -and replaces its entry point with `node -integrations/money/moneybird/build.mjs`'s bundle. The `moneybird` catalog -entry stays `enabled: false` and has no `app-module`: the app is not -published under `apps/` yet (see -[Publishing a drive app](../README.md#publishing-a-drive-app)), so the -catalog's Drive apps install cannot offer it. +**Install.** From the catalog's Drive apps section, like the other drive +apps (see [Publishing a drive app](../README.md#publishing-a-drive-app)). +Version 0.1.0 is published at `apps/moneybird/0.1.0/ui.js`; its version is +recorded in `moneybird/package.json`, not in this folder's `package.json` +(that one is the Bank statements importer's). `apps.mjs` finds the app here, +not at `integrations/moneybird/app/`, through its `APP_FOLDERS` map. The +`moneybird` catalog entry stays `enabled: false` until a real recording +exists, so the published catalog does not list it; the lane's dev-server +serves it enabled for `e2e/moneybird.spec.ts`, which installs it from the +card. To release a new version, bump `moneybird/package.json` and the +catalog entry's `version`, then run +`node integrations/tooling/apps.mjs write moneybird`. Tests: the money vitest command above includes `moneybird/*.test.ts`. The host E2E is `e2e/moneybird.spec.ts` in the money lane's e2e tier. It first diff --git a/integrations/money/e2e/moneybird.spec.ts b/integrations/money/e2e/moneybird.spec.ts index 851c3e48d..49789bc28 100644 --- a/integrations/money/e2e/moneybird.spec.ts +++ b/integrations/money/e2e/moneybird.spec.ts @@ -5,10 +5,12 @@ * proxy serving the SYNTHETIC Moneybird fixture * (`integrations/money/fixtures/moneybird/`, not a recording). * - * The app is installed test-side, the way the Pets spec does it: `New app` - * from the catalog, then its entry point's source is replaced with - * `moneybird/build.mjs`'s bundle. There is no catalog install flow for drive - * apps yet (#94). + * The app is installed from the catalog, the way the Pets spec does it: + * Integrations, Drive apps, Install. The lane's dev-server stands in for + * GitHub Pages: it serves the committed `apps/moneybird//ui.js` and + * points the entry's `app-module` there, keeping `app-module-integrity` as + * committed, and serves the entry enabled although the published catalog + * keeps it `enabled: false` (integrations/tooling/dev-server.mjs). * * Journey: connect through the host's consent bar and the mock proxy, choose * an administration, import typed rows, reload (the fixture fails that @@ -18,12 +20,10 @@ * node integrations/tooling/run-lane.mjs money --tier e2e */ import { test, expect, type Page } from '@playwright/test'; -import { - before, - createFromCatalog, -} from '../../../browser/e2e/tests/test-utils'; -// @ts-expect-error build.mjs is plain JS with no declaration file. -import { build } from '../moneybird/build.mjs'; +import { before } from '../../../browser/e2e/tests/test-utils'; + +/** The catalog's version of the Moneybird app (integrations/catalog.json). */ +const VERSION = '0.1.0'; test.describe('moneybird integration', () => { test.beforeEach(before); @@ -36,18 +36,22 @@ test.describe('moneybird integration', () => { 'Run with the documented mock integration-proxy server configuration', ); test.setTimeout(180_000); - const { text } = (await build()) as { text: string }; - - await createFromCatalog(page, 'App'); const main = page.getByRole('main'); + const app = page.frameLocator('iframe[title="App"]'); + + // Discovery and installation from the catalog's Drive apps section. + const card = await openCatalogCard(page); + await expect( + card.getByRole('heading', { name: 'Moneybird' }), + ).toBeVisible(); + await expect(card).toContainText(`Version ${VERSION}`); + await card.getByRole('button', { name: 'Install Moneybird' }).click(); await expect(main.locator('iframe[title="App"]')).toBeVisible({ timeout: 45_000, }); - await setAppSource(page, text); - await page.reload(); - - const app = page.frameLocator('iframe[title="App"]'); - await expect(app.getByRole('heading', { name: 'Moneybird' })).toBeVisible(); + await expect(app.getByRole('heading', { name: 'Moneybird' })).toBeVisible({ + timeout: 30_000, + }); await expect(app.getByRole('status')).toContainText('Not connected'); await app.getByRole('button', { name: 'Connect Moneybird' }).click(); @@ -158,30 +162,17 @@ async function tableOf(page: Page): Promise { }); } -/** Replaces the app's entry-point source; copied from `pets/e2e/pets.spec.ts`. */ -async function setAppSource(page: Page, source: string) { - await page.evaluate(async (next: string) => { - const store = window.store!; - const subject = decodeURIComponent( - new URL(location.href).searchParams.get('subject')!, - ); - const app = await store.getResource(subject); - - for (const value of Object.values(app.getPropVals())) { - if (typeof value !== 'string' || !value.includes(':')) continue; - const child = await store.getResource(value).catch(() => undefined); - if (!child) continue; - const sourceProp = Object.entries(child.getPropVals()).find( - ([, v]) => - typeof v === 'string' && v.includes('export async function view'), - )?.[0]; - if (!sourceProp) continue; - await child.set(sourceProp, next); - await child.save(); - - return; - } +/** The Integrations page's Moneybird card, with experimental plugins shown. */ +async function openCatalogCard(page: Page) { + await page.goto(new URL('/app/integrations', page.url()).href); + const experimental = page.getByRole('checkbox', { + name: 'Show experimental plugins', + }); + await experimental.check(); + // Disabled while the setting is still saving to the private drive. + await expect(experimental).toBeEnabled({ timeout: 30_000 }); - throw new Error('could not find the app’s entry point'); - }, source); + return page + .getByRole('region', { name: 'Drive apps' }) + .locator('[data-catalog-app="moneybird"]'); } diff --git a/integrations/money/moneybird/package.json b/integrations/money/moneybird/package.json new file mode 100644 index 000000000..a92a38128 --- /dev/null +++ b/integrations/money/moneybird/package.json @@ -0,0 +1,7 @@ +{ + "name": "@atomic-integrations/moneybird-app", + "private": true, + "version": "0.1.0", + "type": "module", + "description": "Moneybird contacts drive app. Records only the version its catalog entry and apps/moneybird//ui.js carry (integrations/tooling/apps.mjs APP_FOLDERS); no npm dependencies. Its version is its own, not integrations/money/package.json's, which belongs to the Bank statements importer." +} diff --git a/integrations/tooling/apps.mjs b/integrations/tooling/apps.mjs index 996fd9eca..12f8565e9 100644 --- a/integrations/tooling/apps.mjs +++ b/integrations/tooling/apps.mjs @@ -6,7 +6,8 @@ * `app-module-integrity` (the SRI hash of those bytes). The host downloads the * module, refuses it unless the hash matches, and stores it as a new app's * entry point (atomic-server `browser/lib/src/catalog-app.ts`). The module is - * `integrations//app/build.mjs`'s output, committed to this + * `integrations//app/build.mjs`'s output (or, for an app listed in + * `APP_FOLDERS`, that folder's `build.mjs`), committed to this * repository at `apps///ui.js`. GitHub Pages publishes * `main` from the repository root (with the root `.nojekyll`, byte for byte), * so the catalog points at: @@ -85,17 +86,36 @@ export function appEntries(catalog) { ); } +/** + * Drive apps whose source is not at `integrations//app/`, by + * catalog shortname: the folder (repository-relative) holding the app's + * `build.mjs` and a `private` `package.json` with just its version. For an + * app that lives inside another plugin's folder, such as Moneybird inside + * `integrations/money/` beside the Bank statements importer, whose own + * package.json version belongs to that importer. + */ +export const APP_FOLDERS = Object.freeze({ + moneybird: 'integrations/money/moneybird', +}); + +/** The repository-relative folder holding an app's `build.mjs`. */ +export const appFolder = id => + Object.hasOwn(APP_FOLDERS, id) ? APP_FOLDERS[id] : `integrations/${id}/app`; + /** * Where an app's version is recorded: the plugin folder's package.json (the * #12 rule `certify.mjs` also enforces for a sandbox package), or, for a * folder that ships only an app and so has no certified package, a - * `private` `app/package.json` holding just the version. + * `private` `app/package.json` holding just the version. An app in + * `APP_FOLDERS` records it only in that folder's package.json. */ export function versionFile(id, base = root) { - for (const relativePath of [ - `integrations/${id}/package.json`, - `integrations/${id}/app/package.json`, - ]) + for (const relativePath of Object.hasOwn(APP_FOLDERS, id) + ? [`${APP_FOLDERS[id]}/package.json`] + : [ + `integrations/${id}/package.json`, + `integrations/${id}/app/package.json`, + ]) if (existsSync(resolve(base, relativePath))) return relativePath; return undefined; @@ -105,7 +125,8 @@ export function versionFile(id, base = root) { * Everything about one app entry that does not need a build: the fields are * there, the version matches the folder's version file (`versionFile`), the * URL is the Pages one for that version, the committed module exists and its - * hash is the pinned integrity, and the folder has an `app/build.mjs`. + * hash is the pinned integrity, and the app's folder (`appFolder`) has a + * `build.mjs`. */ export function staticProblems(entry, base = root) { const id = entry[terms.shortname]; @@ -144,7 +165,9 @@ export function staticProblems(entry, base = root) { if (!file) problems.push( - `${id}: neither integrations/${id}/package.json nor integrations/${id}/app/package.json records a version`, + Object.hasOwn(APP_FOLDERS, id) + ? `${id}: ${APP_FOLDERS[id]}/package.json does not exist to record a version` + : `${id}: neither integrations/${id}/package.json nor integrations/${id}/app/package.json records a version`, ); else { const pkg = JSON.parse(readFileSync(resolve(base, file), 'utf8')); @@ -154,15 +177,15 @@ export function staticProblems(entry, base = root) { ); } - if (!existsSync(resolve(base, 'integrations', id, 'app/build.mjs'))) - problems.push(`${id}: integrations/${id}/app/build.mjs is missing`); + if (!existsSync(resolve(base, appFolder(id), 'build.mjs'))) + problems.push(`${id}: ${appFolder(id)}/build.mjs is missing`); return problems; } /** The app's module, built in memory by its own build.mjs. */ export async function buildApp(id, base = root) { - const file = resolve(base, 'integrations', id, 'app/build.mjs'); + const file = resolve(base, appFolder(id), 'build.mjs'); // Keyed by content, so a changed build.mjs is not served from the module // cache within one process. const version = createHash('sha1').update(readFileSync(file)).digest('hex'); diff --git a/integrations/tooling/apps.test.mjs b/integrations/tooling/apps.test.mjs index 36b5ff5c6..c0d23c083 100644 --- a/integrations/tooling/apps.test.mjs +++ b/integrations/tooling/apps.test.mjs @@ -11,7 +11,9 @@ import { import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { + APP_FOLDERS, appEntries, + appFolder, blobId, check, integrityOf, @@ -178,6 +180,95 @@ test('an app-only folder records its version in app/package.json', () => assert.deepEqual(staticProblems(entry, base), []); })); +test('an app resolves to integrations//app/ unless APP_FOLDERS maps it', () => { + assert.equal(appFolder('gamma'), 'integrations/gamma/app'); + assert.equal(appFolder('moneybird'), 'integrations/money/moneybird'); + // Only own keys map: no prototype property is taken for a folder. + assert.equal(appFolder('constructor'), 'integrations/constructor/app'); + assert.ok(Object.isFrozen(APP_FOLDERS)); +}); + +/** + * The fixture's gamma app moved to where APP_FOLDERS puts moneybird: its + * build.mjs and a version-only package.json in integrations/money/moneybird/, + * next to a money/package.json at another version (the importer's), which + * must never be read for it. + */ +function asMapped(base, version = '1.2.3') { + const folder = join(base, 'integrations/money/moneybird'); + mkdirSync(folder, { recursive: true }); + writeFileSync( + join(folder, 'build.mjs'), + readFileSync(join(base, 'integrations/gamma/app/build.mjs')), + ); + writeFileSync( + join(folder, 'package.json'), + JSON.stringify({ private: true, version }), + ); + writeFileSync( + join(base, 'integrations/money/package.json'), + JSON.stringify({ name: '@x/money', version: '9.9.9' }), + ); + rmSync(join(base, 'integrations/gamma'), { recursive: true }); + const catalog = readCatalog(base); + catalog[1][terms.shortname] = 'moneybird'; + catalog[1][terms.module] = moduleUrl('moneybird', version); + writeFileSync( + join(base, 'integrations/catalog.json'), + JSON.stringify(catalog, null, 2), + ); + mkdirSync(join(base, `apps/moneybird/${version}`), { recursive: true }); + writeFileSync( + join(base, modulePath('moneybird', version)), + readFileSync(join(base, modulePath('gamma', version))), + ); + rmSync(join(base, 'apps/gamma'), { recursive: true }); +} + +test('a mapped app builds from its own folder and versions by its package.json', () => + using({}, async base => { + asMapped(base); + const entry = appEntries(readCatalog(base))[0]; + assert.deepEqual(staticProblems(entry, base), []); + assert.deepEqual(await check({ base }), []); + + writeFileSync( + join(base, 'integrations/money/moneybird/package.json'), + JSON.stringify({ private: true, version: '1.2.4' }), + ); + assert.deepEqual(staticProblems(entry, base), [ + 'moneybird: catalog version 1.2.3 does not match integrations/money/moneybird/package.json 1.2.4', + ]); + + // The enclosing plugin's package.json is never a fallback. + rmSync(join(base, 'integrations/money/moneybird/package.json')); + rmSync(join(base, 'integrations/money/moneybird/build.mjs')); + assert.deepEqual(staticProblems(entry, base), [ + 'moneybird: integrations/money/moneybird/package.json does not exist to record a version', + 'moneybird: integrations/money/moneybird/build.mjs is missing', + ]); + })); + +test('write builds a mapped app from its own folder', () => + using({}, async base => { + asMapped(base); + writeFileSync( + join(base, 'integrations/money/moneybird/build.mjs'), + "export async function build() { return { text: 'mapped' }; }\n", + ); + const [written] = await write({ only: 'moneybird', base }); + assert.deepEqual(written, { + path: 'apps/moneybird/1.2.3/ui.js', + bytes: 6, + integrity: integrityOf('mapped'), + }); + assert.equal( + readFileSync(join(base, 'apps/moneybird/1.2.3/ui.js'), 'utf8'), + 'mapped', + ); + assert.deepEqual(await check({ base }), []); + })); + test('apps/ holds only //ui.js', () => using({}, async base => { writeFileSync(join(base, 'apps/gamma/notes.txt'), 'x'); From e66df9c15cb5dc5049c03085a533b6c9c68e9dd4 Mon Sep 17 00:00:00 2001 From: Michiel de Jong Date: Thu, 1 Oct 2026 16:24:15 +0000 Subject: [PATCH 3/6] catalog: restore the moneybird entry lost in the main merge Co-Authored-By: Claude Opus 5.5 --- integrations/catalog.json | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/integrations/catalog.json b/integrations/catalog.json index 8ea06b68e..7b47d1686 100644 --- a/integrations/catalog.json +++ b/integrations/catalog.json @@ -212,11 +212,14 @@ "https://atomicdata.dev/properties/emoji": "🐦", "https://atomicdata.dev/properties/description": "Import the contacts of one Moneybird administration, read-only.", "https://atomicdata.dev/integrations/properties/capabilities": "Imports the contacts of one administration (archived ones included) into a typed table: name, company, e-mail, city, country, customer ID, archived, version. Invoices, financial mutations, ledger accounts and the other collections are not imported yet.", - "https://atomicdata.dev/integrations/properties/events": "Connect through LocalThought, pick an administration, then contacts refresh whenever the app is opened, or on Sync now.", + "https://atomicdata.dev/integrations/properties/events": "Install from Drive apps, connect Moneybird through the host's consent bar and choose an administration. Contacts refresh whenever the app is opened and on Sync now. Nothing runs while the app is closed.", "https://atomicdata.dev/integrations/properties/limitation": "Read-only: nothing is written back to Moneybird. Contacts only. One administration per app. Tested against a synthetic fixture, not a real Moneybird account.", - "https://atomicdata.dev/integrations/properties/keywords": "moneybird bookkeeping accounting invoices contacts ledger finance administration localthought", - "https://atomicdata.dev/integrations/properties/requires-api-plugins": true, - "https://atomicdata.dev/integrations/properties/platform": "moneybird" + "https://atomicdata.dev/integrations/properties/keywords": "moneybird bookkeeping accounting invoices contacts ledger finance administration drive app", + "https://atomicdata.dev/integrations/properties/version": "0.1.0", + "https://atomicdata.dev/integrations/properties/app-row-name": "Contact", + "https://atomicdata.dev/integrations/properties/app-row-name-plural": "Contacts", + "https://atomicdata.dev/integrations/properties/app-module": "https://ontola.github.io/atomic-plugins/apps/moneybird/0.1.0/ui.js", + "https://atomicdata.dev/integrations/properties/app-module-integrity": "sha384-yc2fJ42WEWVdgEEJuhhnL4Tf3fGLwiPzNq2EluOcSXQVDfu4QyWK5jrAEf+NzKIy" }, { "https://atomicdata.dev/properties/localId": "timesheets", From c9df0a5d3e711312c032863474d9cc2e243fb8a1 Mon Sep 17 00:00:00 2001 From: Michiel de Jong Date: Thu, 1 Oct 2026 16:37:45 +0000 Subject: [PATCH 4/6] issue-tracker 0.2.0: rows of the shared issue-v1 class (#177 item 6) The GitHub issues drive app now syncs into the shared class issue-v1, at its published GitHub Pages subject: - Rows are issue-v1: title in name, task/v1 body and status (the task/v1 tags todo, doing, blocked, done). Shared fields are read by subject through ontology-kit's resolver only. On first open the app adds issue-v1 to its App's renders, declares its row extras (issue number, GitHub source, sync baseline) as row-extras, and sets its own table's classtype to issue-v1. Shown on an Issue table it did not make, it only shows a notice ("Sync this table" is item 14, not built). - Blocked is the GitHub label atomic:blocked, like atomic:doing (#177 Q8): lens, GitHubPort, the tracker actions and the sandbox plugin (plugin.js rebuilt, manifest fixture updated). Board and list get a Blocked column; keys 1-4. - A status that is not exactly one of the four tags no longer fails the pass: the row is shown with its status as it is and keeps the status it last agreed with GitHub for the sync. - Local-only rows (#177 Q6, this plugin's choice): a row with no GitHub issue is left alone until "Publish to GitHub" in its panel; the create is then held for review as before. Cards made with the app's own New issue form are published at once (still reviewed). - Baselines live on the rows as github-sync-baseline (#177 decision 7), not in github-sync-state: written with every row the Bridge writes, written at a checkpoint when they changed otherwise, read back into the Bridge's records when a row is read. The snapshot's identity graph stays in the sync state. - An update over a 0.1.x install rewrites its rows in place once (own Status tags to task/v1 tags, description to task/v1 body, isA to issue-v1) and keeps the sync state, so unsent edits are still offered. e2e: installs 0.2.0 from the catalog, checks the table and rows are issue-v1 and the App renders it, publishes a row added outside the app, and moves it to Blocked, all against the mock proxy; beforeAll checks Pages serves issue-v1 (ontology-kit/served.mjs, copied byte-identical from the money branch, #252). App 0.2.0 (usertest-6); catalog entry stays enabled: false; size limit 167 KiB (measured 154,931 bytes). Co-Authored-By: Claude Opus 5.5 --- apps/issue-tracker/0.2.0/ui.js | 9 + integrations/READINESS.md | 28 +- integrations/catalog.json | 10 +- integrations/issue-tracker/README.md | 116 ++++- integrations/issue-tracker/app/build.test.ts | 13 +- .../issue-tracker/app/controller.test.ts | 187 +++++++- integrations/issue-tracker/app/controller.ts | 92 +++- integrations/issue-tracker/app/fakeStore.ts | 43 +- integrations/issue-tracker/app/frameStore.ts | 17 +- integrations/issue-tracker/app/main.ts | 13 +- integrations/issue-tracker/app/model.test.ts | 4 +- integrations/issue-tracker/app/model.ts | 10 +- integrations/issue-tracker/app/package.json | 2 +- integrations/issue-tracker/app/state.ts | 7 + integrations/issue-tracker/app/styles.css | 2 +- integrations/issue-tracker/app/sync.test.ts | 95 ++++- integrations/issue-tracker/app/sync.ts | 399 +++++++++++++++++- integrations/issue-tracker/app/tracker.ts | 350 +++++++++++---- integrations/issue-tracker/app/ui/dom.ts | 5 +- integrations/issue-tracker/app/ui/kit.css | 3 + integrations/issue-tracker/app/ui/kit.ts | 4 +- integrations/issue-tracker/app/views.test.ts | 4 +- integrations/issue-tracker/app/views.ts | 67 ++- .../devonian/github-issues/adapter.test.ts | 2 +- .../devonian/github-issues/adapter.ts | 12 + .../devonian/github-issues/atomic.ts | 1 + .../devonian/github-issues/lens/index.ts | 60 ++- .../devonian/github-issues/lens/lens.test.ts | 22 +- .../devonian/github-issues/lens/resources.mjs | 1 + .../github-issues/manifest.fixture.json | 12 + .../devonian/github-issues/plugin.js | 52 ++- .../devonian/github-issues/plugin.ts | 34 +- .../devonian/github-issues/ports.mjs | 60 ++- .../devonian/github-issues/ports.test.mjs | 25 ++ .../devonian/github-issues/proxy.mjs | 8 + .../devonian/github-issues/tracker-actions.ts | 31 ++ .../issue-tracker/e2e/issue-tracker.spec.ts | 181 ++++++-- integrations/lanes.json | 6 +- ontology-kit/served.mjs | 116 +++++ usertest/catalog.mjs | 2 +- 40 files changed, 1783 insertions(+), 322 deletions(-) create mode 100644 apps/issue-tracker/0.2.0/ui.js create mode 100644 ontology-kit/served.mjs diff --git a/apps/issue-tracker/0.2.0/ui.js b/apps/issue-tracker/0.2.0/ui.js new file mode 100644 index 000000000..8e46f59e4 --- /dev/null +++ b/apps/issue-tracker/0.2.0/ui.js @@ -0,0 +1,9 @@ +var ir=Object.create;var It=Object.defineProperty;var ar=Object.getOwnPropertyDescriptor;var cr=Object.getOwnPropertyNames;var lr=Object.getPrototypeOf,dr=Object.prototype.hasOwnProperty;var ur=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(n){throw e=0,n}};var pr=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of cr(e))!dr.call(t,s)&&s!==n&&It(t,s,{get:()=>e[s],enumerable:!(r=ar(e,s))||r.enumerable});return t};var fr=(t,e,n)=>(n=t!=null?ir(lr(t)):{},pr(e||!t||!t.__esModule?It(n,"default",{value:t,enumerable:!0}):n,t));var Mt=ur((Ws,Ct)=>{"use strict";Ct.exports=function(t,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var n=typeof e.cycles=="boolean"?e.cycles:!1,r=e.cmp&&(function(o){return function(i){return function(a,c){var d={key:a,value:i[a]},u={key:c,value:i[c]};return o(d,u)}}})(e.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 e=new URL(t);if(!["http:","https:"].includes(e.protocol)&&!(/^did:[a-z0-9]+:[A-Za-z0-9._:%+/=-]+(?:[?#][A-Za-z0-9._~:/?#[\]@!$&'()*+,;=%-]*)?$/.test(t)&&!/%(?![0-9a-fA-F]{2})/.test(t)))throw new Error(`Expected an HTTP(S) URL or DID: ${t}`)}var He=class{properties=new Map([[nt,C.RESOURCEARRAY]]);property(e,n){if(U(e),!Object.values(C).includes(n)||n===C.UNKNOWN)throw new Error(`Unsupported datatype: ${n}`);let r=this.properties.get(e);if(r&&r!==n)throw new Error(`Conflicting property: ${e}`);return this.properties.set(e,n),this}validate(e){U(e["@id"]),this.validateProperties(e,!0)}validateProperties(e,n){if(Object.getPrototypeOf(e)!==Object.prototype)throw new Error("Expected a plain JSON object");for(let[r,s]of Object.entries(e)){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===C.ATOMIC_URL)this.validateLink(s);else if(o===C.RESOURCEARRAY){if(!Array.isArray(s))throw new Error(`Expected a resource array: ${r}`);for(let i of s)this.validateLink(i)}else{if([C.FLOAT,C.INTEGER,C.TIMESTAMP].includes(o)&&typeof s!="number")throw new Error("Expected a number");if(o===C.BOOLEAN&&typeof s!="boolean")throw new Error("Expected a boolean");Pt(s,o)}}}validateLink(e){if(typeof e=="string")U(e);else if(e&&typeof e=="object"&&!Array.isArray(e))this.validateProperties(e,!1);else throw new Error("Expected a resource URL or nested resource")}};var Le=class t{schema;resources=new Map;constructor(e){this.schema=e}get(e){let n=this.resources.get(e);return n&&structuredClone(n)}put(e){this.schema.validate(e),this.resources.set(e["@id"],structuredClone(e))}patch(e,n){if(U(e),Object.hasOwn(n.set??{},"@id")||n.unset?.includes("@id"))throw new Error("A patch cannot change resource identity");let r={...this.get(e)??{"@id":e},...n.set};for(let s of n.unset??[])U(s),delete r[s];return this.put(r),structuredClone(r)}transaction(e){let n=this.resources;this.resources=new Map(n);try{e()}catch(r){throw this.resources=n,r}}apply(e){let n=new t(this.schema);n.resources=new Map(this.resources);for(let r of e)n.patch(r.subject,r.patch);this.resources=n.resources}delete(e){this.resources.delete(e)}all(e){return[...this.resources.values()].filter(n=>{let r=n["https://atomicdata.dev/properties/isA"];return!e||Array.isArray(r)&&r.includes(e)}).map(n=>structuredClone(n))}toJSONAD(){return JSON.stringify(this.all())}loadJSONAD(e){let n=JSON.parse(e),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/",M={class:`${be}Identity.json`,scope:`${be}scope.json`,entity:`${be}entity.json`,localId:`${be}localId.json`,idType:`${be}idType.json`,resource:`${be}resource.json`},Ne=class{store;base;constructor(e,n){this.store=e,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(/\/$/,""),e.schema.property(M.scope,C.ATOMIC_URL).property(M.entity,C.STRING).property(M.localId,C.STRING).property(M.idType,C.STRING).property(M.resource,C.ATOMIC_URL)}key(e,n){if(U(e.scope),!e.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([e.scope,e.entity,typeof n,n]))}subjectFor(e,n){return this.lookup(e,n)??`${this.base}/resources/${this.key(e,n)}`}lookup(e,n){return this.key(e,n),this.find(e).find(r=>r[M.localId]===String(n)&&r[M.idType]===typeof n)?.[M.resource]}externalId(e,n){let r=this.find(e).find(s=>s[M.resource]===n);if(r)return r[M.idType]==="number"?Number(r[M.localId]):r[M.localId]}bind(e,n,r){let s=this.key(e,n);U(r);let o=this.lookup(e,n),i=this.externalId(e,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}`,[nt]:[M.class],[M.scope]:e.scope,[M.entity]:e.entity,[M.localId]:String(n),[M.idType]:typeof n,[M.resource]:r})}unbind(e,n){if(U(e.scope),U(n),!e.entity)throw new Error("Expected an entity");let r=this.find(e).find(o=>o[M.resource]===n);if(!r)return;let s=this.externalId(e,n);return this.store.delete(r["@id"]),s}find(e){let n=this.store.all(M.class).filter(o=>o[M.scope]===e.scope&&o[M.entity]===e.entity),r=new Set,s=new Set;for(let o of n){let i=o[M.localId],a=o[M.idType],c=o[M.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 d=JSON.stringify([a,i]);if(r.has(d)||s.has(c))throw new Error("Conflicting identity mappings in snapshot");r.add(d),s.add(c)}return n}};var De=class{options;pending=Promise.resolve();constructor(e){if(this.options=e,U(e.scope),!e.entity)throw new Error("A lens requires an entity type");if(e.identities.store!==e.store)throw new Error("Lens and identity map must use the same store")}ingest(e){return this.enqueue(async()=>{let{connector:n,identities:r,store:s,read:o}=this.options,i=n.id(e),a=r.subjectFor(this.options,i),c=await o(e,a);return s.transaction(()=>{s.apply([...c.related??[],{subject:a,patch:c}]);for(let d of c.identities??[])r.bind(d.scope,d.id,d.subject);r.bind(this.options,i,a)}),a})}publish(e){return this.enqueue(async()=>{let{connector:n,identities:r,store:s,write:o}=this.options,i=s.get(e);if(!i)throw new Error(`Unknown resource: ${e}`);let a=r.externalId(this.options,e);if(a!==void 0){let p=await n.get(a);return await n.update(a,await o(i,p)),a}let c=JSON.stringify([this.options.scope,this.options.entity,e]),d=await n.create(await o(i,void 0),c),u=n.id(d);return r.bind(this.options,u,e),u})}ingestDelete(e){return this.enqueue(async()=>{let n=this.options.identities.lookup(this.options,e);n&&this.options.store.delete(n)})}delete(e){return this.enqueue(async()=>{let{connector:n,identities:r,store:s}=this.options,o=r.externalId(this.options,e);o!==void 0&&await n.delete(o),s.delete(e)})}enqueue(e){let n=this.pending.then(e);return this.pending=n.catch(()=>{}),n}};var rt=fr(Mt(),1),ye=(t,e)=>(0,rt.default)(t)===(0,rt.default)(e);function st(t,e,n){let r={local:{},remote:{},createLocal:!1,createRemote:!1,deleteLocal:!1,deleteRemote:!1,conflicts:[]};if(ye(e,n))return e!==void 0&&(r.agreed=structuredClone(e)),r;if(e===null||n===null)return ye(e,t)&&n===null?r.deleteLocal=!0:ye(n,t)&&e===null?r.deleteRemote=!0:r.conflicts.push({property:"@record",base:t,local:e,remote:n}),r;if(t!==void 0&&(e===void 0||n===void 0))return r;r.createLocal=t===void 0&&e===void 0&&n!==void 0,r.createRemote=t===void 0&&n===void 0&&e!==void 0;let s=new Set([...Object.keys(t??{}),...Object.keys(e??{}),...Object.keys(n??{})]);for(let o of s){let i=t?.[o],a=e?.[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 Ht=["Todo","Doing","Blocked","Done"],ot={Doing:"atomic:doing",Blocked:"atomic:blocked"},mr=Object.values(ot),gr=t=>(typeof t=="string"?t:t.name).toLowerCase();function _e(t){if(!Number.isSafeInteger(t.number)||t.number<=0||typeof t.title!="string"||!(t.body===null||typeof t.body=="string")||!["open","closed"].includes(t.state)||!Array.isArray(t.labels))throw new Error("GitHub returned an invalid issue");let e=t.labels.map(gr);return{title:t.title,body:t.body??"",status:t.state==="closed"?"Done":e.includes(ot.Blocked)?"Blocked":e.includes(ot.Doing)?"Doing":"Todo"}}function Lt(t){return{title:t.title,body:t.body,state:t.status==="Done"?"closed":"open"}}function Nt(t){let e=[];for(let r of t.labels){let s=typeof r=="string"?r:r?.name;if(typeof s!="string"||mr.includes(s.toLowerCase()))continue;let o=typeof r=="object"?r.color:"",i=typeof o=="string"?o:"";e.push(/^[0-9a-f]{6}$/i.test(i)?{name:s,color:`#${i.toLowerCase()}`}:{name:s})}let n=Array.isArray(t.assignees)?t.assignees.map(r=>r?.login).filter(r=>typeof r=="string"):[];return{labels:e,assignees:n,...Number.isSafeInteger(t.comments)&&t.comments>=0?{commentCount:t.comments}:{}}}var hr={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(t){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(t)||t.split("/").some(e=>e==="."||e===".."))throw new Error("Repository must be owner/name");return`https://api.github.com/repos/${t}/issues`}function W(t,e,n,r,s){return{operation:t,method:e,url:n,id:r,headers:hr,...s===void 0?{}:{body:JSON.stringify(s)}}}var br="https://atomicdata.dev/properties/parent",it=(t,e)=>JSON.stringify(t)===JSON.stringify(e),at=(t,e)=>`${t} +${e}`;function Ge(t,{known:e={},indexed:n=[],overlay:r=new Map}={}){let s=new Map,o={creates:0,saves:0},i=new Map,a=async p=>{if(!t.getMany)return;let m=p.filter(b=>!i.has(b));for(let b=0;b[]);for(let R of v)"error"in R&&R.error||i.set(R.subject,R)}},c=(p,m,b)=>{if(typeof m!="string"||!n.includes(p))return;let v=e[at(p,m)]??=[];v.includes(b)||v.push(b)},d=async p=>{let m=i.get(p);i.delete(p);let b=m??await t.getResource(p),v=r.get(p);if(!v)return b;for(let[R,{stale:$,after:I}]of v){let z=b.get(R);!it(z,I)&&$.some(J=>it(J,z))?I===void 0?b.remove(R):b.set(R,I):v.delete(R)}return v.size||r.delete(p),b},u=p=>{let m={subject:p.subject,error:void 0,get:b=>p.get(b),set(b,v){let R=s.get(m)??new Map;return R.has(b)||R.set(b,p.get(b)),s.set(m,R),p.set(b,v),m},remove(b){let v=s.get(m)??new Map;return v.has(b)||v.set(b,p.get(b)),s.set(m,v),p.remove(b),m},async save(){let b=s.get(m);if(!b)return;await p.save(),o.saves++,i.delete(p.subject),s.delete(m);let v=r.get(p.subject)??new Map;for(let[R,$]of b){let I=p.get(R),z=v.get(R);v.set(R,{stale:z?[...z.stale,z.after]:[$],after:I}),c(R,I,p.subject)}r.set(p.subject,v)},getLoroDoc(){}};return m};return{writes:o,isLocalOnlyDrive:()=>!1,hasCompletedDriveSyncFor:()=>!0,getSaveState:p=>({kind:s.has(p)?"pending":"idle"}),async queryLocalDb({property:p,value:m}){let b=await t.query({property:p,value:String(m)}),v=[...b];await a([...b,...e[at(p,String(m))]??[]]);for(let R of e[at(p,String(m))]??[]){if(v.includes(R))continue;let $=await d(R).catch(()=>{});$&&it($.get(p),m)&&v.push(R)}for(let R of b)c(p,String(m),R);return{count:v.length,subjects:v}},async getResource(p){return u(await d(p))},async newResource({parent:p,isA:m,propVals:b={}}){let v=await t.newResource({parent:p,isA:m,propVals:b});o.creates++,p&&c(br,p,v.subject);for(let[R,$]of Object.entries(b))c(R,$,v.subject);return u(v)}}}var Dt=()=>({version:1,journal:{},known:{},stale:[]});function yr(t){if(typeof t!="string"||!t)return Dt();let e=JSON.parse(t);if(e.version!==1)throw new Error("Unsupported sync state version");return{...Dt(),...e,journal:e.journal??{},known:e.known??{},stale:e.stale??[]}}var wr=t=>Object.values(t?.records??{}).some(e=>e.pending&&(!e.pending.held||e.unconfirmed)),ze=class{constructor(e,n){this.resource=e;this.property=n;this.state=yr(e.get(n))}resource;property;state;dirty=!1;chain=Promise.resolve();async saveSnapshot(e){this.state.snapshot=e,wr(e)?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 e=this.chain.then(async()=>{this.dirty=!1,this.resource.set(this.property,JSON.stringify(this.state)),await this.resource.save()});return this.chain=e.catch(()=>{}),e}};var _t=t=>t!=null&&t!=="";function vr(t){if(!t||typeof t.subject!="string"||!Array.isArray(t.requires)||!Array.isArray(t.recommends))throw new TypeError("a shared class needs subject, requires and recommends (import it from terms.mjs)")}function Gt({classes:t,lenses:e=[]}){if(!Array.isArray(t)||!t.length)throw new TypeError("createResolver needs at least one shared class");let n=new Map;for(let a of t)vr(a),n.set(a.subject,a);let r=new Map;for(let a of e){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 d=o(c),u=d.kind==="lens"?d.lens.read(a):a;if(!u||typeof u!="object")throw new TypeError(`the lens from ${c} returned no row`);let p={};for(let b of i(d.class))_t(u[b])&&(p[b]=u[b]);let m=d.class.requires.filter(b=>!_t(p[b]));return{class:d.class.subject,via:d.kind,values:p,missing:m,complete:m.length===0}},write(a,c,d={}){let u=o(c),p=new Set(i(u.class)),m=Object.keys(a).filter(b=>!p.has(b));if(m.length)throw new Error(`${m.join(", ")} ${m.length===1?"is":"are"} not a field of ${u.class.subject}`);if(u.kind==="shared")return{...a};if(typeof u.lens.write!="function")throw new Error(`the lens from ${c} is read-only`);return u.lens.write(a,d)}}}var oo=Object.freeze({v1:"https://ontola.github.io/atomic-plugins/ontology/v1"}),io=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"})}),Ue=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 Y={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 zt(t){return{[Y.body]:t.body,...t.title===void 0?{}:{[Y.title]:t.title,[Y.status]:[`${Re}${t.status.toLowerCase()}`]}}}function Ut(t,e){if(e!=="issue")return{body:t[Y.body]};let n={[`${Re}todo`]:"Todo",[`${Re}doing`]:"Doing",[`${Re}blocked`]:"Blocked",[`${Re}done`]:"Done"}[t[Y.status]?.[0]];if(!n||t[Y.status].length!==1)throw new Error("Unsupported task status");return{title:t[Y.title],body:t[Y.body],status:n}}var se=(t,e)=>JSON.stringify(t)===JSON.stringify(e),F=t=>structuredClone(t),Fe=class{constructor({devonian:e,local:n,remote:r,base:s,snapshot:o,save:i,imported:a,uncertain:c}){this.api=e,this.uncertain=c,this.unsettled=new Map,this.imported=a,this.local=n,this.remote=r,this.save=i;let{AtomicSchema:d,AtomicStore:u,AtomicIdentityMap:p,Datatype:m}=e;if(this.store=new u(new d().property(Y.title,m.STRING).property(Y.body,m.MARKDOWN).property(Y.status,m.RESOURCEARRAY)),this.identities=new p(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=F(o?.records??{}),this.held=new Map}scope(e,n){return{scope:this[e].scope,entity:n}}id(e,n,r){return this.identities.externalId(this.scope(e,n),r)}context(e,n){if(n==="issue")return{};let r=n.slice(8),s=this.id(e,"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:F(this.records)})}properties(e){return zt(e)}value(e,n){return Ut(e,n)}lens(e,n,r,s){let o=this[e],i=this.context(e,n);return new this.api.AtomicLens({store:this.store,identities:this.identities,...this.scope(e,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}:${e}`,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[e,n]of Object.entries(this.records))n.pending?.held?delete n.pending:n.pending&&await this.attempt(e,n,!0);for(let[e,n,r]of await this.uncertainCreates())this.unsettled.set(e,{subject:e,entity:n,sent:r,candidates:[]});await this.syncEntity("issue");for(let[e,n]of Object.entries(this.records))n.entity==="issue"&&(this.id("local","issue",e)===void 0||this.id("remote","issue",e)===void 0||await this.syncEntity(`comment:${e}`));for(let e of this.unsettled.keys())this.held.delete(e)}async attempt(e,n,r=!1){try{await this.finish(e,n),delete n.unconfirmed,this.held.delete(e)}catch(s){if(s?.name!=="ReviewRequired")throw s;n.pending.held=!0,r&&(n.unconfirmed=!0),await this.checkpoint(),this.held.set(e,{subject:e,entity:n.entity,remoteId:this.id("remote",n.entity,e),before:F(n.pending.remote),after:F(n.pending.desired),key:s.proposal?.key,...n.unconfirmed?{unconfirmed:!0}:{}})}}async uncertainCreates(){if(!this.uncertain)return[];let e=[];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&&e.push([n,r.entity,s])}return e}candidate(e,n,r){return(n.value?.body??"")!==(r.body??"")?!1:e!=="issue"||n.value?.title===r.title}async landed(e,n){let r=this.records[e];if(!r)throw new Error(`Unknown record: ${e}`);let{entity:s}=r,o=await this.uncertain?.sent(s,e);if(!o||this.id("remote",s,e)!==void 0)throw new Error(`No uncertain create on ${e}`);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,e),r.baseline=s==="issue"?{title:o.title,body:o.body??"",status:"Todo"}:{body:o.body??""},delete r.pending,delete r.unconfirmed,this.unsettled.delete(e),this.held.delete(e),await this.checkpoint(),c}async notArrived(e){let n=this.records[e];if(!n)throw new Error(`Unknown record: ${e}`);let{entity:r}=n,s=await this.uncertain?.sent(r,e);if(!s||this.id("remote",r,e)!==void 0)throw new Error(`No uncertain create on ${e}`);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,e),delete n.unconfirmed,this.unsettled.delete(e),await this.checkpoint()}async conflictRows(e){let n=this.records[e];if(!n)throw new Error(`Unknown record: ${e}`);if(n.pending)throw new Error(`Finish the saved operation on ${e} first`);let r={};for(let o of["local","remote"]){let i=this.id(o,n.entity,e);if(i===void 0)throw new Error(`Missing ${o} record: ${e}`);r[o]=await this[o].get(n.entity,i,this.context(o,n.entity))}let s=st(n.baseline,r.local.value,r.remote.value);return{record:n,rows:r,decision:s}}async describeConflict(e){let{record:n,rows:r,decision:s}=await this.conflictRows(e);return s.conflicts.map(({property:o})=>({field:o,base:F(n.baseline?.[o]),local:F(r.local.value[o]),remote:F(r.remote.value[o])}))}async resolveConflict(e,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=d=>typeof n=="string"?n:r[d],{record:o,rows:i,decision:a}=await this.conflictRows(e);for(let{property:d}of a.conflicts){let u=s(d);if(u===void 0&&typeof n!="string")throw new Error(`Choose a side for ${d}`);if(u!=="local"&&u!=="remote")throw new Error("Keep either the local or the remote side")}let c=F(o.baseline??{});for(let{property:d}of a.conflicts){let u=s(d)==="local"?"remote":"local",p=i[u].value[d];p===void 0?delete c[d]:c[d]=F(p)}return o.baseline=c,await this.checkpoint(),a.conflicts.map(d=>d.property)}async keepLocalOnly(e){let n=this.records[e];if(n?.entity!=="issue")throw new Error(`Unknown issue: ${e}`);let r=this.identities.unbind(this.scope("remote","issue"),e);delete n.pending,n.localOnly=!0;for(let[s,o]of Object.entries(this.records))o.entity===`comment:${e}`&&(this.identities.unbind(this.scope("remote",o.entity),s),delete o.pending);return await this.checkpoint(),r}async forget(e){if(this.records[e]?.entity!=="issue")throw new Error(`Unknown issue: ${e}`);let r=[];for(let[s,o]of Object.entries(this.records))if(!(s!==e&&o.entity!==`comment:${e}`)){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(e){let n={};for(let s of["remote","local"]){let o=await this[s].list(e,this.context(s,e));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",e),i=this.identities.subjectFor(o,s.remoteId);this.records[i]?.localOnly||(this.identities.bind(o,s.remoteId,i),this.identities.bind(this.scope("local",e),s.id,i),this.records[i]??={entity:e})}let r=[...this.unsettled.values()].filter(s=>s.entity===e);for(let s of["remote","local"])for(let o of n[s].values()){let i=this.identities.lookup(this.scope(s,e),o.id);if(!i&&s==="remote"){let a=r.filter(c=>this.candidate(e,o,c.sent));for(let c of a)c.candidates.push(F(o));if(a.length)continue}i||(i=await this.lens(s,e).ingest(o)),this.records[i]??={entity:e}}await this.checkpoint();for(let[s,o]of Object.entries(this.records)){if(o.entity!==e)continue;let i=!1;if(o.localOnly){if(this.id("remote",e,s)===void 0)continue;delete o.localOnly,i=!0}let a={};for(let p of["local","remote"]){let m=this.id(p,e,s);if(a[p]=m===void 0?void 0:n[p].get(m),m!==void 0&&!a[p])throw new Error(`Missing ${p} record: ${s}`)}let c=st(o.baseline,a.local?.value,a.remote?.value);if(c.conflicts.length){let p=c.conflicts.map(b=>b.property),m=new Error(`Conflict on ${s}: ${p.join(", ")}`);throw Object.assign(m,{subject:s,entity:e,fields:p}),m}let d={...a.remote?.value??a.local?.value,...c.remote},u=a.remote?.metadata;if(a.remote&&!a.local&&o.baseline===void 0&&!i){this.store.patch(s,{set:this.properties(d)});let p=await this.lens("local",e,crypto.randomUUID(),u).publish(s);o.baseline=F(d),await this.checkpoint(),await this.imported?.({entity:e,subject:s,row:{id:p,...e==="issue"?{remoteId:a.remote.id}:{},value:F(d),...u?{metadata:F(u)}:{}},context:this.context("local",e)});continue}if(a.local&&a.remote&&se(a.local.value,a.remote.value)&&se(a.local.metadata,u)&&!i){o.baseline=F(d),await this.checkpoint();continue}o.pending={operation:crypto.randomUUID(),local:a.local?.value,remote:a.remote?.value,desired:d,metadata:u,...i?{relink:i}:{}},this.store.patch(s,{set:this.properties(d)}),await this.checkpoint(),await this.attempt(s,o)}}async finish(e,n){let{pending:r,entity:s}=n;for(let o of["local","remote"]){let i=this.id(o,s,e);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 ${e}`)}for(let o of["remote","local"]){let i=this.id(o,s,e),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(e),await this.checkpoint())}for(let o of["local","remote"]){let i=await this[o].get(s,this.id(o,s,e),this.context(o,s));if(!se(i.value,r.desired))throw new Error(`Concurrent edit after write on ${e}`)}n.baseline=F(r.desired),delete n.pending,await this.checkpoint()}};var mo=te.properties.commentsFolder??"https://atomicdata.dev/properties/commentsFolder";function Ft(t,e){if(typeof e!="string"||!e)throw new Error("An Atomic drive is required");if(typeof t.isLocalOnlyDrive=="function"&&t.isLocalOnlyDrive(e))return{drive:e,kind:"local-only",ready:!0};let n=typeof t.hasCompletedDriveSyncFor=="function"&&t.hasCompletedDriveSyncFor(e)===!0;return{drive:e,kind:"synced",ready:n}}function Bt(t,e){let n=Ft(t,e);if(!n.ready)throw new Error(`Atomic drive has not finished syncing: ${e}`);return n}function ve(t,e,n,r){if(r==="offline")throw new Error("AtomicServer disconnected");if(Ft(t,e).kind==="local-only")return;if(typeof t.getSaveState!="function")throw new Error(`Atomic write not acknowledged: ${n.subject}`);let s=t.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 qe=async t=>Array.from(new Uint8Array(await crypto.subtle.digest("SHA-256",new TextEncoder().encode(t))),e=>e.toString(16).padStart(2,"0")).join(""),xr=(t,e)=>JSON.stringify(t)===JSON.stringify(e),Be=class{constructor(e,n,r){if(this.store=e,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(e,n,r){let s=await this.call(e,n,await qe(r??`${e}:${JSON.stringify(n)}`));if(s.status<200||s.status>=300)throw new Error(`GitHub ${e} returned ${s.status}`);return s.body?JSON.parse(s.body):void 0}row(e,n,r={}){if(e==="issue"){if(n.pull_request)throw new Error("Pull requests are excluded");return{id:n.number,value:_e(n),metadata:this.metadata(n,{number:n.number,...Nt(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(e,n){return{...n,...e.user?.login?{author:e.user.login}:{},...e.html_url?{url:e.html_url}:{},...e.created_at?{createdAt:e.created_at}:{},...e.updated_at?{updatedAt:e.updated_at}:{}}}async list(e,n={}){let r=[];for(let s=1;s<=100;s++){let o=await this.request(e==="issue"?"list_issues":"list_comments",{page:s,...e==="issue"?{}:{number:n.issueId}});if(!Array.isArray(o))throw new Error("Invalid GitHub page");for(let i of o)e==="issue"&&"pull_request"in i||r.push(this.row(e,i,n));if(o.length<100)return r}throw new Error("More than 10,000 records in one scan")}async get(e,n,r){let s=await this.request(e==="issue"?"get_issue":"get_comment",e==="issue"?{number:n}:{id:n}),o=this.row(e,s,r);if(o.id!==n)throw new Error("Provider returned another identity");return o}async create(e,n,r,s,o){let i=await this.request(e==="issue"?"create_issue":"create_comment",e==="issue"?{title:n.title,body:n.body}:{number:o.issueId,body:n.body},`${r}:create`),a=this.row(e,i,o);return e==="issue"&&n.status!=="Todo"&&await this.update(e,a.id,n,`${r}:initial-state`,s,o),{...a,value:n}}async update(e,n,r,s,o,i){if(e!=="issue"){await this.get(e,n,i),await this.request("update_comment",{id:n,body:r.body},`${s}:body`);return}if(!Ht.includes(r.status))throw new Error("Unsupported task status");if(await this.get(e,n,i),await this.request("update_issue",{number:n,...Lt(r)},`${s}:fields`),r.status==="Done")return;let a=await this.request("get_issue",{number:n}),c=new Set(a.labels.map(u=>(typeof u=="string"?u:u.name).toLowerCase())),d=[["Doing","atomic:doing","add_doing_label","remove_doing_label","doing","todo"],["Blocked","atomic:blocked","add_blocked_label","remove_blocked_label","blocked","unblocked"]];for(let[u,p,,m,,b]of d)r.status!==u&&c.has(p)&&await this.request(m,{number:n},`${s}:${b}`);for(let[u,p,m,,b]of d)r.status===u&&!c.has(p)&&await this.request(m,{number:n},`${s}:${b}`)}},Ve=class{constructor(e,n){this.store=e,this.config=n,this.connection=n.connection,this.scope=`https://atomicdata.dev/devonian-local/${encodeURIComponent(this.connection.table)}`}async subjects(e,n){Bt(this.store,this.connection.drive);let r=await this.store.queryLocalDb({drive:this.connection.drive,property:e,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(e,n){let s=(await Promise.all((await this.subjects(K.properties.localId,n)).map(o=>this.resource(o)))).filter(o=>o.get(K.properties.parent)===e);if(s.length>1)throw new Error("Duplicate Atomic creation identity");return s[0]}async resource(e){let n=await this.store.getResource(e);if(n.error)throw n.error;return n.getLoroDoc(),n}row(e,n,r={}){let s=this.connection,o=n.get(K.properties.isA)??[];if(e==="issue"){if(!o.includes(s.rowClass)||n.get(K.properties.parent)!==s.table)throw new Error("Resource is not a row of this issue tracker")}else if(!o.includes(te.classes.message)||n.get(te.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)),e!=="issue"){let m=i?.commentId;return{id:n.subject,...Number.isSafeInteger(m)&&m>0?{remoteId:m}:{},value:{body:n.get(K.properties.description)??""},...i?{metadata:i}:{}}}let a=n.get(s.status)??[s.tags.Todo],c=Object.keys(s.tags).find(m=>s.tags[m]===a[0]);if(a.length!==1||!c)throw new Error("Choose exactly one Todo/Doing/Blocked/Done status");let d=n.get(K.properties.name),u=n.get(s.body)??"";if(typeof d!="string"||!d.trim()||typeof u!="string")throw new Error("Invalid Atomic issue");let p=n.get(s.number);if(p!==void 0&&(!Number.isSafeInteger(p)||p<=0))throw new Error("Invalid GitHub issue number");return{id:n.subject,remoteId:p,value:{title:d,body:u,status:c},...i?{metadata:i}:{}}}async list(e,n={}){let r=await this.subjects(e==="issue"?K.properties.parent:te.properties.about,e==="issue"?this.connection.table:n.issueId),s=[];for(let o of r){let i=await this.resource(o);(i.get(K.properties.isA)??[]).includes(e==="issue"?this.connection.rowClass:te.classes.message)&&s.push(this.row(e,i,n))}return s}async get(e,n,r){return this.row(e,await this.resource(n),r)}values(e,n,r,s){let o=this.connection;return{...e==="issue"?{[K.properties.name]:n.title,[o.body]:n.body,[o.status]:[o.tags[n.status]],...r?.number?{[o.number]:r.number}:{}}:{[K.properties.description]:n.body,[te.properties.about]:s.issueId},...r?{[this.config.provenance]:r}:{}}}async create(e,n,r,s,o){let i=e==="issue"?this.connection.table:this.config.commentsFolder,a=`devonian:${await qe(r)}`,c=await this.findByLocalId(i,a);if(c){ve(this.store,this.connection.drive,c);let u=await this.get(e,c.subject,o);if(!xr(u.value,n))throw new Error("Recovered Atomic create was edited; reconcile before retry");return u}let d=await this.store.newResource({parent:i,isA:[e==="issue"?this.connection.rowClass:te.classes.message],propVals:{...this.values(e,n,s,o),[K.properties.localId]:a}});return ve(this.store,this.connection.drive,d,await d.save()),this.get(e,d.subject,o)}async update(e,n,r,s,o,i){let a=await this.resource(n);this.row(e,a,i);for(let[c,d]of Object.entries(this.values(e,r,o,i)))await a.set(c,d);ve(this.store,this.connection.drive,a,await a.save())}};var X={type:"integer",description:"Positive identifier or page number"},$e={type:"string",description:"Issue or comment field value"},Vt=[["list_issues","List issues","list",{page:X},["page"]],["update_issue","Update an issue","update",{number:X,title:$e,body:$e,state:$e},["number","title","body","state"]],["add_doing_label","Mark an issue as doing","doing-add",{number:X},["number"]],["remove_doing_label","Remove the doing label","doing-remove",{number:X},["number"]],["add_blocked_label","Mark an issue as blocked","blocked-add",{number:X},["number"]],["remove_blocked_label","Remove the blocked label","blocked-remove",{number:X},["number"]],["list_comments","List issue comments","comments-list",{number:X,page:X},["number","page"]],["get_comment","Get an issue comment","comments-get",{id:X},["id"]],["create_comment","Create an issue comment","comments-create",{number:X,body:$e},["number","body"]],["update_comment","Update an issue comment","comments-update",{id:X,body:$e},["id","body"]]],xo=Vt.map(([t,e,n,r,s])=>({name:t,title:e,description:`${e} in this connected repository. Writes require approval.`,operation:n,inputSchema:{type:"object",properties:r,required:[...s],additionalProperties:!1}}));function qt(t,e,n){let r=Vt.find(c=>c[0]===e);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,d]of Object.entries(n)){if(!(c in o))throw new Error(`Unexpected ${c}`);if(["number","id","page"].includes(c)){if(!Number.isSafeInteger(d)||Number(d)<=0||c==="page"&&Number(d)>100)throw new Error(`Invalid ${c}`)}else if(typeof d!="string")throw new Error(`Invalid ${c}`)}let a=we(t);switch(e){case"list_issues":return W(s,"GET",`${a}?state=all&per_page=100&page=${n.page}&sort=created&direction=asc`,"action");case"list_comments":return W(s,"GET",`${a}/${n.number}/comments?per_page=100&page=${n.page}`,"action");case"get_comment":return W(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 W(s,e==="create_comment"?"POST":"PATCH",e==="create_comment"?`${a}/${n.number}/comments`:`${a}/comments/${n.id}`,"action",{body:n.body});case"add_doing_label":return W(s,"POST",`${a}/${n.number}/labels`,"action",{labels:["atomic:doing"]});case"remove_doing_label":return W(s,"DELETE",`${a}/${n.number}/labels/atomic%3Adoing`,"action");case"add_blocked_label":return W(s,"POST",`${a}/${n.number}/labels`,"action",{labels:["atomic:blocked"]});case"remove_blocked_label":return W(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 W(s,"PATCH",`${a}/${n.number}`,"action",{title:n.title,body:n.body,state:n.state})}}function Jt({repository:t,journal:e,save:n,dispatch:r}){if(typeof r!="function")throw new Error("proxyTransport needs a dispatch function");let s=we(t),o=Promise.resolve();return(i,a,c)=>{let d=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 p=qt(t,i,a)??(i==="get_issue"?W("get","GET",`${s}/${a.number}`,c):i==="create_issue"?W("create","POST",s,c,a):void 0);if(!p)throw new Error("Unsupported GitHub action");let m=p.method!=="GET",b=JSON.stringify({action:i,args:a}),v=e[c];if(m&&v){if(v.signature!==b)throw new Error("Operation identity reused with different arguments");if(v.receipt)return v.receipt;throw new Error(`Uncertain GitHub write (${i}). Inspect its outcome before retrying; it will not be resent.`)}m&&(e[c]={signature:b},await n());let R=new URL(p.url),$=await r(`${R.pathname}${R.search}`,{method:p.method,...p.body?{body:p.body}:{}}).catch(async I=>{throw I?.notSent?(m&&(delete e[c],await n()),I):new Error(`Proxy request failed (${I?.message??I}). Check CORS and reconnect; an uncertain write will not be resent.`)});return m&&$.status>=200&&$.status<300&&(e[c].receipt=$,await n()),$},u=o.then(d);return o=u.catch(()=>{}),u}}var ct=class extends Error{constructor(e){super(`Review required before writing to GitHub: ${e.key}`),this.name="ReviewRequired",this.proposal=e}};function kr(t,e,n){return JSON.stringify([t,e??null,n])}function Kt(t,e=new Set){let n=(r,s,o)=>{let i=kr(r,s,o);if(!e.has(i))throw new ct({key:i,entity:r,id:s,value:o})};return{get scope(){return t.scope},list:(...r)=>t.list(...r),get:(...r)=>t.get(...r),create(r,s,...o){return n(r,void 0,s),t.create(r,s,...o)},update(r,s,o,...i){return n(r,s,o),t.update(r,s,o,...i)}}}var H="https://atomicdata.dev",V=`${H}/properties/parent`,ke=`${H}/properties/isA`,B=`${H}/properties/name`,Q=`${H}/properties/shortname`,ne=`${H}/properties/description`,Sr=`${H}/properties/datatype`,en=`${H}/properties/recommends`,Je=`${H}/properties/properties`,Wt=`${H}/properties/classes`,Yt=`${H}/properties/classtype`,Er=`${H}/properties/allowsOnly`,de=`${H}/properties/localId`,jo=`${H}/properties/color`,ue=`${H}/properties/about`,Tr=`${H}/classes/Property`,Ao=`${H}/classes/SelectProperty`,Rr=`${H}/classes/Class`,Oo=`${H}/classes/Tag`,$r=`${H}/classes/Folder`,tn=`${H}/classes/Message`,jr=`${H}/ontology/server/property/default-ontology`,le=Ue["issue-v1"].subject,xe=`${H}/task/v1`,Ae=`${xe}/status`,Oe=`${xe}/body`,je={string:`${H}/datatypes/string`,integer:`${H}/datatypes/integer`},pe=["Todo","Doing","Blocked","Done"],Ie={Todo:`${xe}/todo`,Doing:`${xe}/doing`,Blocked:`${xe}/blocked`,Done:`${xe}/done`},lt="github-issues:sync",Xt="github-issues:comments",Ar=[{key:"number",shortname:"github-issue-number",name:"GitHub issue number",datatype:je.integer,description:"The issue number in the bound GitHub repository."},{key:"provenance",shortname:"github-source",name:"GitHub source",datatype:je.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:je.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:je.string,description:"The owner/name of the repository this app syncs with."},{key:"syncState",shortname:"github-sync-state",name:"GitHub sync state",datatype:je.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."}],Or=["number","provenance","baseline"],ee=t=>Array.isArray(t)?t.filter(e=>typeof e=="string"):[];async function dt(t,e,n){for(let r of await t.query({property:de,value:n})){let s=await t.getResource(r);if(s.get(V)===e)return s}}async function Ir(t,e){let n=ee(e.get(Je)),r=new Map;for(let i of n){let c=(await t.getResource(i)).get(Q);typeof c=="string"&&r.set(c,i)}let s=[],o={};for(let i of Ar){let a=r.get(i.shortname);a||(a=(await t.newResource({parent:e.subject,isA:[Tr],propVals:{[Q]:i.shortname,[B]:i.name,[ne]:i.description,[Sr]:i.datatype}})).subject,s.push(a)),o[i.key]=a}return s.length>0&&await e.set(Je,[...n,...s]).save(),o}async function Pr(t,e){for(let n of ee(e.get(Je))){let r=await t.getResource(n);if(r.get(Q)!=="issue-status")continue;let s={};for(let o of ee(r.get(Er))){let i=(await t.getResource(o)).get(Q);typeof i=="string"&&(s[i]=o)}return{status:n,tags:s}}}async function nn(t,e,n){let r=(await t.getResource(e)).get(jr);if(typeof r=="string")return t.getResource(r);if(n&&n!==le){let s=(await t.getResource(n)).get(V);if(typeof s=="string")return t.getResource(s)}throw new Error("This app has no ontology of its own to add fields to.")}async function Zt(t,e,n){for(let r of ee(e.get(ke))){let s=await t.getResource(r).catch(()=>{});for(let o of ee(s?.get(en)??[]))if((await t.getResource(o).catch(()=>{}))?.get(Q)===n)return o}}function Qt(t,e,n){if(!e)return!1;let r=ee(t.get(e)??[]),s=n.filter(o=>!r.includes(o));return s.length?(t.set(e,[...r,...s]),!0):!1}var ut=class 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"}};async function Cr(t,e,n,r){let s=await t.getResource(e),o=Qt(s,await Zt(t,s,"renders"),[le]),i=Qt(s,await Zt(t,s,"row-extras"),r);(o||i)&&await s.save();let a=await t.getResource(n);if(a.get(V)!==e)throw new ut;a.get(Yt)!==le&&await a.set(Yt,le).save()}async function rn(t){let e=await t.getData();return e?.table?(await t.getResource(e.table)).get(V)===await t.getApp():!0}async function sn(t,e,n){let r=new Map(Object.entries(n.tags).map(([o,i])=>[i,o])),s=0;for(let o of await t.list()){let i=await t.get(o);if(i.get(V)!==e||ee(i.get(ke)).includes(le))continue;let a=ee(i.get(n.status)??[]).map(d=>{let u=r.get(d),p=pe.find(m=>m.toLowerCase()===u);return p?Ie[p]:d}),c=i.get(ne);i.set(ke,[le]),a.length&&i.set(Ae,a),typeof c=="string"&&i.set(Oe,c),i.remove(n.status),i.remove(ne),await i.save(),s++}return s}async function Mr(t,e,n){let r=ee(e.get(Wt));for(let o of r)if((await t.getResource(o)).get(Q)==="github-issue-tracker-sync")return o;let s=await t.newResource({parent:e.subject,isA:[Rr],propVals:{[Q]:"github-issue-tracker-sync",[B]:"GitHub issue tracker sync",[ne]:"Where the GitHub issues app keeps its bound repository and sync state.",[en]:n}});return await e.set(Wt,[...r,s.subject]).save(),s.subject}async function on(t){let e=await t.getApp(),n=await dt(t,e,lt);if(!n)return;let r=await t.getData(),s=await nn(t,e,r?.rowClass).catch(()=>{});if(s)for(let o of ee(s.get(Je))){if((await t.getResource(o)).get(Q)!=="github-repository")continue;let a=n.get(o);return typeof a=="string"&&a?a:void 0}}async function an(t,e){let n=await t.getApp(),r=await t.getData();if(!r?.table)throw new Error("This app has no table to sync into.");let s=await nn(t,n,r.rowClass),o=await Ir(t,s);await Cr(t,n,r.table,Or.map(b=>o[b]));let i=await Pr(t,s),a=await Mr(t,s,[B,o.repository,o.syncState]),c=await dt(t,n,Xt);c??=await t.newResource({parent:n,isA:[$r],propVals:{[B]:"GitHub comments",[de]:Xt,[ne]:"Comments on the GitHub issues in this app\u2019s table, as Messages about each row."}});let d=await dt(t,n,lt),u=d?.get(o.repository);if(typeof u=="string"&&u){if(e&&e!==u)throw new Error(`This app is bound to ${u}. Install another app for ${e}.`);e=u}if(!e)throw new Error("Choose a GitHub repository first.");d||(d=await t.newResource({parent:n,isA:[a],propVals:{[B]:`GitHub sync: ${e}`,[de]:lt,[o.repository]:e}}));let p=await t.getResource(r.table),m=`${e} issues`;return p.get(B)!==m&&await p.set(B,m).save(),{repository:e,sync:d,...i?{legacy:i}:{},tracker:{app:n,table:r.table,rowClass:le,properties:{status:Ae,body:Oe,...o},tags:Ie,commentsFolder:c.subject}}}var Se="github-issues",Hr=[/^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/],cn=["unknown_connection","not_delegated","capability_scope","platform_mismatch","credential_refresh_failed"],Lr=[...cn,"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 ln(t){let e=t.body,n=typeof e?.error=="string"?e.error:void 0;if(t.status<400||!n||!Lr.includes(n))return;let r=typeof e?.message=="string"?`: ${e.message}`:"";return Object.assign(new Error(cn.includes(n)?`The integration proxy refused this connection (${n}${r}). Connect again.`:`The integration proxy refused the request (${n}${r}).`),{notSent:!0})}function dn(t,e){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 t.request({platform:Se,connectionId:e,path:o.pathname,method:r,...o.search?{query:Object.fromEntries(o.searchParams)}:{},...s===void 0?{}:{body:s}})}catch(c){let d=c instanceof Error?c.message:String(c);throw Object.assign(new Error(d),{notSent:Hr.some(u=>u.test(d))})}let a=ln(i);if(a)throw a;return{status:i.status,body:typeof i.body=="string"?i.body:JSON.stringify(i.body??null)}}}var Nr=5;async function un(t,e){let n=[];for(let r=1;r<=Nr;r++){let s=await t.request({platform:Se,connectionId:e,path:"/user/repos",method:"GET",query:{per_page:"100",page:String(r),sort:"updated"}}),o=ln(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 Dr="https://github-issues-app.invalid/bridge",pt=Ue["issue-v1"],_r=Gt({classes:[pt]}),Gr=[...pt.requires,...pt.recommends],zr=new Map(pe.map(t=>[Ie[t],t])),ft=t=>Array.isArray(t)?t.map(ft):t&&typeof t=="object"?Object.fromEntries(Object.keys(t).sort().map(e=>[e,ft(t[e])])):t,mt=t=>JSON.stringify(ft(t)),Ur=t=>pe.includes(t),gt=class extends Ve{bound=()=>!1;onBaseline=()=>{};baselines=new Map;asIs=new Map;async subjects(e,n){let r=await super.subjects(e,n);if(e!==ue)return r;let s=[];for(let o of r)(await this.store.getResource(o)).get(V)===this.config.commentsFolder&&s.push(o);return s}storedBaseline(e){let n=e.get(this.config.baseline),r;try{r=typeof n=="string"?JSON.parse(n):void 0}catch{r=void 0}return this.baselines.set(e.subject,r===void 0?void 0:mt(r)),r}row(e,n,r={}){let s=this.storedBaseline(n);if(e!=="issue"){let v=super.row(e,n,r);return this.onBaseline(e,n.subject,s),v}let o=this.connection,i=n.get(ke);if(!Array.isArray(i)||!i.includes(o.rowClass)||n.get(V)!==o.table)throw new Error("Resource is not a row of this issue tracker");let{values:a}=_r.read(Object.fromEntries(Gr.map(v=>[v,n.get(v)])),o.rowClass),c=Array.isArray(a[Ae])?a[Ae].filter(v=>typeof v=="string"):[],d=c.length===0?"Todo":c.length===1?zr.get(c[0]):void 0;if(d)this.asIs.delete(n.subject);else{this.asIs.set(n.subject,c);let v=s?.status;d=Ur(v)?v:"Todo"}let u=a[B],p=a[Oe]??"";if(typeof u!="string"||!u.trim()||typeof p!="string")throw new Error("Invalid Atomic issue");let m=n.get(o.number);if(m!==void 0&&(!Number.isSafeInteger(m)||m<=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(e,n.subject,s),{id:n.subject,remoteId:m,value:{title:u,body:p,status:d},...b?{metadata:b}:{}}}localOnly(e,n){return n.get(this.connection.number)===void 0&&!this.bound("issue",e)&&!this.config.publish.has(e)}async issueRows(e){let n=[];for(let r of await this.subjects(V,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&&!e||n.push({id:r,r:s,localOnly:i})}return n}async list(e,n={}){return e!=="issue"?super.list(e,n):(await this.issueRows(!1)).map(({r})=>this.row(e,r,n))}async listAll(){let e=[];for(let{r:n,localOnly:r}of await this.issueRows(!0)){let s;try{s=this.row("issue",n)}catch{let o=n.get(B),i=n.get(Oe);s={id:n.subject,value:{title:typeof o=="string"?o:"",body:typeof i=="string"?i:"",status:"Todo"}}}e.push(r?{...s,localOnly:r}:s)}return e}values(e,n,r,s){let o=super.values(e,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(e,n,r,s,o,i){let a=await this.resource(n),c=this.row(e,a,i),d=e==="issue"&&this.asIs.has(n)&&c.value.status===r.status;for(let[u,p]of Object.entries(this.values(e,r,o,i)))d&&u===this.connection.status||a.set(u,p);ve(this.store,this.connection.drive,a,await a.save()),this.baselines.set(n,mt(r))}},Fr={AtomicIdentityMap:Ne,AtomicLens:De,AtomicSchema:He,AtomicStore:Le,Datatype:C};function Br(t,e){return{get scope(){return t.scope},list:(...n)=>t.list(...n),get:(...n)=>t.get(...n),async create(...n){let r=await t.create(...n);return e.value++,r},async update(...n){let r=await t.update(...n);return e.value++,r}}}var Vr=25,qr=1e4;function oe(t){let{store:e,repository:n,tracker:r,state:s}=t,o=Ge(e,{known:s.state.known,indexed:[V,ue,de],...t.overlay?{overlay:t.overlay}:{}}),i=new gt(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=Jt({repository:n,journal:s.state.journal,save:()=>s.saveJournal(),dispatch:t.dispatch??dn(t.proxy,t.connectionId)}),c=new Be(void 0,{repository:n},a),d=s.state.journal,u=(E,O)=>qe(`${JSON.stringify([c.scope,E,O])}:create`),p={async sent(E,O){let j=d[await u(E,O)];if(!j?.signature||j.receipt)return;let{args:_}=JSON.parse(j.signature);return E==="issue"?{title:_.title,body:_.body??""}:{body:_.body??""}},async forget(E,O){let j=await u(E,O);d[j]?.receipt||(delete d[j],await s.saveJournal())}},m={value:0},b=0,v=Date.now(),R=async({entity:E,row:O,context:j})=>{(++b>=Vr||Date.now()-v>=qr)&&(b=0,v=Date.now(),await s.flush());let _=t.onImported;_&&(E==="issue"?_({entity:E,row:hn(O,[])}):j.issueId&&_({entity:"comment",issue:j.issueId,comment:gn(O.id,O.value.body,O.metadata??{})}))},$={},I=new WeakMap,z=async E=>{for(let[O,j]of Object.entries($)){if(j.baseline===void 0)continue;if(I.get(j)!==j.baseline){let g=J.id("local",j.entity,O);if(typeof g!="string")continue;let h=mt(j.baseline);if(i.baselines.get(g)!==h){let y=await o.getResource(g);y.set(r.properties.baseline,JSON.stringify(j.baseline)),await y.save(),o.writes.saves--,i.baselines.set(g,h)}I.set(j,j.baseline)}let _=E.records?.[O];_&&delete _.baseline}await s.saveSnapshot(E)},J=new Fe({imported:R,devonian:Fr,local:i,remote:Kt(Br(c,m),t.approved??new Set),base:Dr,snapshot:s.state.snapshot,save:z,uncertain:p});$=J.records;let w=(E,O)=>J.identities.lookup(J.scope("local",E),O);return i.bound=(E,O)=>w(E,O)!==void 0,i.onBaseline=(E,O,j)=>{let _=w(E,O),g=_?$[_]:void 0;j===void 0||!g||(g.baseline=structuredClone(j),I.set(g,g.baseline))},{bridge:J,atomicStore:o,sent:m,local:i}}async function Jr(t,e,n,r,s){let o={...e.writes},i=await pn(e,r,s),a=Object.entries(t.records).filter(([c,d])=>t.id("local",d.entity,c)!==void 0&&t.id("remote",d.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:[...t.held.values()].map(c=>{let d=t.id("local",c.entity,c.subject),u=typeof d=="string"?{...c,local:d}:c;if(c.entity==="issue")return u;let p=c.entity.slice(8),m=t.id("remote","issue",p);return m===void 0?u:{...u,issueNumber:m}}),uncertain:[...t.unsettled.values()].map(c=>{let d=t.id("local",c.entity,c.subject),u=c.entity==="issue"?void 0:t.id("remote","issue",c.entity.slice(8));return{subject:c.subject,entity:c.entity,sent:c.sent,candidates:c.candidates.map(Kr),...typeof d=="string"?{local:d}:{},...typeof u=="number"?{issueNumber:u}:{}}}),rows:i}}function Kr(t){let e=t.metadata??{},n=t.value,r={title:q(n.title),url:q(e.url),author:q(e.author),createdAt:q(e.createdAt)};return{id:Number(t.id),body:n.body??"",...Object.fromEntries(Object.entries(r).filter(([,s])=>s!==void 0))}}async function pn(t,e,n){let r=await Wr(t,n),s=new Map,o=async a=>{if(!s.has(a)){let c=pe.find(p=>Ie[p]===a),d=c?void 0:await t.getResource(a).catch(()=>{}),u=d?.get(B)??d?.get(Q);s.set(a,c??(typeof u=="string"&&u?u:a.split("/").pop()))}return s.get(a)},i=[];for(let a of await e.listAll()){let c=e.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 ht(t){let{atomicStore:e,local:n}=oe(t);return pn(e,n,t)}async function ie(t){let{bridge:e,atomicStore:n,sent:r,local:s}=oe(t);try{await e.sync()}catch(a){let c=a,d=/^Missing (local|remote) record: (.+)$/.exec(c?.message??"");if(d){let u=d[2],p=e.records[u]?.entity;c.missing={side:d[1],subject:u,entity:p},c.entity??=p,c.subject??=u}if(c?.subject&&c.entity){let u=e.id("local",c.entity,c.subject);typeof u=="string"&&(c.local=u)}throw await t.state.flush().catch(()=>{}),a}let o=t.state.state.publish??[],i=o.filter(a=>!s.bound("issue",a));return i.length!==o.length&&(t.state.state.publish=i),await t.state.flush(),Jr(e,n,r,s,t)}async function fn(t,e){let{bridge:n}=oe(t);return n.describeConflict(e)}async function mn(t,e,n){let{bridge:r}=oe(t);try{return await r.resolveConflict(e,n)}finally{await t.state.flushIfDirty()}}var q=t=>typeof t=="string"?t:void 0;function gn(t,e,n){return{subject:t,body:e??"",...q(n.author)?{author:q(n.author)}:{},...q(n.createdAt)?{createdAt:q(n.createdAt)}:{},...q(n.url)?{url:q(n.url)}:{}}}function hn(t,e){let n=t.metadata??{},r=Array.isArray(n.labels)?n.labels.filter(o=>typeof o?.name=="string"):[],s={updatedAt:q(n.updatedAt),url:q(n.url),author:q(n.author)};return{subject:t.id,...t.remoteId===void 0?{}:{number:t.remoteId},title:t.value.title,status:t.value.status,body:t.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:e}}async function Wr(t,e){let{tracker:n}=e,r=new Map,{subjects:s}=await t.queryLocalDb({drive:n.app,property:V,value:n.commentsFolder});for(let o of s){let i=await t.getResource(o),a=i.get(ue);if(typeof a!="string")continue;let c={};try{let p=i.get(n.properties.provenance);typeof p=="string"&&(c=JSON.parse(p))}catch{}let d=gn(o,q(i.get(ne)),c),u=r.get(a)??[];u.push(d),r.set(a,u)}for(let o of r.values())o.sort((i,a)=>(i.createdAt??"\uFFFF").localeCompare(a.createdAt??"\uFFFF"));return r}async function bn(t,e){let{bridge:n}=oe(t),r=n.id("local","issue",e);try{if(await n.keepLocalOnly(e),typeof r=="string"){let s=await t.store.getResource(r);s.get(t.tracker.properties.number)!==void 0&&await s.remove(t.tracker.properties.number).save()}}finally{await t.state.flush()}}async function yn(t,e){let{bridge:n}=oe(t),r=[];try{r=await n.forget(e)}finally{await t.state.flush()}for(let s of r)await(await t.store.getResource(s).catch(()=>{}))?.destroy()}async function wn(t,e,n){let{bridge:r,atomicStore:s}=oe(t),o;try{await r.landed(e,n),o=r.records[e]?.entity}finally{await t.state.flush()}let i=r.id("local","issue",e);if(o==="issue"&&typeof i=="string"){let a=await s.getResource(i);a.set(t.tracker.properties.number,n),await a.save()}}async function vn(t,e){let{bridge:n}=oe(t);try{await n.notArrived(e)}finally{await t.state.flush()}}var Yr=[/^GitHub \S+ returned 401$/,/is delegated to this app/,/^The integration proxy refused this connection/],Xr=[[/^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"]];function xn(t){let e=t,n=t instanceof Error?t.message:String(t);if(e?.subject&&Array.isArray(e.fields))return{kind:"conflict",message:n,subject:e.subject,fields:e.fields,...e.local?{local:e.local}:{}};if(Yr.some(s=>s.test(n)))return{kind:"reconnect",message:n};let r=Xr.find(([s])=>s.test(n));return r?{kind:"paused",message:n,reason:r[1],...e?.missing?{missing:{...e.missing,...e.local?{local:e.local}:{}}}:{}}:{kind:"failed",message:n}}var Zr=250,Qr=t=>pe.includes(t)?t:void 0;function kn(t,e=()=>{},n=Date.now){let r={kind:"loading"},s=Promise.resolve(),o,i,a={},c=new Map,d=g=>(r=g,e(g),g),u=g=>{let h=s.then(g,g);return s=h.catch(()=>{}),h},p=async g=>{if(o)return o;let h=await an(t,g),y=new ze(h.sync,h.tracker.properties.syncState);if(o={tracker:h.tracker,sync:h.sync,state:y,overlay:new Map},a={...y.state.view},h.legacy&&y.state.migrated!=="issue-v1"){let k=R(o),{table:S,app:A}=h.tracker;await sn({list:async()=>(await k.queryLocalDb({drive:A,property:V,value:S})).subjects,get:N=>k.getResource(N)},S,h.legacy),y.state.migrated="issue-v1",await y.flush()}return o},m=(g,h,y)=>({store:t,proxy:t.proxy,connectionId:h,repository:y,tracker:g.tracker,state:g.state,overlay:g.overlay,onImported:v}),b=0;function v(g){if(r.kind!=="ready"||!r.busy)return;let h=r,y=h.last?.result??Ke(),k={...h.importing??{issues:0,comments:0}},S;g.entity==="issue"?(S=[...y.rows.filter(f=>f.subject!==g.row.subject),g.row],k.issues++):(S=y.rows.map(f=>f.subject===g.issue?{...f,comments:[...f.comments,g.comment]}:f),k.comments++);let A={...h,last:{at:h.last?.at??0,result:{...y,rows:S}},importing:k},N=n();if(N-bGe(t,{known:g.state.state.known,indexed:[V,ue,de],overlay:g.overlay}),$=g=>r.kind==="ready"?r:g,I=(g,h)=>u(async()=>{if(r.kind!=="ready"||!t.proxy)return r;let y=r;d({...y,busy:g});try{let k=await p(y.repository);if(!y.last&&g==="syncing"){let f=await ht(m(k,y.connectionId,y.repository)).catch(()=>[]);f.length&&r.kind==="ready"&&!r.last&&d({...r,last:{at:0,result:{...Ke(),rows:f}}})}let S=await h(k,y);i=void 0;let A=$(y),N=(A.touched??[]).filter(f=>!(y.touched??[]).includes(f));for(let f of c.keys())N.includes(f)||c.delete(f);return d({kind:"ready",connectionId:y.connectionId,repository:y.repository,...S?{last:{at:n(),result:J(S)}}:A.last?{last:A.last}:{},...N.length?{touched:N}:{}})}catch(k){let S=xn(k);S.kind==="conflict"&&(i=S);let A=$(y),N=A.last;if(o)try{let f=await ht(m(o,y.connectionId,y.repository));N={at:A.last?.at??0,result:J({...A.last?.result??Ke(),rows:f})}}catch{}return d({kind:"ready",connectionId:y.connectionId,repository:y.repository,...N?{last:N}:{},...A.touched?.length?{touched:A.touched}:{},problem:S})}}),z=(g,h,y)=>g.some(k=>k.subject===h)?g.map(k=>k.subject===h?y(k):k):[...g,y(es(h))],J=g=>{let h=g.rows;for(let[y,k]of c)h=z(h,y,k);return h===g.rows?g:{...g,rows:h}},w=(g,h)=>{if(r.kind!=="ready")return;let y=r,k=c.get(g);c.set(g,k?S=>h(k(S)):h),d({...y,last:{at:y.last?.at??0,result:{...y.last?.result??Ke(),rows:z(y.last?.result.rows??[],g,h)}},touched:[...new Set([...y.touched??[],g])]})},E=async(g,h)=>{try{return await u(async()=>h(await p(g.repository))),!0}catch(y){return d({...$(g),problem:xn(y)}),!1}},O=()=>{let g=r.kind==="ready"?r.problem:void 0,h=g?.kind==="paused"?g.missing:void 0;return h?.side==="remote"&&h.entity==="issue"?h.subject:void 0},j=g=>r.kind==="ready"&&!!r.last?.result.uncertain?.some(h=>h.subject===g);return{state:()=>r,async load(){if(!await rn(t))return d({kind:"other-table"});let g=t.proxy;if(!g||typeof g.connections!="function")return d({kind:"no-proxy"});let h=await on(t),y=[];h&&(y=(await p(h)).state.state.stale);let k=(await g.connections({platform:Se})).find(S=>!y.includes(S.connectionId));return d(k?h?{kind:"ready",connectionId:k.connectionId,repository:h}:{kind:"choose-repository",connectionId:k.connectionId}:{kind:"not-connected"})},async start(){let g=await this.load();return g.kind==="choose-repository"?this.listRepositories():g.kind==="ready"?this.sync():g},async connect(){if(!t.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 d({kind:"connecting"}),await t.proxy.connect({platform:Se}),this.start()},async disconnect(){let g=t.proxy;return!g?.disconnect||r.kind!=="ready"?r:(await u(()=>g.disconnect({platform:Se})),this.load())},async listRepositories(){if(r.kind!=="choose-repository"||!t.proxy)return r;let{connectionId:g}=r;d({...r,listing:{kind:"loading"}});let h;try{h={kind:"listed",repositories:await un(t.proxy,g)}}catch(y){h={kind:"unavailable",message:y instanceof Error?y.message:String(y)}}return r.kind!=="choose-repository"?r:d({...r,listing:h})},async choose(g){if(r.kind!=="choose-repository"||r.settingUp)return r;let{connectionId:h,listing:y}=r,k=y?{listing:y}:{},S=g.trim();try{we(S)}catch{return d({kind:"choose-repository",connectionId:h,...k,error:"Enter the repository as owner/name, for example octocat/hello-world."})}d({kind:"choose-repository",connectionId:h,...k,settingUp:S});try{await p(S)}catch(A){return d({kind:"choose-repository",connectionId:h,...k,error:A instanceof Error?A.message:String(A)})}return d({kind:"ready",connectionId:h,repository:S}),this.sync()},sync(){return I("syncing",(g,h)=>ie(m(g,h.connectionId,h.repository)))},send(){let g=r.kind==="ready"?r.last?.result.held:[];return I("sending",(h,y)=>ie({...m(h,y.connectionId,y.repository),approved:new Set((g??[]).map(k=>k.key))}))},keep(g){return this.resolve(g)},async conflict(){let g=i;if(g?.kind!=="conflict"||r.kind!=="ready")return;let h=r;return u(async()=>{let y=await p(h.repository);return fn(m(y,h.connectionId,h.repository),g.subject)})},resolve(g){let h=i;return h?.kind!=="conflict"?Promise.resolve(r):I("resolving",async(y,k)=>{let S=m(y,k.connectionId,k.repository);return await mn(S,h.subject,g),ie(S)})},async edit(g,h){if(r.kind!=="ready")return r;let y=r;return w(g,S=>({...S,...h.title!==void 0?{title:h.title}:{},...h.body!==void 0?{body:h.body}:{},...h.status?{status:h.status}:{}})),await E(y,async S=>{let A=await R(S).getResource(g);h.title!==void 0&&A.set(B,h.title),h.body!==void 0&&A.set(S.tracker.properties.body,h.body);let N=Qr(h.status);N&&A.set(S.tracker.properties.status,[S.tracker.tags[N]]),await A.save()})?this.sync():r},async comment(g,h){if(r.kind!=="ready"||!h.trim())return r;let y=r,k="";return await E(y,async A=>{k=(await R(A).newResource({parent:A.tracker.commentsFolder,isA:[tn],propVals:{[ne]:h,[ue]:g}})).subject})?(w(g,A=>({...A,comments:[...A.comments,{subject:k,body:h}]})),this.sync()):r},async create(g){if(r.kind!=="ready")return{state:r};let h=r,y="";return await E(h,async S=>{y=(await R(S).newResource({parent:S.tracker.table,isA:[S.tracker.rowClass],propVals:{[B]:g.title,[S.tracker.properties.body]:g.body,[S.tracker.properties.status]:[S.tracker.tags[g.status]]}})).subject,S.state.state.publish=[...S.state.state.publish??[],y],await S.state.flush()})?(w(y,S=>({...S,...g})),{state:await this.sync(),subject:y}):{state:r}},async publish(g){return r.kind!=="ready"?r:await E(r,async k=>{let S=k.state.state.publish??[];S.includes(g)||(k.state.state.publish=[...S,g],await k.state.flush())})?this.sync():r},keepHereOnly(){let g=O();return g?I("resolving",async(h,y)=>{let k=m(h,y.connectionId,y.repository);return await bn(k,g),ie(k)}):Promise.resolve(r)},removeFromBoard(){let g=O();return g?I("resolving",async(h,y)=>{let k=m(h,y.connectionId,y.repository);return await yn(k,g),ie(k)}):Promise.resolve(r)},landed(g,h){return j(g)?I("resolving",async(y,k)=>{let S=m(y,k.connectionId,k.repository);return await wn(S,g,h),ie(S)}):Promise.resolve(r)},sendAgain(g){return j(g)?I("resolving",async(h,y)=>{let k=m(h,y.connectionId,y.repository);return await vn(k,g),ie(k)}):Promise.resolve(r)},prefs:()=>({...a}),async savePrefs(g){if(a={...g},!o)return;let h=o;h.state.state.view={...g},await u(()=>h.state.flush())}}}function Ke(){return{issues:0,comments:0,addedHere:0,updatedHere:0,sentToGitHub:0,held:[],uncertain:[],rows:[]}}function es(t){return{subject:t,title:"",status:"Todo",body:"",labels:[],assignees:[],comments:[]}}var bt=(t,e,n=`${e}s`)=>`${t} ${t===1?e:n}`;function Sn(t){switch(t.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"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.";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 t.settingUp?`Setting up this table for ${t.settingUp}\u2026`:t.error??"Connected. Choose the repository to sync with this table.";case"ready":{if(t.busy==="syncing")return`Syncing with ${t.repository}\u2026`;if(t.busy==="sending")return`Sending approved changes to ${t.repository}\u2026`;if(t.busy==="resolving")return"Settling the conflict, then syncing\u2026";if(t.problem){let{kind:n,message:r}=t.problem;return n==="conflict"?`Sync paused: ${t.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(!t.last)return`Bound to ${t.repository}. Sync imports its issues and comments into this table. Nothing is sent to GitHub without your review.`;let e=t.last.result;return`Last synced ${new Date(t.last.at).toLocaleString()}: ${bt(e.issues,"issue")} and ${bt(e.comments,"comment")} in sync with ${t.repository}; ${e.addedHere} added and ${e.updatedHere} updated here, ${e.sentToGitHub} sent to GitHub.`+(e.held.length?` ${bt(e.held.length,"change")} waiting for your review before ${e.held.length===1?"it is":"they are"} sent to GitHub.`:"")}}}function En(t){let e=ts(t);return t.unconfirmed?`${e}. GitHub did not confirm the last attempt, so it may already be there: check GitHub before sending again`:e}function ts(t){if(t.entity!=="issue"){let s=t.issueNumber?`#${t.issueNumber}`:"a new issue";return t.remoteId===void 0?`Add a comment on ${s}: \u201C${t.after.body}\u201D`:`Edit comment ${t.remoteId} on ${s} to \u201C${t.after.body}\u201D`}if(t.remoteId===void 0)return`Create issue \u201C${t.after.title}\u201D (${t.after.status})`;let e=s=>s==="Doing"?"atomic:doing":s==="Blocked"?"atomic:blocked":void 0,n=[],r=t.before;if(r?.title!==t.after.title&&n.push(`title \u201C${r?.title??""}\u201D \u2192 \u201C${t.after.title}\u201D`),r?.body!==t.after.body&&n.push("description"),r?.status!==t.after.status){let s=e(t.after.status),o=e(r?.status),i=t.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 ${t.after.status} (${i})`)}return`Update #${t.remoteId}: ${n.join("; ")||"no visible change"}`}var We=["Todo","Doing","Blocked","Done"];function Ye(t,e){let n=typeof t=="string"?Date.parse(t):t;if(n===void 0||Number.isNaN(n))return"";let r=Math.max(0,Math.round((e-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 Tn(t,e){let n=t?Date.parse(t):NaN;if(Number.isNaN(n))return"";let r=Math.max(0,Math.floor((e-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 Rn(t,e){switch(t.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 t.settingUp?{state:"syncing",text:"Setting up\u2026"}:{state:"synced",text:"Connected"};case"ready":{if(t.busy==="syncing"&&!t.last)return{state:"syncing",text:"Importing\u2026"};if(t.busy==="sending")return{state:"syncing",text:"Sending\u2026"};if(t.busy)return{state:"syncing",text:"Syncing\u2026"};let n=t.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"}:t.last?.at?{state:"synced",text:`Synced ${Ye(t.last.at,e)}`}:{state:"idle",text:"Not synced yet"}}}}var yt=(t,e,n=`${e}s`)=>`${t} ${t===1?e:n}`,ns=t=>(t.last?.result.held??[]).filter(e=>e.unconfirmed);function $n(t,e=!1){if(t.kind!=="ready")return;let n=t.problem,r=i=>{let a=t.last?.result.rows.find(c=>c.subject===i);return a?.number?`#${a.number}`:"An issue"};if(n?.kind==="conflict")return{tone:"warn",icon:"warn",title:"Sync paused.",text:`${r(n.local)} was changed both here and on GitHub since the last sync (${n.fields.join(", ")}). Nothing is sent or fetched until you choose.`,actions:[{label:"Review conflict",action:"review-conflict",primary:!0}],problem:n};if(n?.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:n.message,problem:n};if(n?.kind==="paused"){if(n.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:n.message,problem:n};if(n.reason==="missing"){let i=n.missing?.side==="remote"&&n.missing.entity==="issue",a=r(n.missing?.local);return i&&e?{tone:"warn",icon:"ghost",title:`Remove ${a==="An issue"?"this issue":a} 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:n.message,problem:n}:i?{tone:"warn",icon:"ghost",title:`${a} 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.",actions:[{label:"Keep here only",action:"keep-here"},{label:"Remove from board",action:"remove",danger:!0}],details:n.message,problem:n}:{tone:"warn",icon:"ghost",title:n.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:n.message,problem:n}}return n.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:n.message,problem:n}:{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:n.message,problem:n}}let[s]=t.last?.result.uncertain??[];if(s&&!t.busy)return ss(s);let o=ns(t);if(o.length&&!t.busy)return{tone:"warn",icon:"info",title:`${yt(o.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(t.busy==="syncing"&&!t.last)return{tone:"info",icon:"info",title:"First import running.",text:"You can look around; moving cards is available once it finishes.",actions:[]}}var rs=3;function ss(t){let e=t.entity==="issue",n=e?`\u201C${t.sent.title??""}\u201D`:`Your comment on ${t.issueNumber?`#${t.issueNumber}`:"an issue"}`,r=d=>e?`#${d}`:`comment ${d}`,s=e?"the same title and description":"the same text",o=`${n} was sent to GitHub, but no answer came back.`,i=t.candidates.slice(0,rs),[a]=t.candidates;if(!a)return{tone:"warn",icon:"info",title:o,text:`GitHub shows no ${e?"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:t.subject,primary:!0}]};let c=t.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 ${t.candidates.length} ${e?"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:[...t.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((d,u)=>({label:`It landed as ${r(d.id)}`,action:"landed",subject:t.subject,id:d.id,...u===0?{primary:!0}:{}}))]}}function jn(t){let e=t.last?.result.held.length??0,n=e?` \xB7 ${yt(e,"change")} waiting to send`:t.touched?.length?` \xB7 ${yt(t.touched.length,"change")} saving`:"";if(t.busy==="syncing"&&!t.last)return"Importing\u2026";if(t.busy==="syncing")return`Checking GitHub for changes${n}`;if(t.busy==="sending")return`Sending to GitHub${n}`;if(t.busy==="resolving")return"Settling the conflict\u2026";let r=t.last?.at?new Date(t.last.at).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}):"";return t.problem?.kind==="conflict"||t.problem?.kind==="paused"?`Paused${r?` at ${r}`:""}${n}`:t.last?.at?`Last sync ${r}${n}`:`Not synced yet${n}`}function Xe(t){let e=new Map,n=t.last?.result.held??[],r=t.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&&e.set(a,t.busy==="sending"?"sending":"waiting")}for(let i of t.touched??[])e.set(i,t.busy==="sending"?"sending":"waiting");for(let i of t.last?.result.uncertain??[]){let a=i.local&&s.has(i.local)?s.get(i.local):i.local;a&&e.set(a,"unconfirmed")}let o=t.problem;return o?.kind==="conflict"&&o.local&&e.set(s.get(o.local)??o.local,"conflict"),e}function An(t){let e=new Set;for(let n of t.last?.result.held??[])n.entity!=="issue"&&n.local&&e.add(n.local);return e}var Pe={waiting:"Waiting to send",sending:"Sending",conflict:"Changed on both sides",unconfirmed:"Sent, but GitHub did not answer"};function Ze(t,{search:e,label:n}){if(n&&!t.labels.some(o=>o.name===n))return!1;let r=e.toLowerCase().split(/\s+/).filter(Boolean),s=[t.title.toLowerCase(),...t.labels.map(o=>o.name.toLowerCase())];return r.every(o=>{let i=o.replace(/^#/,"");return/^\d+$/.test(i)&&t.number!==void 0&&String(t.number)===i?!0:s.some(a=>a.includes(o))})}var wt=t=>!!(t.search.trim()||t.label);function On(t){return[...new Set(t.flatMap(e=>e.labels.map(n=>n.name)))].sort((e,n)=>e.localeCompare(n))}var os=(t,e)=>(t.number??-1)-(e.number??-1),is=(t,e)=>(e.updatedAt??"\uFFFF").localeCompare(t.updatedAt??"\uFFFF");function vt(t,e,n=!1){let r=t.filter(s=>Ze(s,e));return We.map(s=>{let o=r.filter(a=>a.status===s).sort(s==="Done"?is:os),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 In(t,e){if(wt(e))return`${t.filter(s=>Ze(s,e)).length} of ${t.length} shown`;let n=t.filter(r=>r.status==="Done").length;return`${t.length-n} open \xB7 ${n} done`}function xt(t,e){return e??(t==="s"||t==="m"?"list":"board")}function Pn(t){return t==="xl"?"docked":t==="s"?"sheet":"drawer"}function fe(t){return t.kind==="ready"&&!!t.last&&t.last.at>0}var kt={1:"Todo",2:"Doing",3:"Blocked",4:"Done"},Cn=[["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 St(t){let e=t;return!e||typeof e.tagName!="string"?!1:e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.tagName==="SELECT"||e.isContentEditable===!0}var Mn=`.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 Hn=Mn;function l(t,e=null,...n){let r=document.createElement(t);for(let[s,o]of Object.entries(e??{}))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 Ln(r,n),r}function Ln(t,e){for(let n of e)n==null||n===!1||(Array.isArray(n)?Ln(t,n):t.appendChild(typeof n=="string"||typeof n=="number"?document.createTextNode(String(n)):n))}var Z=(t,e=1.6)=>``,cs={mark:'',synced:'',syncing:'',paused:'',reauth:Z("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:Z("M8 3v10M3 8h10"),more:'',board:'',list:'',search:'',chevron:Z("m4 6 4 4 4-4",1.8),comment:Z("M2.5 3.5h11v7h-6l-3 2.5v-2.5h-2z",1.3),close:Z("m4 4 8 8M12 4l-8 8"),back:Z("M10 3 5 8l5 5"),external:Z("M6 3H3v10h10v-3M9 3h4v4M13 3 7 9",1.5),info:'',warn:'',plug:Z("M5.5 2v3.5M10.5 2v3.5M3.5 5.5h9V8a4.5 4.5 0 0 1-9 0zM8 12.5V15",1.5),ghost:Z("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:Z("M3 13.5 5.5 5h13l2.5 8.5V19H3z M3 13.5h5l1 2.5h6l1-2.5h5",1.4),filter:Z("M4 5h16l-6 7.5V19l-4-2v-4.5z",1.4),server:'',todo:'',doing:'',blocked:'',done:''},ls={inbox:24,filter:24,server:24,todo:14,doing:14,blocked:14,done:14};function L(t,e=16,n){let r=ls[t]??16,s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(e)),s.setAttribute("height",String(e)),s.setAttribute("viewBox",`0 0 ${r} ${r}`),s.setAttribute("aria-hidden","true"),n&&s.setAttribute("class",n),s.innerHTML=cs[t],s}var ds={idle:"idle",synced:"synced",syncing:"syncing",paused:"paused",reauth:"reauth",error:"error"};function Et(t,e,n){let r=[L(ds[t],12),l("span",null,e)];return n?l("button",{type:"button",class:"pl-pill","data-state":t,"aria-haspopup":"dialog",onclick:n},l("span",{role:"status",class:"pill-status"},r)):l("span",{class:"pl-pill","data-state":t,role:"status"},r)}function Nn(t,...e){return l("header",{class:"pl-header"},l("span",{class:"pl-mark","aria-hidden":"true"},L("mark")),l("h1",{class:"pl-name"},t),...e)}function Dn(t,e){return l("span",{class:"src-chip"},l("b",null,t),l("span",{class:"mono"},e))}function Tt(t,e=[],n){let r=[];t.filter(o=>o!=null&&o!==!1&&o!=="").forEach((o,i)=>{i&&r.push(l("span",{class:"dot-sep","aria-hidden":"true"},"\xB7")),r.push(...Array.isArray(o)?o:[o])});let s=l("div",{class:"pl-conn"},r,l("span",{class:"spacer"}),...e);if(n!==void 0){let o=l("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 _n(t){let e=l("div",{class:"pl-banner","data-tone":t.tone,...t.alert?{role:"alert"}:{}},l("span",{class:"b-icon"},L(t.icon)),l("p",{class:"b-text"},l("b",null,t.title)," ",t.text),t.actions?.length?l("div",{class:"b-actions"},t.actions):null);return t.details?l("div",{class:"banner-wrap"},e,l("details",{class:"b-details"},l("summary",null,"Details"),l("code",null,t.details))):e}function Ce(t,e,n,r,s=!1){return l("div",{class:`pl-empty${s?" tall":""}`},l("span",{class:"e-icon","aria-hidden":"true"},L(t,24)),l("p",null,l("b",null,e),n),r??null)}function D(t,e,{kind:n="",sm:r=!1,iconName:s,...o}={}){return l("button",{type:"button",class:["btn",n,r?"sm":""].filter(Boolean).join(" "),onclick:e,...o},s?L(s,14):null,Array.isArray(t)?t:l("span",null,t))}function Ee(t,e,n,{sm:r=!1,...s}={}){return l("button",{type:"button",class:`icon-btn${r?" sm":""}`,"aria-label":e,title:e,onclick:n,...s},L(t,r?14:16))}function Rt(t,e,n,r,{mode:s="pressed",disabled:o=!1,cls:i=""}={}){let a=l("div",{class:`seg ${i}`.trim(),role:s==="radio"?"radiogroup":"group","aria-label":t});for(let c of e){let d=c.value===n;a.append(l("button",{type:"button",...s==="radio"?{role:"radio","aria-checked":String(d),tabindex:d?0:-1}:{"aria-pressed":String(d)},...c.title?{"aria-label":c.title,title:c.title}:{},"data-value":c.value,disabled:o,onclick:()=>r(c.value)},c.iconName?L(c.iconName,14):null,c.label))}return s==="radio"&&a.addEventListener("keydown",c=>{let d=c,u=d.key==="ArrowRight"||d.key==="ArrowDown"?1:d.key==="ArrowLeft"||d.key==="ArrowUp"?-1:0;if(!u)return;d.preventDefault();let p=Math.max(0,e.findIndex(b=>b.value===n)),m=e[(p+u+e.length)%e.length];r(m.value)}),a}function $t(t,e,n,r=!1){let s=l("input",{type:"search",placeholder:t,"aria-label":t,autocomplete:"off",oninput:o=>n(o.target.value)});return s.value=e,{input:s,field:l("label",{class:`search${r?" wide":""}`},L("search",14),s,l("kbd",{"aria-hidden":"true"},"/"))}}function jt(t,e){let n=l("i",{"aria-hidden":"true"});return e&&/^#[0-9a-f]{6}$/i.test(e)&&(n.style.background=e),l("span",{class:"chip"},n,t)}function me(t,e=14){return L(t,e,`glyph g-${t}`)}function Gn(){let t=l("div",{class:"sr","aria-live":"polite"});return{region:t,say(e){t.textContent="",setTimeout(()=>{t.textContent=e},30)}}}var zn=`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 Un=zn;function ps(t){return t<600?"s":t<720?"m":t<1e3?"l":"xl"}function fs(t){let e=t.trim(),n,r=e.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=e.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 Fn(t,e){let n=t.ownerDocument,r="pl-app-styles";if(n.getElementById(r))return;let s=n.createElement("style");s.id=r,s.textContent=Un+e,n.head.append(s)}function Bn(t,e,n={}){let r=t.ownerDocument.defaultView,s=()=>{let p=n.getTheme?.().colorScheme;if(p){t.dataset.plScheme=p;return}let m=r?.getComputedStyle(t.ownerDocument.documentElement).getPropertyValue("--t-color-bg"),b=m?fs(m):void 0;t.dataset.plScheme=b!==void 0&&b<.4?"dark":"light"},o,i=()=>{let p=t.getBoundingClientRect().width||r?.innerWidth||0,m=ps(p);t.dataset.size=m,m!==o&&(o=m,e(m,p))};s(),i();let a=p=>{p.data?.type==="__atomic_style"&&setTimeout(s,0)};r?.addEventListener("message",a);let c=n.onThemeChange?.(({colorScheme:p})=>{p?t.dataset.plScheme=p:s()}),d=r?.ResizeObserver,u=d?new d(i):void 0;return u?.observe(t),u||r?.addEventListener("resize",i),()=>{r?.removeEventListener("message",a),c?.(),u?.disconnect(),r?.removeEventListener("resize",i)}}var ms=/^https?:\/\/[^\s<>"']+$/i;function ge(t){let e=[],n=/(`[^`]+`)|(\*\*[^*]+\*\*)|(\*[^*\s][^*]*\*|_[^_\s][^_]*_)|(\[[^\]]+\]\([^)\s]+\))/g,r=0,s;for(;s=n.exec(t);){s.index>r&&e.push(document.createTextNode(t.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(...ge(o.slice(2,-2)));else if(s[3])i=a=document.createElement("em"),a.append(...ge(o.slice(1,-1)));else{let[,c,d]=o.match(/^\[([^\]]+)\]\(([^)\s]+)\)$/);if(ms.test(d)){let u=document.createElement("a");u.href=d,u.target="_blank",u.rel="noopener noreferrer",u.append(...ge(c)),i=u}else i=document.createTextNode(o)}e.push(i),r=s.index+o.length}return r{let n=document.createElement(t);return n.append(...e),n};function Qe(t){let e=document.createDocumentFragment(),n=t.replace(/\r\n?/g,` +`).split(` +`),r=0,s=i=>{if(!i.length)return;let a=ae("p");i.forEach((c,d)=>{d&&a.append(ae("br")),a.append(...ge(c))}),e.append(a),i.length=0},o=[];for(;r/.test(i)){s(o);let d=[];for(;r/.test(n[r]);)d.push(n[r++].replace(/^\s*>\s?/,""));let u=ae("blockquote");u.append(Qe(d.join(` +`))),e.append(u);continue}i.trim()?o.push(i):s(o),r++}return s(o),e}var he={Todo:"todo",Doing:"doing",Blocked:"blocked",Done:"done"},re=t=>t.number!==void 0?`#${t.number}`:t.localOnly?"Local":"New",Jn=t=>t.statusAsIs?`Status here: ${t.statusAsIs.join(", ")||"none"} (not synced with GitHub)`:void 0,Kn=t=>`https://github.com/${t}`;function gs(t,e,n){let r=[l("span",{class:"sr"},"GitHub "),"Issues"],s=t.kind==="ready"?t.repository:t.kind==="choose-repository"?"choose a repository":void 0,o=e.size==="s",i=Rn(t,e.now),a=null;if(i){let d=i.state==="error",u=d&&e.retryIn!==void 0?`Sync failed \xB7 retrying in ${Math.max(1,Math.round(e.retryIn/60))} min`:o&&i.state==="synced"&&i.text.startsWith("Synced ")?i.text.slice(7):i.text;a=d?l("span",{class:"pill-wrap"},Et("error",u,()=>n.setUi({menu:e.menu==="pill"?void 0:"pill"})),e.menu==="pill"&&t.kind==="ready"?hs(t,e,n):null):Et(i.state,u)}let c=t.kind==="ready"?o?l("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")},L("plus",14)):D("New issue",()=>n.open({kind:"new"},"new-issue"),{kind:"primary",iconName:"plus","data-key":"new-issue"}):null;return Nn(r,s&&!o?Dn("GitHub",s):null,l("span",{class:"spacer"}),a,c)}function hs(t,e,n){let r=t.problem?.kind==="failed"?t.problem.message:"Unknown error";return l("div",{class:"popover",role:"dialog","aria-label":"Sync failed"},l("p",null,l("b",null,"GitHub or the host did not answer. "),r),l("p",{class:"muted"},e.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."),D("Retry now",()=>{n.setUi({menu:void 0},!1),n.sync()},{kind:"primary",sm:!0}))}function bs(t,e,n){let r=t.problem?0:t.last?.result.held.length??0,s=!!t.busy,o=e.menu==="conn",i=t.busy==="syncing"||t.busy==="sending"?!0:void 0,a=Tt([e.size==="s"?l("span",{class:"mono acct"},t.repository):l("span",{class:"acct"},"GitHub"),e.size==="s"&&!r?null:l("span",null,jn(t))],[r&&!t.last?.result.held.some(c=>c.unconfirmed)?l("button",{type:"button",class:"link-btn","data-key":"review",disabled:s,onclick:()=>n.open({kind:"review"},"review")},"Review and send"):null,l("button",{type:"button",class:"link-btn","data-key":"sync-now",disabled:s,onclick:()=>n.sync()},"Sync now"),l("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?At("Connection",[{label:"Open repository on GitHub",run:()=>n.openGitHub(Kn(t.repository))},{label:"Reconnect GitHub",run:()=>n.connect(),disabled:t.problem?.kind!=="reconnect"},{label:"Disconnect GitHub",run:()=>n.disconnect(),disabled:!e.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=Sn(t),a}function At(t,e,n){let r=l("div",{class:"menu",role:"menu","aria-label":t},e.map(s=>l("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?me(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 ys(t,e,n){let r=$n(t,e.confirmRemove);if(!r||t.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??`${Kn(t.repository)}/issues`)};return _n({tone:r.tone,icon:r.icon,title:r.title,text:r.text,alert:e.alert&&!!r.problem,...r.details?{details:r.details}:{},actions:r.actions.map((o,i)=>D(o.label,()=>s(o),{kind:o.primary?"primary":o.danger?"danger":"",sm:!0,disabled:!!t.busy&&o.action!=="open-github",...i===r.actions.length-1?{"data-key":"banner-action"}:{}}))})}function ws(){return Ce("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 vs(t,e){let n=t.kind==="connecting",r=(s,o,i,a,c=!1)=>l("li",{class:`src${c?" disabled":""}`},l("div",{class:"src-text"},l("b",null,s),l("span",null,o),l("span",{class:"effect"},i)),a);return l("div",{class:"center-wrap"},l("div",{class:"onboard"},l("h2",null,"Bring your issues into this drive"),l("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."),l("ul",{class:"srcs"},r("GitHub Issues","One repository\u2019s issues and comments.","Two-way: status, title, description and comments are sent back to GitHub after you review them.",D(n?"Waiting\u2026":"Connect",()=>e.connect(),{kind:"primary","aria-label":"Connect GitHub Issues","data-key":"connect-github",disabled:n})),r("Jira","One Jira Cloud project.","Read-only for now: nothing is sent back to Jira.",l("span",{class:"muted small"},"Not available on this server yet"),!0),r("Todoist","One Todoist project\u2019s tasks.","Read-only: nothing is sent back to Todoist.",l("span",{class:"muted small"},"Not available in this app yet"),!0)),l("p",{class:"fine"},n?"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.")))}function xs(t){return t.hasIssues?t.openIssues===void 0?"":t.openIssues===0?"no open issues":`about ${t.openIssues} open ${t.openIssues===1?"issue":"issues"}`:"issues disabled"}function ks(t,e,n){let r=t.listing,s=r?.kind==="listed"?r.repositories:void 0,i=!s||s.length===0?e.typedRepo.trim():e.repoChoice,a=!!t.settingUp,c;if(!r||r.kind==="loading")c=l("p",{class:"lede"},"Loading the repositories this connection can see\u2026");else if(s&&s.length){let u=e.repoFilter.toLowerCase(),p=s.filter(b=>b.fullName.toLowerCase().includes(u)),{field:m}=$t(`Filter ${s.length} ${s.length===1?"repository":"repositories"}`,e.repoFilter,b=>n.setUi({repoFilter:b}),!0);m.dataset.key="repo-filter",m.querySelector("input").dataset.key="repo-filter-input",m.querySelector("kbd")?.remove(),c=[m,l("ul",{class:"repos",role:"radiogroup","aria-label":"Repositories"},p.map(b=>l("li",null,l("label",{class:`repo${b.hasIssues?"":" disabled"}`},l("input",{type:"radio",name:"repository",value:b.fullName,checked:e.repoChoice===b.fullName,disabled:!b.hasIssues||a,"data-key":`repo:${b.fullName}`,onchange:()=>n.setUi({repoChoice:b.fullName})}),l("span",{class:"mono"},b.fullName),l("span",{class:"muted small"},xs(b)))))),p.length?null:l("p",{class:"fine"},"No repository matches this filter.")]}else{let u=l("input",{name:"repository",autocomplete:"off",spellcheck:"false",placeholder:"octocat/hello-world","aria-label":"Repository (owner/name)","data-key":"typed-repo",disabled:a,oninput:p=>n.setUi({typedRepo:p.target.value},!1),onkeydown:p=>{p.key==="Enter"&&n.choose(p.target.value)}});u.value=e.typedRepo,c=[l("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."),l("div",{class:"typed"},l("label",{class:"search"},l("span",{class:"sr"},"Repository (owner/name)"),u)),r.kind==="unavailable"?l("details",{class:"b-details",style:"margin:0"},l("summary",null,"Details"),l("code",null,r.message)):null]}let d=i||"repository";return l("div",{class:"center-wrap"},l("div",{class:"onboard"},l("h2",null,"Which repository?"),c,t.error?l("p",{class:"field-error",role:"alert"},t.error):null,l("div",{class:"effects"},l("h3",null,"What this board will do on GitHub"),l("ul",null,l("li",null,"Moving a card to ",l("b",null,"Done")," closes the issue. Moving it back reopens it."),l("li",null,"Moving a card to ",l("b",null,"Doing")," adds the ",l("code",null,"atomic:doing")," label; leaving Doing removes it. Other labels are never touched."),l("li",null,"Moving a card to ",l("b",null,"Blocked")," adds the ",l("code",null,"atomic:blocked")," label the same way."),l("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."),l("li",null,"Nothing is ever deleted on GitHub. One app syncs one repository."))),l("div",{class:"actions-row"},D(a?`Setting up ${t.settingUp}\u2026`:`Import ${d}`,()=>i&&n.choose(i),{kind:"primary",disabled:a||!i,"data-key":"import"}))))}function Wn(t){return t?t==="conflict"||t==="unconfirmed"?l("span",{class:`sync-mark conflict ${t}`,title:Pe[t]},L("warn",14),l("span",{class:"sr"},Pe[t])):l("span",{class:`sync-mark ${t}`,title:Pe[t]},l("span",{class:"sr"},Pe[t])):null}function Yn(t,e){if(!t.labels.length)return null;let n=t.labels.slice(0,e),r=t.labels.length-n.length;return l("span",{class:"chips"},n.map(s=>jt(s.name,s.color)),r>0?l("span",{class:"chip more",title:t.labels.slice(e).map(s=>s.name).join(", ")},`+${r}`):null)}function Xn(t){let e=t.comments.length;return e?l("span",{class:"cmt",title:`${e} ${e===1?"comment":"comments"}`},L("comment",13),l("span",{"aria-hidden":"true"},String(e)),l("span",{class:"sr"},`${e} ${e===1?"comment":"comments"}`)):null}function Zn(t,e,n){return At(`Move ${re(t)} to`,We.map(r=>({label:r,glyph:he[r],checked:t.status===r&&!t.statusAsIs,disabled:!n||t.status===r&&!t.statusAsIs,run:()=>e.move(t.subject,r,"menu")})),e)}function Ss(t,e,n,r,s){let o=fe(e)&&!e.busy,i=`move:${t.subject}`,a=n.menu===i,c=n.panel?.kind==="issue"&&n.panel.subject===t.subject;return l("li",{class:`card${c?" is-selected":""}${n.flash.has(t.subject)?" flash":""}`,"data-subject":t.subject,draggable:o?"true":"false",ondragstart:u=>{let p=u;p.dataTransfer?.setData("text/plain",t.subject),p.dataTransfer&&(p.dataTransfer.effectAllowed="move"),p.currentTarget.classList.add("dragging")},ondragend:u=>u.currentTarget.classList.remove("dragging")},l("button",{type:"button",class:"card-hit","data-key":`card:${t.subject}`,"data-issue":t.subject,onclick:()=>s.open({kind:"issue",subject:t.subject},`card:${t.subject}`),onfocus:()=>s.setUi({focus:t.subject},!1)},l("span",{class:"card-top"},l("span",{class:"ref"},re(t)),l("span",{class:"sr"},`Status: ${t.status}.`),t.statusAsIs?l("span",{class:"muted small",title:Jn(t)},"\u2260"):null,Wn(r.get(t.subject))),l("span",{class:"card-title"},t.title),t.labels.length||t.comments.length?l("span",{class:"card-foot"},Yn(t,3),Xn(t)):null),Ee("more",`Move ${re(t)} 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:${t.subject}`}),a?Zn(t,s,o):null)}function Vn(){return l("li",{class:"card skel","aria-hidden":"true"},l("span",{class:"sk",style:"width:22%"}),l("span",{class:"sk",style:"width:86%"}),l("span",{class:"sk",style:"width:54%"}))}function Es(t,e,n){let r=t.last?.result.rows??[],s=t.busy==="syncing"&&(!t.last||!!t.importing),o={search:e.search,label:e.label},i=vt(r,o,e.allDone),a=Xe(t),c=fe(t)&&!t.busy;return l("div",{class:"board","data-scroll":"board"},i.map(d=>l("section",{class:"col","aria-labelledby":`col-${d.status}`,"data-status":d.status,ondragover:p=>{c&&(p.preventDefault(),p.currentTarget.classList.add("drop"))},ondragleave:p=>p.currentTarget.classList.remove("drop"),ondrop:p=>{let m=p;m.preventDefault(),m.currentTarget.classList.remove("drop");let b=m.dataTransfer?.getData("text/plain");b&&c&&n.move(b,d.status,"drag")}},l("header",{class:"col-head"},me(he[d.status]),l("h2",{id:`col-${d.status}`},d.status),l("span",{class:"count"},s&&!r.length?"\u2026":String(d.total)),Ee("plus",`New issue in ${d.status}`,()=>{n.setDrafts({newStatus:d.status},!1),n.open({kind:"new"},`colnew:${d.status}`)},{sm:!0,"data-key":`colnew:${d.status}`})),l("ul",{class:"cards",role:"list","aria-labelledby":`col-${d.status}`},d.rows.map(p=>Ss(p,t,e,a,n)),s?[Vn(),Vn()]:null),d.hidden?l("button",{type:"button",class:"show-more","data-key":"show-more",onclick:()=>n.setUi({allDone:!0})},`Show ${d.hidden} more`):d.status==="Done"&&e.allDone&&d.total>20?l("button",{type:"button",class:"show-more","data-key":"show-more",onclick:()=>n.setUi({allDone:!1})},"Show fewer"):null)))}var Ts=["Doing","Blocked","Todo","Done"];function Rs(t,e,n){let r=t.last?.result.rows??[],s={search:e.search,label:e.label},o=vt(r,s,e.allDone),i=Xe(t),a=fe(t)&&!t.busy;return l("div",{class:"list"},Ts.map(c=>{let d=o.find(m=>m.status===c),u=e.groups[c]??c!=="Done",p=`group-${c}`;return l("section",{class:"group"},l("button",{type:"button",class:"group-head",id:p,"aria-expanded":String(u),"data-key":p,onclick:()=>n.setUi({groups:{...e.groups,[c]:!u}})},L("chevron",12),me(he[c]),l("span",null,c),l("span",{class:"count"},String(d.total))),u?l("ul",{class:"rows",role:"list","aria-labelledby":p},d.rows.map(m=>{let b=`status:${m.subject}`,v=e.menu===b,R=e.panel?.kind==="issue"&&e.panel.subject===m.subject;return l("li",{class:`row${R?" is-selected":""}`,"data-subject":m.subject},l("button",{type:"button",class:"glyph-btn","aria-label":`Status: ${m.status}. Change status of ${re(m)}`,"aria-haspopup":"menu","aria-expanded":String(v),"data-key":`glyph:${m.subject}`,onclick:()=>n.setUi({menu:v?void 0:b})},me(he[m.status],16)),l("button",{type:"button",class:"row-hit","data-key":`card:${m.subject}`,"data-issue":m.subject,onclick:()=>n.open({kind:"issue",subject:m.subject},`card:${m.subject}`),onfocus:()=>n.setUi({focus:m.subject},!1)},l("span",{class:"row-line"},l("span",{class:"ref"},re(m)),Wn(i.get(m.subject)),l("span",{class:"when"},Tn(m.updatedAt,e.now))),l("span",{class:"row-title"},m.title),m.labels.length||m.comments.length?l("span",{class:"row-foot"},Yn(m,2),Xn(m)):null),v?Zn(m,n,a):null)})):null,u&&d.hidden?l("button",{type:"button",class:"show-more",style:"margin:4px 12px","data-key":"show-more",onclick:()=>n.setUi({allDone:!0})},`Show ${d.hidden} more`):null)}))}function $s(t,e,n,r){let s=t.last?.result.rows??[],o=On(s),i=e.size==="s",{field:a,input:c}=$t("Search issues",e.search,u=>r.setUi({search:u}));c.dataset.key="search",c.id="issue-search";let d=e.menu==="label";return l("div",{class:"toolbar"},Rt("Layout",[{value:"board",label:i?[]:"Board",iconName:"board",title:"Board"},{value:"list",label:i?[]:"List",iconName:"list",title:"List"}],n,u=>r.setUi({layout:u})),a,i?null:l("span",{class:"tb-menu label-menu"},l("button",{type:"button",class:"btn ghost","aria-haspopup":"menu","aria-expanded":String(d),"data-key":"label-filter",disabled:!o.length&&!e.label,onclick:()=>r.setUi({menu:d?void 0:"label"})},e.label?`Label: ${e.label}`:"Label",L("chevron",10)),d?At("Filter by label",[{label:"Any label",checked:!e.label,run:()=>r.setUi({label:void 0})},...o.map(u=>({label:u,checked:e.label===u,run:()=>r.setUi({label:u})}))],r):null),i?null:l("span",{class:"tb-count"},t.busy==="syncing"&&!t.last?"Importing\u2026":t.busy&&t.importing?js(t.importing):In(s,{search:e.search,label:e.label})))}function js(t){let e=(n,r)=>`${n} ${r}${n===1?"":"s"}`;return`Importing\u2026 ${e(t.issues,"issue")}${t.comments?`, ${e(t.comments,"comment")}`:""} so far`}function As(t,e,n){let r=t.last?.result.rows??[];if(!t.last)return null;let s={search:e.search,label:e.label};if(!r.length)return Ce("inbox",`No issues in ${t.repository} yet.`,"Create one here and it goes to GitHub once you review and send it.",D("New issue",()=>n.open({kind:"new"},"empty-new"),{kind:"primary",iconName:"plus","data-key":"empty-new"}),!0);if(wt(s)&&!r.some(o=>Ze(o,s))){let o=[e.search.trim()?`\u201C${e.search.trim()}\u201D`:"",e.label?`label ${e.label}`:""].filter(Boolean).join(" with ");return Ce("filter",`No issues match ${o}.`,`${r.length} ${r.length===1?"issue is":"issues are"} hidden by these filters.`,D("Clear filters",()=>n.setUi({search:"",label:void 0}),{"data-key":"clear-filters"}),!0)}return null}function Os(t){return(t??"?").replace(/[^a-z0-9]/gi,"").slice(0,2)||"?"}function et(t,e,n){let r=()=>n.open(void 0);return l("div",{class:"d-bar"},e==="sheet"?Ee("back","Back to issues",r,{"data-key":"detail-close"}):null,l("span",{class:"ref"},t),l("span",{class:"spacer"}),e==="sheet"?null:Ee("close","Close",r,{"data-key":"detail-close"}))}function Qn(t,e,n){return Rt("Status",We.map(r=>({value:r,label:[me(he[r]),r]})),t,e,{mode:"radio",disabled:n,cls:"status-seg"})}function Is(t,e,n,r,s){let o=n.drafts,i=fe(e),a=An(e),c=Xe(e),d=!1,u=l("textarea",{class:"d-title",rows:1,"aria-label":"Title","data-key":"detail-title",oninput:w=>s.setDrafts({title:w.target.value},!1),onkeydown:w=>{let E=w,O=E.target;if(E.key==="Enter"){E.preventDefault();let j=O.value.trim();d=!0,j&&j!==t.title?s.saveTitle(t.subject,j):s.setDrafts({title:void 0}),O.blur()}else E.key==="Escape"&&O.value!==t.title&&(E.preventDefault(),E.stopPropagation(),O.value=t.title,s.setDrafts({title:void 0}))},onblur:w=>{let E=w.target.value.trim();!d&&E&&E!==t.title&&s.saveTitle(t.subject,E),d=!1}});u.value=o.title??t.title;let p=l("div",{class:"tabs",role:"tablist","aria-label":"Description"},["write","preview"].map(w=>l("button",{type:"button",role:"tab","aria-selected":String(o.tab===w),"data-key":`tab:${w}`,onclick:()=>s.setDrafts({tab:w,...w==="write"&&o.body===void 0?{body:t.body}:{}})},w==="write"?"Write":"Preview"))),m;if(o.tab==="write"){let w=l("textarea",{class:"editor","aria-label":"Description (Markdown)","data-key":"detail-body",oninput:E=>s.setDrafts({body:E.target.value},!1)});w.value=o.body??t.body,m=[w,l("div",{class:"row-actions"},D("Cancel",()=>s.setDrafts({tab:"preview",body:void 0}),{sm:!0}),D("Save description",()=>s.saveBody(t.subject,w.value),{sm:!0,kind:"primary","data-key":"save-body"}))]}else{let w=l("div",{class:"md"});t.body.trim()?w.append(Qe(t.body)):w.append(l("p",{class:"md-empty"},"No description.")),m=w}let b=l("ul",{class:"comments"},t.comments.map(w=>{let E=a.has(w.subject)||!w.author;return l("li",{class:E?"pending":""},l("span",{class:`avatar${w.author?"":" me"}`,"aria-hidden":"true"},w.author?Os(w.author):"You".slice(0,2)),l("div",null,l("p",{class:"c-meta"},w.author?[l("b",null,w.author)," on GitHub",w.createdAt?` \xB7 ${Ye(w.createdAt,n.now)}`:""]:[l("b",null,"You")," \xB7 ",l("span",{class:"pend"},e.busy==="sending"?"Sending":"Waiting to send")]),l("div",{class:"md"},Qe(w.body))))})),v=l("textarea",{placeholder:"Add a comment\u2026 (Markdown)","aria-label":"Add a comment","data-key":"composer",rows:3,oninput:w=>{let E=w.target.value;s.setDrafts({comment:E},!1),R.disabled=!E.trim()},onkeydown:w=>{let E=w;E.key==="Enter"&&(E.metaKey||E.ctrlKey)&&(E.preventDefault(),s.comment(t.subject,E.target.value))}});v.value=o.comment;let R=D("Comment",()=>s.comment(t.subject,v.value),{kind:"primary",sm:!0,disabled:!o.comment.trim(),"data-key":"comment"}),$=t.number!==void 0,I=c.get(t.subject),z=l("div",{class:"d-body"},u,l("div",{class:"d-props"},l("span",{class:"d-k"},"Status"),Qn(t.status,w=>w!==t.status&&s.move(t.subject,w,"menu"),!i||!!e.busy),l("span",{class:"d-k"},"Labels"),l("span",{class:"chips"},t.labels.map(w=>jt(w.name,w.color)),l("span",{class:"muted small"},t.labels.length?"Labels are edited on GitHub":"None \xB7 edited on GitHub")),t.assignees.length?l("span",{class:"d-k"},"Assignees"):null,t.assignees.length?l("span",{class:"small"},t.assignees.join(", ")):null),t.statusAsIs?l("p",{class:"ro-note"},L("info",14),`${Jn(t)}.`):null,t.localOnly?l("div",{class:"ro-note"},L("info",14),l("span",null,`Only in this table. It becomes an issue in ${e.repository} once you publish it and then review and send it.`),D("Publish to GitHub",()=>s.publish(t.subject),{sm:!0,kind:"primary",disabled:!!e.busy,"data-key":"publish"})):null,I?l("p",{class:"ro-note"},L(I==="conflict"?"warn":"info",14),I==="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,l("h3",{class:"d-h"},"Description"),p,m,l("h3",{class:"d-h"},"Comments",l("span",{class:"count"},String(t.comments.length))),t.comments.length?b:l("p",{class:"muted small",style:"margin:0"},"No comments yet."),l("div",{class:"composer"},v,l("div",{class:"cmp-row"},l("span",{class:"muted small"},$?"Sent to GitHub after you review it":"Sent once the issue is on GitHub"),R))),J=l("div",{class:"d-foot"},l("span",{class:"mono"},$?`${e.repository}#${t.number}`:t.localOnly?"Only in this table":`${e.repository} \xB7 not on GitHub yet`),e.last?.at?` \xB7 synced ${Ye(e.last.at,n.now)}`:"",t.url?[" \xB7 ",l("a",{href:t.url,target:"_blank",rel:"noopener noreferrer"},"Open on GitHub",L("external",12))]:null);return[et($?`#${t.number}`:"New issue",r,s),z,J]}function Ps(t,e,n,r){let s=e.drafts,o=l("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=l("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,[et("New issue",n,r),l("div",{class:"d-body"},o,l("div",{class:"d-props"},l("span",{class:"d-k"},"Status"),Qn(s.newStatus,a=>r.setDrafts({newStatus:a}),!1)),l("h3",{class:"d-h"},"Description"),i,l("p",{class:"ro-note"},L("info",14),`Created in this table first. It becomes an issue in ${t.repository} once you review and send it.`)),l("div",{class:"d-actions"},D("Cancel",()=>r.open(void 0)),D("Create issue",()=>r.create(),{kind:"primary",disabled:!s.newTitle.trim()||!!t.busy,"data-key":"create"}))]}function Cs(t,e,n){let r=t.last?.result.held??[],s=r.length;return[et("Waiting to send",e,n),l("section",{class:"d-body","aria-label":"Changes to send to GitHub"},l("h2",{class:"d-title ro"},s?`Send ${s} ${s===1?"change":"changes"} to GitHub?`:"Nothing is waiting"),l("p",{class:"muted small",style:"margin:0"},"Nothing reaches GitHub until you send it. A change edited after this review is held again."),s?l("ol",{class:"review"},r.map(o=>l("li",null,En(o)))):null),l("div",{class:"d-actions"},D("Not now",()=>n.open(void 0)),D(`Send ${s} ${s===1?"change":"changes"} to GitHub`,()=>n.send(),{kind:"primary",disabled:!s||!!t.busy,"data-key":"send"}))]}var qn={title:"Title",body:"Description",status:"Status"};function Ms(t,e,n){if(t==="status"&&typeof e=="string"&&e in he)return l("span",{class:"cf-val"},me(he[e]),e);let r=typeof e=="string"?e:JSON.stringify(e??""),s=typeof n=="string"?n:"",o=0;for(;od.subject===s?.local),i=e.fields??[],a=i.filter(d=>!e.choices[d.field]),c;return s?e.error?c=l("p",{class:"field-error"},e.error):e.fields?c=[l("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(d=>l("fieldset",{class:"cf"},l("legend",null,qn[d.field]??d.field),["local","remote"].map(u=>l("label",{class:"cf-opt"},l("input",{type:"radio",name:`cf-${d.field}`,value:u,checked:e.choices[d.field]===u,"data-key":`cf:${d.field}:${u}`,onchange:()=>r.open({...e,choices:{...e.choices,[d.field]:u}})}),l("span",{class:"cf-src"},u==="local"?"Here":"On GitHub"),Ms(d.field,d[u],u==="local"?d.remote:d.local))))),l("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=l("p",{class:"muted"},"Reading both versions\u2026"):c=l("p",null,"This conflict is settled."),[et("Conflict",n,r),l("div",{class:"d-body"},l("h2",{class:"d-title ro"},o?`${re(o)} ${o.title}`:"Changed on both sides"),c),l("div",{class:"d-actions"},D("Apply and resume sync",()=>r.resolve(),{kind:"primary",disabled:!s||!e.fields||a.length>0||!!t.busy,"data-key":"apply"}),a.length&&e.fields?l("p",{class:"hint muted small"},`Choose ${a.map(d=>qn[d.field]??d.field).join(" and ")} first`):null)]}function Ls(t,e,n,r){let s=e.panel;if(!s)return null;let o,i="Issue";if(s.kind==="issue"){let a=t.last?.result.rows.find(c=>c.subject===s.subject);if(!a)return null;o=Is(a,t,e,n,r),i=`${re(a)} ${a.title}`}else s.kind==="new"?(o=Ps(t,e,n,r),i="New issue"):s.kind==="review"?(o=Cs(t,n,r),i="Changes to send"):(o=Hs(t,s,n,r),i="Conflict review");return l("aside",{class:`detail ${n}`,"aria-label":i,...n==="docked"?{}:{role:"dialog","aria-modal":"true"},"data-panel":s.kind},o)}function Ns(t){return l("div",{class:"overlay",onclick:e=>{e.target===e.currentTarget&&t.setUi({help:!1})}},l("div",{class:"dialog",role:"dialog","aria-modal":"true","aria-labelledby":"help-title"},l("h2",{id:"help-title"},"Keyboard shortcuts"),l("dl",{class:"keys"},Cn.map(([e,n])=>[l("dt",null,l("kbd",null,e)),l("dd",null,n)])),l("div",{class:"actions-row"},D("Close",()=>t.setUi({help:!1}),{"data-key":"help-close"}))))}function er(t,e,n,r,s){let o=gs(t,e,s);if(t.kind==="no-proxy")return[o,ws()];if(t.kind==="other-table")return[o,Ce("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.",void 0,!0)];if(t.kind==="loading")return[o,l("p",{class:"lede",style:"padding:24px 16px"},"Loading\u2026")];if(t.kind==="not-connected"||t.kind==="connecting")return[o,vs(t,s)];if(t.kind==="choose-repository")return[o,Tt([l("span",{class:"acct"},"GitHub"),"connected"]),ks(t,e,s)];let i=l("div",{class:"split-main"},ys(t,e,s),$s(t,e,n,s),As(t,e,s)??(n==="board"?Es(t,e,s):Rs(t,e,s))),a=Ls(t,e,r,s),c=a&&r==="docked"?l("div",{class:"split app-body"},i,a):l("div",{class:"app-body"},i),d=[o,bs(t,e,s),c];return a&&r!=="docked"&&d.push(l("div",{class:"scrim","aria-hidden":"true",onclick:()=>s.open(void 0)}),a),e.help&&d.push(Ns(s)),d}var tr=240,Ds=3600,Ot=()=>({tab:"preview",comment:"",newTitle:"",newBody:"",newStatus:"Todo"});async function Ei({root:t,store:e}){Fn(t,Hn),t.classList.add("pl-app");let n=t.ownerDocument,r=n.defaultView,s=Gn(),o={size:"xl",search:"",allDone:!1,groups:{},help:!1,drafts:Ot(),repoFilter:"",typedRepo:"",alert:!1,canDisconnect:typeof e.proxy?.disconnect=="function",flash:new Set,now:Date.now()},i,a=!1,c,d=tr,u,p,m,b=!1,v=()=>{o.now=Date.now(),u?o.retryIn=Math.max(0,(u-o.now)/1e3):delete o.retryIn;let f=w.state(),x=n.activeElement,T=x&&t.contains(x)?x.dataset.key:void 0,P=x,G=T&&typeof P?.selectionStart=="number"?[P.selectionStart,P.selectionEnd??P.selectionStart]:void 0,ce=[...t.querySelectorAll(".board, .detail, .repos")].map(Te=>[Te.className.split(" ")[0],Te.scrollLeft,Te.scrollTop]),nr=xt(o.size,o.layout),rr=Pn(o.size);t.replaceChildren(...er(f,o,nr,rr,g),s.region);for(let[Te,sr,or]of ce){let tt=t.querySelector(`.${Te}`);tt&&(tt.scrollLeft=sr,tt.scrollTop=or)}if(!T)return;let Me=R(T);if(Me&&(Me.focus({preventScroll:!0}),G&&"setSelectionRange"in Me))try{Me.setSelectionRange(G[0],G[1])}catch{}};function R(f){let x=f.replace(/["\\]/g,"\\$&");return t.querySelector(`[data-key="${x}"]`)}let $=f=>{f&&R(f)?.focus()},I=f=>{if(!(f.kind==="ready"&&f.problem?.kind==="failed")){c&&clearTimeout(c),c=void 0,u=void 0,f.kind==="ready"&&!f.problem&&!f.busy&&(d=tr);return}c||(u=Date.now()+d*1e3,c=setTimeout(()=>{c=void 0,u=void 0,d=Math.min(Ds,d*2),w.sync()},d*1e3))},z=f=>{if(f.kind!=="ready"||f.busy||!f.last)return;let x=new Map(f.last.result.rows.map(T=>[T.subject,[T.title,T.status,T.body,T.comments.length,T.updatedAt].join(` +`)]));if(o.flash=new Set,m){let T=new Set(f.touched??[]);for(let[P,G]of x){let ce=m.get(P);ce!==void 0&&ce!==G&&!T.has(P)&&o.flash.add(P)}}m=x},w=kn(e,f=>{if(f.kind==="ready"){if(!b){b=!0;let x=w.prefs();x.layout&&(o.layout=x.layout),x.search&&(o.search=x.search),x.label&&(o.label=x.label)}(f.problem?.kind!=="paused"||!f.problem.missing)&&(o.confirmRemove=!1),o.alert=a&&!!f.problem,o.panel?.kind==="conflict"&&f.problem?.kind!=="conflict"&&!f.busy&&(o.panel=void 0)}z(f),I(f),v()}),E=()=>{p&&clearTimeout(p),p=setTimeout(()=>{w.state().kind==="ready"&&w.savePrefs({...o.layout?{layout:o.layout}:{},...o.search?{search:o.search}:{},...o.label?{label:o.label}:{}})},800)},O=async f=>{if(/^https?:/i.test(f)){if(e.openExternal){await e.openExternal(f).catch(()=>{});return}try{r.open(f,"_blank","noopener")}catch{}}};t.addEventListener("click",f=>{let x=f.target.closest?.("a[href]");if(!x||!e.openExternal)return;let T=x.href;/^https?:/i.test(T)&&(f.preventDefault(),O(T))});let j=()=>{let f=w.state();return f.kind==="ready"?f:void 0},_=f=>j()?.last?.result.rows.find(x=>x.subject===f),g={connect:()=>{w.connect()},listRepositories:()=>{w.listRepositories()},choose:f=>{w.choose(f)},sync:()=>{w.sync()},send:()=>{o.panel?.kind==="review"&&(o.panel=void 0),w.send().then(()=>$(i??"sync-now"))},move(f,x,T){let P=j(),G=_(f);!P||!G||G.status===x&&!G.statusAsIs||!fe(P)||(s.say(`Moved ${re(G)} to ${x}`),T==="key"&&(o.focus=f),w.edit(f,{status:x}))},open(f,x){f&&x&&(i=x);let T=f?.kind!==o.panel?.kind||f?.kind==="issue"&&o.panel?.kind==="issue"&&f.subject!==o.panel.subject;if(T&&(o.drafts={...Ot(),newStatus:o.drafts.newStatus,...f?.kind==="new"?{newTitle:o.drafts.newTitle,newBody:o.drafts.newBody}:{}}),o.panel=f,o.menu=void 0,v(),!f){$(i),i=void 0,o.drafts.newStatus="Todo";return}f.kind==="conflict"&&!f.fields&&!f.error&&w.conflict().then(P=>{o.panel?.kind==="conflict"&&(o.panel=P?{...o.panel,fields:P}:{...o.panel,error:"This conflict is already settled."},v())}).catch(P=>{o.panel?.kind==="conflict"&&(o.panel={...o.panel,error:P instanceof Error?P.message:String(P)},v())}),!(!T||o.size==="xl")&&$(f.kind==="new"?"new-title":"detail-close")},saveTitle(f,x){o.drafts.title=void 0,w.edit(f,{title:x})},saveBody(f,x){o.drafts={...o.drafts,body:void 0,tab:"preview"},w.edit(f,{body:x})},comment(f,x){x.trim()&&(o.drafts.comment="",s.say("Comment added; waiting to send"),w.comment(f,x))},create(){let f=o.drafts;if(!f.newTitle.trim())return;let x={title:f.newTitle.trim(),body:f.newBody,status:f.newStatus};o.drafts=Ot(),w.create(x).then(({subject:T})=>{T&&o.panel?.kind==="new"&&(o.panel={kind:"issue",subject:T},i=`card:${T}`,v())})},resolve(){let f=o.panel;f?.kind==="conflict"&&w.resolve(f.choices)},setUi(f,x=!0){let T="layout"in f||"search"in f||"label"in f;Object.assign(o,f),"label"in f&&f.label===void 0&&delete o.label,T&&E(),x&&v()},setDrafts(f,x=!0){o.drafts={...o.drafts,...f},x&&v()},openGitHub(f){O(f)},focusSearch(){$("search")},disconnect(){w.disconnect()},keepHereOnly(){w.keepHereOnly()},removeFromBoard(){o.confirmRemove=!1,w.removeFromBoard()},landed(f,x){w.landed(f,x)},sendAgain(f){w.sendAgain(f)},publish(f){s.say("Publishing to GitHub after your review"),w.publish(f)}},h,y=()=>[...t.querySelectorAll("[data-issue]")].filter(f=>!f.closest(".detail")),k=()=>n.activeElement?.closest("[data-subject]")?.dataset.subject??(o.panel?.kind==="issue"?o.panel.subject:void 0),S=()=>{let f=o.menu??"";o.menu=void 0,v(),$(f.startsWith("move:")?`cardmenu:${f.slice(5)}`:f.startsWith("status:")?`glyph:${f.slice(7)}`:f==="label"?"label-filter":void 0)},A=f=>{let x=t.querySelector(".detail"),T=x?[...x.querySelectorAll('button:not(:disabled), textarea, input:not(:disabled), a[href], [tabindex="0"]')]:[];if(!T.length)return;let P=T[0],G=T[T.length-1];!x.contains(n.activeElement)||f.shiftKey&&n.activeElement===P?(f.preventDefault(),(f.shiftKey?G:P).focus()):!f.shiftKey&&n.activeElement===G&&(f.preventDefault(),P.focus())},N=f=>{let x=f.key;if(h&&x.toLowerCase()==="s")return clearTimeout(h),h=void 0,g.sync(),!0;if(x==="g"||x==="G")return h=setTimeout(()=>h=void 0,1e3),!1;if(x==="/")g.focusSearch();else if(x==="?")g.setUi({help:!0}),$("help-close");else if(x==="b"||x==="B"){let T=xt(o.size,o.layout);g.setUi({layout:T==="board"?"list":"board"})}else if(x==="n"||x==="N")g.open({kind:"new"},"new-issue");else if(x==="c"||x==="C"){if(o.panel?.kind!=="issue")return!1;$("composer")}else if(["j","k","J","K","ArrowDown","ArrowUp"].includes(x)){if(o.panel&&o.size!=="xl")return!1;let T=y();if(!T.length)return!1;let P=T.indexOf(n.activeElement),G=x==="j"||x==="J"||x==="ArrowDown",ce=P<0?G?0:T.length-1:Math.min(T.length-1,Math.max(0,P+(G?1:-1)));T[ce].focus()}else if(x in kt){let T=k();if(!T)return!1;g.move(T,kt[x],"key")}else return!1;return!0};n.addEventListener("keydown",f=>{if(!(f.defaultPrevented||f.metaKey||f.ctrlKey||f.altKey)){if(f.key==="Escape"){if(o.menu)S();else if(o.help)g.setUi({help:!1});else if(o.panel)g.open(void 0);else return;f.preventDefault();return}if(f.key==="Tab"&&o.panel&&o.size!=="xl"){A(f);return}St(f.target)||o.help||!j()||o.menu&&(f.key==="ArrowDown"||f.key==="ArrowUp")||N(f)&&f.preventDefault()}}),n.addEventListener("click",f=>{!o.menu||f.target.closest?.(".menu, .popover, [aria-haspopup]")||(o.menu=void 0,v())}),Bn(t,f=>{o.size=f,v()},{...e.getTheme?{getTheme:()=>e.getTheme()}:{},...e.onThemeChange?{onThemeChange:f=>e.onThemeChange(f)}:{}}),setInterval(()=>{St(n.activeElement)||v()},3e4),v();try{await w.start()}catch(f){let x=f instanceof Error?f.message:String(f),T=n.createElement("p");T.className="field-error",T.style.padding="16px",T.textContent=`Could not load: ${x}`,t.append(T)}finally{a=!0}}export{Ei as view}; diff --git a/integrations/READINESS.md b/integrations/READINESS.md index 684fe8b76..81fdd5d6f 100644 --- a/integrations/READINESS.md +++ b/integrations/READINESS.md @@ -74,20 +74,20 @@ read from the atomic-server source at the pin. ## Matrix -| Plugin (catalog id) | Runtime of the current code | Install entry point at the pin | Import / write scope (declared) | Evidence | Open blockers | -| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Pets, drive app (`pets`) | Drive app `pets/app/`: iframe, `syncables/browser` over `store.proxy` | Integrations → Show experimental plugins → Drive apps → Install (`pets` 0.1.1, from GitHub Pages, integrity-checked). The host E2E installs this way, then updates from an older recorded version | Read-only. Pets from the mock `pets` platform into the app's own table | Unit; **Host E2E** (`pets` lane: catalog install and update, connect, 5 rows, datatypes) | None filed | -| Pets, static demo (`pets`) | Sandbox `pets/plugin.js`, no network | None. Its setup dialog was removed in `4bab16ee6` | Five static pets into a Pets table | Unit; `certify.mjs --layer js`. Historical: Rust sandbox test (removed from atomic-server in `4bab16ee6`) | None filed; the catalog card still describes this demo, not the drive app | -| Notion, drive app (`notion`) | Drive app `notion/app/`: iframe, `syncables/browser` + Devonian `AtomicLens` over `store.proxy`; the #89 UI (table, board and list views, side peek, sync details, Disconnect), and since 0.2.0 "Review changes" (compare on open, review, send) | Published (`notion` 0.2.0 on GitHub Pages) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | Every shared data source into one table; plain fields and select/status/multi-select options. Two-way for those fields on existing pages, after review (`PATCH /v1/pages/{id}`, baseline on the row); no page creation, no deletes | Unit; **Host E2E** (`notion` lane: catalog install, connect, 3 rows, column datatypes, formatted-text warning, the #89 states against the fixture's scenarios, an edit made in the host found on open and sent, a conflict resolved). No live run | [#8](https://github.com/ontola/atomic-plugins/issues/8) live evidence for writes; page creation; #177 Q9 (sync-status view only) | -| Notion, two-way pilot (no card; shares `notion`'s version) | Sandbox `notion/plugin.js` | None. `ConnectNotion` was removed in `4bab16ee6`. The `notion` catalog card now describes the drive app | Two-way on one data source: plain fields, property names, table/board view subset (`package.json` capabilities) | Unit; `certify.mjs --layer js`; `live` tier runs the installer against the pinned server with Notion stubbed. Historical: live UI import and title edits via `ConnectNotion` | Retire once the drive app's writes (0.2.0) have live evidence ([#8](https://github.com/ontola/atomic-plugins/issues/8)) | -| Clockify (`timesheets`) | Drive app `timesheets/app/`: iframe, own Clockify client over `store.proxy.request`. The #89 UI (week grid, entries, projects, read-only drawer, settings) over the #123 M1 observation log and M2 timeline | Published (`timesheets` 0.1.0 on GitHub Pages) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | Read-only. The user's own entries in one workspace, rolling 7- or 30-day look-back; completed entries as rows. Conflicts and not-loaded time shown read-only. No writes to Clockify yet | Unit (fake store; #123 M1 scenarios and fold property tests, M2 timeline incl. DST days); **Host E2E** (`timesheets` lane: catalog install, connect, setup, import, reload, changed entry, 7 → 30 days, 503 recovery, an M2 conflict and unknown time). The mock's Clockify endpoints follow API behaviour checked against a live account on 2026-09-24 (#123); the app itself has no live run | [#123](https://github.com/ontola/atomic-plugins/issues/123) M3/M4 (writes, resolving conflicts), [#97](https://github.com/ontola/atomic-plugins/issues/97) | -| Bank statements, importer (`money`) | Sandbox `money/plugin.js` (0.3.0), file handed over as `ctx.upload`, no network | Draft from a published release (Integrations → Community plugins → Create draft), then Set up and Import on the plugin page (atomic-server#1653's `accepts`/`destination`, in the pin). Publishing the bundle to a server is manual (#94). An importer set up before 0.3.0's `tables` pauses until Set up runs again | Import only. MT940 ≤ 512 KB, camt.053 ≤ 5 MB, ≤ 500 transactions per file, into Bank transactions plus one Imported statements row per statement (`destination.tables`, atomic-server#1768) | Unit; `certify.mjs --layer js`; host E2E `money/e2e/money.spec.ts` (synthetic MT940/camt.053: import with its statement row, reload, reimport, local edit, conflict, refused files). Historical: a real 272-transaction bunq MT940 export through `ImportMT940` (2026-09-11) | [#94](https://github.com/ontola/atomic-plugins/issues/94) | -| Money, drive app (`money`) | Drive app `money/app/`: iframe, a view of the importer's table (`store.getData()`), no `store.proxy`; imports through the importer (`store.importer.run`, atomic-server#1774) | Published (`money` 0.3.0 on GitHub Pages) but `enabled: false`. A catalog Install would not give a working app yet: it gets its own empty table with no importer, and the importer's table offers under Add view only apps rendering its class. The host E2E installs test-side and adds the Bank transaction class to the app's `renders` | Reads the importer's Bank transactions and Imported statements tables. Writes only `money-category` and `money-note` on a row, after the person allows row editing (atomic-server#1788) | Unit (fake store modelling a current and an older host); axe and screenshots (`app/harness/`); **Host E2E** (`money` lane, second test: Add view, import through the host's review, closing balance, category after Allow editing, in-app check). At pin `2567fc30b` the second test could fail on atomic-server#1846 ('New app' missing); fixed at pin `1432e244a`, where both tests passed once on 2026-09-29 | Install path above; [#179](https://github.com/ontola/atomic-plugins/pull/179) pin | -| Willow drop (`willow-drop`) | Sandbox `willow-drop/plugin.js`, drop file handed over as `ctx.upload` text and turned back into bytes, no network | As for Bank statements: draft from a published release, then Set up and Import on the plugin page. Publishing is manual (#94) | Import only. Willow'25 drops up to 5,000,000 bytes and 1,000 entries (declared); no delegated capabilities, no partial payloads | Unit (fixtures written by willow25 0.7.9); host E2E `willow-drop/e2e/willow-drop.spec.ts` (raw and base64 upload, reimport, refused drops) | [#139](https://github.com/ontola/atomic-plugins/issues/139) follow-ups: delegations, partial payloads | -| Google Calendar (`calendar`) | Drive app `calendar/app/`: iframe, `calendar/adapter.ts` through `app/relay.ts` over `store.proxy`. The #89 UI (agenda, week, drawer, review sheet; Month hands off to the table's Calendar view, which spans all-day ranges because rows use the host's `atomic-calendar-*` field names) | Published (`calendar` 0.1.4 on GitHub Pages; 0.1.0 wrote `day`/`all-day` and no end day; 0.1.4 removed the adapter's unused sandbox manifest and credential placeholder, and the relay enforces the declared scope of `app/operations.ts`) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | One calendar's single non-recurring events in (≤ 25,000 per scan); reviewed edits of five fields out with If-Match and `sendUpdates=none`; no creates or deletes in Google | Unit; **Host E2E** (`calendar` lane: catalog install, connect, import, refresh after a Google-side edit, review and send, 412 conflict, lost response, links/Month/Disconnect through the host, the host Calendar view spanning a three-day all-day event and placing a timed one, responsive and theme). Historical: live import (2026-09-09, proxy v39) through the retired LocalThought snapshot importer. No live run of the drive app | [#101](https://github.com/ontola/atomic-plugins/issues/101) live verification | -| Todoist (`devonian-todoist`) | Library only: `issue-tracker/todoist.ts` projection | None. Its host hook was removed in `f3efedf65` | Declared: read-only, active tasks and projects | Unit. Recorded-fixture tests skip until a recording exists | [#99](https://github.com/ontola/atomic-plugins/issues/99), [#46](https://github.com/ontola/atomic-plugins/issues/46) | -| GitHub issues (`issue-tracker`) | Drive app `issue-tracker/app/`: iframe, the Devonian bridge from `issue-tracker/devonian/github-issues/` (npm `devonian` 0.8.0) over `store.proxy`. The #89 board/list UI. The lens's sandbox `plugin.ts` has no host | Published (`issue-tracker` 0.1.1 on GitHub Pages; #206) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | Two-way for one repository: title, body, Todo/Doing/Done status, comments. Every GitHub write is held for review before send. An issue gone from GitHub: "Keep here only" or "Remove from board". An uncertain create has no in-app way out yet | Unit (incl. state 13); **Host E2E** (`issue-tracker` lane: catalog install, connect, repository picker, import, reload, reviewed status update, conflict review, keyboard move, comment). Opt-in lens `*.live.test.ts` (need `GITHUB_TOKEN`; not run in CI). Historical: live GitHub read (2026-09-09, proxy v38) via the retired server flow. No live run of the drive app | [#156](https://github.com/ontola/atomic-plugins/issues/156) "It landed", [#100](https://github.com/ontola/atomic-plugins/issues/100) | -| Moneybird (`moneybird`) | Drive app `money/moneybird/`: iframe, own Moneybird reader over `store.proxy.request` (contacts only) | None. The catalog entry is `enabled: false` with no `app-module` yet; the host E2E installs test-side (`New app` + source) | Read-only. Contacts of one administration into a typed table | Unit; **Host E2E** on a SYNTHETIC fixture (`money` lane, `moneybird.spec.ts`: connect, choose an administration, 5 typed rows, failed refresh keeps rows, resync). Nothing verified against real Moneybird | [#102](https://github.com/ontola/atomic-plugins/issues/102) (a real recording needs a Moneybird account) | +| Plugin (catalog id) | Runtime of the current code | Install entry point at the pin | Import / write scope (declared) | Evidence | Open blockers | +| ---------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Pets, drive app (`pets`) | Drive app `pets/app/`: iframe, `syncables/browser` over `store.proxy` | Integrations → Show experimental plugins → Drive apps → Install (`pets` 0.1.1, from GitHub Pages, integrity-checked). The host E2E installs this way, then updates from an older recorded version | Read-only. Pets from the mock `pets` platform into the app's own table | Unit; **Host E2E** (`pets` lane: catalog install and update, connect, 5 rows, datatypes) | None filed | +| Pets, static demo (`pets`) | Sandbox `pets/plugin.js`, no network | None. Its setup dialog was removed in `4bab16ee6` | Five static pets into a Pets table | Unit; `certify.mjs --layer js`. Historical: Rust sandbox test (removed from atomic-server in `4bab16ee6`) | None filed; the catalog card still describes this demo, not the drive app | +| Notion, drive app (`notion`) | Drive app `notion/app/`: iframe, `syncables/browser` + Devonian `AtomicLens` over `store.proxy`; the #89 UI (table, board and list views, side peek, sync details, Disconnect), and since 0.2.0 "Review changes" (compare on open, review, send) | Published (`notion` 0.2.0 on GitHub Pages) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | Every shared data source into one table; plain fields and select/status/multi-select options. Two-way for those fields on existing pages, after review (`PATCH /v1/pages/{id}`, baseline on the row); no page creation, no deletes | Unit; **Host E2E** (`notion` lane: catalog install, connect, 3 rows, column datatypes, formatted-text warning, the #89 states against the fixture's scenarios, an edit made in the host found on open and sent, a conflict resolved). No live run | [#8](https://github.com/ontola/atomic-plugins/issues/8) live evidence for writes; page creation; #177 Q9 (sync-status view only) | +| Notion, two-way pilot (no card; shares `notion`'s version) | Sandbox `notion/plugin.js` | None. `ConnectNotion` was removed in `4bab16ee6`. The `notion` catalog card now describes the drive app | Two-way on one data source: plain fields, property names, table/board view subset (`package.json` capabilities) | Unit; `certify.mjs --layer js`; `live` tier runs the installer against the pinned server with Notion stubbed. Historical: live UI import and title edits via `ConnectNotion` | Retire once the drive app's writes (0.2.0) have live evidence ([#8](https://github.com/ontola/atomic-plugins/issues/8)) | +| Clockify (`timesheets`) | Drive app `timesheets/app/`: iframe, own Clockify client over `store.proxy.request`. The #89 UI (week grid, entries, projects, read-only drawer, settings) over the #123 M1 observation log and M2 timeline | Published (`timesheets` 0.1.0 on GitHub Pages) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | Read-only. The user's own entries in one workspace, rolling 7- or 30-day look-back; completed entries as rows. Conflicts and not-loaded time shown read-only. No writes to Clockify yet | Unit (fake store; #123 M1 scenarios and fold property tests, M2 timeline incl. DST days); **Host E2E** (`timesheets` lane: catalog install, connect, setup, import, reload, changed entry, 7 → 30 days, 503 recovery, an M2 conflict and unknown time). The mock's Clockify endpoints follow API behaviour checked against a live account on 2026-09-24 (#123); the app itself has no live run | [#123](https://github.com/ontola/atomic-plugins/issues/123) M3/M4 (writes, resolving conflicts), [#97](https://github.com/ontola/atomic-plugins/issues/97) | +| Bank statements, importer (`money`) | Sandbox `money/plugin.js` (0.3.0), file handed over as `ctx.upload`, no network | Draft from a published release (Integrations → Community plugins → Create draft), then Set up and Import on the plugin page (atomic-server#1653's `accepts`/`destination`, in the pin). Publishing the bundle to a server is manual (#94). An importer set up before 0.3.0's `tables` pauses until Set up runs again | Import only. MT940 ≤ 512 KB, camt.053 ≤ 5 MB, ≤ 500 transactions per file, into Bank transactions plus one Imported statements row per statement (`destination.tables`, atomic-server#1768) | Unit; `certify.mjs --layer js`; host E2E `money/e2e/money.spec.ts` (synthetic MT940/camt.053: import with its statement row, reload, reimport, local edit, conflict, refused files). Historical: a real 272-transaction bunq MT940 export through `ImportMT940` (2026-09-11) | [#94](https://github.com/ontola/atomic-plugins/issues/94) | +| Money, drive app (`money`) | Drive app `money/app/`: iframe, a view of the importer's table (`store.getData()`), no `store.proxy`; imports through the importer (`store.importer.run`, atomic-server#1774) | Published (`money` 0.3.0 on GitHub Pages) but `enabled: false`. A catalog Install would not give a working app yet: it gets its own empty table with no importer, and the importer's table offers under Add view only apps rendering its class. The host E2E installs test-side and adds the Bank transaction class to the app's `renders` | Reads the importer's Bank transactions and Imported statements tables. Writes only `money-category` and `money-note` on a row, after the person allows row editing (atomic-server#1788) | Unit (fake store modelling a current and an older host); axe and screenshots (`app/harness/`); **Host E2E** (`money` lane, second test: Add view, import through the host's review, closing balance, category after Allow editing, in-app check). At pin `2567fc30b` the second test could fail on atomic-server#1846 ('New app' missing); fixed at pin `1432e244a`, where both tests passed once on 2026-09-29 | Install path above; [#179](https://github.com/ontola/atomic-plugins/pull/179) pin | +| Willow drop (`willow-drop`) | Sandbox `willow-drop/plugin.js`, drop file handed over as `ctx.upload` text and turned back into bytes, no network | As for Bank statements: draft from a published release, then Set up and Import on the plugin page. Publishing is manual (#94) | Import only. Willow'25 drops up to 5,000,000 bytes and 1,000 entries (declared); no delegated capabilities, no partial payloads | Unit (fixtures written by willow25 0.7.9); host E2E `willow-drop/e2e/willow-drop.spec.ts` (raw and base64 upload, reimport, refused drops) | [#139](https://github.com/ontola/atomic-plugins/issues/139) follow-ups: delegations, partial payloads | +| Google Calendar (`calendar`) | Drive app `calendar/app/`: iframe, `calendar/adapter.ts` through `app/relay.ts` over `store.proxy`. The #89 UI (agenda, week, drawer, review sheet; Month hands off to the table's Calendar view, which spans all-day ranges because rows use the host's `atomic-calendar-*` field names) | Published (`calendar` 0.1.4 on GitHub Pages; 0.1.0 wrote `day`/`all-day` and no end day; 0.1.4 removed the adapter's unused sandbox manifest and credential placeholder, and the relay enforces the declared scope of `app/operations.ts`) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | One calendar's single non-recurring events in (≤ 25,000 per scan); reviewed edits of five fields out with If-Match and `sendUpdates=none`; no creates or deletes in Google | Unit; **Host E2E** (`calendar` lane: catalog install, connect, import, refresh after a Google-side edit, review and send, 412 conflict, lost response, links/Month/Disconnect through the host, the host Calendar view spanning a three-day all-day event and placing a timed one, responsive and theme). Historical: live import (2026-09-09, proxy v39) through the retired LocalThought snapshot importer. No live run of the drive app | [#101](https://github.com/ontola/atomic-plugins/issues/101) live verification | +| Todoist (`devonian-todoist`) | Library only: `issue-tracker/todoist.ts` projection | None. Its host hook was removed in `f3efedf65` | Declared: read-only, active tasks and projects | Unit. Recorded-fixture tests skip until a recording exists | [#99](https://github.com/ontola/atomic-plugins/issues/99), [#46](https://github.com/ontola/atomic-plugins/issues/46) | +| GitHub issues (`issue-tracker`) | Drive app `issue-tracker/app/`: iframe, the Devonian bridge from `issue-tracker/devonian/github-issues/` (npm `devonian` 0.8.0) over `store.proxy`. The #89 board/list UI. The lens's sandbox `plugin.ts` has no host | Published (`issue-tracker` 0.1.1 on GitHub Pages; #206) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | Two-way for one repository: title, body, Todo/Doing/Blocked/Done status (`atomic:doing`/`atomic:blocked` labels), comments. Rows are of the shared `issue-v1` class since 0.2.0 (#177 item 6); rows added outside the app stay local until "Publish to GitHub". Every GitHub write is held for review before send. An issue gone from GitHub: "Keep here only" or "Remove from board". An uncertain create has no in-app way out yet | Unit (incl. state 13); **Host E2E** (`issue-tracker` lane: catalog install, connect, repository picker, import, reload, reviewed status update, conflict review, keyboard move, comment). Opt-in lens `*.live.test.ts` (need `GITHUB_TOKEN`; not run in CI). Historical: live GitHub read (2026-09-09, proxy v38) via the retired server flow. No live run of the drive app | [#156](https://github.com/ontola/atomic-plugins/issues/156) "It landed", [#100](https://github.com/ontola/atomic-plugins/issues/100) | +| Moneybird (`moneybird`) | Drive app `money/moneybird/`: iframe, own Moneybird reader over `store.proxy.request` (contacts only) | None. The catalog entry is `enabled: false` with no `app-module` yet; the host E2E installs test-side (`New app` + source) | Read-only. Contacts of one administration into a typed table | Unit; **Host E2E** on a SYNTHETIC fixture (`money` lane, `moneybird.spec.ts`: connect, choose an administration, 5 typed rows, failed refresh keeps rows, resync). Nothing verified against real Moneybird | [#102](https://github.com/ontola/atomic-plugins/issues/102) (a real recording needs a Moneybird account) | `integrations/localthought/` is shared tooling, not a user-facing plugin: the shared mock proxy every E2E lane uses (`mock-proxy.mjs`, which speaks diff --git a/integrations/catalog.json b/integrations/catalog.json index 6ad835216..d66debbea 100644 --- a/integrations/catalog.json +++ b/integrations/catalog.json @@ -374,15 +374,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, Done) or a list, with search and a label filter. Title, description (Markdown), status and comments sync both ways; 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.", "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. 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. Mock-tested only: not yet verified against live GitHub or the real integration proxy.", + "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/keywords": "github issues board kanban tracker two-way review drive app devonian", - "https://atomicdata.dev/integrations/properties/version": "0.1.3", + "https://atomicdata.dev/integrations/properties/version": "0.2.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.1.3/ui.js", - "https://atomicdata.dev/integrations/properties/app-module-integrity": "sha384-DcdXfSVucGQv/u8CnLD2rhNSR5MIYP35GK0oo8/W0Qeqpyd58Pg4bwv9Sg2a945f" + "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/properties/localId": "open-cloud-mesh", diff --git a/integrations/issue-tracker/README.md b/integrations/issue-tracker/README.md index 5b7dc6ac7..4777db86c 100644 --- a/integrations/issue-tracker/README.md +++ b/integrations/issue-tracker/README.md @@ -19,13 +19,16 @@ This folder also holds the plugin's other issue sources: | ----------------------------------------- | ----------- | | Issue title | Card title | | Markdown body (`null` becomes empty text) | Description | -| Open, without `atomic:doing` | Todo | +| Open, without a workflow label | Todo | | Open, with `atomic:doing` | Doing | +| Open, with `atomic:blocked` | Blocked | | Closed | Done | Dragging a card to Done closes its issue; moving it back reopens it. Other labels -are preserved: the adapter adds/removes only `atomic:doing`, never replaces the -whole label set. Create that label in the test repository before using Doing. +are preserved: the adapter adds/removes only `atomic:doing` and +`atomic:blocked` (#177 Q8), never replaces the whole label set. An open issue +with both is Blocked. Closing keeps the labels as they are. Create both +labels in the test repository before using Doing or Blocked. Pull requests are excluded. Comments, assignees, milestones, GitHub Projects and issue deletion are outside this first scope. A missing issue/card is a conflict, not permission to delete the other side. @@ -79,11 +82,11 @@ 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, about 134 KB) 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/Done status -and comments. +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 +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. **Flow.** The first screen offers GitHub Issues (Jira and Todoist are shown as not available). "Connect" asks the host for a connection @@ -98,26 +101,90 @@ now" (or `G` `S`), after each edit made in the app, and after a transient failure (4, 8, … up to 60 minutes, while the view is open). **The view** follows `design/DESIGN.md` and `design/mockups.html` (#89): -a board (Todo / Doing / Done, Done collapsed to the 20 most recently +a board (Todo / Doing / Blocked / Done, Done collapsed to the 20 most recently updated) at 720 px and wider, a list below that, and an explicit Board/List choice (`B`) that wins at every width; search and a label filter shared by both; an issue panel (docked at 1000 px and wider, a drawer from 600 px, a full-screen sheet below) with the title, status, read-only labels, the description (Write / Preview, a safe Markdown preview) and comments; "New issue" (`N`); the sync pill and connection bar; one banner per problem; -and `?` for the keyboard shortcuts. Cards move by drag, by `1`/`2`/`3` on a +and `?` for the keyboard shortcuts. Cards move by drag, by `1`/`2`/`3`/`4` on a focused card or by their "Move to…" menu. The shared chrome (the `--pl-*` aliases of the host's `--t-*` theme variables, pill, banner, empty state, buttons) is in `app/ui/`, separate from the issue views, so it can move to a shared package later. Layout and filters persist on the app's sync resource. **What it writes, and where.** Everything goes into the app's own subtree -(the only place a drive app may write): the Status select (Todo / Doing / -Done tags), GitHub issue number and GitHub source columns under the app's -ontology; one row per issue in the app's table, the body in Atomic's own -`description`; one Message per comment (`about` its row) in a "GitHub -comments" folder under the app; and one sync resource holding the bound -repository and the sync state as JSON text. +(the only place a drive app may write without a row grant). Since 0.2.0 the +rows are of the shared class `issue-v1` (#177 item 6, `ontology-kit/`), at +its published GitHub Pages subject: + +- one row per issue in the app's table, of class `issue-v1`: the title in + Atomic's `name`, the body in task/v1 `body`, the status as one of the + task/v1 tags `todo`, `doing`, `blocked`, `done` in task/v1 `status`. The + app reads these by subject through `ontology-kit/resolver.mjs`, never by + shortname; +- on each row, three provider extras under the app's own ontology: GitHub + 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; +- 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 + text: the Bridge's snapshot without the per-record baselines, the + transport's write journal, rows waiting to be published and the view + 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. + +**Baselines on the rows (#177 decision 7).** The Bridge still keeps a +baseline per record in memory. At each checkpoint, a baseline that differs +from what its row holds is written onto the row, and the sync state is saved +without it. A row the Bridge itself writes (an import, or bringing in a +GitHub change) carries its baseline in that same write, so the first import +needs no extra writes; a change sent to GitHub costs one extra row write. +Reading a row puts its baseline back into the record. Not moved: the +Bridge's identity map and its copy of each record's values (the snapshot's +`graph`) stay in the sync state, so the state still grows with the issues' +text. If a row's baseline is missing or unreadable, the next pass treats +both sides as unknown; when they agree it writes the baseline back. +Not guarded: a write the Bridge makes to a row whose verify read then shows +a concurrent edit leaves the row's baseline at the written value, so that +edit is sent as a change instead of reported as a conflict. + +**Local-only rows (#177 Q6, this plugin's choice).** A row with no GitHub +issue behind it is local only: the pass leaves it alone and the card is +marked "Local". "Publish to GitHub" in its issue panel asks for it to be +created; the next pass holds that create for review like any other write. +A card made with this app's own "New issue" form is published at once, +still only after review; a row added anywhere else (the table, another +view, another device) waits for "Publish to GitHub". Safer than 0.1.x, +which proposed a create for every row without a number. + +**A status outside the four.** A row whose status is not exactly one of the +four task/v1 tags (another tag, or several) is shown as it is ("Status +here: …, not synced with GitHub") instead of failing the pass. For the sync +it keeps the status it last agreed with GitHub, so nothing is sent for it; +if GitHub's status changes, GitHub's value replaces it. + +**From 0.1.x.** An update from 0.1.x over an existing install (the host's +Update on the Integrations page keeps rows and schema) rewrites the table's +rows in place once, before the first pass: the app's own Status tags become +the task/v1 tags with the same shortname, `description` becomes task/v1 +`body`, `isA` becomes `issue-v1`. The sync state is kept, and the +baselines it held move onto the rows at the first pass, so an edit made under +0.1.x and not sent yet is still found and offered for review (unit-tested +with the fake host only). The old Status property and class stay in the +app's ontology, unused. #177 Q10 says test installs are reinstalled and +re-synced; this pass exists so that unsent edits are not lost. **First import (#206).** An issue or comment that is on GitHub, never synced and not in the table is created from the list page GitHub returned @@ -338,10 +405,19 @@ persistence, alerts, the conflict review). `app/build.test.ts` checks the bundle and typechecks `app/`. The e2e (`e2e/issue-tracker.spec.ts`) covers connect, picking the repository, import, reload with an unchanged refresh, a reviewed update (closing #1), a title conflict settled for GitHub's side -in the review panel, a card moved with the `3` key and a comment, each -sent after review, 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). +in the review panel, a card moved with the `4` key and a comment, each +sent after review; then (0.2.0) that the table and its rows are `issue-v1` +and the App renders it, a row added in the table outside the app staying +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 +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`). 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 5a7851bb8..edd5fe2ac 100644 --- a/integrations/issue-tracker/app/build.test.ts +++ b/integrations/issue-tracker/app/build.test.ts @@ -20,11 +20,14 @@ 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 137,315 bytes (134.1 KiB) on 2026-10-01, with the JS and the - // embedded stylesheets minified, after resolving uncertain creates - // (#156); 125,472 bytes on 2026-09-24 for the designed board/list/detail - // UI (#89). The limit is that plus 10%, rounded up to the next KiB. - expect(bytes).toBeLessThan(148 * 1024); + // 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 + // 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); }); 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 59509e085..ce5992f12 100644 --- a/integrations/issue-tracker/app/controller.test.ts +++ b/integrations/issue-tracker/app/controller.test.ts @@ -7,8 +7,31 @@ import { describeHeld, type ViewState, } from './controller.js'; -import { fakeStore, TABLE, type FakeStore } from './fakeStore.js'; -import { ABOUT, DESCRIPTION, NAME, PARENT, SHORTNAME } from './tracker.js'; +import { + APP, + ONTOLOGY, + RENDERS, + ROW_CLASS, + ROW_EXTRAS, + fakeStore, + TABLE, + type FakeStore, +} from './fakeStore.js'; +import { + ABOUT, + ALLOWS_ONLY, + CLASSTYPE, + DESCRIPTION, + IS_A, + ISSUE_V1, + NAME, + PARENT, + PROPERTIES, + SHORTNAME, + TASK_BODY, + TASK_STATUS, + TASK_TAGS, +} from './tracker.js'; type Ready = Extract; @@ -165,11 +188,7 @@ group('issue-tracker controller: conflict review', () => { it('describes each field and applies one side per field', async () => { const { store, controller } = await bound(); const subject = rowByNumber(ready(controller.state()), 2).subject; - const status = property(store, 'issue-status'); - const done = [...store.resources.entries()].find( - ([, p]) => p[PARENT] === status && p[SHORTNAME] === 'done', - )![0]; - store.edit(subject, { [NAME]: 'Here', [status]: [done] }); + store.edit(subject, { [NAME]: 'Here', [TASK_STATUS]: [TASK_TAGS.Done] }); store.github.updateIssue(SEEDED_REPOSITORY, 2, { title: 'There', state: 'closed', @@ -511,3 +530,157 @@ group('issue-tracker controller: the Doing label on GitHub', () => { expect(pages.map(c => c.query?.page)).toEqual(['1', '2']); }); }); + +group( + 'issue-tracker controller: the shared issue-v1 class (#177 item 6)', + () => { + it('makes itself a view of issue-v1 and declares its row extras', async () => { + const { store } = await bound(); + const app = store.resources.get(APP)!; + expect(app[RENDERS]).toEqual([ROW_CLASS, ISSUE_V1]); + expect(app[ROW_EXTRAS]).toEqual([ + property(store, 'github-issue-number'), + property(store, 'github-source'), + property(store, 'github-sync-baseline'), + ]); + expect(store.resources.get(TABLE)![CLASSTYPE]).toBe(ISSUE_V1); + // Idempotent: a second open writes neither again. + const writes = store.writes.length; + await createController(store).start(); + expect( + store.writes + .slice(writes) + .filter(w => w.subject === APP || w.subject === TABLE), + ).toEqual([]); + }); + + it('syncs Blocked as the atomic:blocked label, both ways (#177 Q8)', async () => { + const { store, controller } = await bound(); + const first = rowByNumber(ready(controller.state()), 1).subject; + await controller.edit(first, { status: 'Blocked' }); + const held = ready(controller.state()); + expect(held.last!.result.held.map(describeHeld)).toEqual([ + 'Update #1: status Todo → Blocked (add the atomic:blocked label)', + ]); + await controller.send(); + const issue = store.github.snapshot(SEEDED_REPOSITORY).issues[0]; + expect(issue.state).toBe('open'); + expect( + issue.labels.map((l: { name?: string } | string) => + typeof l === 'string' ? l : l.name, + ), + ).toContain('atomic:blocked'); + expect(store.resources.get(first)![TASK_STATUS]).toEqual([ + TASK_TAGS.Blocked, + ]); + + // #2 is Doing; GitHub adds atomic:blocked: Blocked wins. + store.github.updateIssue(SEEDED_REPOSITORY, 2, { + labels: ['atomic:doing', 'atomic:blocked'], + }); + const synced = ready(await controller.sync()); + expect(rowByNumber(synced, 2).status).toBe('Blocked'); + expect(rowByNumber(synced, 2).labels).toEqual([]); + }); + + it('shows a status outside the four tags as it is, and does not fail or send it', async () => { + const { store, controller } = await bound(); + const subject = rowByNumber(ready(controller.state()), 1).subject; + store.edit(subject, { + [TASK_STATUS]: [TASK_TAGS.Doing, TASK_TAGS.Blocked], + }); + const state = ready(await controller.sync()); + expect(state.problem).toBeUndefined(); + expect(state.last!.result.held).toEqual([]); + expect(rowByNumber(state, 1)).toMatchObject({ + status: 'Todo', + statusAsIs: ['Doing', 'Blocked'], + }); + // A title change on GitHub comes in; the status here stays as it is. + store.github.updateIssue(SEEDED_REPOSITORY, 1, { + title: 'Renamed there', + }); + const after = ready(await controller.sync()); + expect(after.problem).toBeUndefined(); + expect(store.resources.get(subject)![NAME]).toBe('Renamed there'); + expect(store.resources.get(subject)![TASK_STATUS]).toEqual([ + TASK_TAGS.Doing, + TASK_TAGS.Blocked, + ]); + }); + + it('rewrites a 0.1.x table in place and keeps an edit not yet sent', async () => { + // A 0.1.x install: its own Status column, tags and rows, synced. + const store = fakeStore(); + const status = 'did:ad:prop-issue-status'; + const tags = { + todo: 'did:ad:tag-todo', + doing: 'did:ad:tag-doing', + done: 'did:ad:tag-done', + }; + store.resources.set(status, { + [PARENT]: ONTOLOGY, + [SHORTNAME]: 'issue-status', + [ALLOWS_ONLY]: Object.values(tags), + }); + for (const [shortname, tag] of Object.entries(tags)) + store.resources.set(tag, { [PARENT]: status, [SHORTNAME]: shortname }); + store.resources.get(ONTOLOGY)![PROPERTIES] = [status]; + const { controller } = await bound(store); + + // Turn the rows back into 0.1.x rows, as 0.1.3 wrote them. + for (const [subject, p] of store.resources) { + if (p[PARENT] !== TABLE) continue; + const done = (p[TASK_STATUS] as string[])[0] === TASK_TAGS.Doing; + const { [TASK_STATUS]: _s, [TASK_BODY]: body, ...rest } = p; + store.resources.set(subject, { + ...rest, + [IS_A]: [ROW_CLASS], + [status]: [done ? tags.doing : tags.todo], + [DESCRIPTION]: body, + }); + } + + store.resources.get(TABLE)![CLASSTYPE] = ROW_CLASS; + // 0.1.x never set the marker. + const syncState = property(store, 'github-sync-state'); + + for (const p of store.resources.values()) + if (typeof p[syncState] === 'string') { + const { migrated: _m, ...old } = JSON.parse(p[syncState] as string); + p[syncState] = JSON.stringify(old); + } + + const first = rowByNumber(ready(controller.state()), 1).subject; + // An edit made under 0.1.x, not sent yet. + store.edit(first, { [NAME]: 'Edited before the update' }); + + const updated = createController(store); + await updated.load(); + const state = ready(await updated.sync()); + expect(state.problem).toBeUndefined(); + expect(store.resources.get(first)).toMatchObject({ + [IS_A]: [ISSUE_V1], + [TASK_STATUS]: [TASK_TAGS.Todo], + [TASK_BODY]: + 'Refreshing the page resets the selection to **All calendars**.', + }); + expect(store.resources.get(first)![status]).toBeUndefined(); + expect(store.resources.get(first)![DESCRIPTION]).toBeUndefined(); + expect(state.last!.result.held.map(describeHeld)).toEqual([ + 'Update #1: title “Keep the selected calendar after refresh” → “Edited before the update”', + ]); + }); + + it('only shows a notice on an Issue table it did not make', 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(store.writes).toEqual([]); + }); + }, +); diff --git a/integrations/issue-tracker/app/controller.ts b/integrations/issue-tracker/app/controller.ts index 6ce32f5f2..44b9482ab 100644 --- a/integrations/issue-tracker/app/controller.ts +++ b/integrations/issue-tracker/app/controller.ts @@ -29,8 +29,11 @@ import { MESSAGE, NAME, PARENT, + STATUSES, boundRepository, + migrateRows, provision, + showsOwnTable, type Tracker, } from './tracker.js'; import { listRepositories, PLATFORM, type Repository } from './transport.js'; @@ -87,6 +90,12 @@ export type RepositoryListing = export type ViewState = | { kind: 'loading' } | { 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). + */ + | { kind: 'other-table' } | { kind: 'not-connected' } | { kind: 'connecting' } | { @@ -155,8 +164,16 @@ export interface Controller { edit(subject: string, patch: Partial): Promise; /** Adds a comment Message about the row, then syncs (held for review). */ comment(subject: string, body: string): Promise; - /** Adds a row to the table; resolves with its subject once written. */ + /** + * Adds a row to the table and asks to publish it, so the next pass holds + * its create for review; resolves with its subject once written. + */ create(input: IssueInput): Promise<{ state: ViewState; subject?: string }>; + /** + * "Publish to GitHub" for a local-only row (#177 Q6): the next pass holds + * its create for review, like any write. Nothing is sent before that. + */ + publish(subject: string): Promise; /** * For an issue GitHub no longer has (the paused `missing` problem): keep * it in the table only, or remove it from the board. Neither sends @@ -195,7 +212,7 @@ const PAUSED: [RegExp, PausedReason][] = [ [/^Recovered Atomic create was edited/, 'other'], [/^Conflict during saved operation/, 'other'], [/^Concurrent edit after write/, 'other'], - [/^Choose exactly one Todo\/Doing\/Done status/, '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'], @@ -247,7 +264,7 @@ interface Session { const PROGRESS_MS = 250; const statusOf = (value: unknown): Status | undefined => - value === 'Todo' || value === 'Doing' || value === 'Done' ? value : undefined; + STATUSES.includes(value as Status) ? (value as Status) : undefined; export function createController( store: PluginStore, @@ -300,6 +317,31 @@ export function createController( }; prefs = { ...state.state.view }; + // A table made by 0.1.x: its rows become issue-v1 rows in place, once, + // through the same frame store the passes use (#177 §5). The sync + // state is kept, so edits not yet sent are still found. + if (provisioned.legacy && state.state.migrated !== 'issue-v1') { + const frame = tableStore(session); + const { table, app } = provisioned.tracker; + await migrateRows( + { + list: async () => + ( + await frame.queryLocalDb({ + drive: app, + property: PARENT, + value: table, + }) + ).subjects, + get: subject => frame.getResource(subject), + }, + table, + provisioned.legacy, + ); + state.state.migrated = 'issue-v1'; + await state.flush(); + } + return session; }; @@ -529,6 +571,7 @@ export function createController( state: () => current, async load() { + if (!(await showsOwnTable(store))) return set({ kind: 'other-table' }); const proxy = store.proxy; if (!proxy || typeof proxy.connections !== 'function') return set({ kind: 'no-proxy' }); @@ -721,7 +764,8 @@ export function createController( const ok = await write(ready, async s => { const row = await tableStore(s).getResource(subject); if (patch.title !== undefined) row.set(NAME, patch.title); - if (patch.body !== undefined) row.set(DESCRIPTION, patch.body); + if (patch.body !== undefined) + row.set(s.tracker.properties.body, patch.body); const status = statusOf(patch.status); if (status) row.set(s.tracker.properties.status, [s.tracker.tags[status]]); @@ -762,11 +806,16 @@ export function createController( isA: [s.tracker.rowClass], propVals: { [NAME]: input.title, - [DESCRIPTION]: input.body, + [s.tracker.properties.body]: input.body, [s.tracker.properties.status]: [s.tracker.tags[input.status]], }, }); subject = row.subject; + // Made with this app's New issue form: meant for GitHub, so it is + // proposed at once (still held for review). A row made anywhere + // else stays local until "Publish to GitHub". + s.state.state.publish = [...(s.state.state.publish ?? []), subject]; + await s.state.flush(); }); if (!ok) return { state: current }; optimistic(subject, row => ({ ...row, ...input })); @@ -774,6 +823,19 @@ export function createController( return { state: await this.sync(), subject }; }, + async publish(subject) { + if (current.kind !== 'ready') return current; + const ready = current; + const ok = await write(ready, async s => { + const list = s.state.state.publish ?? []; + if (list.includes(subject)) return; + s.state.state.publish = [...list, subject]; + await s.state.flush(); + }); + + return ok ? this.sync() : current; + }, + keepHereOnly() { const gone = missingIssue(); if (!gone) return Promise.resolve(current); @@ -868,6 +930,8 @@ export function describe(state: ViewState): string { return 'Loading…'; 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.'; case 'not-connected': return 'Not connected. Connect a GitHub account to sync one repository’s issues and comments with this table.'; case 'connecting': @@ -936,6 +1000,12 @@ function describeChange(held: Held): string { if (held.remoteId === undefined) return `Create issue “${held.after.title}” (${held.after.status})`; + const label = (status?: Status) => + status === 'Doing' + ? 'atomic:doing' + : status === 'Blocked' + ? 'atomic:blocked' + : undefined; const changes: string[] = []; const before = held.before; if (before?.title !== held.after.title) @@ -943,14 +1013,18 @@ function describeChange(held: Held): string { if (before?.body !== held.after.body) changes.push('description'); if (before?.status !== held.after.status) { + const add = label(held.after.status); + const drop = label(before?.status); const verb = held.after.status === 'Done' ? 'close it' : before?.status === 'Done' - ? 'reopen it' - : held.after.status === 'Doing' - ? 'add the atomic:doing label' - : 'remove the atomic:doing label'; + ? `reopen it${add ? ` with the ${add} label` : ''}` + : add && drop + ? `${drop} label → ${add}` + : add + ? `add the ${add} label` + : `remove the ${drop ?? 'atomic:doing'} label`; changes.push( `status ${before?.status ?? '?'} → ${held.after.status} (${verb})`, ); diff --git a/integrations/issue-tracker/app/fakeStore.ts b/integrations/issue-tracker/app/fakeStore.ts index 05cce8d74..d56647db4 100644 --- a/integrations/issue-tracker/app/fakeStore.ts +++ b/integrations/issue-tracker/app/fakeStore.ts @@ -20,12 +20,25 @@ import type { PluginResource, PluginStore, } from './store.js'; -import { IS_A, NAME, PARENT, PROPERTIES, RECOMMENDS } from './tracker.js'; +import { + CLASSTYPE, + DEFAULT_ONTOLOGY, + IS_A, + NAME, + PARENT, + PROPERTIES, + RECOMMENDS, + SHORTNAME, +} from './tracker.js'; export const APP = 'did:ad:app'; export const ONTOLOGY = 'did:ad:ontology'; export const ROW_CLASS = 'did:ad:class-item'; export const TABLE = 'did:ad:table-items'; +/** The drive's plugin vocabulary, as `pluginSchema()` mints it per drive. */ +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'; export interface FakeStore extends PluginStore { readonly resources: Map>; @@ -60,7 +73,10 @@ export function fakeStore({ existing = false, relay = true, hostApis = true, + table = TABLE, }: { + /** The table the app is shown on; another one is a view on someone's table. */ + table?: string; connected?: boolean; /** * The person has a GitHub connection this app is not delegated yet: @@ -72,11 +88,23 @@ export function fakeStore({ /** The host calls of atomic-server pin 007869464 (getMany, openExternal, …). */ hostApis?: boolean; } = {}): FakeStore { + // As `createApp` lays it out at the pin. const resources = new Map>([ - [APP, { [NAME]: 'New app' }], + [ + APP, + { + [NAME]: 'New app', + [IS_A]: [APP_CLASS], + [DEFAULT_ONTOLOGY]: ONTOLOGY, + [RENDERS]: [ROW_CLASS], + }, + ], + [APP_CLASS, { [SHORTNAME]: 'app', [RECOMMENDS]: [RENDERS, ROW_EXTRAS] }], + [RENDERS, { [SHORTNAME]: 'renders' }], + [ROW_EXTRAS, { [SHORTNAME]: 'row-extras' }], [ONTOLOGY, { [PARENT]: APP, [PROPERTIES]: [] }], [ROW_CLASS, { [PARENT]: ONTOLOGY, [NAME]: 'Item', [RECOMMENDS]: [NAME] }], - [TABLE, { [PARENT]: APP, [NAME]: 'Items' }], + [TABLE, { [PARENT]: APP, [NAME]: 'Items', [CLASSTYPE]: ROW_CLASS }], ]); /** What a lagging read still returns, and for how many more reads. */ const stale = new Map< @@ -242,7 +270,14 @@ export function fakeStore({ if (lag) lag.props = { ...lag.props, ...structuredClone(props) }; }, getApp: async () => APP, - getData: async () => ({ table: TABLE, rowClass: ROW_CLASS }), + getData: async () => { + const classtype = resources.get(table)?.[CLASSTYPE]; + + return { + table, + ...(typeof classtype === 'string' ? { rowClass: classtype } : {}), + }; + }, async getResource(subject) { count('getResource'); const lag = stale.get(subject); diff --git a/integrations/issue-tracker/app/frameStore.ts b/integrations/issue-tracker/app/frameStore.ts index af0f14b21..5bdc5945f 100644 --- a/integrations/issue-tracker/app/frameStore.ts +++ b/integrations/issue-tracker/app/frameStore.ts @@ -46,6 +46,8 @@ export interface FrameResource { readonly error: undefined; get(property: string): JSONValue; set(property: string, value: JSONValue): FrameResource; + /** Removes `property` on the next `save`, as `set` changes one. */ + remove(property: string): FrameResource; save(): Promise; getLoroDoc(): void; } @@ -141,9 +143,10 @@ export function frameStore( for (const [property, { stale, after }] of saved) { const now = resource.get(property); - if (!same(now, after) && stale.some(value => same(value, now))) - resource.set(property, after); - else saved.delete(property); + if (!same(now, after) && stale.some(value => same(value, now))) { + if (after === undefined) resource.remove(property); + else resource.set(property, after); + } else saved.delete(property); } if (!saved.size) overlay.delete(subject); @@ -164,6 +167,14 @@ export function frameStore( return resource; }, + remove(property) { + const pending = unsent.get(resource) ?? new Map(); + if (!pending.has(property)) pending.set(property, inner.get(property)); + unsent.set(resource, pending); + inner.remove(property); + + return resource; + }, async save() { // A just-created resource was already written by `create`; saving // it again unchanged would be a second, empty commit. diff --git a/integrations/issue-tracker/app/main.ts b/integrations/issue-tracker/app/main.ts index 92476234c..4a1be11b0 100644 --- a/integrations/issue-tracker/app/main.ts +++ b/integrations/issue-tracker/app/main.ts @@ -286,7 +286,13 @@ export async function view({ root, store }: ViewArgs): Promise { move(subject, status, via) { const state = readyState(); const row = rowOf(subject); - if (!state || !row || row.status === status || !canMove(state)) return; + if ( + !state || + !row || + (row.status === status && !row.statusAsIs) || + !canMove(state) + ) + return; live.say(`Moved ${refOf(row)} to ${status}`); if (via === 'key') ui.focus = subject; void controller.edit(subject, { status }); @@ -430,6 +436,11 @@ export async function view({ root, store }: ViewArgs): Promise { sendAgain(subject) { void controller.sendAgain(subject); }, + + publish(subject) { + live.say('Publishing to GitHub after your review'); + void controller.publish(subject); + }, }; // ---------------------------------------------------------- keyboard diff --git a/integrations/issue-tracker/app/model.test.ts b/integrations/issue-tracker/app/model.test.ts index c7eb396be..8c772d3bf 100644 --- a/integrations/issue-tracker/app/model.test.ts +++ b/integrations/issue-tracker/app/model.test.ts @@ -69,7 +69,7 @@ describe('board columns', () => { ])( 'collapses Done at %i issues to %i shown and %i more', (n, shown, more) => { - const col = columns(done(n), { search: '' })[2]; + const col = columns(done(n), { search: '' })[3]; expect(col).toMatchObject({ status: 'Done', total: n, hidden: more }); expect(col.rows).toHaveLength(shown); expect(DONE_LIMIT).toBe(20); @@ -77,7 +77,7 @@ describe('board columns', () => { ); it('shows every Done issue when expanded, most recent first', () => { - const col = columns(done(25), { search: '' }, true)[2]; + const col = columns(done(25), { search: '' }, true)[3]; expect(col.rows).toHaveLength(25); expect(col.rows[0].updatedAt! >= col.rows[1].updatedAt!).toBe(true); }); diff --git a/integrations/issue-tracker/app/model.ts b/integrations/issue-tracker/app/model.ts index 4353d4b96..ab03414ae 100644 --- a/integrations/issue-tracker/app/model.ts +++ b/integrations/issue-tracker/app/model.ts @@ -11,7 +11,7 @@ import type { IconName } from './ui/dom.js'; import type { PillState, Tone } from './ui/kit.js'; import type { Size } from './ui/theme.js'; -export const STATUSES: Status[] = ['Todo', 'Doing', 'Done']; +export const STATUSES: Status[] = ['Todo', 'Doing', 'Blocked', 'Done']; /** Done shows this many most recently updated issues, then "Show N more". */ export const DONE_LIMIT = 20; @@ -56,6 +56,7 @@ export function pillFor(state: ViewState, now: number): Pill | undefined { case 'loading': return { state: 'idle', text: 'Loading…' }; case 'no-proxy': + case 'other-table': return undefined; case 'not-connected': return { state: 'idle', text: 'Not connected' }; @@ -474,7 +475,7 @@ const byRecent = (a: IssueRow, b: IssueRow) => (b.updatedAt ?? '￿').localeCompare(a.updatedAt ?? '￿'); /** - * Three columns. Todo and Doing in issue order (new, unsent ones first); + * Four columns. Todo, Doing and Blocked in issue order (new, unsent ones first); * Done by most recent update, collapsed to `DONE_LIMIT` unless `allDone`. */ export function columns( @@ -532,7 +533,8 @@ export function canMove(state: ViewState): boolean { export const STATUS_KEYS: Record = { '1': 'Todo', '2': 'Doing', - '3': 'Done', + '3': 'Blocked', + '4': 'Done', }; /** The `?` overlay, from DESIGN.md → Interactions. */ @@ -540,7 +542,7 @@ export const SHORTCUTS: [string, string][] = [ ['J / K or arrows', 'Move focus between issues'], ['Enter', 'Open the focused issue'], ['Esc', 'Close the panel'], - ['1 / 2 / 3', 'Set status to Todo / Doing / Done'], + ['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'], diff --git a/integrations/issue-tracker/app/package.json b/integrations/issue-tracker/app/package.json index 68fb02b78..295806367 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.1.3", + "version": "0.2.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/state.ts b/integrations/issue-tracker/app/state.ts index 8fe013bac..44fac45f1 100644 --- a/integrations/issue-tracker/app/state.ts +++ b/integrations/issue-tracker/app/state.ts @@ -42,6 +42,13 @@ export interface PersistedState { stale: string[]; /** Board/List choice and filters (IT-14). Kept here, not in frame storage, which a null-origin frame lacks. */ view?: ViewPrefs; + /** + * Local-only rows a person chose "Publish to GitHub" for, until the next + * pass has them in the Bridge (held for review, then sent). + */ + publish?: string[]; + /** Set once a 0.1.x table's rows were rewritten as `issue-v1` (`migrateRows`). */ + migrated?: 'issue-v1'; } const empty = (): PersistedState => ({ diff --git a/integrations/issue-tracker/app/styles.css b/integrations/issue-tracker/app/styles.css index 6c11c05d3..5bd57dc14 100644 --- a/integrations/issue-tracker/app/styles.css +++ b/integrations/issue-tracker/app/styles.css @@ -24,7 +24,7 @@ } .board { display: grid; - grid-template-columns: repeat(3, minmax(240px, 1fr)); + grid-template-columns: repeat(4, minmax(220px, 1fr)); gap: 12px; padding: 8px 16px 20px; overflow-x: auto; diff --git a/integrations/issue-tracker/app/sync.test.ts b/integrations/issue-tracker/app/sync.test.ts index 55e31761d..34d8508df 100644 --- a/integrations/issue-tracker/app/sync.test.ts +++ b/integrations/issue-tracker/app/sync.test.ts @@ -15,11 +15,15 @@ import { ABOUT, DESCRIPTION, IS_A, + ISSUE_V1, MESSAGE, NAME, PARENT, PROPERTIES, SHORTNAME, + TASK_BODY, + TASK_STATUS, + TASK_TAGS, } from './tracker.js'; import { relayDispatch } from './transport.js'; @@ -82,35 +86,52 @@ group('GitHub issues drive app', () => { /2 issues and 1 comment in sync with atomic-fixture\/tracker/, ); - const status = property(store, 'issue-status'); const number = property(store, 'github-issue-number'); - const tags = Object.fromEntries( - [...store.resources.entries()] - .filter(([, p]) => p[PARENT] === status) - .map(([subject, p]) => [p[SHORTNAME], subject]), - ); const imported = rows(store) .map(([, p]) => ({ + isA: p[IS_A], title: p[NAME], - body: p[DESCRIPTION], + body: p[TASK_BODY], number: p[number], - status: p[status], + status: p[TASK_STATUS], })) .sort((a, b) => Number(a.number) - Number(b.number)); expect(imported).toEqual([ { + isA: [ISSUE_V1], title: 'Keep the selected calendar after refresh', body: 'Refreshing the page resets the selection to **All calendars**.', number: 1, - status: [tags.todo], + status: [TASK_TAGS.Todo], }, { + isA: [ISSUE_V1], title: 'Export the board as CSV', body: '', number: 2, - status: [tags.doing], + status: [TASK_TAGS.Doing], }, ]); + // The baseline is on each row, not in the sync state (#177 decision 7). + const baseline = property(store, 'github-sync-baseline'); + for (const [, p] of rows(store)) + expect(JSON.parse(String(p[baseline]))).toEqual({ + title: p[NAME], + body: p[TASK_BODY], + status: p[number] === 1 ? 'Todo' : 'Doing', + }); + const syncState = JSON.parse( + String( + [...store.resources.values()].find( + p => p[property(store, 'github-sync-state')], + )![property(store, 'github-sync-state')], + ), + ); + expect( + Object.values( + syncState.snapshot.records as Record, + ).filter(r => r.baseline !== undefined), + ).toEqual([]); const [issue] = rows(store).find(([, p]) => p[number] === 1)!; const messages = [...store.resources.values()].filter(p => @@ -171,13 +192,9 @@ group('GitHub issues drive app', () => { it('holds a local change for review and sends exactly that once approved', async () => { const { store, controller } = await bound(); - const status = property(store, 'issue-status'); const number = property(store, 'github-issue-number'); - const done = [...store.resources.entries()].find( - ([, p]) => p[PARENT] === status && p[SHORTNAME] === 'done', - )![0]; const [issue] = rows(store).find(([, p]) => p[number] === 1)!; - store.edit(issue, { [status]: [done] }); + store.edit(issue, { [TASK_STATUS]: [TASK_TAGS.Done] }); const held = ready(await controller.sync()); expect(held.last?.result.held).toHaveLength(1); @@ -224,7 +241,7 @@ group('GitHub issues drive app', () => { }); const imported = ready(await controller.sync()); expect(imported.problem).toBeUndefined(); - expect(store.resources.get(issue)?.[DESCRIPTION]).toBe('Edited on GitHub'); + expect(store.resources.get(issue)?.[TASK_BODY]).toBe('Edited on GitHub'); const last = ready(await controller.sync()); expect(last.problem).toBeUndefined(); expect(last.last?.result).toMatchObject({ @@ -346,16 +363,21 @@ group('GitHub issues drive app', () => { /** A new row's create, approved and sent, whose answer is lost. */ async function lostCreate(lands: boolean) { const { store, controller } = await bound(); - const status = property(store, 'issue-status'); - const doing = [...store.resources.entries()].find( - ([, p]) => p[PARENT] === status && p[SHORTNAME] === 'doing', - )![0]; const { subject } = await store.newResource({ parent: TABLE, - isA: ['did:ad:class-item'], - propVals: { [NAME]: 'Written here first', [status]: [doing] }, + isA: [ISSUE_V1], + propVals: { + [NAME]: 'Written here first', + [TASK_STATUS]: [TASK_TAGS.Doing], + }, }); - const proposed = ready(await controller.sync()); + // Local only until a person publishes it (#177 Q6). + const quiet = ready(await controller.sync()); + expect(quiet.last?.result.held).toEqual([]); + expect( + quiet.last?.result.rows.find(r => r.subject === subject), + ).toMatchObject({ localOnly: true, title: 'Written here first' }); + const proposed = ready(await controller.publish(subject)); expect(proposed.last?.result.held.map(describeHeld)).toEqual([ 'Create issue “Written here first” (Doing)', ]); @@ -598,3 +620,30 @@ group('frame store adapter', () => { expect(listed.length).toBe(5); }); }); + +group('baselines on the rows (#177 decision 7)', () => { + it('writes a missing row baseline back once both sides agree, and nothing on an unchanged pass', async () => { + const { store } = await bound(); + const baseline = property(store, 'github-sync-baseline'); + + for (const [subject] of rows(store)) { + const { [baseline]: _gone, ...rest } = store.resources.get(subject)!; + store.resources.set(subject, rest); + } + + const reopened = createController(store); + const healed = ready(await reopened.start()); + expect(healed.problem).toBeUndefined(); + expect(healed.last?.result.held).toEqual([]); + for (const [, p] of rows(store)) + expect(JSON.parse(String(p[baseline]))).toMatchObject({ title: p[NAME] }); + + const writes = store.writes.length; + const again = ready(await reopened.sync()); + expect(again.last?.result).toMatchObject({ addedHere: 0, updatedHere: 0 }); + const rowSubjects = rows(store).map(([s]) => s); + expect( + store.writes.slice(writes).filter(w => rowSubjects.includes(w.subject)), + ).toEqual([]); + }); +}); diff --git a/integrations/issue-tracker/app/sync.ts b/integrations/issue-tracker/app/sync.ts index ec52a00f8..f78567f19 100644 --- a/integrations/issue-tracker/app/sync.ts +++ b/integrations/issue-tracker/app/sync.ts @@ -9,6 +9,18 @@ * included (see devonian/github-issues/review.mjs). Everything the pass * would send is returned as `held`. Writes into the app's own table (the * import) are not gated, as for pets and notion. + * + * Since 0.2.0 (#177 item 6): + * - Rows are `issue-v1`; their shared fields are read by subject through + * `ontology-kit`'s resolver. A status that is not exactly one of the four + * task/v1 tags is shown as it is and not synced, instead of failing the + * pass. + * - A row with no GitHub issue behind it is local only: the pass leaves it + * alone until a person chooses "Publish to GitHub" (#177 Q6, this + * plugin's choice). Then its create is held for review like any write. + * - The Bridge's per-record baseline lives on the row (and on a comment's + * Message) as `github-sync-baseline`, not in the sync state (#177 + * decision 7). See `bridgeFor`. */ import { AtomicIdentityMap, @@ -17,6 +29,8 @@ import { AtomicStore, } from 'devonian/atomic'; import { Datatype } from '@tomic/lib'; +import { createResolver } from '../../../ontology-kit/resolver.mjs'; +import { classes } from '../../../ontology-kit/terms.mjs'; // Plain JS modules of the lens; see devonian/github-issues/README.md. import { Bridge } from '../devonian/github-issues/bridge.mjs'; import { @@ -26,18 +40,27 @@ import { } from '../devonian/github-issues/ports.mjs'; import { proxyTransport } from '../devonian/github-issues/proxy.mjs'; import { reviewGate } from '../devonian/github-issues/review.mjs'; +import { assertSaved } from '../devonian/github-issues/target.mjs'; import { frameStore, type FrameAtomicStore, + type FrameResource, type Overlay, } from './frameStore.js'; import type { SyncState } from './state.js'; -import type { HostProxy, PluginStore } from './store.js'; +import type { HostProxy, JSONValue, PluginStore } from './store.js'; import { ABOUT, DESCRIPTION, + IS_A, LOCAL_ID, + NAME, PARENT, + SHORTNAME, + STATUSES, + TASK_BODY, + TASK_STATUS, + TASK_TAGS, type Tracker, } from './tracker.js'; import { relayDispatch, type Dispatch } from './transport.js'; @@ -45,7 +68,7 @@ import { relayDispatch, type Dispatch } from './transport.js'; /** Stable, so saved snapshots keep binding (`Bridge` checks `binding.base`). */ export const BRIDGE_BASE = 'https://github-issues-app.invalid/bridge'; -export type Status = 'Todo' | 'Doing' | 'Done'; +export type Status = 'Todo' | 'Doing' | 'Blocked' | 'Done'; export interface Held { subject: string; @@ -92,6 +115,17 @@ export interface IssueRow { author?: string; /** Comments in this table (GitHub's plus any waiting to be sent), oldest first. */ comments: CommentRow[]; + /** + * Not on GitHub and not asked to be: only "Publish to GitHub" sends it + * (#177 Q6). + */ + localOnly?: boolean; + /** + * The row's own status when it is not exactly one task/v1 tag (another + * tag, or several), by name. It is shown as it is and not synced; `status` + * is then the last one GitHub agreed with. + */ + statusAsIs?: string[]; } /** One field of a conflict: last synced value and both sides' current ones. */ @@ -161,18 +195,90 @@ export interface PassError extends Error { missing?: { side: 'local' | 'remote'; subject: string; entity?: string }; } +/** Reads `issue-v1` rows by property subject, strictly (#177 decision 1). */ +const ISSUE_V1 = classes['issue-v1']; +const resolver = createResolver({ classes: [ISSUE_V1] }); +const ISSUE_FIELDS = [...ISSUE_V1.requires, ...ISSUE_V1.recommends]; +const STATUS_BY_TAG = new Map( + STATUSES.map(status => [TASK_TAGS[status], status]), +); + +const sortKeys = (value: unknown): unknown => + Array.isArray(value) + ? value.map(sortKeys) + : value && typeof value === 'object' + ? Object.fromEntries( + Object.keys(value) + .sort() + .map(key => [ + key, + sortKeys((value as Record)[key]), + ]), + ) + : value; + +/** JSON text that is the same whatever the key order: compares baselines. */ +export const stableJson = (value: unknown): string => + JSON.stringify(sortKeys(value)); + +const isStatus = (value: unknown): value is Status => + STATUSES.includes(value as Status); + +interface PortConfig { + connection: { + drive: string; + table: string; + rowClass: string; + body: string; + status: string; + number: string; + tags: Record; + }; + provenance: string; + /** The row extra holding the baseline (#177 decision 7). */ + baseline: string; + commentsFolder: string; + /** Rows a person chose "Publish to GitHub" for, not yet in the Bridge. */ + publish: Set; +} + +/** A table row as the board shows it, local-only ones included. */ +interface ListedRow extends ImportedRow { + localOnly?: boolean; +} + /** - * `AtomicPort` over the frame store. Two app-specific narrowings: + * `AtomicPort` over the frame store. App-specific narrowings: * - Comments are the Messages in the app's own comments folder. A comment * made in the data-browser's comment panel on a row lives in the drive's * comments folder, outside the app's subtree, which the app cannot write * back to; it is left alone instead of failing every pass. - * - The GitHub source is stored as JSON text (a string property), so its - * key order, which the Bridge compares, survives the round trip. + * - The GitHub source and the baseline are stored as JSON text (string + * properties), so the source's key order, which the Bridge compares, + * survives the round trip. + * - Issue rows are `issue-v1`, read through the resolver. A status that is + * not exactly one of the four task/v1 tags (another tag, or several) does + * not fail the pass: the row reports the status of its baseline, so the + * Bridge sees no status change to send, and the stored tags are kept in + * `asIs` for the view. A write the Bridge makes leaves such a status + * alone unless GitHub changed the status. + * - Rows with no GitHub issue behind them are local only (`list` leaves + * them out) unless the Bridge already has them or a person asked to + * publish them. */ class FrameAtomicPort extends AtomicPort { declare store: FrameAtomicStore; - declare config: { commentsFolder: string; provenance: string }; + declare config: PortConfig; + declare connection: PortConfig['connection']; + /** Whether the Bridge already has a record for this local row; set by `bridgeFor`. */ + bound: (entity: string, id: string) => boolean = () => false; + /** Called with each row's stored baseline as it is read; set by `bridgeFor`. */ + onBaseline: (entity: string, id: string, baseline: unknown) => void = + () => {}; + /** Row -> `stableJson` of the baseline it holds, as last read or written. */ + readonly baselines = new Map(); + /** Rows whose status is shown as it is: their task/v1 status values. */ + readonly asIs = new Map(); async subjects(property: string, value: string): Promise { const subjects: string[] = await super.subjects(property, value); @@ -188,6 +294,154 @@ class FrameAtomicPort extends AtomicPort { return own; } + /** The row's stored baseline, or undefined when it has none or it is unreadable. */ + private storedBaseline(r: { subject: string; get(p: string): unknown }) { + const raw = r.get(this.config.baseline); + let baseline: unknown; + + try { + baseline = typeof raw === 'string' ? JSON.parse(raw) : undefined; + } catch { + baseline = undefined; + } + + this.baselines.set( + r.subject, + baseline === undefined ? undefined : stableJson(baseline), + ); + + return baseline; + } + + row(entity: string, r: FrameResource, context: object = {}) { + const baseline = this.storedBaseline(r); + + if (entity !== 'issue') { + const row = super.row(entity, r, context); + this.onBaseline(entity, r.subject, baseline); + + return row; + } + + const c = this.connection; + const isA = r.get(IS_A); + if ( + !Array.isArray(isA) || + !isA.includes(c.rowClass) || + r.get(PARENT) !== c.table + ) + throw new Error('Resource is not a row of this issue tracker'); + const { values } = resolver.read( + Object.fromEntries(ISSUE_FIELDS.map(p => [p, r.get(p)])), + c.rowClass, + ); + const tags = Array.isArray(values[TASK_STATUS]) + ? (values[TASK_STATUS] as unknown[]).filter( + (t): t is string => typeof t === 'string', + ) + : []; + let status = + tags.length === 0 + ? 'Todo' + : tags.length === 1 + ? STATUS_BY_TAG.get(tags[0]) + : undefined; + + if (status) this.asIs.delete(r.subject); + else { + this.asIs.set(r.subject, tags); + const agreed = (baseline as { status?: unknown } | undefined)?.status; + status = isStatus(agreed) ? agreed : 'Todo'; + } + + const title = values[NAME]; + const body = values[TASK_BODY] ?? ''; + if (typeof title !== 'string' || !title.trim() || typeof body !== 'string') + throw new Error('Invalid Atomic issue'); + const remoteId = r.get(c.number); + if ( + remoteId !== undefined && + (!Number.isSafeInteger(remoteId) || (remoteId as number) <= 0) + ) + throw new Error('Invalid GitHub issue number'); + let metadata = r.get(this.config.provenance); + if (typeof metadata === 'string') metadata = JSON.parse(metadata); + this.onBaseline(entity, r.subject, baseline); + + return { + id: r.subject, + remoteId, + value: { title, body, status }, + ...(metadata ? { metadata } : {}), + }; + } + + /** Whether an issue row is local only: no GitHub issue, not in the Bridge, not asked to publish. */ + private localOnly(id: string, r: FrameResource): boolean { + return ( + r.get(this.connection.number) === undefined && + !this.bound('issue', id) && + !this.config.publish.has(id) + ); + } + + /** Issue rows of this table's class, read; `all` keeps local-only ones too. */ + private async issueRows(all: boolean) { + const out: { id: string; r: FrameResource; localOnly: boolean }[] = []; + + for (const id of await this.subjects(PARENT, this.connection.table)) { + const r = (await this.resource(id)) as FrameResource; + const isA = r.get(IS_A); + if (!Array.isArray(isA) || !isA.includes(this.connection.rowClass)) + continue; + const localOnly = this.localOnly(id, r); + if (localOnly && !all) continue; + out.push({ id, r, localOnly }); + } + + return out; + } + + async list(entity: string, context: object = {}) { + if (entity !== 'issue') return super.list(entity, context); + + return (await this.issueRows(false)).map(({ r }) => + this.row(entity, r, context), + ); + } + + /** + * Every issue row of the table for the board, local-only ones included. + * Never fails on one row: a row the Bridge would refuse (no title) is + * shown with what it has. + */ + async listAll(): Promise { + const out: ListedRow[] = []; + + for (const { r, localOnly } of await this.issueRows(true)) { + let row: ImportedRow; + + try { + row = this.row('issue', r) as ImportedRow; + } catch { + const title = r.get(NAME); + const body = r.get(TASK_BODY); + row = { + id: r.subject, + value: { + title: typeof title === 'string' ? title : '', + body: typeof body === 'string' ? body : '', + status: 'Todo', + }, + }; + } + + out.push(localOnly ? { ...row, localOnly } : row); + } + + return out; + } + values( entity: string, value: unknown, @@ -199,9 +453,38 @@ class FrameAtomicPort extends AtomicPort { const provenance = this.config.provenance; if (all[provenance] !== undefined) all[provenance] = JSON.stringify(all[provenance]); + // The Bridge writes a row only with what both sides now agree on. + all[this.config.baseline] = JSON.stringify(value); return values; } + + async update( + entity: string, + id: string, + value: { status?: Status }, + _key: unknown, + metadata: unknown, + context: object, + ) { + const r = (await this.resource(id)) as FrameResource; + const current = this.row(entity, r, context) as ImportedRow; + // A status shown as it is stays, unless GitHub changed the status. + const keep = + entity === 'issue' && + this.asIs.has(id) && + current.value.status === value.status; + + for (const [p, v] of Object.entries( + this.values(entity, value, metadata, context), + )) { + if (keep && p === this.connection.status) continue; + r.set(p, v as JSONValue); + } + + assertSaved(this.store, this.connection.drive, r, await r.save()); + this.baselines.set(id, stableJson(value)); + } } const devonian = { @@ -289,13 +572,15 @@ function bridgeFor(options: PassOptions) { drive: tracker.app, table: tracker.table, rowClass: tracker.rowClass, - body: 'https://atomicdata.dev/properties/description', + body: tracker.properties.body, status: tracker.properties.status, number: tracker.properties.number, tags: tracker.tags, }, provenance: tracker.properties.provenance, + baseline: tracker.properties.baseline, commentsFolder: tracker.commentsFolder, + publish: new Set(state.state.publish ?? []), }); const transport = proxyTransport({ repository, @@ -365,6 +650,55 @@ function bridgeFor(options: PassOptions) { }); }; + /** + * Baselines on the rows (#177 decision 7). The Bridge keeps them in its + * records; at each checkpoint, a baseline that differs from what its row + * holds is written onto the row, and the sync state is saved without it. + * A row the Bridge itself writes gets its baseline in the same write + * (`FrameAtomicPort.values`), so an import costs no extra write. Reading a + * row puts its baseline back into the record (`onBaseline`). A record + * whose row was never read keeps the baseline the snapshot had: that is + * how a 0.1.x state, which kept them all in the snapshot, moves onto the + * rows at its first pass. + */ + // The Bridge's live records; read only after it is constructed below. + let records: Record = {}; + /** Per live Bridge record: the baseline object its row is known to hold. */ + const onRow = new WeakMap(); + + const saveSnapshot = async (snapshot: { + records?: Record; + }) => { + for (const [subject, record] of Object.entries(records)) { + if (record.baseline === undefined) continue; + + // The Bridge replaces a baseline object whenever it changes one, so an + // unchanged one is skipped without a lookup (`bridge.id` scans every + // identity) or comparing its text. + if (onRow.get(record) !== record.baseline) { + const id = bridge.id('local', record.entity, subject); + if (typeof id !== 'string') continue; + const json = stableJson(record.baseline); + + if (local.baselines.get(id) !== json) { + const row = await atomicStore.getResource(id); + row.set(tracker.properties.baseline, JSON.stringify(record.baseline)); + await row.save(); + // Bookkeeping, not a change to what the row says. + atomicStore.writes.saves--; + local.baselines.set(id, json); + } + + onRow.set(record, record.baseline); + } + + const saved = snapshot.records?.[subject]; + if (saved) delete saved.baseline; + } + + await state.saveSnapshot(snapshot); + }; + const bridge = new Bridge({ imported, devonian, @@ -372,9 +706,21 @@ function bridgeFor(options: PassOptions) { remote: reviewGate(counted(remote, sent), options.approved ?? new Set()), base: BRIDGE_BASE, snapshot: state.state.snapshot, - save: (snapshot: unknown) => state.saveSnapshot(snapshot), + save: saveSnapshot, uncertain, }); + records = bridge.records; + const subjectOf = (entity: string, id: string): string | undefined => + bridge.identities.lookup(bridge.scope('local', entity), id); + local.bound = (entity, id) => subjectOf(entity, id) !== undefined; + + local.onBaseline = (entity, id, baseline) => { + const subject = subjectOf(entity, id); + const record = subject ? records[subject] : undefined; + if (baseline === undefined || !record) return; + record.baseline = structuredClone(baseline); + onRow.set(record, record.baseline); + }; return { bridge, atomicStore, sent, local }; } @@ -467,10 +813,37 @@ async function tableRows( options: PassOptions, ): Promise { const comments = await commentsByIssue(atomicStore, options); + const names = new Map(); + + const nameOf = async (tag: string) => { + if (!names.has(tag)) { + const known = STATUSES.find(s => TASK_TAGS[s] === tag); + const resource = known + ? undefined + : await atomicStore.getResource(tag).catch(() => undefined); + const name = resource?.get(NAME) ?? resource?.get(SHORTNAME); + names.set( + tag, + known ?? + (typeof name === 'string' && name ? name : tag.split('/').pop()!), + ); + } - return ((await local.list('issue')) as ImportedRow[]).map(row => - issueRow(row, comments.get(row.id) ?? []), - ); + return names.get(tag)!; + }; + + const out: IssueRow[] = []; + + for (const row of await local.listAll()) { + const asIs = local.asIs.get(row.id); + out.push({ + ...issueRow(row, comments.get(row.id) ?? []), + ...(row.localOnly ? { localOnly: true } : {}), + ...(asIs ? { statusAsIs: await Promise.all(asIs.map(nameOf)) } : {}), + }); + } + + return out; } /** @@ -517,6 +890,10 @@ export async function runPass(options: PassOptions): Promise { throw error; } + // A row asked to be published is in the Bridge now (held or sent). + const publish = options.state.state.publish ?? []; + const left = publish.filter(id => !local.bound('issue', id)); + if (left.length !== publish.length) options.state.state.publish = left; await options.state.flush(); return summary(bridge, atomicStore, sent, local, options); diff --git a/integrations/issue-tracker/app/tracker.ts b/integrations/issue-tracker/app/tracker.ts index bb93c7d1c..8589d79b3 100644 --- a/integrations/issue-tracker/app/tracker.ts +++ b/integrations/issue-tracker/app/tracker.ts @@ -1,24 +1,36 @@ // @wc-ignore-file /** - * The app's own data in the user's drive, all inside the app's subtree (the - * only place a drive app may write): + * The app's own data in the user's drive. Since 0.2.0 its rows are of the + * shared class `issue-v1` (ontola/atomic-plugins#177 item 6), published on + * GitHub Pages, so any view of that class can read them and this app is + * offered on any table of it: * - * - Properties under the ontology that holds the table's row class, created - * once and found again by shortname, as pets/app does: Status (a select - * with Todo / Doing / Done tags, parented to the property the way the - * data-browser's own select columns are), GitHub issue number, GitHub - * source, and the two properties of the sync resource. The issue body uses - * Atomic's own `description`, so rows read as ordinary described rows. + * - Shared fields, by subject (`ontology-kit`, read through its strict + * resolver in sync.ts): Atomic's `name` as the title, and task/v1 + * `status` (the task/v1 tags todo, doing, blocked, done) and `body`. + * - Provider extras, the app's own properties under its own ontology, + * created once and found again by shortname: GitHub issue number, GitHub + * source (JSON) and the sync baseline (JSON, #177 decision 7: bookkeeping + * lives on the row). They are declared as the App's `row-extras` + * (atomic-server #1849), so a row grant on another table may cover them. * - One sync resource under the app (found by its `localId`): the bound - * repository and the sync state as JSON text. Its class is created under - * the same ontology. + * repository and the sync state as JSON text (snapshot without the + * per-record baselines, write journal, view preferences). * - One folder under the app for the GitHub comments (Messages `about` a * row), also found by `localId`. * + * 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 + * table's `classtype` to it, through the frame store, inside its own + * subtree (#177 spike S2). A catalog Install cannot do that yet (#177 H2). + * A table made by 0.1.x still holds rows of the app's own class with its + * own Status tags; `legacy` describes them for `migrateRows`. + * * Every lookup goes through a resource the host reads back (`getResource`) * or a `localId`, which AtomicServer keeps unique per parent, so running * this twice does not create anything twice. */ +import { classes as shared } from '../../../ontology-kit/terms.mjs'; import type { JSONValue, PluginResource, PluginStore } from './store.js'; const A = 'https://atomicdata.dev'; @@ -43,19 +55,30 @@ export const CLASS_CLASS = `${A}/classes/Class`; export const TAG = `${A}/classes/Tag`; export const FOLDER = `${A}/classes/Folder`; export const MESSAGE = `${A}/classes/Message`; +/** The drive's default ontology on an App (`createApp` sets it). */ +export const DEFAULT_ONTOLOGY = `${A}/ontology/server/property/default-ontology`; + +/** The shared class this app's rows are (#177 §2.3). */ +export const ISSUE_V1: string = shared['issue-v1'].subject; +const TASK = `${A}/task/v1`; + +/** task/v1 terms every AtomicServer embeds; `issue-v1` recommends them. */ +export const TASK_STATUS = `${TASK}/status`; +export const TASK_BODY = `${TASK}/body`; const datatypes = { string: `${A}/datatypes/string`, integer: `${A}/datatypes/integer`, - resourceArray: `${A}/datatypes/resourceArray`, }; -export const STATUSES = ['Todo', 'Doing', 'Done'] as const; +export const STATUSES = ['Todo', 'Doing', 'Blocked', 'Done'] as const; export type Status = (typeof STATUSES)[number]; -const TAG_COLOURS: Record = { - Todo: '#8a8a8a', - Doing: '#2f6fd6', - Done: '#2f8f5b', +/** The task/v1 tag of each status (GitHub: atomic:doing, atomic:blocked). */ +export const TASK_TAGS: Record = { + Todo: `${TASK}/todo`, + Doing: `${TASK}/doing`, + Blocked: `${TASK}/blocked`, + Done: `${TASK}/done`, }; export const SYNC_LOCAL_ID = 'github-issues:sync'; @@ -65,11 +88,14 @@ export const COMMENTS_LOCAL_ID = 'github-issues:comments'; export interface Tracker { app: string; table: string; + /** Always `ISSUE_V1`. */ rowClass: string; properties: { status: string; + body: string; number: string; provenance: string; + baseline: string; repository: string; syncState: string; }; @@ -77,25 +103,23 @@ export interface Tracker { commentsFolder: string; } +/** A 0.1.x table's own Status column and its tags, by tag shortname. */ +export interface Legacy { + status: string; + tags: Record; +} + +type OwnProperty = Exclude; + interface PropertySpec { - key: keyof Tracker['properties']; + key: OwnProperty; shortname: string; name: string; datatype: string; description: string; - select?: boolean; } const PROPERTY_SPECS: PropertySpec[] = [ - { - key: 'status', - shortname: 'issue-status', - name: 'Status', - datatype: datatypes.resourceArray, - description: - 'Todo, Doing or Done. Done is a closed GitHub issue; Doing is an open one with the atomic:doing label.', - select: true, - }, { key: 'number', shortname: 'github-issue-number', @@ -111,6 +135,14 @@ const PROPERTY_SPECS: PropertySpec[] = [ 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: datatypes.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', @@ -128,6 +160,9 @@ const PROPERTY_SPECS: PropertySpec[] = [ }, ]; +/** The provider extras kept on rows, declared as the App's `row-extras`. */ +const ROW_EXTRAS: OwnProperty[] = ['number', 'provenance', 'baseline']; + const asList = (value: JSONValue): string[] => Array.isArray(value) ? value.filter((v): v is string => typeof v === 'string') @@ -153,7 +188,7 @@ export async function findByLocalId( async function ensureProperties( store: PluginStore, ontology: PluginResource, -): Promise> { +): Promise> { const listed = asList(ontology.get(PROPERTIES)); const byShortname = new Map(); @@ -164,7 +199,7 @@ async function ensureProperties( } const created: string[] = []; - const out = {} as Record; + const out = {} as Record; for (const spec of PROPERTY_SPECS) { let subject = byShortname.get(spec.shortname); @@ -172,13 +207,12 @@ async function ensureProperties( if (!subject) { const property = await store.newResource({ parent: ontology.subject, - isA: spec.select ? [PROPERTY_CLASS, SELECT_PROPERTY] : [PROPERTY_CLASS], + isA: [PROPERTY_CLASS], propVals: { [SHORTNAME]: spec.shortname, [NAME]: spec.name, [DESCRIPTION]: spec.description, [DATATYPE]: spec.datatype, - ...(spec.select ? { [CLASSTYPE]: TAG, [ALLOWS_ONLY]: [] } : {}), }, }); subject = property.subject; @@ -194,44 +228,186 @@ async function ensureProperties( return out; } -async function ensureTags( +/** The 0.1.x Status column and its tags, when this app's ontology has it. */ +async function legacyStatus( store: PluginStore, - statusProperty: string, -): Promise> { - const property = await store.getResource(statusProperty); - const allowed = asList(property.get(ALLOWS_ONLY)); - const byShortname = new Map(); + ontology: PluginResource, +): Promise { + for (const subject of asList(ontology.get(PROPERTIES))) { + const property = await store.getResource(subject); + if (property.get(SHORTNAME) !== 'issue-status') continue; + const tags: Record = {}; - for (const subject of allowed) { - const tag = await store.getResource(subject); - const shortname = tag.get(SHORTNAME); - if (typeof shortname === 'string') byShortname.set(shortname, subject); + for (const tag of asList(property.get(ALLOWS_ONLY))) { + const shortname = (await store.getResource(tag)).get(SHORTNAME); + if (typeof shortname === 'string') tags[shortname] = tag; + } + + return { status: subject, tags }; } - const tags = {} as Record; - const created: string[] = []; + return undefined; +} + +/** + * The app's own ontology: the App's default ontology, as `createApp` sets + * it. A 0.1.x app found it as its row class's parent, which is no longer + * the app's once the table is `issue-v1`. + */ +async function appOntology( + store: PluginStore, + app: string, + rowClass: string | undefined, +): Promise { + const own = (await store.getResource(app)).get(DEFAULT_ONTOLOGY); + if (typeof own === 'string') return store.getResource(own); + + if (rowClass && rowClass !== ISSUE_V1) { + const parent = (await store.getResource(rowClass)).get(PARENT); + if (typeof parent === 'string') return store.getResource(parent); + } - for (const status of STATUSES) { - const shortname = status.toLowerCase(); - let subject = byShortname.get(shortname); + throw new Error('This app has no ontology of its own to add fields to.'); +} - if (!subject) { - const tag = await store.newResource({ - parent: statusProperty, - isA: [TAG], - propVals: { [SHORTNAME]: shortname, [COLOR]: TAG_COLOURS[status] }, - }); - subject = tag.subject; - created.push(subject); +/** + * An App property of the drive's plugin vocabulary (`renders`, + * `row-extras`), found by shortname among what the App's class recommends; + * their subjects are minted per drive. + */ +async function appProperty( + store: PluginStore, + app: PluginResource, + shortname: string, +): Promise { + for (const klass of asList(app.get(IS_A))) { + const resource = await store.getResource(klass).catch(() => undefined); + + for (const subject of asList(resource?.get(RECOMMENDS) ?? [])) { + const term = await store.getResource(subject).catch(() => undefined); + if (term?.get(SHORTNAME) === shortname) return subject; } + } + + return undefined; +} + +/** Adds `wanted` to the list `property` holds on `resource`; true if changed. */ +function include( + resource: PluginResource, + property: string | undefined, + wanted: string[], +): boolean { + if (!property) return false; + const list = asList(resource.get(property) ?? []); + const missing = wanted.filter(s => !list.includes(s)); + if (!missing.length) return false; + resource.set(property, [...list, ...missing]); + + return true; +} - tags[status] = subject; +/** 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'; } +} - if (created.length > 0) - await property.set(ALLOWS_ONLY, [...allowed, ...created]).save(); +/** + * 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. + */ +async function adopt( + store: PluginStore, + app: string, + table: string, + extras: string[], +): Promise { + const resource = await store.getResource(app); + const renders = include( + resource, + await appProperty(store, resource, 'renders'), + [ISSUE_V1], + ); + const declared = include( + resource, + await appProperty(store, resource, 'row-extras'), + extras, + ); + 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(); +} + +/** Whether the table shown is the app's own, not one it was added to as a view. */ +export async function showsOwnTable(store: PluginStore): Promise { + const data = await store.getData(); + if (!data?.table) return true; + + return ( + (await store.getResource(data.table)).get(PARENT) === (await store.getApp()) + ); +} + +/** + * Rewrites a 0.1.x table's rows in place as `issue-v1` rows (#177 §5): the + * app's own Status tag becomes the task/v1 tag with the same shortname, + * Atomic's `description` becomes task/v1 `body`, and `isA` becomes + * `issue-v1`. Everything else on the row (title, number, GitHub source) + * stays, and so does the sync state, so edits not yet sent are still found + * by the next pass. Rows already `issue-v1` are left alone. Returns how + * many rows it rewrote. + */ +/** A row as `migrateRows` reads and writes it (the frame store's resources). */ +export interface MigratedRow { + get(property: string): JSONValue; + set(property: string, value: JSONValue): unknown; + remove(property: string): unknown; + save(): Promise; +} + +export async function migrateRows( + rows: { + list(): Promise; + get(subject: string): Promise; + }, + table: string, + legacy: Legacy, +): Promise { + const byTag = new Map( + Object.entries(legacy.tags).map(([shortname, tag]) => [tag, shortname]), + ); + let rewritten = 0; + + for (const subject of await rows.list()) { + const row = await rows.get(subject); + if (row.get(PARENT) !== table || asList(row.get(IS_A)).includes(ISSUE_V1)) + continue; + const status = asList(row.get(legacy.status) ?? []).map(tag => { + const shortname = byTag.get(tag); + const known = STATUSES.find(s => s.toLowerCase() === shortname); + + return known ? TASK_TAGS[known] : tag; + }); + const body = row.get(DESCRIPTION); + row.set(IS_A, [ISSUE_V1]); + if (status.length) row.set(TASK_STATUS, status); + if (typeof body === 'string') row.set(TASK_BODY, body); + row.remove(legacy.status); + row.remove(DESCRIPTION); + await row.save(); + rewritten++; + } - return tags; + return rewritten; } async function ensureClass( @@ -270,13 +446,12 @@ export async function boundRepository( const sync = await findByLocalId(store, app, SYNC_LOCAL_ID); if (!sync) return undefined; const data = await store.getData(); - if (!data?.rowClass) return undefined; - const ontology = (await store.getResource(data.rowClass)).get(PARENT); - if (typeof ontology !== 'string') return undefined; + const ontology = await appOntology(store, app, data?.rowClass).catch( + () => undefined, + ); + if (!ontology) return undefined; - for (const subject of asList( - (await store.getResource(ontology)).get(PROPERTIES), - )) { + 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); @@ -294,34 +469,24 @@ export async function boundRepository( export async function provision( store: PluginStore, repository?: string, -): Promise<{ tracker: Tracker; sync: PluginResource; repository: string }> { +): Promise<{ + tracker: Tracker; + sync: PluginResource; + repository: string; + legacy?: Legacy; +}> { const app = await store.getApp(); const data = await store.getData(); - if (!data?.rowClass) - throw new Error('This app has no table with a row class to sync into.'); - const klass = await store.getResource(data.rowClass); - const ontologySubject = klass.get(PARENT); - if (typeof ontologySubject !== 'string') - throw new Error('The row class has no parent ontology to add fields to.'); - const ontology = await store.getResource(ontologySubject); - + 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); - const tags = await ensureTags(store, properties.status); - - const recommends = asList(klass.get(RECOMMENDS)); - const wanted = [ - NAME, - DESCRIPTION, - properties.status, - properties.number, - properties.provenance, - ]; - const merged = [ - ...recommends, - ...wanted.filter(s => !recommends.includes(s)), - ]; - if (merged.length !== recommends.length || klass.get(NAME) !== 'Issue') - await klass.set(RECOMMENDS, merged).set(NAME, 'Issue').save(); + await adopt( + store, + app, + data.table, + ROW_EXTRAS.map(key => properties[key]), + ); + const legacy = await legacyStatus(store, ontology); // 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. @@ -375,12 +540,13 @@ export async function provision( return { repository, sync, + ...(legacy ? { legacy } : {}), tracker: { app, table: data.table, - rowClass: data.rowClass, - properties, - tags, + rowClass: ISSUE_V1, + properties: { status: TASK_STATUS, body: TASK_BODY, ...properties }, + tags: TASK_TAGS, commentsFolder: comments.subject, }, }; diff --git a/integrations/issue-tracker/app/ui/dom.ts b/integrations/issue-tracker/app/ui/dom.ts index e09ea27f3..e2906d60e 100644 --- a/integrations/issue-tracker/app/ui/dom.ts +++ b/integrations/issue-tracker/app/ui/dom.ts @@ -102,10 +102,12 @@ const ICONS = { filter: stroke('M4 5h16l-6 7.5V19l-4-2v-4.5z', 1.4), server: '', - // Status glyphs (14px box): ring, half ring, filled check. + // Status glyphs (14px box): ring, half ring, barred ring, filled check. todo: '', doing: '', + blocked: + '', done: '', } as const; @@ -117,6 +119,7 @@ const BOX: Partial> = { server: 24, todo: 14, doing: 14, + blocked: 14, done: 14, }; diff --git a/integrations/issue-tracker/app/ui/kit.css b/integrations/issue-tracker/app/ui/kit.css index 331a16b3d..f8e62b59a 100644 --- a/integrations/issue-tracker/app/ui/kit.css +++ b/integrations/issue-tracker/app/ui/kit.css @@ -478,6 +478,9 @@ kbd { .g-doing { color: var(--pl-warn); } +.g-blocked { + color: var(--pl-neg); +} .g-done { color: var(--pl-accent); } diff --git a/integrations/issue-tracker/app/ui/kit.ts b/integrations/issue-tracker/app/ui/kit.ts index 72c5ba520..19b428cda 100644 --- a/integrations/issue-tracker/app/ui/kit.ts +++ b/integrations/issue-tracker/app/ui/kit.ts @@ -337,9 +337,9 @@ export function chip(name: string, color?: string): HTMLElement { return h('span', { class: 'chip' }, dot, name); } -export type Glyph = 'todo' | 'doing' | 'done'; +export type Glyph = 'todo' | 'doing' | 'blocked' | 'done'; -/** Ring, half ring, filled check: status readable without colour. */ +/** Ring, half ring, barred ring, filled check: status readable without colour. */ export function statusGlyph(status: Glyph, size = 14): SVGSVGElement { return icon(status, size, `glyph g-${status}`); } diff --git a/integrations/issue-tracker/app/views.test.ts b/integrations/issue-tracker/app/views.test.ts index cb8b42aa6..3f48b317f 100644 --- a/integrations/issue-tracker/app/views.test.ts +++ b/integrations/issue-tracker/app/views.test.ts @@ -135,7 +135,7 @@ describe('board and list', () => { expect(columnOf(root, '#1')).toBe('Todo'); const card = cardOf(root, '#1'); card.focus(); - key(card, '3'); + key(card, '4'); expect(columnOf(root, '#1')).toBe('Done'); await wait(40); expect(q(root, '[aria-live=polite]').textContent).toBe('Moved #1 to Done'); @@ -166,7 +166,7 @@ describe('board and list', () => { const { root, store } = await mount(); const card = cardOf(root, '#1'); card.focus(); - key(card, '3'); + key(card, '4'); await settle(root); q(root, '[data-key=review]').click(); const panel = q(root, '[aria-label="Changes to send to GitHub"]'); diff --git a/integrations/issue-tracker/app/views.ts b/integrations/issue-tracker/app/views.ts index 91126de7e..3a22ca881 100644 --- a/integrations/issue-tracker/app/views.ts +++ b/integrations/issue-tracker/app/views.ts @@ -130,16 +130,25 @@ export interface Actions { removeFromBoard(): void; landed(subject: string, id: number): void; sendAgain(subject: string): void; + /** "Publish to GitHub" for a local-only row (#177 Q6). */ + publish(subject: string): void; } const GLYPH: Record = { Todo: 'todo', Doing: 'doing', + Blocked: 'blocked', Done: 'done', }; export const refOf = (row: IssueRow) => - row.number !== undefined ? `#${row.number}` : 'New'; + row.number !== undefined ? `#${row.number}` : row.localOnly ? 'Local' : 'New'; + +/** "Status here: In review (not synced)" for a status shown as it is. */ +const asIsText = (row: IssueRow) => + row.statusAsIs + ? `Status here: ${row.statusAsIs.join(', ') || 'none'} (not synced with GitHub)` + : undefined; const repoUrl = (repository: string) => `https://github.com/${repository}`; @@ -683,7 +692,16 @@ function chooseRepository( h( 'li', null, - 'Title, description and comment edits are sent to GitHub, and new cards become new issues, each only after you review and send it.', + 'Moving a card to ', + h('b', null, 'Blocked'), + ' adds the ', + h('code', null, 'atomic:blocked'), + ' label the same way.', + ), + h( + '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.', ), h( 'li', @@ -772,8 +790,8 @@ function moveMenu( STATUSES.map(status => ({ label: status, glyph: GLYPH[status], - checked: row.status === status, - disabled: !movable || row.status === status, + checked: row.status === status && !row.statusAsIs, + disabled: !movable || (row.status === status && !row.statusAsIs), run: () => actions.move(row.subject, status, 'menu'), })), actions, @@ -826,6 +844,9 @@ function card( { class: 'card-top' }, h('span', { class: 'ref' }, refOf(row)), h('span', { class: 'sr' }, `Status: ${row.status}.`), + row.statusAsIs + ? h('span', { class: 'muted small', title: asIsText(row) }, '≠') + : null, marker(marks.get(row.subject)), ), h('span', { class: 'card-title' }, row.title), @@ -958,7 +979,7 @@ function board(state: Ready, ui: Ui, actions: Actions): HTMLElement { // ---------------------------------------------------------------- list -const LIST_ORDER: Status[] = ['Doing', 'Todo', 'Done']; +const LIST_ORDER: Status[] = ['Doing', 'Blocked', 'Todo', 'Done']; function list(state: Ready, ui: Ui, actions: Actions): HTMLElement { const rows = state.last?.result.rows ?? []; @@ -1500,6 +1521,27 @@ function issueDetail( ? h('span', { class: 'small' }, row.assignees.join(', ')) : null, ), + row.statusAsIs + ? h('p', { class: 'ro-note' }, icon('info', 14), `${asIsText(row)}.`) + : null, + row.localOnly + ? h( + 'div', + { class: 'ro-note' }, + icon('info', 14), + h( + 'span', + null, + `Only in this table. It becomes an issue in ${state.repository} once you publish it and then review and send it.`, + ), + button('Publish to GitHub', () => actions.publish(row.subject), { + sm: true, + kind: 'primary', + disabled: !!state.busy, + 'data-key': 'publish', + }), + ) + : null, mark ? h( 'p', @@ -1549,7 +1591,9 @@ function issueDetail( { class: 'mono' }, bound ? `${state.repository}#${row.number}` - : `${state.repository} · not on GitHub yet`, + : row.localOnly + ? 'Only in this table' + : `${state.repository} · not on GitHub yet`, ), state.last?.at ? ` · synced ${ago(state.last.at, ui.now)}` : '', row.url @@ -1927,6 +1971,17 @@ export function page( const top = appHeader(state, ui, actions); 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, + ), + ]; if (state.kind === 'loading') return [ top, diff --git a/integrations/issue-tracker/devonian/github-issues/adapter.test.ts b/integrations/issue-tracker/devonian/github-issues/adapter.test.ts index 8cda3869e..b02445f15 100644 --- a/integrations/issue-tracker/devonian/github-issues/adapter.test.ts +++ b/integrations/issue-tracker/devonian/github-issues/adapter.test.ts @@ -15,7 +15,7 @@ const issue = (number: number): Issue => ({ }); describe('GitHub package', () => { it('uses a strict repository-scoped manifest', () => { - expect(validateManifest(manifest('owner/repo')).operations).toHaveLength(6); + expect(validateManifest(manifest('owner/repo')).operations).toHaveLength(8); expect(() => manifest('../escape')).toThrow(); expect(() => manifest('owner/repo?token=x')).toThrow(); }); diff --git a/integrations/issue-tracker/devonian/github-issues/adapter.ts b/integrations/issue-tracker/devonian/github-issues/adapter.ts index cc364ea49..19c3c717d 100644 --- a/integrations/issue-tracker/devonian/github-issues/adapter.ts +++ b/integrations/issue-tracker/devonian/github-issues/adapter.ts @@ -135,6 +135,18 @@ export function manifest(repository: string) { url: `${url}/{number}/labels/atomic%3Adoing`, effect: 'write', }, + { + id: 'blocked-add', + method: 'POST', + url: `${url}/{number}/labels`, + effect: 'write', + }, + { + id: 'blocked-remove', + method: 'DELETE', + url: `${url}/{number}/labels/atomic%3Ablocked`, + effect: 'write', + }, ], }; } diff --git a/integrations/issue-tracker/devonian/github-issues/atomic.ts b/integrations/issue-tracker/devonian/github-issues/atomic.ts index 35d3c3a98..1e44cf123 100644 --- a/integrations/issue-tracker/devonian/github-issues/atomic.ts +++ b/integrations/issue-tracker/devonian/github-issues/atomic.ts @@ -81,6 +81,7 @@ export async function install( const tags: Record = { Todo: taskSchema.tags.Todo, Doing: taskSchema.tags.Doing, + Blocked: taskSchema.tags.Blocked, Done: taskSchema.tags.Done, }; const number = await create(plugin.subject, [core.classes.property], { diff --git a/integrations/issue-tracker/devonian/github-issues/lens/index.ts b/integrations/issue-tracker/devonian/github-issues/lens/index.ts index 38bc0616b..c258fb90d 100644 --- a/integrations/issue-tracker/devonian/github-issues/lens/index.ts +++ b/integrations/issue-tracker/devonian/github-issues/lens/index.ts @@ -1,6 +1,23 @@ // @wc-ignore-file -/** Passive GitHub issue mapping. No store, transport or synchronization state. */ -export type Status = 'Todo' | 'Doing' | 'Done'; +/** + * Passive GitHub issue mapping. No store, transport or synchronization state. + * + * GitHub has only open and closed. The two workflow labels carry the rest + * (ontola/atomic-plugins#177, Q8): `atomic:doing` is Doing and + * `atomic:blocked` is Blocked. Closed is Done whatever the labels say; an + * open issue with both labels is Blocked. + */ +export type Status = 'Todo' | 'Doing' | 'Blocked' | 'Done'; +export const STATUSES: readonly Status[] = ['Todo', 'Doing', 'Blocked', 'Done']; +/** The workflow labels, lower case, by the status they stand for. */ +export const STATUS_LABELS = { + Doing: 'atomic:doing', + Blocked: 'atomic:blocked', +} as const; +const WORKFLOW_LABELS: string[] = Object.values(STATUS_LABELS); +const labelName = (label: string | { name: string }) => + (typeof label === 'string' ? label : label.name).toLowerCase(); + export type Projection = { title: string; body: string; @@ -25,19 +42,19 @@ export function project(issue: Issue): Projection { ) throw new Error('GitHub returned an invalid issue'); + const names = issue.labels.map(labelName); + return { title: issue.title, body: issue.body ?? '', status: issue.state === 'closed' ? 'Done' - : issue.labels.some( - l => - (typeof l === 'string' ? l : l.name).toLowerCase() === - 'atomic:doing', - ) - ? 'Doing' - : 'Todo', + : names.includes(STATUS_LABELS.Blocked) + ? 'Blocked' + : names.includes(STATUS_LABELS.Doing) + ? 'Doing' + : 'Todo', }; } export function validate(value: Projection): void { @@ -45,10 +62,10 @@ export function validate(value: Projection): void { typeof value.title !== 'string' || !value.title.trim() || typeof value.body !== 'string' || - !['Todo', 'Doing', 'Done'].includes(value.status) + !STATUSES.includes(value.status) ) throw new Error( - 'Cards require a title, Markdown body and exactly one Todo/Doing/Done status', + 'Cards require a title, Markdown body and exactly one Todo/Doing/Blocked/Done status', ); } @@ -65,15 +82,17 @@ export function issueFields(value: Projection): { }; } -/** Reverse mapping preserves every field and label outside the projection. */ +/** + * Reverse mapping preserves every field and label outside the projection. + * Each status leaves exactly its own workflow label, if it has one. + */ export function unproject(value: Projection, previous: T): T { validate(value); const labels = previous.labels.filter( - label => - (typeof label === 'string' ? label : label.name).toLowerCase() !== - 'atomic:doing', + label => !WORKFLOW_LABELS.includes(labelName(label)), ); - if (value.status === 'Doing') labels.push('atomic:doing'); + if (value.status === 'Doing' || value.status === 'Blocked') + labels.push(STATUS_LABELS[value.status]); return { ...previous, ...issueFields(value), labels }; } @@ -110,8 +129,8 @@ export interface IssueExtras { } /** - * Labels (without the `atomic:doing` workflow label, which is the Doing - * status), assignee logins and GitHub's comment count. Only ever written to + * Labels (without the `atomic:doing` and `atomic:blocked` workflow labels, + * which are the Doing and Blocked statuses), assignee logins and GitHub's comment count. Only ever written to * the Atomic side as provenance metadata: `issueFields`/`issuePatch` above * do not read these, so they cannot reach GitHub. */ @@ -125,7 +144,10 @@ export function issueExtras( for (const label of issue.labels) { const name = typeof label === 'string' ? label : label?.name; - if (typeof name !== 'string' || name.toLowerCase() === 'atomic:doing') + if ( + typeof name !== 'string' || + WORKFLOW_LABELS.includes(name.toLowerCase()) + ) continue; const raw = typeof label === 'object' ? (label as { color?: unknown }).color : ''; diff --git a/integrations/issue-tracker/devonian/github-issues/lens/lens.test.ts b/integrations/issue-tracker/devonian/github-issues/lens/lens.test.ts index 489f13a1f..c2373e362 100644 --- a/integrations/issue-tracker/devonian/github-issues/lens/lens.test.ts +++ b/integrations/issue-tracker/devonian/github-issues/lens/lens.test.ts @@ -19,7 +19,7 @@ const issue: Issue & { assignee: string } = { }; describe('passive GitHub issues lens', () => { - it.each(['Todo', 'Doing', 'Done'] as const)( + it.each(['Todo', 'Doing', 'Blocked', 'Done'] as const)( 'round trips GitHub %s without changing unrelated data', status => { const desired = { title: 'After', body: 'Edited', status }; @@ -34,6 +34,26 @@ describe('passive GitHub issues lens', () => { }, ); + it('maps atomic:blocked to Blocked, ahead of atomic:doing, and closed to Done (#177 Q8)', () => { + const open = (...labels: string[]) => ({ ...issue, labels }); + expect(project(open('atomic:blocked')).status).toBe('Blocked'); + expect(project(open('ATOMIC:BLOCKED', 'atomic:doing')).status).toBe( + 'Blocked', + ); + expect(project(open('atomic:doing')).status).toBe('Doing'); + expect(project({ ...open('atomic:blocked'), state: 'closed' }).status).toBe( + 'Done', + ); + const result = unproject( + { title: 'T', body: '', status: 'Blocked' }, + open('bug', 'atomic:doing'), + ); + expect(result.labels).toEqual(['bug', 'atomic:blocked']); + expect(issueExtras(open('bug', 'atomic:blocked')).labels).toEqual([ + { name: 'bug' }, + ]); + }); + it('keeps the GitHub runtime patch minimal', () => { const before = project(issue); expect(issuePatch(before, before)).toEqual({}); diff --git a/integrations/issue-tracker/devonian/github-issues/lens/resources.mjs b/integrations/issue-tracker/devonian/github-issues/lens/resources.mjs index 183ae5e6b..952d97dec 100644 --- a/integrations/issue-tracker/devonian/github-issues/lens/resources.mjs +++ b/integrations/issue-tracker/devonian/github-issues/lens/resources.mjs @@ -24,6 +24,7 @@ export function value(resource, entity) { const status = { [`${tag}todo`]: 'Todo', [`${tag}doing`]: 'Doing', + [`${tag}blocked`]: 'Blocked', [`${tag}done`]: 'Done', }[resource[propertiesByField.status]?.[0]]; if (!status || resource[propertiesByField.status].length !== 1) diff --git a/integrations/issue-tracker/devonian/github-issues/manifest.fixture.json b/integrations/issue-tracker/devonian/github-issues/manifest.fixture.json index c58538809..83d6cd065 100644 --- a/integrations/issue-tracker/devonian/github-issues/manifest.fixture.json +++ b/integrations/issue-tracker/devonian/github-issues/manifest.fixture.json @@ -83,6 +83,18 @@ "method": "DELETE", "url": "https://api.github.com/repos/atomic-fixtures/issues/issues/{number}/labels/atomic%3Adoing", "effect": "write" + }, + { + "id": "blocked-add", + "method": "POST", + "url": "https://api.github.com/repos/atomic-fixtures/issues/issues/{number}/labels", + "effect": "write" + }, + { + "id": "blocked-remove", + "method": "DELETE", + "url": "https://api.github.com/repos/atomic-fixtures/issues/issues/{number}/labels/atomic%3Ablocked", + "effect": "write" } ] } diff --git a/integrations/issue-tracker/devonian/github-issues/plugin.js b/integrations/issue-tracker/devonian/github-issues/plugin.js index fced2dbcd..b23a21317 100644 --- a/integrations/issue-tracker/devonian/github-issues/plugin.js +++ b/integrations/issue-tracker/devonian/github-issues/plugin.js @@ -28,9 +28,9 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge mod )); -// browser/lib/node_modules/fast-json-stable-stringify/index.js +// ../../../../atomic-server-pin/browser/node_modules/.pnpm/fast-json-stable-stringify@2.1.0/node_modules/fast-json-stable-stringify/index.js var require_fast_json_stable_stringify = __commonJS({ - "browser/lib/node_modules/fast-json-stable-stringify/index.js"(exports, module) { + "../../../../atomic-server-pin/browser/node_modules/.pnpm/fast-json-stable-stringify@2.1.0/node_modules/fast-json-stable-stringify/index.js"(exports, module) { "use strict"; module.exports = function(data, opts) { if (!opts) opts = {}; @@ -85,21 +85,27 @@ var require_fast_json_stable_stringify = __commonJS({ }); // integrations/issue-tracker/devonian/github-issues/lens/index.ts +var STATUSES = ["Todo", "Doing", "Blocked", "Done"]; +var STATUS_LABELS = { + Doing: "atomic:doing", + Blocked: "atomic:blocked" +}; +var WORKFLOW_LABELS = Object.values(STATUS_LABELS); +var labelName = (label) => (typeof label === "string" ? label : label.name).toLowerCase(); function project(issue) { if (!Number.isSafeInteger(issue.number) || issue.number <= 0 || typeof issue.title !== "string" || !(issue.body === null || typeof issue.body === "string") || !["open", "closed"].includes(issue.state) || !Array.isArray(issue.labels)) throw new Error("GitHub returned an invalid issue"); + const names = issue.labels.map(labelName); return { title: issue.title, body: issue.body ?? "", - status: issue.state === "closed" ? "Done" : issue.labels.some( - (l) => (typeof l === "string" ? l : l.name).toLowerCase() === "atomic:doing" - ) ? "Doing" : "Todo" + status: issue.state === "closed" ? "Done" : names.includes(STATUS_LABELS.Blocked) ? "Blocked" : names.includes(STATUS_LABELS.Doing) ? "Doing" : "Todo" }; } function validate(value) { - if (typeof value.title !== "string" || !value.title.trim() || typeof value.body !== "string" || !["Todo", "Doing", "Done"].includes(value.status)) + if (typeof value.title !== "string" || !value.title.trim() || typeof value.body !== "string" || !STATUSES.includes(value.status)) throw new Error( - "Cards require a title, Markdown body and exactly one Todo/Doing/Done status" + "Cards require a title, Markdown body and exactly one Todo/Doing/Blocked/Done status" ); } function issuePatch(desired, previous) { @@ -111,7 +117,7 @@ function issuePatch(desired, previous) { return patch; } -// browser/lib/src/subject.ts +// ../../../../atomic-server-pin/browser/lib/src/subject.ts var ATOMIC_PREFIX = "atomic:"; var DID_AD_PREFIX = "did:ad:"; function isLegacyAtomicLink(raw) { @@ -136,7 +142,7 @@ function canonicalIdentifier(raw) { return canonicalizeScheme(raw.split(/[?#]/)[0]); } -// browser/lib/src/import-records.ts +// ../../../../atomic-server-pin/browser/lib/src/import-records.ts var IMPORT_LOCAL_ID = "https://atomicdata.dev/properties/localId"; var PARENT = "https://atomicdata.dev/properties/parent"; var pure = (subject) => typeof subject === "string" ? canonicalIdentifier(subject) : subject; @@ -152,7 +158,7 @@ function claimImportIdentity(host, parent2, sourceId, subject) { return { [IMPORT_LOCAL_ID]: sourceId }; } -// browser/lib/src/plugin-reconcile.ts +// ../../../../atomic-server-pin/browser/lib/src/plugin-reconcile.ts var import_fast_json_stable_stringify = __toESM(require_fast_json_stable_stringify(), 1); var equal = (a, b) => (0, import_fast_json_stable_stringify.default)(a) === (0, import_fast_json_stable_stringify.default)(b); function reconcileRecord(base, local, remote) { @@ -474,7 +480,7 @@ async function run(input) { { title: desired.title, body: desired.body, - labels: desired.status === "Doing" ? ["atomic:doing"] : [] + labels: desired.status === "Doing" ? ["atomic:doing"] : desired.status === "Blocked" ? ["atomic:blocked"] : [] } ); const remote = project(issue(change.number)); @@ -503,28 +509,32 @@ async function run(input) { patch ); cursor = next; - } else if (cursor.stage === "labels") { + } else if (cursor.stage === "labels" || cursor.stage === "labels-blocked") { + const blocked = cursor.stage === "labels-blocked"; + const status = blocked ? "Blocked" : "Doing"; + const label = blocked ? "atomic:blocked" : "atomic:doing"; + const op = blocked ? "blocked" : "doing"; const current = issue(cursor.number); - const doing = current.labels.some( - (l) => (typeof l === "string" ? l : l.name).toLowerCase() === "atomic:doing" + const has = current.labels.some( + (l) => (typeof l === "string" ? l : l.name).toLowerCase() === label ); - const next = { ...cursor, stage: "local" }; - if (desired.status === "Doing" && !doing) + const next = { ...cursor, stage: blocked ? "local" : "labels-blocked" }; + if (desired.status === status && !has) return external( - "doing-add", + `${op}-add`, "POST", `${root}/${cursor.number}/labels`, "label", next, { - labels: ["atomic:doing"] + labels: [label] } ); - if (desired.status !== "Doing" && doing) + if (desired.status !== status && has) return external( - "doing-remove", + `${op}-remove`, "DELETE", - `${root}/${cursor.number}/labels/atomic%3Adoing`, + `${root}/${cursor.number}/labels/${encodeURIComponent(label)}`, "label", next ); diff --git a/integrations/issue-tracker/devonian/github-issues/plugin.ts b/integrations/issue-tracker/devonian/github-issues/plugin.ts index 6b2fccb09..127a26759 100644 --- a/integrations/issue-tracker/devonian/github-issues/plugin.ts +++ b/integrations/issue-tracker/devonian/github-issues/plugin.ts @@ -261,7 +261,12 @@ export async function run(input: Input): Promise { { title: desired.title, body: desired.body, - labels: desired.status === 'Doing' ? ['atomic:doing'] : [], + labels: + desired.status === 'Doing' + ? ['atomic:doing'] + : desired.status === 'Blocked' + ? ['atomic:blocked'] + : [], }, ); const remote = project(issue(change.number)); @@ -290,29 +295,34 @@ export async function run(input: Input): Promise { patch, ); cursor = next; - } else if (cursor.stage === 'labels') { + } else if (cursor.stage === 'labels' || cursor.stage === 'labels-blocked') { + // One workflow label per stage (#177 Q8): `atomic:doing`, then + // `atomic:blocked`. + const blocked = cursor.stage === 'labels-blocked'; + const status = blocked ? 'Blocked' : 'Doing'; + const label = blocked ? 'atomic:blocked' : 'atomic:doing'; + const op = blocked ? 'blocked' : 'doing'; const current = issue(cursor.number!); - const doing = current.labels.some( - l => - (typeof l === 'string' ? l : l.name).toLowerCase() === 'atomic:doing', + const has = current.labels.some( + l => (typeof l === 'string' ? l : l.name).toLowerCase() === label, ); - const next = { ...cursor, stage: 'local' }; - if (desired.status === 'Doing' && !doing) + const next = { ...cursor, stage: blocked ? 'local' : 'labels-blocked' }; + if (desired.status === status && !has) return external( - 'doing-add', + `${op}-add`, 'POST', `${root}/${cursor.number}/labels`, 'label', next, { - labels: ['atomic:doing'], + labels: [label], }, ); - if (desired.status !== 'Doing' && doing) + if (desired.status !== status && has) return external( - 'doing-remove', + `${op}-remove`, 'DELETE', - `${root}/${cursor.number}/labels/atomic%3Adoing`, + `${root}/${cursor.number}/labels/${encodeURIComponent(label)}`, 'label', next, ); diff --git a/integrations/issue-tracker/devonian/github-issues/ports.mjs b/integrations/issue-tracker/devonian/github-issues/ports.mjs index 6bab347a7..2b2552e50 100644 --- a/integrations/issue-tracker/devonian/github-issues/ports.mjs +++ b/integrations/issue-tracker/devonian/github-issues/ports.mjs @@ -1,4 +1,4 @@ -import { project, issueFields, issueExtras } from './lens/index.js'; +import { project, issueFields, issueExtras, STATUSES } from './lens/index.js'; import { core, dataBrowser } from '@tomic/lib'; import { assertEnumerable, assertSaved } from './target.mjs'; @@ -137,9 +137,9 @@ export class GitHubPort { return; } - if (!['Todo', 'Doing', 'Done'].includes(value.status)) + if (!STATUSES.includes(value.status)) throw new Error('Unsupported task status'); - const current = await this.get(entity, id, context); + await this.get(entity, id, context); // validate it is an issue before writing await this.request( 'update_issue', { @@ -148,24 +148,42 @@ export class GitHubPort { }, `${key}:fields`, ); + // Closing keeps the labels as they are, like the pilot. Every open + // status leaves exactly its own workflow label (#177 Q8); other labels + // are never touched. Read the raw labels: a closed issue may still + // carry either one. + if (value.status === 'Done') return; + const raw = await this.request('get_issue', { number: id }); + const has = new Set( + raw.labels.map(l => (typeof l === 'string' ? l : l.name).toLowerCase()), + ); + const labels = [ + // [status, label, add action, remove action, add key, remove key] + [ + 'Doing', + 'atomic:doing', + 'add_doing_label', + 'remove_doing_label', + 'doing', + 'todo', + ], + [ + 'Blocked', + 'atomic:blocked', + 'add_blocked_label', + 'remove_blocked_label', + 'blocked', + 'unblocked', + ], + ]; - // Only this workflow label is managed. Closing preserves the label like the pilot. - if (value.status === 'Doing' && current.value.status !== 'Doing') { - await this.request('add_doing_label', { number: id }, `${key}:doing`); - } else if (value.status === 'Todo') { - // Closed issues may still carry the doing label, so inspect raw labels. - const raw = await this.request('get_issue', { number: id }); + for (const [status, label, , remove, , removeKey] of labels) + if (value.status !== status && has.has(label)) + await this.request(remove, { number: id }, `${key}:${removeKey}`); - if ( - raw.labels.some( - l => - (typeof l === 'string' ? l : l.name).toLowerCase() === - 'atomic:doing', - ) - ) { - await this.request('remove_doing_label', { number: id }, `${key}:todo`); - } - } + for (const [status, label, add, , addKey] of labels) + if (value.status === status && !has.has(label)) + await this.request(add, { number: id }, `${key}:${addKey}`); } } @@ -251,9 +269,7 @@ export class AtomicPort { const statuses = r.get(c.status) ?? [c.tags.Todo]; const status = Object.keys(c.tags).find(s => c.tags[s] === statuses[0]); if (statuses.length !== 1 || !status) - throw new Error( - 'Choose exactly one Todo/Doing/Done status; Blocked is unmapped', - ); + throw new Error('Choose exactly one Todo/Doing/Blocked/Done status'); const title = r.get(core.properties.name), body = r.get(c.body) ?? ''; if (typeof title !== 'string' || !title.trim() || typeof body !== 'string') diff --git a/integrations/issue-tracker/devonian/github-issues/ports.test.mjs b/integrations/issue-tracker/devonian/github-issues/ports.test.mjs index dac9d60ac..3dda8109b 100644 --- a/integrations/issue-tracker/devonian/github-issues/ports.test.mjs +++ b/integrations/issue-tracker/devonian/github-issues/ports.test.mjs @@ -27,6 +27,8 @@ it('declares and prepares scoped issue/comment actions with validated arguments' ['update_issue', { number: 5, title: 'Title', body: '', state: 'closed' }], ['add_doing_label', { number: 5 }], ['remove_doing_label', { number: 5 }], + ['add_blocked_label', { number: 5 }], + ['remove_blocked_label', { number: 5 }], ]) { const intent = trackerAction('owner/repo', action, args); expect( @@ -100,6 +102,14 @@ function github() { value = issues.get(args.number); value.labels = value.labels.filter(l => l !== 'atomic:doing'); break; + case 'add_blocked_label': + value = issues.get(args.number); + value.labels.push('atomic:blocked'); + break; + case 'remove_blocked_label': + value = issues.get(args.number); + value.labels = value.labels.filter(l => l !== 'atomic:blocked'); + break; case 'create_comment': value = { id: comments.size + 1, @@ -147,6 +157,21 @@ it('creates closed/doing issues and reopens while preserving unrelated labels', expect(issues.get(1).labels).toEqual(['bug']); }); +it('moves an issue between Doing and Blocked with one workflow label each (#177 Q8)', async () => { + const { port, issues } = github(); + const value = { title: 'First', body: '', status: 'Blocked' }; + await port.update('issue', 1, value, 'block'); + expect(issues.get(1).labels).toEqual(['bug', 'atomic:blocked']); + expect((await port.get('issue', 1)).value.status).toBe('Blocked'); + await port.update('issue', 1, { ...value, status: 'Doing' }, 'unblock'); + expect(issues.get(1).labels).toEqual(['bug', 'atomic:doing']); + await port.update('issue', 1, { ...value, status: 'Done' }, 'close'); + expect(issues.get(1).labels).toEqual(['bug', 'atomic:doing']); + await port.update('issue', 1, { ...value, status: 'Todo' }, 'reopen'); + expect(issues.get(1).state).toBe('open'); + expect(issues.get(1).labels).toEqual(['bug']); +}); + it('creates/edits comments with replay-safe IDs and rejects another issue’s comment', async () => { const { port, comments } = github(); const context = { issueId: 1 }; diff --git a/integrations/issue-tracker/devonian/github-issues/proxy.mjs b/integrations/issue-tracker/devonian/github-issues/proxy.mjs index 291351296..41d5c1917 100644 --- a/integrations/issue-tracker/devonian/github-issues/proxy.mjs +++ b/integrations/issue-tracker/devonian/github-issues/proxy.mjs @@ -151,6 +151,14 @@ export function fixtureTransport(state, save) { issue.labels = issue.labels.filter(l => l !== 'atomic:doing'); value = issue; break; + case 'add_blocked_label': + issue.labels = [...new Set([...issue.labels, 'atomic:blocked'])]; + value = issue; + break; + case 'remove_blocked_label': + issue.labels = issue.labels.filter(l => l !== 'atomic:blocked'); + value = issue; + break; case 'list_comments': value = state.comments .filter(c => c.issue_url.endsWith(`/${args.number}`)) diff --git a/integrations/issue-tracker/devonian/github-issues/tracker-actions.ts b/integrations/issue-tracker/devonian/github-issues/tracker-actions.ts index 9e62ccdb8..8f9b3acf5 100644 --- a/integrations/issue-tracker/devonian/github-issues/tracker-actions.ts +++ b/integrations/issue-tracker/devonian/github-issues/tracker-actions.ts @@ -33,6 +33,20 @@ const definitions = [ { number: integer }, ['number'], ], + [ + 'add_blocked_label', + 'Mark an issue as blocked', + 'blocked-add', + { number: integer }, + ['number'], + ], + [ + 'remove_blocked_label', + 'Remove the blocked label', + 'blocked-remove', + { number: integer }, + ['number'], + ], [ 'list_comments', 'List issue comments', @@ -182,6 +196,23 @@ export function trackerAction( `${root}/${args.number}/labels/atomic%3Adoing`, 'action', ); + case 'add_blocked_label': + return request( + operation, + 'POST', + `${root}/${args.number}/labels`, + 'action', + { + labels: ['atomic:blocked'], + }, + ); + case 'remove_blocked_label': + return request( + operation, + 'DELETE', + `${root}/${args.number}/labels/atomic%3Ablocked`, + 'action', + ); case 'update_issue': if (!['open', 'closed'].includes(String(args.state))) throw new Error('Invalid issue state'); diff --git a/integrations/issue-tracker/e2e/issue-tracker.spec.ts b/integrations/issue-tracker/e2e/issue-tracker.spec.ts index 022cc3de0..9bb2e9303 100644 --- a/integrations/issue-tracker/e2e/issue-tracker.spec.ts +++ b/integrations/issue-tracker/e2e/issue-tracker.spec.ts @@ -17,10 +17,22 @@ * pauses sync; the conflict review keeps GitHub's title. * 5. Moving a card on the board with the keyboard, reviewed and sent. * 6. A comment added in the issue panel, reviewed and sent. - * 7. Disconnect in the app, then connect again through the host's "Use + * 7. Since 0.2.0 (#177 item 6): the app made itself a view of the shared + * class `issue-v1` (its table's class, its App's `renders`). A row added + * to the table outside the app stays local until "Publish to GitHub", + * whose create is reviewed and sent; moving it to Blocked adds the + * `atomic:blocked` label (#177 Q8). + * 8. Disconnect in the app, then connect again through the host's "Use * existing connection", with no reload: the app syncs again by itself * (#196 user test; it used to stop at an unsynced board). * + * 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 + * published subjects"). `beforeAll` first checks Pages serves `issue-v1` + * with the committed bytes (`ontology-kit/served.mjs`), so this needs + * network access to https://ontola.github.io. + * * GitHub-side reads and edits go through the mock's test drivers for the * github-issues fixture (`POST /fixture/github-issues/`), standing * in for someone working on GitHub. The connection itself lives at the @@ -36,11 +48,28 @@ 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.1.3'; +const VERSION = '0.2.0'; const REPOSITORY = 'atomic-fixture/tracker'; const NAME = 'https://atomicdata.dev/properties/name'; +const CLASSTYPE = 'https://atomicdata.dev/properties/classtype'; +const PARENT = 'https://atomicdata.dev/properties/parent'; +const IS_A = 'https://atomicdata.dev/properties/isA'; +const TASK = 'https://atomicdata.dev/task/v1'; test.describe('GitHub issues drive app', () => { + test.beforeAll(async () => { + const served = (await import( + '../../../ontology-kit/served.mjs' as string + )) as { + classTermPaths(name: string): string[]; + servedProblems(paths: string[]): Promise; + notServedMessage(problems: string[]): string; + }; + const problems = await served.servedProblems( + served.classTermPaths('issue-v1'), + ); + if (problems.length) throw new Error(served.notServedMessage(problems)); + }); test.beforeEach(before); test('imports, refreshes, sends reviewed updates, moves a card, comments and recovers from a conflict', async ({ @@ -167,7 +196,7 @@ test.describe('GitHub issues drive app', () => { // 5. Move a card in the app: #2 to Done with the keyboard, then send. await card(app, '#2').focus(); - await page.keyboard.press('3'); + await page.keyboard.press('4'); await expect(column(app, 'Done')).toContainText('Export as CSV'); await app .getByRole('button', { name: 'Review and send' }) @@ -209,6 +238,117 @@ test.describe('GitHub issues drive app', () => { comments.filter(c => c.issue_url.endsWith('/issues/1')).map(c => c.body), ).toEqual(['I can reproduce this in Firefox.', 'Fixed in the app.']); + // 7. The shared class (#177 item 6). The app's own table is an issue-v1 + // table, and the App renders issue-v1, so Add view offers it on others. + const issueV1 = ( + (await import('../../../ontology-kit/terms.mjs' as string)) as { + classes: Record; + } + ).classes['issue-v1'].subject; + const appSubject = new URL(page.url()).searchParams.get('subject')!; + const shared = await page.evaluate( + async args => { + const store = window.store!; + const row = await store.getResource(args.row); + const table = await store.getResource(row.get(args.parent) as string); + await store.reloadResource?.(args.app); + const appResource = await store.getResource(args.app); + + return { + rowIsA: row.get(args.isA), + classtype: table.get(args.classtype), + table: table.subject, + renders: Object.values(appResource.getPropVals()).some( + v => Array.isArray(v) && v.includes(args.issueV1), + ), + }; + }, + { + row: first, + app: appSubject, + parent: PARENT, + isA: IS_A, + classtype: CLASSTYPE, + issueV1, + }, + ); + expect(shared).toMatchObject({ + rowIsA: [issueV1], + classtype: issueV1, + renders: true, + }); + + // A row added in the table, outside the app: local only, nothing held. + await page.evaluate( + async args => { + const store = window.store!; + const row = await store.newResource({ + parent: args.table, + isA: [args.issueV1], + propVals: { + [args.name]: 'Written in the table', + [`${args.task}/status`]: [`${args.task}/todo`], + }, + }); + await row.save(); + }, + { table: shared.table, issueV1, name: NAME, task: TASK }, + ); + await app.getByRole('button', { name: 'Sync now' }).click(); + await expect(card(app, 'Local')).toContainText('Written in the table', { + timeout: 30_000, + }); + await expect(bar).toHaveAttribute('title', /0 sent to GitHub/); + expect( + (await fixture('snapshot', [REPOSITORY])) as { issues: unknown[] }, + ).toMatchObject({ issues: { length: 2 } }); + + // Publish to GitHub: the create is held for review, then sent. + await card(app, 'Local').click(); + await detail.getByRole('button', { name: 'Publish to GitHub' }).click(); + await page.keyboard.press('Escape'); + await app + .getByRole('button', { name: 'Review and send' }) + .click({ timeout: 30_000 }); + await expect(review).toContainText( + 'Create issue “Written in the table” (Todo)', + ); + 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 github('GET', '/issues/3')).title).toBe( + 'Written in the table', + ); + // The row gets its number from GitHub's answer on the next pass. + await app.getByRole('button', { name: 'Sync now' }).click(); + await expect(card(app, '#3')).toContainText('Written in the table', { + timeout: 30_000, + }); + + // Blocked is the atomic:blocked label (#177 Q8). + await card(app, '#3').focus(); + await page.keyboard.press('3'); + await expect(column(app, 'Blocked')).toContainText('Written in the table'); + await app + .getByRole('button', { name: 'Review and send' }) + .click({ timeout: 30_000 }); + await expect(review).toContainText( + 'Update #3: status Todo → Blocked (add the atomic:blocked label)', + ); + await app.getByRole('button', { name: 'Send 1 change to GitHub' }).click(); + await expect(bar).toHaveAttribute('title', /1 sent to GitHub/, { + timeout: 30_000, + }); + const third = (await github('GET', '/issues/3')) as { + state: string; + labels: (string | { name: string })[]; + }; + expect(third.state).toBe('open'); + expect( + third.labels.map(l => (typeof l === 'string' ? l : l.name)), + ).toContain('atomic:blocked'); + // 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'); @@ -221,7 +361,7 @@ test.describe('GitHub issues drive app', () => { ]), ); - // 7. Disconnect this app, then connect again through the existing + // 8. Disconnect this app, then connect again through the existing // connection. The consent bar resolves with no reload, so the app must // start its sync itself, as it does when the view opens. const appUrl = page.url(); @@ -238,7 +378,7 @@ test.describe('GitHub issues drive app', () => { await expect(consent).toBeHidden(); await expect(bar).toHaveAttribute( 'title', - /2 issues and 2 comments in sync with atomic-fixture\/tracker/, + /3 issues and 2 comments in sync with atomic-fixture\/tracker/, { timeout: 60_000 }, ); // Nothing new to send. "Updated here" is left open: the comment sent @@ -285,34 +425,15 @@ async function setName(page: Page, subject: string, name: string) { ); } -/** A person changing a row's Status select to the tag with this shortname. */ +/** A person changing a row's task/v1 Status to the tag with this shortname. */ async function setStatus(page: Page, subject: string, shortname: string) { await page.evaluate( - async ({ target, wanted }) => { - const A = 'https://atomicdata.dev/properties'; - const store = window.store!; - const row = await store.getResource(target); - const klass = await store.getResource( - (row.get(`${A}/isA`) as string[])[0], - ); - - for (const property of klass.get(`${A}/recommends`) as string[]) { - const p = await store.getResource(property); - if (p.get(`${A}/shortname`) !== 'issue-status') continue; - - for (const tag of p.get(`${A}/allowsOnly`) as string[]) { - const t = await store.getResource(tag); - if (t.get(`${A}/shortname`) !== wanted) continue; - await row.set(property, [tag]); - await row.save(); - - return; - } - } - - throw new Error(`No ${wanted} status`); + async ({ target, wanted, task }) => { + const row = await window.store!.getResource(target); + await row.set(`${task}/status`, [`${task}/${wanted}`]); + await row.save(); }, - { target: subject, wanted: shortname }, + { target: subject, wanted: shortname, task: TASK }, ); } diff --git a/integrations/lanes.json b/integrations/lanes.json index e8ae2e530..dc271522d 100644 --- a/integrations/lanes.json +++ b/integrations/lanes.json @@ -59,9 +59,11 @@ "paths": [ "devonian/src/**", "devonian/package.json", - "devonian/pnpm-lock.yaml" + "devonian/pnpm-lock.yaml", + "ontology/**", + "ontology-kit/**" ], - "note": "paths: devonian/github-issues/ imports the devonian package from source (vitest.config.ts aliases it to devonian/src/main.ts), so a devonian change runs this lane too. Its tests ran in devonian CI before the lens moved here. The e2e installs the GitHub issues drive app (app/, npm devonian from app/package.json) from the catalog's Drive apps section, as the committed apps/issue-tracker//ui.js, and drives it through the host's proxy relay (atomic-server#1657, in the pin) against the mock proxy's seeded atomic-fixture/tracker repository.", + "note": "paths: the app bundles ontology-kit/terms.mjs and resolver.mjs and its rows are of the shared issue-v1 class (#177 item 6), so an ontology change runs this lane too; the e2e reads issue-v1 from its published GitHub Pages subject (checked first with ontology-kit/served.mjs), so it needs network access to ontola.github.io. devonian/github-issues/ imports the devonian package from source (vitest.config.ts aliases it to devonian/src/main.ts), so a devonian change runs this lane too. Its tests ran in devonian CI before the lens moved here. The e2e installs the GitHub issues drive app (app/, npm devonian from app/package.json) from the catalog's Drive apps section, as the committed apps/issue-tracker//ui.js, and drives it through the host's proxy relay (atomic-server#1657, in the pin) against the mock proxy's seeded atomic-fixture/tracker repository.", "e2e": ["integrations/issue-tracker/e2e/issue-tracker.spec.ts"] }, { diff --git a/ontology-kit/served.mjs b/ontology-kit/served.mjs new file mode 100644 index 000000000..08adcebc2 --- /dev/null +++ b/ontology-kit/served.mjs @@ -0,0 +1,116 @@ +/** + * Whether the shared ontology's terms are served at their subjects, with + * exactly the committed bytes: the precondition of a plugin e2e that uses + * them (ontola/atomic-plugins#177). + * + * A plugin bundles the published subjects (`terms.mjs`), so in an e2e the + * pinned atomic-server and the browser fetch those terms from GitHub Pages + * themselves, the same way they do in production: the server once, on first + * use, and the browser through its local-database worker (spike S1). Nothing + * is rewritten. A term that is not on Pages yet (a new class version in the + * same pull request, or Pages lagging behind `main`) would make that e2e fail + * somewhere deep in Set up; `servedProblems` says so up front instead. + * README.md, "Plugin e2e tests and the published subjects", has the reasons. + * + * node ontology-kit/served.mjs classes/bank-transaction-v1 # a class and its properties + * node ontology-kit/served.mjs # every term file + */ +import { readFileSync, readdirSync } from 'node:fs'; +import { join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { readBase, root, TERMS_DIR } from './ontology.mjs'; + +const REQUIRES = 'https://atomicdata.dev/properties/requires'; +const RECOMMENDS = 'https://atomicdata.dev/properties/recommends'; + +/** Every committed term file, as a path under `ontology/`. */ +export function termPaths(base = root) { + const dir = resolve(base, TERMS_DIR); + + return readdirSync(dir, { recursive: true, withFileTypes: true }) + .filter(entry => entry.isFile()) + .map(entry => relative(dir, join(entry.parentPath, entry.name))) + .sort(); +} + +/** + * A class's term file plus those of the properties it requires and + * recommends that this ontology defines (not reused ones such as Atomic's + * `name`), as paths under `ontology/`. + */ +export function classTermPaths(name, base = root) { + const ontologyBase = readBase(base); + const path = `classes/${name}`; + const klass = JSON.parse( + readFileSync(resolve(base, TERMS_DIR, path), 'utf8'), + ); + const properties = [...(klass[REQUIRES] ?? []), ...(klass[RECOMMENDS] ?? [])] + .filter(subject => subject.startsWith(`${ontologyBase}/`)) + .map(subject => subject.slice(ontologyBase.length + 1)); + + return [path, ...properties]; +} + +/** + * The term files of `paths` that are not served at their subject with the + * committed bytes, one line each; empty when all are. One request per file, + * no retries; a cache-busting query avoids Pages' CDN copy. + */ +export async function servedProblems( + paths = termPaths(), + { base = root, fetch: get = fetch, timeoutMs = 15_000 } = {}, +) { + const ontologyBase = readBase(base); + const problems = []; + + await Promise.all( + paths.map(async path => { + const url = `${ontologyBase}/${path}`; + const committed = readFileSync(resolve(base, TERMS_DIR, path)); + + try { + const res = await get(`${url}?v=${Date.now()}`, { + signal: AbortSignal.timeout(timeoutMs), + }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const served = Buffer.from(await res.arrayBuffer()); + if (!served.equals(committed)) + problems.push(`${url}: served bytes differ from ontology/${path}`); + } catch (error) { + problems.push(`${url}: ${error.message}`); + } + }), + ); + + return problems.sort(); +} + +/** The message an e2e fails with when `servedProblems` found any. */ +export const notServedMessage = problems => + `These shared ontology terms are not served at their subjects yet, so the ` + + `server and browser cannot read them:\n ${problems.join('\n ')}\n` + + `A new term is only usable in an e2e once it is on main and GitHub Pages ` + + `serves it (.github/workflows/ontology-published.yml checks that). Land ` + + `the ontology change first, or check this machine can reach the base URL.`; + +if ( + process.argv[1] && + resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + const names = process.argv.slice(2); + const paths = names.length + ? names.flatMap(name => + name.startsWith('classes/') + ? classTermPaths(name.slice('classes/'.length)) + : [name], + ) + : termPaths(); + const problems = await servedProblems([...new Set(paths)]); + + if (problems.length) { + console.error(notServedMessage(problems)); + process.exit(1); + } + + console.info(`${paths.length} term file(s) served as committed`); +} diff --git a/usertest/catalog.mjs b/usertest/catalog.mjs index 54e98e964..c8113f472 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-8', - 'issue-tracker': 'usertest-5', + 'issue-tracker': 'usertest-6', money: 'usertest-2', notion: 'usertest-4', timesheets: 'usertest-3', From e30a35aa5c823771110180fdef1b85d0c20751f9 Mon Sep 17 00:00:00 2001 From: Michiel de Jong Date: Thu, 1 Oct 2026 17:07:39 +0000 Subject: [PATCH 5/6] timesheets 0.5.0: rows are the shared time-entry-v1 class (#177 item 7) - Rows are time-entry-v1: name, work-start, work-end, work-billable, and work-project and work-person as links (#177 Q11), from ontology-kit/terms.mjs and read and written through ontology-kit's strict resolver only (app/fields.ts). - The app makes and owns two more tables under its App, "Projects" (work-project-v1) and "People" (work-person-v1), found again by class. A sync makes a row per active Clockify project and per user an entry names, with Clockify's names (app/links.ts). The Clockify ids stay provider extras of the app's own ontology: clockify-entry-id on time entry rows, clockify-project-id and clockify-user-id on project and person rows. - A link to a project row without a Clockify id is resolved by name when listed to send, as a typed project name was up to 0.4.0. - First open (app/adopt.ts): moves a 0.4.0 table's rows onto time-entry-v1 in place (old fields to shared fields and links, isA rewritten, old values removed), so unsent edits survive (#177 Q10); then the table's classtype, renders and row-extras. - On another time-entry-v1 table (via Add view) the app shows its rows read only and syncs nothing. - e2e checks the three classes are served on Pages first (ontology-kit/served.mjs), uses the real subjects, checks the rows and their links, and adds the app to a hand-made time-entry-v1 table. - Release: apps/timesheets/0.5.0, catalog stays enabled: false, usertest-5, size limit 177,000 bytes (measured 160,904). Co-Authored-By: Claude Opus 5.5 --- apps/timesheets/0.5.0/ui.js | 2 + integrations/READINESS.md | 28 +- integrations/catalog.json | 10 +- integrations/lanes.json | 3 +- integrations/timesheets/README.md | 107 ++++++- integrations/timesheets/app/adopt.test.ts | 269 ++++++++++++++++ integrations/timesheets/app/adopt.ts | 273 +++++++++++++++++ integrations/timesheets/app/build.test.ts | 15 +- .../timesheets/app/controller.test.ts | 46 ++- integrations/timesheets/app/controller.ts | 58 +++- integrations/timesheets/app/fakeStore.ts | 86 ++++-- integrations/timesheets/app/fields.ts | 60 ++++ integrations/timesheets/app/links.ts | 193 ++++++++++++ integrations/timesheets/app/model/rows.ts | 88 ++++++ integrations/timesheets/app/ontology.ts | 62 ++-- integrations/timesheets/app/package.json | 2 +- integrations/timesheets/app/schema.ts | 256 ++++++++++++---- integrations/timesheets/app/sync.test.ts | 103 ++++--- integrations/timesheets/app/sync.ts | 71 +++-- integrations/timesheets/app/ui/shell.ts | 7 +- integrations/timesheets/app/ui/states.ts | 12 + integrations/timesheets/app/writeBack.test.ts | 44 ++- integrations/timesheets/app/writeBack.ts | 288 ++++++++++++------ integrations/timesheets/e2e/clockify.spec.ts | 251 ++++++++++++++- usertest/catalog.mjs | 2 +- 25 files changed, 1992 insertions(+), 344 deletions(-) create mode 100644 apps/timesheets/0.5.0/ui.js create mode 100644 integrations/timesheets/app/adopt.test.ts create mode 100644 integrations/timesheets/app/adopt.ts create mode 100644 integrations/timesheets/app/fields.ts create mode 100644 integrations/timesheets/app/links.ts create mode 100644 integrations/timesheets/app/model/rows.ts diff --git a/apps/timesheets/0.5.0/ui.js b/apps/timesheets/0.5.0/ui.js new file mode 100644 index 000000000..fdf20fdb5 --- /dev/null +++ b/apps/timesheets/0.5.0/ui.js @@ -0,0 +1,2 @@ +var Qi=Object.create;var Ir=Object.defineProperty;var es=Object.getOwnPropertyDescriptor;var ts=Object.getOwnPropertyNames;var ns=Object.getPrototypeOf,rs=Object.prototype.hasOwnProperty;var os=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}};var is=(e,t,n,o)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of ts(t))!rs.call(e,r)&&r!==n&&Ir(e,r,{get:()=>t[r],enumerable:!(o=es(t,r))||o.enumerable});return e};var ss=(e,t,n)=>(n=e!=null?Qi(ns(e)):{},is(t||!e||!e.__esModule?Ir(n,"default",{value:e,enumerable:!0}):n,e));var $o=os((il,Ao)=>{"use strict";Ao.exports=function(e,t){t||(t={}),typeof t=="function"&&(t={cmp:t});var n=typeof t.cycles=="boolean"?t.cycles:!1,o=t.cmp&&(function(i){return function(s){return function(a,c){var l={key:a,value:s[a]},d={key:c,value:s[c]};return i(l,d)}}})(t.cmp),r=[];return(function i(s){if(s&&s.toJSON&&typeof s.toJSON=="function"&&(s=s.toJSON()),s!==void 0){if(typeof s=="number")return isFinite(s)?""+s:"null";if(typeof s!="object")return JSON.stringify(s);var a,c;if(Array.isArray(s)){for(c="[",a=0;a[o.type,o.value]));return Date.UTC(Number(n.year),Number(n.month)-1,Number(n.day),Number(n.hour),Number(n.minute),Number(n.second))}var Sn=(e,t)=>ue(e,t)-Math.floor(e/1e3)*1e3,Cn=(e,t)=>new Date(ue(e,t)).toISOString().replace(/\.\d{3}Z$/,"Z");function Re(e,t){let o=[...new Set([Sn(e-504e5-432e5,t),Sn(e,t),Sn(e+504e5+432e5,t)])].map(i=>e-i),r=o.filter(i=>ue(i,t)===e);return(r.length?r:o).sort((i,s)=>i-s)}var it="clockify",ge=class extends Error{constructor(n,o,r,i){let s=r&&typeof r=="object"&&"message"in r?`: ${String(r.message)}`:"";super(`Clockify request ${n} failed with ${o}${s}`);this.path=n;this.status=o;this.body=r;this.retryAfter=i;this.name="ProxyError"}path;status;body;retryAfter};async function Se(e,t,n){let{status:o,body:r,headers:i}=await e.request(t,n);if(o<200||o>=300)throw new ge(t,o,r,i?.["retry-after"]);return r}var Pr=["unknown_connection","not_delegated","capability_scope","platform_mismatch","credential_refresh_failed"],as=[...Pr,"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 cs(e){let t=e.body,n=typeof t?.error=="string"?t.error:void 0;if(e.status<400||!n||!as.includes(n))return;let o=typeof t?.message=="string"?`: ${t.message}`:"";return new ot(Pr.includes(n)?`The integration proxy refused this connection (${n}${o}). Connect again.`:`The integration proxy refused the request (${n}${o}).`,n)}var ot=class extends Error{constructor(n,o){super(n);this.code=o;this.name="ProxyRefusal"}code};function Wt(e,t){return{async request(n,o,r){let i=await e.request({platform:t.platform,connectionId:t.connectionId,path:n,method:r?.method??"GET",...o?{query:o}:{},...r?.body!==void 0?{body:r.body}:{}}),s=cs(i);if(s)throw s;return i}}}var st=50,at=200;async function ls(e,t,n={}){let o=[];for(let r=1;r<=at;r++){let i=await Se(e,t,{...n,page:String(r),"page-size":String(st)});if(!Array.isArray(i))throw new Error(`Clockify ${t} did not return a list`);if(o.push(...i),i.length{if(!(r instanceof ge)||r.status!==403&&r.status!==404)throw r;n.warnings.push(r.message)};try{let r=await Se(e,"/api/v1/user"),i=r?.settings?.timeZone;typeof r?.settings?.weekStart=="string"&&(n.weekStart=r.settings.weekStart);let s=r?.name??r?.email;typeof s=="string"&&s&&(n.userName=s),Tr(i)?n.timeZone=i:n.warnings.push("Clockify did not name a known time zone for this account; the window is read less precisely.")}catch(r){o(r)}try{let r=await Se(e,"/api/v1/workspaces"),i=Array.isArray(r)?r.find(a=>a?.id===t):void 0,s=i?.settings?.forceProjects;typeof i?.name=="string"&&i.name&&(n.workspaceName=i.name),typeof s=="boolean"&&(n.forceProjects=s)}catch(r){o(r)}return n}async function Nr(e){let t=await Se(e,"/api/v1/user");if(!t||typeof t.id!="string"||!t.id)throw new Error("Clockify did not say which account is connected");let n=await Se(e,"/api/v1/workspaces");if(!Array.isArray(n))throw new Error("Clockify /api/v1/workspaces did not return a list");return{user:t,workspaces:n.filter(o=>o&&typeof o.id=="string"&&typeof o.name=="string")}}async function jn(e,t,n){try{return{items:await ls(e,`/api/v1/workspaces/${encodeURIComponent(t)}/${n}`)}}catch(o){if(o instanceof ge&&(o.status===403||o.status===404))return{items:[],warning:o.message};throw o}}var Dr=e=>e!=null&&e!=="";function ds(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 Ar({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)ds(a),n.set(a.subject,a);let o=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(o.has(a.from))throw new Error(`two lenses map from ${a.from}`);o.set(a.from,a)}let r=a=>{if(n.has(a))return{kind:"shared",class:n.get(a)};let c=o.get(a);return c?{kind:"lens",class:n.get(c.to),lens:c}:null},i=a=>{let c=r(a);if(!c)throw new Error(`${a} is not a class this view renders, and no lens maps it`);return c},s=a=>[...a.requires,...a.recommends];return{classes:[...n.keys()],match:r,accepts:a=>r(a)!==null,read(a,c){let l=i(c),d=l.kind==="lens"?l.lens.read(a):a;if(!d||typeof d!="object")throw new TypeError(`the lens from ${c} returned no row`);let p={};for(let k of s(l.class))Dr(d[k])&&(p[k]=d[k]);let y=l.class.requires.filter(k=>!Dr(p[k]));return{class:l.class.subject,via:l.kind,values:p,missing:y,complete:y.length===0}},write(a,c,l={}){let d=i(c),p=new Set(s(d.class)),y=Object.keys(a).filter(k=>!p.has(k));if(y.length)throw new Error(`${y.join(", ")} ${y.length===1?"is":"are"} not a field of ${d.class.subject}`);if(d.kind==="shared")return{...a};if(typeof d.lens.write!="function")throw new Error(`the lens from ${c} is read-only`);return d.lens.write(a,l)}}}var za=Object.freeze({v1:"https://ontola.github.io/atomic-plugins/ontology/v1"}),He=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"})}),ct=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 te=ct["time-entry-v1"].subject,ze=ct["work-project-v1"].subject,lt=ct["work-person-v1"].subject,L={start:He["work-start"].subject,end:He["work-end"].subject,billable:He["work-billable"].subject,project:He["work-project"].subject,person:He["work-person"].subject},In={start:"start",end:"end",billable:"billable",projectId:"clockify-project-id",projectName:"project",memberId:"clockify-user-id",memberName:"member"},Vt=Ar({classes:[ct["time-entry-v1"]]});function dt(e){return Vt.read(e,te).values}var ne="https://atomicdata.dev",O={name:`${ne}/properties/name`,description:`${ne}/properties/description`,shortname:`${ne}/properties/shortname`,datatype:`${ne}/properties/datatype`,parent:`${ne}/properties/parent`,isA:`${ne}/properties/isA`,properties:`${ne}/properties/properties`,recommends:`${ne}/properties/recommends`,classtype:`${ne}/properties/classtype`,propertyClass:`${ne}/classes/Property`,tableClass:`${ne}/classes/Table`,defaultOntology:`${ne}/ontology/server/property/default-ontology`},U=O.name,G={string:`${ne}/datatypes/string`,timestamp:`${ne}/datatypes/timestamp`,boolean:`${ne}/datatypes/boolean`,integer:`${ne}/datatypes/integer`},X=(e,t,n,o)=>({shortname:e,name:t,datatype:n,description:o}),Rn={entryId:X("clockify-entry-id","Clockify entry id",G.string,"The id of the Clockify time entry this row was imported from.")},En={projectId:X("clockify-project-id","Clockify project id",G.string,"The id of the Clockify project this row stands for."),memberId:X("clockify-user-id","Clockify user id",G.string,"The id of the Clockify user this row stands for.")},Tn={workspaceId:X("clockify-workspace","Clockify workspace id",G.string,"The Clockify workspace this app imports from."),userId:X("clockify-account","Clockify account id",G.string,"The Clockify user whose time entries this app imports."),lookbackDays:X("clockify-lookback-days","Look-back (days)",G.integer,"How many days back each import reads: 7 or 30.")},Pn={log:X("clockify-observation-log","Clockify observation log",G.string,"The subject of this app's Clockify observation log head."),head:X("clockify-log-head","Clockify log head",G.string,"JSON text: the current snapshot, the incrementals after it and what has been read. Written by the timesheets app; do not edit."),observation:X("clockify-observation","Clockify observation",G.string,"JSON text: one read from Clockify, as a diff against what the app knew before. Written by the timesheets app; do not edit."),snapshot:X("clockify-snapshot","Clockify snapshot",G.string,"JSON text: the Clockify mirror folded up to a point in the log. Written by the timesheets app; do not edit."),lease:X("clockify-lease","Clockify send lease",G.string,"JSON text: which open copy of the timesheets app is sending changes to Clockify, and until when (#123 M5). Advisory. Written by the timesheets app; do not edit."),intent:X("clockify-intent","Clockify range edit",G.string,"JSON text: one range edit or conflict resolution made in the timesheets app (#123 M5), with the rows it changed and the edits it replaces. Written by the timesheets app; do not edit."),intentOf:X("clockify-intent-of","Clockify range edit of",G.string,"The Clockify observation log head this range edit belongs to, so the app can find every range edit.")},On={baseline:X("clockify-sync-baseline","Clockify sync baseline",G.string,"JSON text: the values this row and Clockify last agreed on. A row that differs from it has changes to send. Written by the timesheets app; do not edit."),outbox:X("clockify-outbox","Clockify outbox",G.string,"JSON text: a write to Clockify that was started and not yet confirmed; empty when none. Written by the timesheets app; do not edit."),deleteRequested:X("clockify-delete","Delete in Clockify",G.boolean,"True when someone asked to delete this entry in Clockify and it has not been sent yet."),create:X("clockify-create","Clockify create",G.string,"JSON text: this row is a new entry still to be created in Clockify (a range edit, #123 M4), and what it copies; empty once created. Written by the timesheets app; do not edit.")};var Ft=e=>typeof e=="string"&&e?e:null,$r=(e,t)=>`Clockify ${e==="project"?"project":"user"} ${t}`,Je=class{constructor(t,n,o){this.store=t;this.tables=n;this.props=o}store;tables;props;described=new Map;byId={project:new Map,person:new Map};idProperty(t){return t==="project"?this.props.projectId:this.props.memberId}table(t){return t==="project"?this.tables.projects:this.tables.people}async describe(t,n){let o=this.described.get(n);if(o)return o;let r;try{let i=await this.store.getResource(n);r={id:Ft(i.get(this.idProperty(t))),name:Ft(i.get(U))}}catch{r={id:null,name:n}}return this.described.set(n,r),r.id&&!this.byId[t].has(r.id)&&this.byId[t].set(r.id,n),r}nameOf(t,n){let o=this.byId[t].get(n);return o&&this.described.get(o)?.name||void 0}async ensure(t,n,o,r={}){let i=this.byId[t].get(n);if(!i){let s=this.table(t);for(let a of await this.store.query({property:this.idProperty(t),value:n})){let c=await this.store.getResource(a).catch(()=>{});if(c?.get(O.parent)===s){i=a,this.described.set(a,{id:n,name:Ft(c.get(U))});break}}}return i?r.rename&&o&&this.described.get(i)?.name!==o&&(await(await this.store.getResource(i)).set(U,o).save(),this.described.set(i,{id:n,name:o})):(i=(await this.store.newResource({parent:this.table(t),isA:[t==="project"?ze:lt],propVals:{[U]:o??$r(t,n),[this.idProperty(t)]:n}})).subject,this.described.set(i,{id:n,name:o??$r(t,n)})),this.byId[t].set(n,i),i}async named(t){let n=this.tables.projects;for(let r of await this.store.query({property:U,value:t})){let i=await this.store.getResource(r).catch(()=>{});if(i?.get(O.parent)===n&&!Ft(i.get(this.props.projectId)))return this.described.set(r,{id:null,name:t}),r}let o=await this.store.newResource({parent:n,isA:[ze],propVals:{[U]:t}});return this.described.set(o.subject,{id:null,name:t}),o.subject}};var Lr=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],Mr={projects:"Projects",people:"People"};async function Kt(e){let t=await e.getData();if(!t?.table||!t.rowClass)throw new Error("This app has no table with a row class to import into.");let n=await e.getApp(),o=(await e.getResource(n)).get(O.defaultOntology);if(typeof o!="string"&&t.rowClass!==te&&(o=(await e.getResource(t.rowClass)).get(O.parent)),typeof o!="string")throw new Error("This app has no ontology of its own to add fields to.");let r=await e.getResource(t.table);return{app:n,table:t.table,rowClass:t.rowClass,ontology:o,own:r.get(O.parent)===n}}async function _r(e,t){let n=await e.getResource(t),o=new Map;for(let r of Lr(n.get(O.properties))){let i=await e.getResource(r),s=i.get(O.shortname);typeof s=="string"&&o.set(s,i)}return o}function pt(e,t){let n={};for(let o of Object.keys(e)){let r=t.get(e[o].shortname);r&&r.get(O.datatype)===e[o].datatype&&(n[o]=r.subject)}return n}async function Nn(e,t,n){for(let o of await e.query({property:O.classtype,value:n}))if((await e.getResource(o).catch(()=>{}))?.get(O.parent)===t)return o}async function Ze(e){let t=await Kt(e),n=await _r(e,t.ontology),o=await Nn(e,t.app,ze),r=await Nn(e,t.app,lt);return{...t,row:{...L,...pt(Rn,n)},link:pt(En,n),settings:pt(Tn,n),log:pt(Pn,n),sync:pt(On,n),tables:{...o?{projects:o}:{},...r?{people:r}:{}}}}async function Dn(e,t){let n=await e.getResource(t.ontology),o=await _r(e,t.ontology),r=[],i=async y=>{let k=o.get(y.shortname);if(k){if(k.get(O.datatype)!==y.datatype)throw new Error(`The field "${y.name}" already exists with another datatype.`);return k.subject}let f=await e.newResource({parent:n.subject,isA:[O.propertyClass],propVals:{[O.shortname]:y.shortname,[O.name]:y.name,[O.datatype]:y.datatype,[O.description]:y.description}});return r.push(f.subject),o.set(y.shortname,f),f.subject},s=async y=>{let k={};for(let f of Object.keys(y))k[f]=await i(y[f]);return k},a=await s(Rn),c=await s(En),l=await s(Tn),d=await s(Pn),p=await s(On);return r.length&&(n.set(O.properties,[...Lr(n.get(O.properties)),...r]),await n.save()),{row:a,link:c,settings:l,log:d,sync:p}}async function An(e,t){let n=async(o,r)=>await Nn(e,t,o)??(await e.newResource({parent:t,isA:[O.tableClass],propVals:{[O.name]:r,[O.classtype]:o,[O.description]:"Filled by the Clockify timesheets app from what it last read in Clockify; time entries link to these rows. Names follow Clockify: a name changed here is set back on the next sync."}})).subject;return{projects:await n(ze,Mr.projects),people:await n(lt,Mr.people)}}async function Ee(e){let t=await Kt(e);if(!t.own)throw new Error("This table is not the app\u2019s own: the app syncs only its own table.");let n=await Dn(e,t),o=await An(e,t.app);return{...t,...n,row:{...L,...n.row},tables:o,links:new Je(e,o,n.link)}}var qe=e=>Array.isArray(e)?e.filter(t=>typeof t=="string"):[],Ht=e=>typeof e=="string"&&e?e:null,ps=(e,t)=>e.length===t.length&&e.every(n=>t.includes(n)),us=["entryId","baseline","outbox","deleteRequested","create"];async function fs(e,t,n){let o=new Map,r=qe((await e.getResource(t)).get(O.properties));for(let i of r){let s=await e.getResource(i).then(a=>a.get(O.shortname)).catch(()=>{});typeof s=="string"&&n.includes(s)&&o.set(s,i)}return o}async function ms(e,t,n){let o=new Map;for(let r of qe(t.get(O.isA))){let i=await e.getResource(r).then(s=>qe(s.get(O.recommends))).catch(()=>[]);for(let s of i){let a=await e.getResource(s).then(c=>c.get(O.shortname)).catch(()=>{});typeof a=="string"&&n.includes(a)&&o.set(a,s)}}return o}async function gs(e,t,n){let o=!1,r=d=>{let p=t[d];if(!p)return;let y=e.get(p);if(y!==void 0)return e.remove(p),o=!0,y};for(let d of["start","end","billable"]){let p=r(d),y=e.get(L[d]);p!==void 0&&p!==""&&(y==null||y==="")&&e.set(L[d],p)}let i=Ht(r("projectId")??null),s=Ht(r("projectName")??null),a=Ht(r("memberId")??null),c=Ht(r("memberName")??null);if(e.get(L.project)===void 0&&(i||s)){let d;try{d=JSON.parse(String(e.get(n.sync.baseline)??""))}catch{d=void 0}let p=!!s&&!!d&&(d.projectId??null)===i&&d.project!==s;e.set(L.project,i&&!p?await n.links.ensure("project",i,s):await n.links.named(s??i))}e.get(L.person)===void 0&&a&&e.set(L.person,await n.links.ensure("person",a,c));let l=qe(e.get(O.isA));return(l.length!==1||l[0]!==te)&&(e.set(O.isA,[te]),o=!0),o&&await e.save(),o}async function Wr(e){let t=await Kt(e),n=0,o=await Dn(e,t);if(t.own&&t.rowClass!==te){let l=await An(e,t.app),d=new Je(e,l,o.link),p=await fs(e,t.ontology,Object.values(In)),y={};for(let[f,m]of Object.entries(In)){let b=p.get(m);b&&(y[f]=b)}for(let f of await e.query({property:O.parent,value:t.table}))await gs(await e.getResource(f),y,{links:d,sync:o.sync})&&n++;await(await e.getResource(t.table)).set(O.classtype,te).save()}let r=await e.getResource(t.app),i=await ms(e,r,["renders","row-extras"]),s=i.get("renders"),a=i.get("row-extras"),c=!1;if(s){let l=qe(r.get(s));l.includes(te)||(r.set(s,[...l,te]),c=!0)}if(a){let l=us.map(d=>d==="entryId"?o.row.entryId:o.sync[d]);ps(qe(r.get(a)),l)||(r.set(a,l),c=!0)}return c&&await r.save(),{own:t.own,migrated:n}}var Vr={TIMESTAMP:"https://atomicdata.dev/datatypes/timestamp"};var Ue="clockify",$n="timeentry",ys="project",bs="member",Te={start:"start",end:"end"},hs=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{},Fr=e=>{if(typeof e!="string")return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0};function Mn(e){if(e.platform!==Ue)return e;let t=e.ontology.terms.find(i=>i.kind==="class"&&i.shortname===$n);if(!t)return e;let o=[[Te.start,"Start instant of the entry, from Clockify's UTC interval."],[Te.end,"End instant of the completed entry, from Clockify's UTC interval."]].map(([i,s])=>({path:`urn:atomic:clockify:${i}`,kind:"property",shortname:i,datatype:Vr.TIMESTAMP,description:s,requires:[],recommends:[]}));if(e.ontology.terms.some(i=>o.some(s=>s.shortname===i.shortname)))throw new Error("Clockify projection property collides with provider ontology");let r=[];for(let i of e.records){if(i.resource!==$n){r.push(i);continue}if(i.values.type==="BREAK")continue;let s=hs(i.values.timeinterval),a=Fr(s.start),c=Fr(s.end);if(a===void 0)throw new Error(`Clockify entry ${i.id} has no valid start`);if(c===void 0)continue;if(ci===t?{...i,recommends:[...i.recommends,...o.map(s=>s.path)]}:i),...o]},records:r}}function Ln(e){if(e.platform!==Ue)return[];let t=new Map(e.records.filter(r=>r.resource===ys).map(r=>[r.id,r])),n=new Map(e.records.filter(r=>r.resource===bs).map(r=>[r.id,r])),o=[];for(let r of e.records){if(r.resource!==$n)continue;let i=typeof r.values.projectid=="string"?r.values.projectid:void 0,s=typeof r.values.userid=="string"?r.values.userid:void 0;i===void 0&&s===void 0||o.push({timeEntryId:r.id,...i===void 0?{}:{projectId:i},...s===void 0?{}:{userId:s},...i!==void 0&&t.has(i)?{project:t.get(i)}:{},...s!==void 0&&n.has(s)?{member:n.get(s)}:{}})}return o}var ws={BREAK:"break",HOLIDAY:"holiday",TIME_OFF:"timeOff"},Kr=e=>typeof e=="string"?Date.parse(e):NaN;function Hr(e,t){let{start:n,end:o,projectId:r,type:i,isLocked:s,customFieldValues:a}=e.fields,c=Kr(n),l=o==null,d=l?t:Kr(o);if(!Number.isFinite(c)||!Number.isFinite(d)||!(d>c))return;let p=typeof i=="string"?ws[i]:void 0;return{entryId:e.id,from:n,to:l?new Date(t).toISOString().replace(/\.\d{3}Z$/,"Z"):o,label:p?{kind:"didNotWork",badge:p}:{kind:"worked",projectId:typeof r=="string"&&r?r:null},...l?{open:!0}:{},...s===!0?{locked:!0}:{},...Array.isArray(a)&&a.length?{customFields:!0}:{}}}var ft=["name","projectId","billable","start","end"],Be="Time entry";var zr=e=>{if(typeof e!="string")return;let t=Date.parse(e);return Number.isFinite(t)?t:void 0},ut=e=>new Date(Math.floor(e/1e3)*1e3).toISOString().replace(/\.\d{3}Z$/,"Z");function ye(e,t){if((e.type??"REGULAR")!=="REGULAR")return;let n=zr(e.timeInterval?.start),o=zr(e.timeInterval?.end);if(n===void 0||o===void 0||o{let t=e.trim();return t===Be?"":t};function mt(e,t){return ft.filter(n=>e[n]!==t[n])}var gt=e=>Math.floor(e/6e4)*6e4;function Me(e,t,n){let o=[],r=e.type??"REGULAR";if(e.timeInterval?.end||o.push("It is a running timer. Stop it in Clockify first."),r!=="REGULAR"&&o.push(`It is a ${r.toLowerCase().replace("_"," ")} entry.`),e.isLocked===!0&&o.push("It is locked in Clockify."),Array.isArray(e.customFieldValues)&&e.customFieldValues.length&&o.push("It has custom field values, which this app cannot write back yet."),!n)return o;if(n.startt.now&&o.push("End is in the future."),t.forceProjects&&!n.projectId&&o.push("This workspace requires a project on every entry."),n.projectId&&n.projectId!==(e.projectId??null)){let i=t.projects.find(s=>s.id===n.projectId);i?i.archived===!0&&o.push(`The project ${i.name} is archived.`):o.push("The project is not one of this workspace\u2019s projects.")}return o}function Jr(e,t){let n=ye(e);if(!n)throw new Error(`Clockify entry ${e.id} is not a completed entry`);let o=new Set(mt(n,t)),r=o.has("projectId")?t.projectId:n.projectId,i=!o.has("projectId")&&typeof e.taskId=="string"?e.taskId:void 0;return{start:o.has("start")?ut(t.start):e.timeInterval.start,end:o.has("end")?ut(t.end):e.timeInterval.end,billable:o.has("billable")?t.billable:n.billable,description:o.has("name")?Ye(t.name):typeof e.description=="string"?e.description:"",...r?{projectId:r}:{},...i?{taskId:i}:{},tagIds:Array.isArray(e.tagIds)?[...e.tagIds]:[],type:e.type??"REGULAR"}}var Zr=e=>typeof e=="string"?Date.parse(e):NaN;function qr(e,t){return t.to<=e.from||t.from>=e.to?[e]:[...t.from>e.from?[{from:e.from,to:t.from}]:[],...t.to{let n=Math.max(e.from,t.from),o=Math.min(e.to,t.to);return ne.start-t.start||(e.idt.id?1:0),_n=(e,t)=>t&&e.projects.find(n=>n.id===t)?.name||null;function vs(e,t,n){let o=[],r={from:t.from,to:t.to};if(t.fromn.now&&o.push("The range ends in the future."),t.target.kind==="worked"){let{projectId:a}=t.target;if(a===null)n.forceProjects&&o.push("This workspace requires a project on every entry.");else{let c=n.projects.find(l=>l.id===a);c?c.archived===!0&&o.push(`The project ${c.name} is archived.`):o.push("The project is not one of this workspace\u2019s projects.")}}let i=new Set,s=a=>{i.has(a)||o.push(a),i.add(a)};for(let a of e){let c=Zr(a.timeInterval?.start),l=a.timeInterval?.end?Zr(a.timeInterval.end):Math.max(n.now,c);if(!Number.isFinite(c)||!Number.isFinite(l)||!yt({from:c,to:l},r))continue;let d=a.type??"REGULAR";a.timeInterval?.end?d!=="REGULAR"?t.target.kind==="worked"&&s(`A ${d.toLowerCase().replace("_"," ")} entry is in this range; it can only be changed in Clockify.`):a.isLocked===!0?s("A locked entry is in this range."):Array.isArray(a.customFieldValues)&&a.customFieldValues.length&&s("An entry with custom field values is in this range; this app cannot write those back yet."):s("A running timer is in this range. Stop it in Clockify first.")}return o}function Yr(e,t,n){let o=vs(e,t,n);if(o.length)return{steps:[],refused:o};let r={from:t.from,to:t.to},i=f=>_n(n,f)??void 0,s=t.target.kind==="worked"?t.target.projectId:void 0,a=f=>f.isLocked!==!0&&!(Array.isArray(f.customFieldValues)&&f.customFieldValues.length),c=e.map(f=>({entry:f,values:ye(f,i)})).filter(f=>!!f.values&&a(f.entry)&&(!!yt({from:f.values.start,to:f.values.end},r)||f.values.projectId===s&&(f.values.end===r.from||f.values.start===r.to))).map(f=>({...f,id:f.entry.id,start:f.values.start})).sort(ks),l=new Map(c.map(f=>[f.id,[{from:f.values.start,to:f.values.end}]])),d=new Map(c.map(f=>[f.id,f.values.projectId])),p=(f,m)=>l.set(f,l.get(f).flatMap(b=>qr(b,m))),y=[];if(t.target.kind==="didNotWork")for(let f of c)p(f.id,r);else{let f=c.filter(v=>v.values.projectId===s),m=c.filter(v=>v.values.projectId!==s),b=f.some(v=>!!yt({from:v.values.start,to:v.values.end},r))?void 0:m.find(v=>v.values.start===r.from&&v.values.end===r.to);b&&d.set(b.id,t.target.projectId);for(let v of m)v!==b&&p(v.id,r);let T=b?[r]:[];for(let v of f){for(let R of T){let $=yt({from:v.values.start,to:v.values.end},R);$&&p(v.id,$)}for(let R of l.get(v.id)){let $=yt(R,r);$&&T.push($)}}let S=[r];for(let v of T)S=S.flatMap(R=>qr(R,v));let I=()=>c.filter(v=>d.get(v.id)===s).flatMap(v=>l.get(v.id));for(let v of S){let R=I(),$=R.find(ae=>ae.to===v.from),oe=R.find(ae=>ae.from===v.to);$?$.to=v.to:oe?oe.from=v.from:y.push(v)}}let k=[];for(let f of c){let m=[...l.get(f.id)].sort(($,oe)=>$.from-oe.from),b=d.get(f.id)??null,T=b!==f.values.projectId,S=T?_n(n,b):f.values.project;if(!m.length){k.push({op:"delete",entryId:f.id,phase:"shrink"});continue}let[I,...v]=m,R={...f.values,start:I.from,end:I.to,projectId:b,project:S};(R.start!==f.values.start||R.end!==f.values.end||T)&&k.push({op:"update",entryId:f.id,current:f.values,desired:R,phase:!T&&R.start>=f.values.start&&R.end<=f.values.end?"shrink":"grow"});for(let $ of v)k.push({op:"create",values:{...R,start:$.from,end:$.to},copyOf:f.id,phase:"grow"})}if(t.target.kind==="worked"){let{projectId:f}=t.target;for(let m of y)k.push({op:"create",values:{name:Be,start:m.from,end:m.to,billable:n.billableDefault?.(f)??!1,projectId:f,project:_n(n,f)},phase:"grow"})}return{steps:xs(k),refused:[]}}var Ur={delete:0,update:1,create:2},Br=e=>e.op==="create"?e.values.start:e.op==="update"?e.desired.start:0,xs=e=>[...e].sort((t,n)=>(t.phase===n.phase?0:t.phase==="shrink"?-1:1)||Ur[t.op]-Ur[n.op]||Br(t)-Br(n));var Gr=[7,30];var Xr=e=>typeof e=="string"&&e.trim()?e.trim():void 0,Ss=e=>Gr.find(t=>String(t)===String(e));function Wn(e,t){let n=s=>s?e(s):void 0,o=Xr(n(t.settings.workspaceId)),r=Xr(n(t.settings.userId)),i=Ss(n(t.settings.lookbackDays));return o&&r&&i?{ok:!0,settings:{workspaceId:o,userId:r,lookbackDays:i}}:{ok:!1,missing:[...o?[]:["workspaceId"],...r?[]:["userId"],...i?[]:["lookbackDays"]],partial:{...o?{workspaceId:o}:{},...r?{userId:r}:{},...i?{lookbackDays:i}:{}}}}var Cs=6e4,Vn=864e5,Qr=["MONDAY","TUESDAY","WEDNESDAY","THURSDAY","FRIDAY","SATURDAY","SUNDAY"],qt=e=>Qr.find(t=>t===String(e).toUpperCase())??"MONDAY",eo=e=>Math.round(Math.max(0,e)/Cs);function fe(e){let t=eo(e);return`${Math.floor(t/60)}:${String(t%60).padStart(2,"0")}`}function he(e){let t=eo(e),n=Math.floor(t/60),o=t%60;return[...n?[`${n} ${n===1?"hour":"hours"}`]:[],...o||!n?[`${o} ${o===1?"minute":"minutes"}`]:[]].join(" ")}var zt=e=>String(e).padStart(2,"0"),to=e=>{let t=new Date(e);return`${t.getUTCFullYear()}-${zt(t.getUTCMonth()+1)}-${zt(t.getUTCDate())}`},Jt=e=>Date.parse(`${e}T00:00:00Z`),_=(e,t)=>to(Math.floor(ue(e,t)/Vn)*Vn),be=(e,t)=>to(Jt(e)+t*Vn),Fn=e=>(new Date(Jt(e)).getUTCDay()+6)%7;function Le(e,t){let[n]=Re(Jt(e),t);return _(n,t)===e?n:Math.max(...Re(Jt(e),t))}function js(e,t){let n=(Fn(e)-Qr.indexOf(t)+7)%7,o=be(e,-n);return{start:o,days:[0,1,2,3,4,5,6].map(r=>be(o,r))}}var no=(e,t,n)=>js(_(e,n),t),Kn=(e,t)=>({start:be(e.start,7*t),days:e.days.map(o=>be(o,7*t))}),ro=(e,t)=>({from:Le(e.start,t),to:Le(be(e.start,7),t)}),oo=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],io=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],Zt=e=>{let[t,n,o]=e.split("-").map(Number);return{y:t,m:n,d:o}},Ut=e=>Zt(e).d,Ge=e=>io[Fn(e)].slice(0,3),_e=e=>io[Fn(e)];function H(e,t=!1){let{y:n,m:o,d:r}=Zt(e);return`${r} ${oo[o-1]}${t?` ${n}`:""}`}function Pe(e,t,n=!0){let o=Zt(e),r=Zt(t),i=n?` ${r.y}`:"";return o.y!==r.y&&n?`${H(e,!0)} \u2013 ${H(t,!0)}`:o.m===r.m?`${o.d} \u2013 ${r.d} ${oo[r.m-1]}${i}`:`${H(e)} \u2013 ${H(t)}${i}`}function re(e,t){let n=new Date(ue(e,t));return`${zt(n.getUTCHours())}:${zt(n.getUTCMinutes())}`}var so=()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC"}catch{return"UTC"}};function Hn(e,t){let n=Math.max(0,Math.round((t-e)/1e3));if(n<60)return"just now";let o=Math.floor(n/60);if(o<60)return`${o} min ago`;let r=Math.floor(o/60);return r<48?`${r} h ago`:`${Math.floor(r/24)} days ago`}async function ao(e,t,n){let o=new Map,r=async a=>{if(!(typeof a!="string"||!a)){if(!o.has(a)){let c=await e.getResource(a).then(l=>l.get(U)).catch(()=>{});o.set(a,typeof c=="string"&&c?c:void 0)}return o.get(a)}},i=[],s=0;for(let a of await e.query({property:O.parent,value:t})){let c=await e.getResource(a).catch(()=>{});if(!c)continue;let l=dt(c.props),d=l[L.start],p=l[L.end];if(typeof d!="number"||typeof p!="number"){s++;continue}let y=l[L.project],k=await r(y),f=typeof y=="string"?{id:y,...k?{name:k}:{}}:void 0,m=await r(l[L.person]),b=l[U];i.push({id:a,description:typeof b=="string"?b:"",start:d,end:p,billable:l[L.billable]===!0,...f?{project:f}:{},...m?{member:m}:{}})}return i.sort((a,c)=>a.start-c.start||(a.id({records:{},coverage:[]}),zn=(e,t)=>`${e}/${t}`,K=e=>Date.parse(e);function Bt(e,t){let n=K(e.receivedAt)-K(t.receivedAt);return n!==0?n:e.receivedAt!==t.receivedAt?e.receivedAt`${JSON.stringify(t)}:${bt(e[t])}`).join(",")}}`:JSON.stringify(e)}function Is(e){let t=2166136261;for(let n=0;n>>0;return t.toString(16).padStart(8,"0")}function ht(e){let t=Object.keys(e.params).sort().map(n=>`${n}=${e.params[n]}`).join("&");return`${e.collection}?${t}#${e.field}`}function Rs(e,t){if(t.collection!==e.collection)return!1;if(e.type==="id")return t.id===e.id;for(let[r,i]of Object.entries(e.params))if(t.fields[r]!==i)return!1;let n=t.fields[e.field];if(typeof n!="string")return!1;let o=K(n);return o>=K(e.from)&&o{let n={};for(let o of t)n[o]=e[o]??null;return n};function co(e,t){let{records:n,...o}=t,{collection:r}=t.scope,i=[],s=new Set,a=0;for(let l of n){s.add(l.id);let d=Es(l.fields,t.mask),p=e.records[zn(r,l.id)];p&&!p.absentSince&&!p.deletedAt&&t.mask.every(k=>bt(p.fields[k]??null)===bt(d[k]))?a++:i.push({id:l.id,fields:d})}let c=t.complete?Object.values(e.records).filter(l=>!l.deletedAt&&(!l.absentSince||t.scope.type==="id")&&!s.has(l.id)&&Rs(t.scope,l)).map(l=>l.id).sort():[];return{v:1,...o,upserts:i,absent:c,unchanged:a,digest:Is(bt([...n].sort((l,d)=>l.idd.id?1:0).map(l=>({id:l.id,fields:l.fields}))))}}var lo=e=>!e.upserts.length&&!e.absent.length;function po(e,t,n,o,r){if(!(K(n)p.key===t),s=e.filter(p=>p.key!==t),a=[...i,{key:t,from:n,to:o,confirmedAt:r}],c=new Map;for(let p of a)c.has(K(p.from))||c.set(K(p.from),p.from),c.has(K(p.to))||c.set(K(p.to),p.to);let l=[...c.keys()].sort((p,y)=>p-y),d=[];for(let p=0;p+1K(T.from)<=y&&K(T.to)>=k);if(!f.length)continue;let m=f.map(T=>T.confirmedAt).reduce((T,S)=>K(S)>K(T)?S:T),b=d.at(-1);b&&K(b.to)===y&&b.confirmedAt===m?b.to=c.get(k):d.push({key:t,from:c.get(y),to:c.get(k),confirmedAt:m})}return[...s,...d]}function wt(e,t){return t.reduce((n,o)=>po(n,o.key,o.from,o.to,o.confirmedAt),e)}var Ts=e=>[...e].sort((t,n)=>(t.keyn.key?1:0)||K(t.from)-K(n.from));function Ps(e,t){let{collection:n}=t.scope;for(let o of t.upserts){let r=zn(n,o.id),i=e.records[r];e.records[r]={id:o.id,collection:n,fields:{...i?.fields??{},...o.fields},lastSeenAt:t.receivedAt}}for(let o of t.absent){let r=e.records[zn(n,o)];r&&(t.scope.type==="id"?(r.deletedAt=t.receivedAt,delete r.absentSince):!r.deletedAt&&!r.absentSince&&(r.absentSince=t.receivedAt))}t.complete&&t.scope.type==="range"&&(e.coverage=po(e.coverage,ht(t.scope),t.scope.from,t.scope.to,t.receivedAt))}function kt(e,t){let n=structuredClone(e);for(let o of[...t].sort(Bt))Ps(n,o);return n.coverage=Ts(n.coverage),n}var Oe="timeEntry",Os="method or path is not in the catalog",Ns="Time entry doesn't belong to Workspace",Ds=36e5,vt=24*Ds,Zn=["start","end","projectId","taskId","description","billable","tagIds","type","isLocked","userId","workspaceId","customFieldValues","extra"],xt=[...Zn],fo=e=>e===void 0?null:JSON.parse(JSON.stringify(e));function St(e){let{id:t,timeInterval:n,...o}=e,{start:r,end:i,...s}=n??{},a={},c={start:typeof r=="string"?r:null,end:typeof i=="string"?i:null};for(let[l,d]of Object.entries(o))Zn.includes(l)?c[l]=fo(d):a[l]=d;for(let l of Zn)!(l in c)&&l!=="extra"&&(c[l]=null);return Object.keys(s).length&&(a.timeInterval=s),c.extra=fo(a),{id:t,fields:c}}function Ce(e){let{start:t,end:n,extra:o,...r}=e.fields,{timeInterval:i,...s}=o&&typeof o=="object"&&!Array.isArray(o)?o:{};return{...s,...r,id:e.id,timeInterval:{...i&&typeof i=="object"?i:{},start:typeof t=="string"?t:null,end:typeof n=="string"?n:null}}}var Yt=e=>new Date(e).toISOString(),Gt=e=>new Date(e).toISOString().replace(/\.\d{3}Z$/,"Z"),Jn=e=>`/api/v1/workspaces/${encodeURIComponent(e.workspaceId)}/user/${encodeURIComponent(e.userId)}/time-entries`;function go(e,t,n){return{type:"range",collection:Oe,params:{workspaceId:e.workspaceId,userId:e.userId},field:"start",from:t,to:n}}function As(e,t,n){let[o,r]=[e,t].map(i=>Math.floor(i/1e3)*1e3);return n?{query:{start:Cn(o,n),end:Cn(r,n)},from:Math.max(...Re(ue(o,n),n)),to:Math.min(...Re(ue(r,n),n))}:{query:{start:Gt(o),end:Gt(r)},from:o+504e5,to:r-504e5}}async function Xt(e,t,n){let o=As(t,n,e.timeZone),r=go(e,Gt(o.from),Gt(Math.max(o.from,o.to))),i=Yt(e.clock()),s=[],a,c=!1;for(let l=1;l<=at;l++){let d;try{if(d=await Se(e.transport,Jn(e),{...o.query,page:String(l),"page-size":String(st)}),!Array.isArray(d))throw new Error(`Clockify ${Jn(e)} did not return a list`)}catch(p){if(l===1)throw p;a=p;break}for(let p of d)p&&typeof p.id=="string"&&s.push(St(p));if(d.length[...new Map(e.map(t=>[t.id,t])).values()];function Ms(e){if(!(e instanceof ge))return!1;let t=e.body&&typeof e.body=="object"&&"message"in e.body?e.body.message:void 0;return e.status===400?t===Ns:e.status===404&&e.body!==Os}async function Qt(e,t){let n=Yt(e.clock()),o=`/api/v1/workspaces/${encodeURIComponent(e.workspaceId)}/time-entries/${encodeURIComponent(t)}`,r;try{let i=await Se(e.transport,o);if(!i||i.id!==t)throw new Error(`Clockify ${o} returned another entry`);r=[St(i)]}catch(i){if(!Ms(i))throw i;r=[]}return{id:e.newId(),device:e.device,sentAt:n,receivedAt:Yt(e.clock()),kind:"point",scope:{type:"id",collection:Oe,id:t},mask:xt,complete:!0,records:r}}var se=e=>Object.values(e.records).filter(t=>t.collection===Oe),en=e=>se(e).filter(t=>t.absentSince&&!t.deletedAt).sort((t,n)=>t.id{let{start:n,end:o}=e.fields;if(typeof n!="string")return;let r=K(n),i=typeof o=="string"?K(o):t;return Number.isFinite(r)&&Number.isFinite(i)&&i>r?{from:r,to:i}:void 0};function Ls(e,t){let n=vt;for(let o of se(e)){if(o.deletedAt)continue;let r=yo(o,t);r&&(n=Math.max(n,r.to-r.from))}return n}function _s(e){let t=[];for(let n of[...e].sort((o,r)=>o.from-r.from)){let o=t.at(-1);o&&n.from<=o.to?o.to=Math.max(o.to,n.to):t.push({...n})}return t}function mo(e,t){return e.flatMap(n=>t.to<=n.from||t.from>=n.to?[n]:[...t.from>n.from?[{from:n.from,to:t.from}]:[],...t.toc.key===r).map(c=>({from:K(c.from),to:K(c.to)})))){let c=a.from+i;cd.from-p.from))}return s.filter(a=>a.to>a.from)}var bo=e=>e.reduce((t,n)=>t+(n.to-n.from),0);var Ws=e=>Object.fromEntries(Object.entries(e).map(([t,n])=>[t.toLowerCase(),n])),qn=(e,t,n,o)=>({resource:e,namespace:Ue,id:t,name:n,values:Ws(o)}),Vs=e=>({path:`urn:atomic:clockify:${e}`,kind:"class",shortname:e,description:`Clockify ${e}`,datatype:"https://atomicdata.dev/datatypes/resourceArray",requires:[],recommends:[]});function Fs(e,t,n){return{platform:Ue,ontology:{description:"Clockify, fetched by the timesheets drive app",terms:["timeentry","project","member"].map(Vs)},records:[...e.map(o=>qn("timeentry",o.id,"",o)),...t.map(o=>qn("project",o.id,o.name,o)),...n.map(o=>qn("member",o.id,o.name,o))]}}var ho=e=>typeof e=="string"&&e?e:void 0;function tn(e,t,n){let o=Mn(Fs(e,t,n)),r=new Map(Ln(o).map(i=>[i.timeEntryId,i]));return o.records.filter(i=>i.resource==="timeentry").map(i=>{let s=r.get(i.id),a=i.values.billable;return{entryId:i.id,name:i.name,start:i.values[Te.start],end:i.values[Te.end],...typeof a=="boolean"?{billable:a}:{},...s?.projectId?{projectId:s.projectId}:{},...ho(s?.project?.name)?{projectName:s.project.name}:{},...s?.userId?{memberId:s.userId}:{},...ho(s?.member?.name)?{memberName:s.member.name}:{}}})}var Ks=(e,t)=>(e.fields.workspaceId??t.workspaceId)===t.workspaceId&&(e.fields.userId??t.userId)===t.userId;function Hs(e,t,n){return se(e).filter(o=>!o.deletedAt&&!o.absentSince&&Ks(o,t)).map(o=>Hr(o,n)).filter(o=>!!o).sort((o,r)=>Date.parse(o.from)-Date.parse(r.from)||(o.entryIdr.entryId?1:0))}var jt=e=>e.kind==="worked"?`0${e.projectId===null?"1":`0${e.projectId}`}`:`1${e.badge??""}`,zs=(e,t)=>jt(e)jt(t)?1:0;function Js(e,t,n){if(t)return{state:"unknown",entryIds:[],readOnly:["unknown"]};if(!e.length)return{state:"didNotWork",label:{kind:"didNotWork"},entryIds:[],readOnly:[]};let o=e.map(l=>l.entryId).sort(),r=[...new Map(e.map(l=>[jt(l.label),l.label])).values()].sort(zs),i=r.filter(l=>l.kind==="worked"),s=new Set;for(let l of e)l.open&&s.add("running"),l.locked&&s.add("locked"),l.label.kind==="didNotWork"&&s.add("entryType"),l.customFields&&s.add("customFields"),n&&l.label.kind==="worked"&&l.label.projectId===null&&s.add("forceProjects");let a={entryIds:o,readOnly:[...s].sort(),...e.some(l=>l.open)?{open:!0}:{}};return i.length?r.length===1?{state:"worked",label:r[0],...e.length>1?{duplicate:!0}:{},...a}:{state:"conflict",conflict:{kind:i.lengthJSON.stringify({...e,from:0,to:0});function ko(e){let t=[];for(let n of e){let o=t.at(-1);o&&o.to===n.from&&wo(o)===wo(n)?o.to=n.to:t.push({...n})}return t}function Zs(e,t,n){let o=[];for(let r=_(e,n);;r=be(r,1)){let i=Le(r,n);if(i>=t)break;o.push({day:r,from:i,to:Math.min(t,Le(be(r,1),n))})}return o}function vo(e){let{mirror:t,settings:n,window:o,now:r,timeZone:i}=e,s=Zs(o.from,r,i),a={from:s[0]?.from??o.from,to:r},c=Ct(t,n,a,r),l=Hs(t,n,r).map(m=>({claim:m,from:Math.max(a.from,Date.parse(m.from)),to:Math.min(a.to,Date.parse(m.to))})).filter(m=>m.to>m.from),d=new Set([a.from,a.to]);for(let m of s)d.add(m.from).add(m.to);for(let m of l)d.add(m.from).add(m.to);for(let m of c)d.add(m.from).add(m.to);let p=[...d].filter(m=>m>=a.from&&m<=a.to).sort((m,b)=>m-b),y=[];for(let m=0;m+1v.from<=b&&v.to>=T).map(v=>v.claim),I=c.some(v=>v.from<=b&&v.to>=T);y.push({from:b,to:T,...Js(S,I,e.forceProjects===!0)})}let k=s.map(m=>({...m,segments:ko(y.filter(b=>b.from>=m.from&&b.to<=m.to))})),f=ko(y.filter(m=>m.state==="conflict"||m.duplicate)).map(m=>({entryId:m.entryIds[0],entryIds:m.entryIds,fields:m.duplicate?["start","end"]:m.conflict.kind==="whichProject"?["projectId"]:["type"],kind:m.duplicate?"duplicate":m.conflict.kind,candidates:m.duplicate?[m.label]:m.conflict.candidates,from:m.from,to:m.to}));return{timeZone:i,window:o,days:k,unknown:Ct(t,n,o,r),conflicts:f}}var qs=864e5,It=e=>typeof e=="string"&&e?e:void 0;function nn(e,t){if(!e)return;let n=t.find(s=>s.id===e),o=It(n?.name),r=It(n?.color),i=It(n?.clientName);return{id:e,...o?{name:o}:{},...r&&/^#[0-9a-f]{3,8}$/i.test(r)?{color:r}:{},...i?{client:i}:{}}}var Us=(e,t)=>!t||(e.fields.workspaceId??t.workspaceId)===t.workspaceId&&(e.fields.userId??t.userId)===t.userId;function xo(e){let{mirror:t,settings:n,now:o,timeZone:r}=e,i=e.projects??[],s=e.members??[],a=n?{from:o-n.lookbackDays*qs,to:o}:void 0,c=se(t).filter(S=>!S.deletedAt&&Us(S,n)),l=new Map(c.map(S=>[S.id,S])),d=S=>{let I=S.fields.start;return typeof I!="string"?!1:!a||K(I)>=a.from&&K(I)Number.isFinite(S.start)&&Number.isFinite(S.end)).map(S=>{let I=l.get(S.entryId)?.fields??{},v=nn(It(I.projectId),i);return{id:S.entryId,description:It(I.description)??"",start:S.start,end:S.end,billable:I.billable===!0,...v?{project:v}:{},...S.memberName?{member:S.memberName}:{}}}),f=n?ht({type:"range",collection:Oe,params:{workspaceId:n.workspaceId,userId:n.userId},field:"start",from:"",to:""}):void 0,b=t.coverage.filter(S=>!f||S.key===f).map(S=>S.confirmedAt).sort((S,I)=>K(S)-K(I)).at(-1),T=n&&a?vo({mirror:t,settings:n,window:a,now:o,timeZone:r,forceProjects:e.forceProjects}):void 0;return{entries:k,running:p,breaks:y,...a?{window:a}:{},...b?{lastChecked:b}:{},weekStart:qt(e.weekStart),timeZone:r,...T?{unknown:T.unknown,conflicts:T.conflicts,timeline:T.days}:{unknown:[],conflicts:[]}}}var Bs=60,Ys=new Set(["unknown_connection","not_delegated","capability_scope","platform_mismatch","credential_refresh_failed","capability_expired"]),Gs=new Set(["unauthorized","forbidden","access_denied","not_owner"]);function Un(e,t){if(!e)return;let n=e.trim();if(/^\d+$/.test(n))return Number(n);let o=Date.parse(n);return Number.isFinite(o)?Math.max(0,Math.ceil((o-t)/1e3)):void 0}var Xs=e=>e instanceof Error?e.message:String(e);function Bn(e,t=Date.now()){if(e instanceof ge){let r=e.body&&typeof e.body=="object"&&"message"in e.body?` "${String(e.body.message)}"`:typeof e.body=="string"&&e.body?` "${e.body}"`:"",i=`HTTP ${e.status} on GET ${e.path}${r}`;return e.status===401?{kind:"reauth",detail:i}:e.status===403?{kind:"forbidden",detail:i}:e.status===429?{kind:"rate-limited",retryAfterSeconds:Un(e.retryAfter,t)??Bs,detail:i}:{kind:"other",detail:i}}let n=Xs(e),o=typeof e?.code=="string"?e.code:/refused (?:this connection|the request) \((\w+)/.exec(n)?.[1];return/refused this connection/.test(n)||o&&Ys.has(o)?{kind:"reauth",detail:n}:o&&Gs.has(o)?{kind:"forbidden",detail:n}:o||/refused the request/.test(n)?{kind:"other",detail:n}:/returned more than \d+ pages/.test(n)?{kind:"too-many",detail:n}:e instanceof TypeError||/fetch|network|relay|proxy/i.test(n)?{kind:"network",detail:n}:{kind:"other",detail:n}}var Qs=e=>{if(!(typeof e!="string"||!e))try{let t=JSON.parse(e);return typeof t?.id=="string"&&typeof t.from=="number"&&typeof t.to=="number"&&Array.isArray(t.rows)&&Array.isArray(t.supersedes)?t:void 0}catch{return}},So=(e,t)=>e.createdAtt.createdAt?1:e.idt.id?1:0;async function Co(e,t){let o=(await e.getResource(await e.getApp())).get(t.log.log);return typeof o=="string"&&o?o:void 0}async function jo(e,t,n=[]){let o=await Co(e,t);if(!o)return[];let r=new Set([...await e.query({property:t.log.intentOf,value:o}),...n]),i=[];for(let s of r){let a;try{a=Qs((await e.getResource(s)).get(t.log.intent))}catch{continue}a&&i.push({...a,subject:s})}return i.sort(So)}async function Io(e,t,n){let o=await Co(e,t);if(!o)throw new Error("Sync first: there is no observation log yet.");return(await e.newResource({parent:o,propVals:{[U]:`Clockify range edit ${n.createdAt}`,[t.log.intent]:JSON.stringify(n),[t.log.intentOf]:o}})).subject}var Ro=(e,t)=>e.frome.kind===t.kind&&(e.kind==="didNotWork"||t.kind==="worked"&&e.projectId===t.projectId);function Yn(e,t){let n=new Set(e.flatMap(o=>o.supersedes));return e.filter(o=>!n.has(o.id)&&o.rows.some(r=>t.has(r)))}function Eo(e){let t=e.map((i,s)=>s),n=i=>t[i]===i?i:t[i]=n(t[i]),o=new Set;for(let i=0;i{let s=[...i].sort(So);return{from:Math.min(...s.map(a=>a.from)),to:Math.max(...s.map(a=>a.to)),intents:s}}).sort((i,s)=>i.from-s.from||i.to-s.to)}function To(e){return new Set(e.flatMap(t=>t.intents.flatMap(n=>n.rows)))}function Po(e,t){let n=e.filter(o=>Ro(o,t));return{replace:n,outside:n.filter(o=>o.fromt.to)}}var Gn=e=>e.kind==="worked"?{kind:"worked",projectId:e.projectId}:{kind:"didNotWork"};var rn=e=>{if(!(typeof e!="string"||!e))try{let t=JSON.parse(e);return typeof t?.device=="string"&&typeof t.until=="string"?t:void 0}catch{return}},on=(e,t)=>!!e&&Date.parse(e.until)>t;async function Oo(e,t){let o=(await e.getResource(await e.getApp())).get(t.log.log);return typeof o=="string"&&o?o:void 0}async function No(e,t,{device:n,clock:o}){let r=await Oo(e,t);if(!r)return;let i=rn((await e.getResource(r)).get(t.log.lease));return i&&i.device!==n&&on(i,o())?i:void 0}function Xn(e,t){return`Another open copy of this app (another device or tab) is sending changes to Clockify. Nothing was sent; try again after ${new Date(e.until).toLocaleTimeString(void 0,{...t?{timeZone:t}:{},hour:"2-digit",minute:"2-digit",second:"2-digit"})}, when its turn ends at the latest.`}var Rt=class e{constructor(t,n,o,r,i){this.store=t;this.schema=n;this.options=o;this.head=r;this.until=i}store;schema;options;head;until;static async take(t,n,o){let r=await Oo(t,n);if(!r)return new e(t,n,o,void 0,0);let i=new e(t,n,o,r,0),s=await i.write();return s?{heldBy:s}:i}async renew(){if(!this.head)return;let t=this.options.clock(),n=await this.read();if(n&&n.device!==this.options.device&&on(n,t))return n;if(!(n?.device===this.options.device&&this.until-t>6e4/2))return this.write()}async release(){if(!this.head)return;let t=await this.store.getResource(this.head),n=rn(t.get(this.schema.log.lease));if(n?.device!==this.options.device)return;let o=new Date(this.options.clock()).toISOString();t.set(this.schema.log.lease,JSON.stringify({...n,until:o})),await t.save()}async read(){return rn((await this.store.getResource(this.head)).get(this.schema.log.lease))}async write(){let{device:t,clock:n}=this.options,o=await this.store.getResource(this.head),r=rn(o.get(this.schema.log.lease)),i=n();if(r&&r.device!==t&&on(r,i))return r;let s={device:t,takenAt:r?.device===t&&on(r,i)?r.takenAt:new Date(i).toISOString(),until:new Date(i+6e4).toISOString()};o.set(this.schema.log.lease,JSON.stringify(s)),await o.save();let a=await this.read();if(a?.device!==t)return a;this.until=i+6e4}};var ta=50,na=256*1024,Et=(e,t)=>{if(typeof e!="string")throw new Error(`The ${t} is missing.`);try{return JSON.parse(e)}catch{throw new Error(`The ${t} is not valid JSON.`)}},ra=(e,t)=>!t||Bt(e,t)>0,Ne=class e{constructor(t,n,o,r,i,s){this.store=t;this.fields=n;this.options=o;this.headSubject=r;this.head=i;this.current=s}store;fields;options;headSubject;head;current;appended=0;snapshotsWritten=0;dirty=!1;ancestors=new Set;absorbed=new Set;static async open(t,n,o){let r=n.log,s=(await t.getResource(await t.getApp())).get(r.log);if(typeof s!="string"||!s)return new e(t,r,o,void 0,void 0,we());let a=Et((await t.getResource(s)).get(r.head),"Clockify log head"),c=await Qn(t,r,a.snapshot),l=await er(t,r,a.tail),p=!!a.others?.length||a.tail.some(y=>!ra(y,c.cut))?kt(we(),tr([...await Do(t,r,We(a)),...l])):kt(c.mirror,l);return p.coverage=wt(p.coverage,a.coverage),new e(t,r,o,s,a,p)}static async replay(t,n){let o=n.log,i=(await t.getResource(await t.getApp())).get(o.log);if(typeof i!="string"||!i)return we();let s=Et((await t.getResource(i)).get(o.head),"Clockify log head"),a=kt(we(),tr([...await Do(t,o,We(s)),...await er(t,o,s.tail)]));return a.coverage=wt(a.coverage,s.coverage),a}get mirror(){return this.current}get lastComplete(){return this.head?.lastComplete}get tail(){return this.head?.tail??[]}async append(t){let n=co(this.current,t),o=await this.ensureHead();if(!lo(n)){let r=JSON.stringify(n),i=await this.store.newResource({parent:this.headSubject,propVals:{[U]:`Clockify ${n.kind} read ${n.receivedAt}`,[this.fields.observation]:r}});o.tail.push({subject:i.subject,id:n.id,receivedAt:n.receivedAt,bytes:r.length}),this.appended++}return this.current=kt(this.current,[n]),n.complete&&n.scope.type==="range"&&(o.coverage=wt(o.coverage,this.current.coverage.filter(r=>r.confirmedAt===n.receivedAt)),o.lastComplete=n.receivedAt),this.dirty=!0,n}async compactIfNeeded(){if(!this.head)return!1;let t=this.head.tail.reduce((n,o)=>n+o.bytes,0);return!this.head.others?.length&&this.head.tail.length{try{return Et(t.get(this.fields.head),"log head")}catch{return}})();n&&await this.merge(n),t.set(this.fields.head,JSON.stringify(this.head)),await t.save(),this.dirty=!1}async merge(t){let n=this.head,o=new Map([[n.snapshot,n.cut]]);for(let c of We(t)){if(this.ancestors.has(c)||We(n).includes(c))continue;let l=await Qn(this.store,this.fields,c);o.set(c,l.cut);for(let d of l.compacted)this.absorbed.add(d.id);for(let d of[l.previous,...l.merged??[]])d&&this.ancestors.add(d)}let r=[...new Set([...We(n),...We(t)])].filter(c=>!this.ancestors.has(c)),i=r.includes(n.snapshot)?n.snapshot:r[0];o.has(i)&&(n.cut=o.get(i)),n.snapshot=i;let s=r.filter(c=>c!==i).sort();s.length?n.others=s:delete n.others;let a=new Set;n.tail=[...n.tail,...t.tail].filter(c=>a.has(c.id)||this.absorbed.has(c.id)?!1:(a.add(c.id),!0)),n.coverage=wt(n.coverage,t.coverage),t.lastComplete&&(!n.lastComplete||Date.parse(t.lastComplete)>Date.parse(n.lastComplete))&&(n.lastComplete=t.lastComplete)}async ensureHead(){if(this.head)return this.head;let t=await this.store.getResource(await this.store.getApp()),n=await this.store.newResource({parent:t.subject,propVals:{[U]:"Clockify observation log"}});this.headSubject=n.subject;let o=await this.store.newResource({parent:n.subject,propVals:{[U]:"Clockify snapshot (empty)",[this.fields.snapshot]:JSON.stringify({v:1,mirror:we(),cut:null,previous:null,compacted:[],writtenAt:new Date(this.options.clock()).toISOString()})}});return this.head={v:1,snapshot:o.subject,cut:null,tail:[],coverage:[]},n.set(this.fields.head,JSON.stringify(this.head)),await n.save(),t.set(this.fields.log,n.subject),await t.save(),this.head}async writeSnapshot(){let t=this.head,n=[...t.tail,...t.cut?[t.cut]:[]].reduce((c,l)=>!c||Bt(l,c)>0?l:c,null),o=new Date(this.options.clock()).toISOString(),r={v:1,mirror:this.current,cut:n&&{receivedAt:n.receivedAt,id:n.id},previous:t.snapshot,compacted:t.tail,...t.others?.length?{merged:t.others}:{},writtenAt:o},i=await this.store.newResource({parent:this.headSubject,propVals:{[U]:`Clockify snapshot ${o}`,[this.fields.snapshot]:JSON.stringify(r)}});for(let c of We(t))this.ancestors.add(c);for(let c of t.tail)this.absorbed.add(c.id);let{others:s,...a}=t;this.head={...a,snapshot:i.subject,cut:r.cut,tail:[]},this.snapshotsWritten++,this.dirty=!0}};async function Qn(e,t,n){return Et((await e.getResource(n)).get(t.snapshot),"Clockify snapshot")}async function er(e,t,n){let o=[];for(let r of n)o.push(Et((await e.getResource(r.subject)).get(t.observation),"Clockify observation"));return o}var We=e=>[e.snapshot,...e.others??[]],tr=e=>{let t=new Set;return e.filter(n=>!t.has(n.id)&&!!t.add(n.id))};async function Do(e,t,n){let o=[],r=new Set,i=[...n];for(;i.length;){let s=i.pop();if(r.has(s))continue;r.add(s);let a=await Qn(e,t,s);o.push(...await er(e,t,a.compacted)),a.previous&&i.push(a.previous),i.push(...a.merged??[])}return tr(o)}var nr=ss($o(),1),Xe=(e,t)=>(0,nr.default)(e)===(0,nr.default)(t);function rr(e,t,n){let o={local:{},remote:{},createLocal:!1,createRemote:!1,deleteLocal:!1,deleteRemote:!1,conflicts:[]};if(Xe(t,n))return t!==void 0&&(o.agreed=structuredClone(t)),o;if(t===null||n===null)return Xe(t,e)&&n===null?o.deleteLocal=!0:Xe(n,e)&&t===null?o.deleteRemote=!0:o.conflicts.push({property:"@record",base:e,local:t,remote:n}),o;if(e!==void 0&&(t===void 0||n===void 0))return o;o.createLocal=e===void 0&&t===void 0&&n!==void 0,o.createRemote=e===void 0&&n===void 0&&t!==void 0;let r=new Set([...Object.keys(e??{}),...Object.keys(t??{}),...Object.keys(n??{})]);for(let i of r){let s=e?.[i],a=t?.[i],c=n?.[i];Xe(a,c)||(Xe(a,s)?o.local[i]=structuredClone(c):Xe(c,s)?o.remote[i]=structuredClone(a):o.conflicts.push({property:i,base:s,local:a,remote:c}))}return o}var _o="new:",ir=e=>`${_o}${e}`,sr=e=>e.startsWith(_o),cn=e=>typeof e=="string"&&e?e:null,Tt=(e,t)=>JSON.stringify(e)===JSON.stringify(t),z=e=>({name:e.name,start:e.start,end:e.end,billable:e.billable,projectId:e.projectId,project:e.project});function sn(e){if(!(typeof e!="string"||!e))try{return JSON.parse(e)}catch{return}}function oa(e){let t=e;return!!t&&typeof t.name=="string"&&typeof t.start=="number"&&typeof t.end=="number"&&typeof t.billable=="boolean"}var ia={id:null,name:null};async function Wo(e,t){let n=dt(e.props)[L.project];return typeof n=="string"?t.links.describe("project",n):ia}async function ln(e,t){let n=dt(e.props),o=n[L.start],r=n[L.end];if(typeof o!="number"||typeof r!="number")return;let i=n[U],s=await Wo(e,t);return{name:typeof i=="string"?i:"",start:o,end:r,billable:n[L.billable]===!0,projectId:s.id,project:s.name}}async function De(e,t){let n=cn(e.get(t.row.entryId)),o=n?await ln(e,t):void 0;if(!n||!o)return;let r=sn(e.get(t.sync.baseline)),i=sn(e.get(t.sync.outbox));return{subject:e.subject,entryId:n,local:o,...oa(r)?{baseline:z(r)}:{},...i?.op?{outbox:i}:{},deleteRequested:e.get(t.sync.deleteRequested)===!0}}async function Vo(e,t){if(t.projectId)return e.links.ensure("project",t.projectId,t.project);if(t.project)return e.links.named(t.project)}async function le(e,t,n){let o=Vt.write({[U]:n.name,[L.start]:n.start,[L.end]:n.end,[L.billable]:n.billable},te),r=!1;for(let[a,c]of Object.entries(o))e.get(a)!==c&&(e.set(a,c),r=!0);let i=await Wo(e,t);if(!(n.projectId?i.id===n.projectId:i.id===null&&i.name===(n.project??null))){let a=await Vo(t,n);a?e.set(L.project,a):e.remove(L.project),r=!0}return r}async function Fo(e,t){let n=await Vo(e,t);return Vt.write({[U]:t.name,[L.start]:t.start,[L.end]:t.end,[L.billable]:t.billable,...n?{[L.project]:n}:{}},te)}async function Ko(e,t){return{...await Fo(e,t),[e.sync.baseline]:JSON.stringify(z(t))}}async function dn(e,t,n,o){if(!n)return!1;let r=await t.links.ensure("person",n,o);return e.get(L.person)===r?!1:(e.set(L.person,r),!0)}var ar=(e,t)=>n=>cr(t)(n)??e.links.nameOf("project",n);function Y(e,t,n){let o=!1,r=(i,s)=>{let a=e.get(i);a===s||s===""&&a===void 0||s===!1&&a===void 0||(e.set(i,s),o=!0)};return n.baseline&&r(t.sync.baseline,JSON.stringify(z(n.baseline))),n.outbox!==void 0&&r(t.sync.outbox,n.outbox?JSON.stringify(n.outbox):""),n.delete!==void 0&&r(t.sync.deleteRequested,n.delete),n.create!==void 0&&r(t.sync.create,n.create?JSON.stringify(n.create):""),o}function $e(e,t){let n=se(e).find(o=>o.id===t);if(!(!n||n.deletedAt))return Ce(n)}var cr=e=>t=>e.find(n=>n.id===t)?.name;function Ho(e,t,n,o=new Set){let r=[],i={...z(e),name:e.name.trim()||Be},s=a=>o.has(a)?a:gt(a);if(i.start!==t.start&&(i.start=s(i.start)),i.end!==t.end&&(i.end=s(i.end)),i.projectId===null&&i.project){let a=n.filter(c=>c.name===i.project&&c.archived!==!0);a.length===1?i.projectId=a[0].id:r.push(a.length?`More than one active project is named \u201C${i.project}\u201D.`:`No active project is named \u201C${i.project}\u201D.`)}return r.length||(i.project=i.projectId?cr(n)(i.projectId)??i.project:null),{desired:i,problems:r}}function Pt(e,t,n,o){let r=e.baseline;if(!r)return;let i=t?[]:["This entry is not in what was last read from Clockify. Sync first."],s={entryId:e.entryId,subject:e.subject,title:r.name,base:r,local:e.local};if(e.deleteRequested)return{...s,kind:"delete",desired:r,fields:[],blockers:[...i,...t?Me(t,n):[]]};let{desired:a,problems:c}=Ho(e.local,r,n.projects,o),l=mt(r,a),d=ft.filter(p=>l.includes(p)||p==="projectId"&&a.projectId===null&&!!a.project);if(d.length)return{...s,kind:"update",desired:a,fields:d,blockers:[...i,...c,...t?Me(t,n,a):[]]}}function sa(e,t){let n=e.baseline;if(!n)return{values:t,baseline:t,providerWon:[],deleteDropped:!1};let o=rr(z(n),z(e.local),z(t)),r={...z(e.local)};for(let s of Object.keys(o.local))r[s]=t[s];let i=[];for(let s of o.conflicts){let a=s.property;r[a]=t[a],ft.includes(a)&&i.push(a)}return{values:r,baseline:t,providerWon:i,deleteDropped:e.deleteRequested&&!Tt(z(n),z(t))}}function aa(e,t){let n=t.providerWon.map(o=>({field:o,yours:e.local[o],clockify:t.values[o]}));if(t.deleteDropped&&n.push({field:"delete",yours:"delete",clockify:"kept"}),!!n.length)return{entryId:e.entryId,title:t.values.name,fields:n}}async function zo(e,t,n,o={}){let r=await De(e,t),i=!1;for(let[d,p]of Object.entries(o))e.get(d)!==p&&(e.set(d,p),i=!0);if(!r){let d=await le(e,t,n)||i;return Y(e,t,{baseline:n}),await e.save(),{valuesChanged:d,state:await De(e,t)}}let s=sa(r,n),a=await le(e,t,s.values)||i,c=Y(e,t,{baseline:s.baseline,...r.outbox?{outbox:null}:{},...s.deleteDropped?{delete:!1}:{}});(a||c)&&await e.save();let l=aa(r,s);return{valuesChanged:a,...l?{notice:l}:{},...r.outbox?{recovered:Tt(z(r.local),z(n))?"applied":"not-applied"}:{},state:{...r,local:s.values,baseline:s.baseline}}}async function lr(e,t,n){Y(e,t,{delete:n})&&await e.save()}async function pn(e,t){if(await un(e,t))return e.destroy();let n=await De(e,t);if(!n?.baseline)return;let o=await le(e,t,n.baseline),r=Y(e,t,{delete:!1});(o||r)&&await e.save()}async function un(e,t){if(cn(e.get(t.row.entryId)))return;let n=sn(e.get(t.sync.create));if(!n||typeof n!="object")return;let o=await ln(e,t);if(!o)return;let r=sn(e.get(t.sync.outbox));return{subject:e.subject,local:o,create:n,...r?.op?{outbox:r}:{}}}function Jo(e,t){let n=[];if(e.startt.now&&n.push("End is in the future."),t.forceProjects&&!e.projectId&&n.push("This workspace requires a project on every entry."),e.projectId){let o=t.projects.find(r=>r.id===e.projectId);o?o.archived===!0&&n.push(`The project ${o.name} is archived.`):n.push("The project is not one of this workspace\u2019s projects.")}return n}function dr(e,t){let n={...z(e.local),project:e.local.projectId?cr(t.projects)(e.local.projectId)??null:null},{desired:o,problems:r}=Ho(e.local,n,t.projects);return{kind:"create",entryId:ir(e.subject),subject:e.subject,title:o.name,base:o,local:e.local,desired:o,fields:[],...e.create.copyOf?{copyOf:e.create.copyOf}:{},blockers:[...e.outbox?["An earlier send of this entry did not get an answer. Sync first: that settles whether it arrived."]:[],...r,...Jo(o,t)]}}function Ot(e){let t=new Set;for(let n of se(e))if(!n.deletedAt)for(let o of[n.fields.start,n.fields.end])typeof o=="string"&&t.add(Date.parse(o));return t}async function pr(e,t){return e.query({property:O.parent,value:t.table})}async function ca(e,t,n){let o=new Set;for(let r of n){let i=cn((await e.getResource(r)).get(t.row.entryId));i&&o.add(i)}return o}async function Zo(e,t,n,o,r){let i=[],s=async a=>{let c=await r(a);if(!c)throw new Error(`Entry ${a} has no row in the table.`);return i.push(c),e.getResource(c)};for(let a of o)if(a.op==="update"){let c=await s(a.entryId);await le(c,t,a.desired)&&await c.save()}else if(a.op==="delete")await lr(await s(a.entryId),t,!0);else{let c=a.copyOf?$e(n,a.copyOf):void 0,l={...a.copyOf?{copyOf:a.copyOf}:{},...typeof c?.taskId=="string"?{taskId:c.taskId}:{},...Array.isArray(c?.tagIds)&&c.tagIds.length?{tagIds:[...c.tagIds]}:{}},d=await e.newResource({parent:t.table,isA:[te],propVals:{...await Fo(t,a.values),[t.sync.create]:JSON.stringify(l)}});i.push(d.subject)}return[...new Set(i)]}function qo(e,t,n,o){return se(e).filter(r=>!r.deletedAt&&!r.absentSince&&(r.fields.userId??t)===t).map(r=>Ce(r)).filter(r=>{let i=Date.parse(r.timeInterval.start??""),s=r.timeInterval.end?Date.parse(r.timeInterval.end):o;return in.from}).sort((r,i)=>r.id{let n=ye(e);return!!n&&n.start===t.start&&n.end===t.end&&n.projectId===t.projectId};async function Bo(e,t,n,o=[]){let r=typeof n.userId=="string"?n.userId:void 0,i=o.find(s=>s.id===r)?.name;await dn(e,t,r,typeof i=="string"&&i?i:null)}async function Yo(e,t,n,o,r){e.set(t.row.entryId,n.id),await Bo(e,t,n,r),await le(e,t,o),Y(e,t,{baseline:o,create:null,outbox:null}),await e.save()}async function Go(e,t,n,o){let r=[],i=new Set;for(let c of await pr(e,t)){let l=await e.getResource(c),d=cn(l.get(t.row.entryId)),p=d?void 0:await un(l,t);d&&i.add(d),p&&r.push({row:l,state:p})}let s=[],a=[];for(let{row:c,state:l}of r){let{subject:d,local:p}=l;if(l.outbox?.op!=="post"||o.busy){a.push(l);continue}let y=qo(n,o.userId,{from:p.start,to:p.end},o.now).find(k=>!i.has(k.id)&&Uo(k,p));if(y){let k=ye(y,ar(t,o.projects));await Yo(c,t,y,k,o.members),i.add(y.id),s.push({subject:d,title:k.name,entryId:y.id})}else Y(c,t,{outbox:null}),await c.save(),s.push({subject:d,title:p.name}),a.push({subject:d,local:p,create:l.create})}return{settled:s,pending:a}}var Mo=60,Xo="method or path is not in the catalog",Qe=e=>e instanceof Error?e.message:String(e),Qo=e=>typeof e=="string"?e:e&&typeof e=="object"&&"message"in e?String(e.message):"",Ae=class extends Error{},Ve=class extends Error{},an=class extends Ve{};async function ei(e,t){let n=[],o=!1,r,i=a=>new an(Xn(a,e.timeZone));if(e.lease){let a=await Rt.take(e.store,e.schema,e.lease);if(!(a instanceof Rt)){let c=Xn(a.heldBy,e.timeZone);return t.map(l=>({entryId:l.entryId,title:l.title,kind:l.kind,status:"not-sent",message:c}))}r=a}let s=r?{...e,renew:async()=>{let a=await r.renew();if(a)throw i(a)}}:e;try{for(let[a,c]of t.entries()){e.onProgress?.(a,t.length);let l={entryId:c.entryId,title:c.title,kind:c.kind};if(o){n.push({...l,status:"not-sent"});continue}try{await s.renew?.(),n.push({...l,...await(c.kind==="create"?da:la)(s,c)})}catch(d){d instanceof Ae?(n.push({...l,status:"uncertain",message:d.message}),o=!0):d instanceof an?(n.push({...l,status:"not-sent",message:d.message}),o=!0):d instanceof Ve?(n.push({...l,status:"failed",message:d.message}),o=!0):n.push({...l,status:"failed",message:Qe(d)})}}e.onProgress?.(t.length,t.length),await e.log.compactIfNeeded(),await e.log.flush()}finally{await r?.release()}return n}async function la(e,t){let{store:n,schema:o,log:r}=e,i=await n.getResource(t.subject),s=await De(i,o);if(!s||!Tt(z(s.local),z(t.local))||s.deleteRequested!==(t.kind==="delete"))return{status:"changed",message:"The row changed after this list was made. Review it again."};let a=ar(o,e.write.projects),c=await or(e,t.entryId);if(!c)return await i.destroy(),{status:t.kind==="delete"?"sent":"gone",...t.kind==="delete"?{message:"Already deleted in Clockify."}:{}};let l=ye(c,a);if(!l)return{status:"refused",message:Me(c,e.write).join(" ")};let d=t.desired;if(t.kind==="delete"){if(!Tt(z(l),z(t.base)))return await le(i,o,l),Y(i,o,{baseline:l,delete:!1}),await i.save(),{status:"conflict",message:"Changed in Clockify since it was read; it was not deleted."}}else{let I=rr(z(t.base),z(t.desired),z(l));if(I.agreed)return await le(i,o,l),Y(i,o,{baseline:l}),await i.save(),{status:"already"};if(I.conflicts.length){let v=I.conflicts.map($=>$.property).filter($=>ft.includes($)),R={...z(s.local)};for(let $ of[...Object.keys(I.local),...I.conflicts.map(oe=>oe.property)])R[$]=l[$];return await le(i,o,R),Y(i,o,{baseline:l}),await i.save(),{status:"conflict",fields:v,message:"Changed in Clockify since it was read; Clockify\u2019s values were kept for those fields."}}d={...z(l),...I.remote},d.project=d.projectId?a(d.projectId)??d.project:null}let p=Me(c,e.write,t.kind==="update"?d:void 0);if(p.length)return{status:"refused",message:p.join(" ")};let y=`/api/v1/workspaces/${encodeURIComponent(e.read.workspaceId)}/time-entries/${encodeURIComponent(t.entryId)}`,k=t.kind==="delete"?{method:"DELETE"}:{method:"PUT",body:JSON.stringify(Jr(c,d))},f=new Date(e.read.clock()).toISOString();Y(i,o,{outbox:{op:t.kind==="delete"?"delete":"put",sentAt:f}}),await i.save();let m=await ti(e,y,k);if(!(m.status===404&&t.kind==="delete"))if(m.status<200||m.status>=300){Y(i,o,{outbox:null}),await i.save();let I=Qo(m.body);if(m.status===404&&I===Xo)throw new Ve("The integration proxy does not allow writing to Clockify (its catalog has no time-entry write overlay).");return{status:"failed",message:`Clockify answered ${m.status}${I?`: ${I}`:""}.`}}else t.kind==="update"&&m.body&&await r.append({id:e.read.newId(),device:e.read.device,sentAt:f,receivedAt:new Date(e.read.clock()).toISOString(),kind:"write-response",scope:{type:"id",collection:Oe,id:t.entryId},mask:xt,complete:!0,records:[St(m.body)]});let b;try{b=await or(e,t.entryId)}catch(I){throw new Ae(`Sent, but the check afterwards failed (${Qe(I)}). The next sync reads it back.`)}if(t.kind==="delete")return b?(Y(i,o,{outbox:null}),await i.save(),{status:"failed",message:"Clockify still has the entry after the delete."}):(await i.destroy(),{status:"sent"});let T=b&&ye(b,a);if(!T)return b?(Y(i,o,{outbox:null}),await i.save()):await i.destroy(),{status:b?"failed":"gone",...b?{message:"Clockify no longer lists it as a completed entry."}:{}};await le(i,o,T),Y(i,o,{baseline:T,outbox:null}),await i.save();let S=mt(d,T);return S.length?{status:"adjusted",fields:S,message:"Clockify stored other values than were sent; the row has them."}:{status:"sent"}}async function da(e,t){let{store:n,schema:o,log:r}=e,i=await n.getResource(t.subject),s=await un(i,o);if(!s||!Tt(z(s.local),z(t.local)))return{status:"changed",message:"The row changed after this list was made. Review it again."};let a=t.desired,c=ar(o,e.write.projects),l;try{l=await Xt(e.read,a.start-vt,a.end)}catch(I){return{status:"failed",message:`Could not read this range from Clockify first (${Qe(I)}). Nothing was created.`}}if(await r.append(l.observation),l.error)return{status:"failed",message:`Could not read all of this range from Clockify first (${Qe(l.error)}). Nothing was created.`};let d=qo(r.mirror,e.read.userId,{from:a.start,to:a.end},e.write.now);if(d.length){let I=await ca(n,o,await pr(n,o)),v=d.find(R=>!I.has(R.id)&&Uo(R,a));return v&&d.length===1?(await Yo(i,o,v,ye(v,c),e.members),{status:"bound",message:"Clockify already had it, from an earlier send."}):{status:"conflict",message:"Clockify has time in this range now, so nothing was created. Discard this and edit the range again."}}let p=Jo(a,e.write);if(p.length)return{status:"refused",message:p.join(" ")};let y={start:ut(a.start),end:ut(a.end),billable:a.billable,description:Ye(a.name),...a.projectId?{projectId:a.projectId}:{},...s.create.taskId?{taskId:s.create.taskId}:{},tagIds:[...s.create.tagIds??[]],type:"REGULAR"},k=new Date(e.read.clock()).toISOString();Y(i,o,{outbox:{op:"post",sentAt:k}}),await i.save();let f=await ti(e,`/api/v1/workspaces/${encodeURIComponent(e.read.workspaceId)}/time-entries`,{method:"POST",body:JSON.stringify(y)});if(f.status<200||f.status>=300){Y(i,o,{outbox:null}),await i.save();let I=Qo(f.body);if(f.status===404&&I===Xo)throw new Ve("The integration proxy does not allow writing to Clockify (its catalog has no time-entry write overlay).");return{status:"failed",message:`Clockify answered ${f.status}${I?`: ${I}`:""}.`}}let m=f.body;if(!m||typeof m.id!="string")throw new Ae("Clockify\u2019s answer did not name the new entry. The next sync looks for it.");await r.append({id:e.read.newId(),device:e.read.device,sentAt:k,receivedAt:new Date(e.read.clock()).toISOString(),kind:"write-response",scope:{type:"id",collection:Oe,id:m.id},mask:xt,complete:!0,records:[St(m)]}),i.set(o.row.entryId,m.id),await Bo(i,o,m,e.members),Y(i,o,{create:null,baseline:a}),await i.save();let b;try{b=await or(e,m.id)}catch(I){throw new Ae(`Created, but the check afterwards failed (${Qe(I)}). The next sync reads it back.`)}let T=b&&ye(b,c);if(!T)return b?(Y(i,o,{outbox:null}),await i.save()):await i.destroy(),{status:b?"failed":"gone",...b?{message:"Clockify does not list it as a completed entry."}:{}};await le(i,o,T),Y(i,o,{baseline:T,outbox:null}),await i.save();let S=mt(a,T);return S.length?{status:"adjusted",fields:S,message:"Clockify stored other values than were sent; the row has them."}:{status:"sent"}}async function or(e,t){let n=await Qt(e.read,t);return await e.log.append(n),$e(e.log.mirror,t)}async function ti(e,t,n){let o=e.sleep??(r=>new Promise(i=>setTimeout(i,r)));for(let r=0;;r++){let i;await e.renew?.();try{i=await e.read.transport.request(t,void 0,n)}catch(a){throw a instanceof ot?new Ve(a.message):new Ae(`No answer from Clockify (${Qe(a)}). The next sync reads back whether it was applied.`)}if(i.status>=500)throw new Ae(`Clockify or the proxy answered ${i.status}; it may have been applied. The next sync reads it back.`);if(i.status!==429||r>0)return i;let s=Un(i.headers?.["retry-after"],e.read.clock())??Mo;if(s>Mo)return i;await o(s*1e3)}}async function fn(e,t,n,o){let r=[],i=Ot(n);for(let s of await pr(e,t)){let a=await e.getResource(s),c=await un(a,t);if(c){r.push(dr(c,o));continue}let l=await De(a,t);if(!l)continue;let d=Pt(l,$e(n,l.entryId),o,i);d&&r.push(d)}return Nt(r)}function Lo(e){if(e.kind==="delete")return 0;if(e.kind==="create")return 2;let{base:t,desired:n}=e;return n.start>=t.start&&n.end<=t.end&&n.projectId===t.projectId?0:1}var Nt=e=>[...e].sort((t,n)=>Lo(t)-Lo(n)||t.desired.start-n.desired.start||(t.entryIdArray.from(crypto.getRandomValues(new Uint8Array(e)),t=>t.toString(16).padStart(2,"0")).join(""),mn=(e=Date.now)=>`${e().toString(36).padStart(9,"0")}-${ni(8)}`,ur=`frame-${ni(6)}`,ua="Generated by the Clockify timesheets app from what it last read in Clockify. Read-only: edits made here are overwritten on the next sync.",fa=`Filled by the Clockify timesheets app from what it last read in Clockify. Edits to Name, Start, End, Billable and Project are listed under "Changes to send" in the app the next time it opens, and reach Clockify only once sent there. If the same field was also changed in Clockify, Clockify's value is kept.`,ma=`Filled by the Clockify timesheets app from what it last read in Clockify, as shared Time entry rows. Project and Person link to rows of the app's Projects and People tables. Edits to Name, Start, End, Billable and Project are listed under "Changes to send" in the app the next time it opens, and reach Clockify only once sent there. If the same field was also changed in Clockify, Clockify's value is kept.`;async function ri(e,t,n,o,r=Date.now(),i={}){let s=i.clock??Date.now,a=await Or(t,n.workspaceId),c={transport:t,workspaceId:n.workspaceId,userId:n.userId,...a.timeZone?{timeZone:a.timeZone}:{},clock:s,newId:i.newId??(()=>mn(s)),device:i.device??ur},l=await Ne.open(e,o,{clock:s}),d=[...a.warnings];for(let S of en(l.mirror))try{await l.append(await Qt(c,S.id))}catch(I){d.push(`Could not re-check entry ${S.id}: ${I instanceof Error?I.message:String(I)}`)}let p={from:r-n.lookbackDays*pa,to:r},y;try{y=await Xt(c,p.from-vt,p.to)}catch(S){throw await l.flush(),S}if(await l.append(y.observation),y.error)throw await l.flush(),y.error;let k=await jn(t,n.workspaceId,"projects"),f=await jn(t,n.workspaceId,"users");d.push(...[k.warning,f.warning].filter(S=>!!S));let m=await l.compactIfNeeded();await l.flush();let b=await No(e,o,{device:c.device,clock:s});return{...await ga(e,o,l,k.items,f.items,{now:r,...a.forceProjects!==void 0?{forceProjects:a.forceProjects}:{},projects:k.items},i.onProgress,n.userId,!!b),warnings:d,...b?{sendingElsewhereUntil:b.until}:{},log:{incrementals:l.appended,snapshotWritten:m,candidates:en(l.mirror).length,unknownMs:bo(Ct(l.mirror,n,p,r))},account:{...a.timeZone?{timeZone:a.timeZone}:{},...a.forceProjects!==void 0?{forceProjects:a.forceProjects}:{},...a.weekStart?{weekStart:a.weekStart}:{},...a.userName?{userName:a.userName}:{},...a.workspaceName?{workspaceName:a.workspaceName}:{}},mirror:l.mirror,projects:k.items,members:f.items}}async function ga(e,t,n,o,r,i,s,a="",c=!1){let l={created:0,updated:0,unchanged:0,removed:0,review:[],providerWon:[],recovered:[]},{settled:d,pending:p}=await Go(e,t,n.mirror,{userId:a,now:i.now,projects:i.projects,members:r,busy:c}),y=new Map(d.filter(v=>v.entryId).map(v=>[v.entryId,v.subject]));for(let v of d)l.recovered.push({entryId:v.entryId??ir(v.subject),title:v.title,applied:!!v.entryId});let k=new Set(await e.query({property:O.parent,value:t.table})),f=async v=>y.get(v)??(await e.query({property:t.row.entryId,value:v})).find(R=>k.has(R)),m=Ot(n.mirror),b=await e.getResource(t.table),T=b.get(O.description);(!T||T===ua||T===fa)&&(b.set(O.description,ma),await b.save());for(let v of o)v.archived!==!0&&await t.links.ensure("project",v.id,v.name,{rename:!0});let S=se(n.mirror),I=tn(S.filter(v=>!v.deletedAt).map(Ce),o,r).sort((v,R)=>v.start-R.start||(v.entryIdR.deletedAt)){let R=await f(v.id);R&&(await(await e.getResource(R)).destroy(),k.delete(R),l.removed++)}return l.review=Nt(l.review),l}function ya(e){return{name:e.name,start:e.start,end:e.end,billable:e.billable===!0,projectId:e.projectId??null,project:e.projectName??null}}async function oi(e,t=Date.now){let n=await Ze(e),{log:o,head:r,observation:i,snapshot:s}=n.log;return!o||!r||!i||!s?we():(await Ne.open(e,n,{clock:t})).mirror}var fr="",mr=e=>Math.max(0,e.end-e.start),ii=e=>e.project?.id??fr,ke=e=>e?e.name??`Project ${e.id.slice(-6)}`:"No project",si=(e,t)=>{if(!e.project!=!t.project)return e.project?-1:1;if(e.total!==t.total)return t.total-e.total;let[n,o]=[ke(e.project),ke(t.project)];return no?1:0};function ai(e,t,{timeZone:n,now:o,window:r}){let i=_(o,n),s=new Map(t.days.map((p,y)=>[p,y])),a=new Map,c=t.days.map(()=>0),l=0,d=0;for(let p of e){let y=s.get(_(p.start,n));if(y===void 0)continue;let k=ii(p),f=a.get(k);f||(f={key:k,...p.project?{project:p.project}:{},cells:t.days.map(()=>0),total:0},a.set(k,f));let m=mr(p);f.cells[y]+=m,f.total+=m,c[y]+=m,d+=m,p.billable&&(l+=m)}return{days:t.days.map(p=>({key:p,isToday:p===i,isFuture:p>i,inWindow:!r||Le(be(p,1),n)>r.from})),rows:[...a.values()].sort(si),dayTotals:c,total:d,billable:l,notBillable:d-l}}function gr(e,t,n){let o=new Set(t.days),r=new Map;for(let i of e){let s=_(i.start,n);if(!o.has(s))continue;let a=r.get(s);a||(a={key:s,total:0,entries:[]},r.set(s,a)),a.entries.push(i),a.total+=mr(i)}for(let i of r.values())i.entries.sort((s,a)=>a.start-s.start||(s.idi.keya+c,0);if(!n)return e.map(()=>0);let o=e.map(a=>a*t/n),r=o.map(Math.floor),i=t-r.reduce((a,c)=>a+c,0),s=o.map((a,c)=>({i:c,r:a-Math.floor(a)})).sort((a,c)=>c.r-a.r||a.i-c.i);for(let{i:a}of s){if(i<=0)break;r[a]++,i--}return r}function ci(e,t){let n=new Map,o=0,r=0;for(let l of e){if(t&&(l.start=t.to))continue;let d=ii(l),p=n.get(d);p||(p={key:d,...l.project?{project:l.project}:{},total:0,billable:0},n.set(d,p));let y=mr(l);p.total+=y,o+=y,l.billable&&(p.billable+=y,r+=y)}let i=[...n.values()].sort((l,d)=>si({...l,cells:[]},{...d,cells:[]})),s=i[0]?.total??0,a=ba(i.map(l=>Math.round(l.total/6e4)),1e3),c=l=>s?Math.round(l/s*1e3)/10:0;return{total:o,billable:r,notBillable:o-r,rows:i.map((l,d)=>({...l,shareTenths:a[d],barPercent:c(l.total),billableBarPercent:c(l.billable)}))}}var li=e=>`${Math.floor(e/10)}.${e%10}%`;function di(e){return Object.assign((n,o,...r)=>{let i=e.createElement(n);for(let[s,a]of Object.entries(o??{}))a===!1||a===null||a===void 0||i.setAttribute(s,a===!0?"":String(a));return ha(i,r),i},{doc:e})}function ha(e,t){for(let n of t.flat())n==null||n===!1||e.appendChild(typeof n=="string"?e.ownerDocument.createTextNode(n):n)}var wa="http://www.w3.org/2000/svg",ka={clock:'',left:'',right:'',sync:'',x:'',warn:'',err:'',info:'',check:'',minus:'',ext:'',plug:'',empty:''};function je(e,t,n=""){let o=e.createElementNS(wa,"svg");return o.setAttribute("class",`i${n?` ${n}`:""}`),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("aria-hidden","true"),o.innerHTML=ka[t],o}var pi=(e,t,n)=>e("span",{class:"pill","data-state":t},n);function ui(e,t){let n=e.doc;return e("header",{class:"hdr"},e("span",{class:"mark"},je(n,t.mark)),e("h1",null,t.srPrefix?e("span",{class:"sr"},t.srPrefix):null,t.title),t.chip?e("span",{class:"chip"},e("span",{class:"src","aria-hidden":"true"},t.chip.letter),t.chip.text):null,e("span",{class:"spacer"}),t.pill,t.action)}function N(e,t,n={}){let o=e.doc,r=n.variant&&n.variant!=="primary"?` ${n.variant}`:"",i=e("button",{type:"button",class:`btn${r}${n.iconOnly?" icon":""}`,disabled:!!n.disabled,"data-k":n.key,"aria-label":n.iconOnly?t:n.label},n.icon?je(o,n.icon):null,n.iconOnly?null:t);return n.onClick&&i.addEventListener("click",n.onClick),i}function de(e,t){let n=e.doc;return e("div",{class:`banner ${t.tone}`,role:t.role},je(n,t.icon),e("p",null,e("strong",null,t.lead),t.text?` ${t.text}`:null),t.action??e("span"),t.details?e("details",null,e("summary",null,t.details.summary),e("code",null,t.details.text)):null)}function fi(e,t){let n=e.doc;return e("div",{class:"empty"},je(n,"empty"),e("p",null,e("strong",null,t.lead)),t.text?e("p",{class:"muted",style:"font-size: 13px"},t.text):null,e("div",{class:"row",style:"justify-content: center"},...t.actions),t.link??null)}var et=(e,t,...n)=>e("div",{class:"centre"},e("div",{class:"panel"},e("h2",null,t),...n)),gn=(e,t,n,o="link",r)=>{let i=e.doc,s=o.includes("btn")?je(i,"ext"):null;if(r){let a=e("button",{type:"button",class:o,"data-k":`open:${t}`},n,s);return a.addEventListener("click",()=>r(t)),a}return e("a",{class:o,href:t,target:"_blank",rel:"noopener noreferrer"},n,s)};var va={break:"Break",holiday:"Holiday",timeOff:"Time off"};function bn({from:e,to:t},n){let[o,r]=[_(e,n),_(t-1,n)],i=`${H(o)} ${re(e,n)}`;return o===r?`${i} \u2013 ${re(t,n)}`:`${i} \u2013 ${H(_(t,n))} ${re(t,n)}`}function yn(e,t){if(e.kind==="didNotWork")return e.badge?va[e.badge]:"Did not work";if(e.projectId===null)return"No project";let n=t.entries.find(o=>o.project?.id===e.projectId)?.project;return ke(n??{id:e.projectId})}var Dt=e=>"kind"in e&&"candidates"in e&&"from"in e;function xa(e,t){if(!Dt(e))return`Entry ${e.entryId}: ${e.fields.join(", ")} disagree`;let n=bn(e,t.timeZone),o=e.candidates.map(i=>yn(i,t)).join(" \xB7 "),r=`${e.entryIds.length} entries`;switch(e.kind){case"duplicate":return`${o} twice (${r}), ${n}`;case"whichProject":return`Unclear which project: ${o} (${r}), ${n}`;case"whetherWorked":return`Unclear whether worked: ${o} (${r}), ${n}`;case"local":return`Your range edits disagree, not sent: ${(e.edits??[]).map(s=>`${yn(s.label,t)} (${s.here?"here":"another device or an earlier visit"}, ${re(s.createdAt,t.timeZone)})`).join(" \xB7 ")||o}, ${n}`}}function Sa(e,t,n=!1){if(!Dt(e))return[];let o={label:"Did not work",target:{kind:"didNotWork"}};switch(e.kind){case"duplicate":{let r=e.candidates[0];return r?.kind==="worked"?[{label:"Remove duplicate",target:{kind:"worked",projectId:r.projectId}}]:[]}case"whetherWorked":return[o];case"local":return[...e.candidates.filter(r=>r.kind==="worked"&&!(n&&r.projectId===null)).map(r=>({label:`Keep ${yn(r,t)}`,target:{kind:"worked",projectId:r.projectId}})),o];case"whichProject":return[...e.candidates.filter(r=>r.kind==="worked"&&!(n&&r.projectId===null)).map(r=>({label:`Keep ${yn(r,t)}`,target:{kind:"worked",projectId:r.projectId}})),o]}}function Ca(e){let t=e.filter(r=>Dt(r)&&r.kind==="local").length,n=e.length-t,o=r=>`${r} ${r===1?"conflict":"conflicts"}`;return[...n?[`${o(n)} in Clockify`]:[],...t?[`${o(t)} between your edits`]:[]].join(", ")}function mi(e,t,n){return n.length?e("div",{class:"unknown",role:"note","aria-label":"Not loaded"},e("strong",null,"Not loaded: "),n.map(o=>bn(o,t.timeZone)).join("; "),". No complete read of Clockify covers this time, so it is not shown as \u201Cdid not work\u201D."):null}function gi(e,t,n){if(!t.conflicts.length)return null;let o=r=>{if(!n||!Dt(r))return null;let i=Sa(r,t,n.projectRequired);return i.length?e("div",{class:"row",role:"group","aria-label":"Resolve"},...i.map(s=>N(e,s.label,{variant:"sec",key:`resolve:${r.from}:${s.label}`,disabled:!n.enabled,onClick:()=>n.onResolve(r,s.target)}))):null};return e("section",{class:"conflicts","aria-label":"Conflicts in Clockify"},e("p",null,e("strong",null,Ca(t.conflicts)),n?" Choose what is right. It is listed under \u201CChanges to send\u201D first, and reaches Clockify only when you send it.":t.conflicts.every(r=>Dt(r)&&r.kind==="local")?" (connect and sync to choose)":" (read-only here: fix them in Clockify)"),e("ul",null,t.conflicts.map(r=>e("li",null,e("span",null,xa(r,t)),o(r)))))}var ja="This table isn\u2019t synced with Clockify: the app syncs only its own table. Its time entries are shown here, read only.",ce=e=>e instanceof Error?e.message:String(e),Ia="Two range edits not sent yet disagree about this time (made apart, for example on two devices). Choose one under Conflicts first.";function bi(e,t=()=>{},n=Date.now,o=ur){let r={kind:"loading"},i=!1,s,a,c={review:[],providerWon:[],recovered:[]},l=[],d=new Set,p=so(),y=async g=>{try{l=await jo(e,g,d)}catch{}},k=()=>Eo(Yn(l,new Set(c.review.map(g=>g.subject)))),f=g=>g.kind==="ready"||g.kind==="syncing"?g.settings:g.kind==="setup"?yi(g.draft):void 0,m=async()=>{try{s={...s,mirror:await oi(e,n)}}catch{s??={mirror:we()}}},b=g=>(r=g,t(g),g),T=async(g,w)=>{let C=e.proxy;b({kind:"setup",connection:g,draft:w,busy:"options"});try{let x=await Nr(Wt(C,g));return b({kind:"setup",connection:g,draft:w,options:x})}catch(x){return b({kind:"setup",connection:g,draft:w,error:ce(x)})}},S={state:()=>r,async load(){try{if(!(await Wr(e)).own){let C=await e.getData(),P=(await e.getResource(C.table)).get(O.name);return a=await ao(e,C.table,p),b({kind:"local",tableName:typeof P=="string"&&P?P:"Time entries"}),{}}}catch(w){return b({kind:"failed",message:ce(w)}),{}}let g=e.proxy;if(!g||typeof g.connections!="function")return await m(),b({kind:"no-proxy"}),{};try{let[w]=await g.connections({platform:it});if(!w)return b({kind:"not-connected"}),{};let C=await Ze(e),x=await e.getResource(await e.getApp()),P=Wn(E=>x.get(E),C);return P.ok?(await m(),b({kind:"ready",connection:w,settings:P.settings}),{syncing:S.sync()}):(await T(w,P.partial),{})}catch(w){return b({kind:"failed",message:ce(w)}),{}}},async appChanged(){if(r.kind!=="setup"||r.busy)return{};let{connection:g}=r;try{let w=await Ze(e),C=await e.getResource(await e.getApp()),x=Wn(P=>C.get(P),w);return!x.ok||r.kind!=="setup"||r.busy?{}:(b({kind:"ready",connection:g,settings:x.settings}),{syncing:S.sync()})}catch{return{}}},async connect(){if(r.kind!=="not-connected"||!e.proxy)return r;b({kind:"connecting"});try{return(await e.proxy.connect({platform:it}))?.status==="connected"?(await S.load(),r):b({kind:"not-connected"})}catch(g){return b({kind:"failed",message:ce(g)})}},async openSettings(){if(r.kind!=="ready"&&r.kind!=="setup")return r;let g=r.kind==="ready"?r.settings:r.draft;return T(r.connection,g)},async saveSettings(g){if(r.kind!=="setup"||!r.options)return r;let{connection:w,options:C}=r,x={...g,userId:C.user.id};b({...r,draft:x,busy:"saving"});try{if(!C.workspaces.some(D=>D.id===g.workspaceId))throw new Error("Choose one of the listed workspaces");let P=await Ee(e),E=await e.getResource(await e.getApp());E.set(P.settings.workspaceId,g.workspaceId),E.set(P.settings.userId,C.user.id),E.set(P.settings.lookbackDays,g.lookbackDays),await E.save()}catch(P){return b({kind:"setup",connection:w,draft:x,options:C,error:ce(P)})}return b({kind:"ready",connection:w,settings:x}),S.sync()},async sync(){if(r.kind!=="ready"||!e.proxy||i)return r;i=!0;let{connection:g,settings:w}=r;b({kind:"syncing",connection:g,settings:w});let C=E=>{r.kind==="syncing"&&b({...r,progress:E})},x=Wt(e.proxy,g),P={request(E,D,J){return E.endsWith("/time-entries")&&D?.page&&C({phase:"fetch",page:Number(D.page)}),x.request(E,D,J)}};try{let E=await Ee(e),D=await ri(e,P,w,E,n(),{clock:n,device:o,onProgress:({done:J,total:ie})=>C({phase:"save",done:J,total:ie})});return await y(E),c={review:D.review,providerWon:D.providerWon,recovered:D.recovered,...c.outcomes?{outcomes:c.outcomes}:{}},s={mirror:D.mirror,projects:D.projects,members:D.members,...D.account.weekStart?{weekStart:D.account.weekStart}:{},...D.account.userName?{userName:D.account.userName}:{},...D.account.workspaceName?{workspaceName:D.account.workspaceName}:{},...D.account.timeZone?{timeZone:D.account.timeZone}:{},...D.account.forceProjects!==void 0?{forceProjects:D.account.forceProjects}:{}},b({kind:"ready",connection:g,settings:w,last:{ok:!0,result:D,at:n()}})}catch(E){return b({kind:"ready",connection:g,settings:w,last:{ok:!1,error:ce(E),at:n(),problem:Bn(E,n())}})}finally{i=!1}},cancelSettings(){if(r.kind!=="setup"||r.busy)return r;let g=yi(r.draft);return g?b({kind:"ready",connection:r.connection,settings:g}):r},async setLookback(g){if(r.kind!=="ready")return r;let{connection:w}=r,C={...r.settings,lookbackDays:g};try{let x=await Ee(e),P=await e.getResource(await e.getApp());P.set(x.settings.lookbackDays,g),await P.save()}catch(x){return b({...r,last:{ok:!1,error:ce(x),at:n(),problem:Bn(x,n())}})}return b({kind:"ready",connection:w,settings:C}),S.sync()},async reconnect(){if(r.kind!=="ready"||!e.proxy)return r;let g=r;b({kind:"connecting"});try{return(await e.proxy.connect({platform:it}))?.status==="connected"?(await S.load(),r):b(g)}catch(w){return b({kind:"failed",message:ce(w)})}},canDisconnect:()=>typeof e.proxy?.disconnect=="function",canOpen:()=>({external:typeof e.openExternal=="function",resource:typeof e.openResource=="function"}),async openExternal(g){if(typeof e.openExternal!="function")return!1;try{return(await e.openExternal(g)).status==="opened"}catch{return!1}},async openRow(g){if(typeof e.openResource!="function")return!1;try{if(r.kind==="local")return await e.openResource(g),!0;let w=await Ze(e);if(!w.row.entryId)return!1;let C=await R(w,g);return C?(await e.openResource(C),!0):!1}catch{return!1}},async disconnect(){let g=e.proxy;if(typeof g?.disconnect!="function"||r.kind!=="ready"&&r.kind!=="setup")return r;try{await g.disconnect({platform:it})}catch(w){return b({kind:"failed",message:ce(w)})}return b({kind:"not-connected"})},names:()=>({...s?.userName?{userName:s.userName}:{},...s?.workspaceName?{workspaceName:s.workspaceName}:{},...s?.timeZone?{timeZone:s.timeZone}:{}}),sheet(g=n()){if(r.kind==="local")return a;if(!s)return;let w=f(r);return ae(xo({mirror:s.mirror,...s.projects?{projects:s.projects}:{},...s.members?{members:s.members}:{},...w?{settings:w}:{},now:g,timeZone:s.timeZone??p,...s.weekStart?{weekStart:s.weekStart}:{},...s.forceProjects!==void 0?{forceProjects:s.forceProjects}:{}}))},changes(){let g=To(k());return g.size?{...c,review:c.review.map(w=>g.has(w.subject)?{...w,blockers:[...w.blockers,Ia]}:w)}:c},editBlockers(g){if(sr(g))return["It is not in Clockify yet: it is created when you send it. Discard it to undo."];if(!s)return["Nothing has been read from Clockify yet."];let w=$e(s.mirror,g);return w?[...r.kind==="ready"&&e.proxy?[]:["Connect and sync first."],...Me(w,v())]:["This entry is not in what was last read."]},projectChoices:()=>({projects:I(),required:s?.forceProjects===!0}),async editEntry(g,w){await $(g,async(C,x)=>{let P=await ln(C,x);if(!P)throw new Error("The row has no start or end.");let E=w.projectId===void 0?P.projectId:w.projectId,D={...P,...w,projectId:E,project:E===P.projectId?P.project:E&&(s?.projects??[]).find(J=>J.id===E)?.name||null};await le(C,x,D)&&await C.save()})},async deleteEntry(g){await $(g,(w,C)=>lr(w,C,!0))},async discard(g){if(!sr(g)){await $(g,(w,C)=>pn(w,C));return}try{if(i)throw new Error("Wait for the sync or send to finish.");let w=c.review.find(x=>x.entryId===g),C=await Ee(e);w&&await pn(await e.getResource(w.subject),C),c={...c,review:c.review.filter(x=>x.entryId!==g)},delete c.error}catch(w){c={...c,error:ce(w)}}t(r)},async editRange(g){try{if(i)throw new Error("Wait for the sync or send to finish.");let w=r.kind==="ready"&&e.proxy?r.settings:void 0;if(!w||!s)throw new Error("Connect and sync first.");let C=g.exact?g.from:gt(g.from),x=g.exact?g.to:gt(g.to),P=S.sheet(),E=P?.window;if(!P||!E||CE.to)throw new Error(`The range has to be inside the last ${w.lookbackDays} days, which are what is loaded.`);if(P.unknown.some(j=>j.fromC))throw new Error("Part of this range is not loaded from Clockify. Sync, or load older entries, first.");let D=se(s.mirror).filter(j=>!j.deletedAt&&!j.absentSince&&(j.fields.workspaceId??w.workspaceId)===w.workspaceId&&(j.fields.userId??w.userId)===w.userId).map(j=>Ce(j)),J=s.projects??[],ie=Yr(D,{from:C,to:x,target:g.target},{...v(),billableDefault:j=>J.find(q=>q.id===j)?.billable===!0});if(ie.refused.length)throw new Error(ie.refused.join(" "));if(!ie.steps.length)throw new Error("Nothing to change: Clockify already says this for that range.");let me=await Ee(e);await y(me);let Ie=await fn(e,me,s.mirror,v()),{replace:Q,outside:Ke}=Po(Yn(l,new Set(Ie.map(j=>j.subject))),{from:C,to:x});if(Ke.length)throw new Error(`A range edit not sent yet (${Ke.map(j=>bn(j,s.timeZone??p)).join("; ")}) reaches outside this range. Send or discard it first, or edit a range that covers all of it.`);let Mt=new Set(Q.flatMap(j=>j.rows)),Lt=Ie.filter(j=>!Mt.has(j.subject)),vn=new Set(Lt.filter(j=>j.kind!=="create").map(j=>j.entryId));if(ie.steps.some(j=>j.op!=="create"&&vn.has(j.entryId))||Lt.some(j=>j.kind==="create"&&j.desired.startC))throw new Error("An entry in this range has a change that is not sent yet. Send or discard it first.");for(let j of Ie.filter(q=>Mt.has(q.subject)))await pn(await e.getResource(j.subject),me);let u=await Zo(e,me,s.mirror,ie.steps,j=>R(me,j)),h=new Date(n()).toISOString(),A={v:1,id:mn(n),device:o,createdAt:h,from:C,to:x,target:g.target,rows:u,supersedes:Q.map(j=>j.id)},Z=await Io(e,me,A);return d.add(Z),l=[...l,{...A,subject:Z}],c={...c,review:await fn(e,me,s.mirror,v())},delete c.error,t(r),!0}catch(w){return c={...c,error:ce(w)},t(r),!1}},resolveConflict:(g,w)=>S.editRange({from:g.from,to:g.to,target:w,exact:!0}),async send(){if(r.kind!=="ready"||!e.proxy||i)return r;let g=S.changes().review.filter(x=>!x.blockers.length);if(!g.length)return r;i=!0;let{connection:w,settings:C}=r;c={...c,sending:{done:0,total:g.length}},delete c.outcomes,delete c.error,t(r);try{let x=await Ee(e),P=await Ne.open(e,x,{clock:n}),E=await ei({store:e,schema:x,log:P,read:{transport:Wt(e.proxy,w),workspaceId:C.workspaceId,userId:C.userId,...s?.timeZone?{timeZone:s.timeZone}:{},clock:n,newId:()=>mn(n),device:o},write:v(),members:s?.members??[],lease:{device:o,clock:n},...s?.timeZone?{timeZone:s.timeZone}:{},onProgress:(J,ie)=>{c={...c,sending:{done:J,total:ie}},t(r)}},g);s={...s??{},mirror:P.mirror},c={review:await fn(e,x,P.mirror,v()),providerWon:c.providerWon,recovered:[],outcomes:{at:n(),results:E}}}catch(x){c={...c,error:ce(x)},delete c.sending}finally{i=!1}return b(r)}};function I(){return(s?.projects??[]).filter(g=>typeof g.id=="string"&&typeof g.name=="string"&&g.archived!==!0).sort((g,w)=>g.name.localeCompare(w.name))}function v(){return{now:n(),...s?.forceProjects!==void 0?{forceProjects:s.forceProjects}:{},projects:s?.projects??[]}}async function R(g,w){let C=new Set(await e.query({property:O.parent,value:g.table}));return(await e.query({property:g.row.entryId,value:w})).find(x=>C.has(x))}async function $(g,w){try{if(i)throw new Error("Wait for the sync or send to finish.");let C=await Ee(e),x=await R(C,g);if(!x)throw new Error("This entry has no row in the table.");let P=await e.getResource(x);if(!(await De(P,C))?.baseline)throw new Error("Sync first: this row has not been compared yet.");await w(P,C);let E=await De(await e.getResource(x),C),D=E&&Pt(E,s?$e(s.mirror,g):void 0,v(),s?Ot(s.mirror):void 0);c={...c,review:Nt([...c.review.filter(J=>J.entryId!==g),...D?[D]:[]])},delete c.error}catch(C){c={...c,error:ce(C)}}t(r)}function oe(){return k().map(g=>{let w=x=>x.kind==="didNotWork"?"2":x.projectId===null?"1":`0${x.projectId}`,C=[];for(let x of g.intents){let P=Gn(x.target);C.some(E=>w(E)===w(P))||C.push(P)}return C.sort((x,P)=>w(x)({id:x.id,label:Gn(x.target),here:x.device===o,createdAt:Date.parse(x.createdAt)}))}})}function ae(g){let w=oe(),C=w.length?{...g,conflicts:[...g.conflicts,...w]}:g;if(!c.review.length)return C;let x=new Map(c.review.map(E=>[E.entryId,E])),P=c.review.filter(E=>E.kind==="create").map(({entryId:E,desired:D})=>{let J=nn(D.projectId??void 0,s?.projects??[]);return{id:E,description:Ye(D.name),start:D.start,end:D.end,billable:D.billable,...J?{project:J}:{},pending:"create"}});return{...C,entries:[...C.entries,...P].map(E=>{if(E.pending==="create")return E;let D=x.get(E.id);if(!D)return E;if(D.kind==="delete")return{...E,pending:"delete"};let{desired:J}=D,ie=nn(J.projectId??void 0,s?.projects??[]),{project:me,...Ie}=E;return{...Ie,description:Ye(J.name),start:J.start,end:J.end,billable:J.billable,...ie?{project:ie}:{},pending:"update"}})}}return S}function yi(e){let{workspaceId:t,userId:n,lookbackDays:o}=e;return t&&n&&o?{workspaceId:t,userId:n,lookbackDays:o}:void 0}var Ra=e=>{let t=Math.round(e/6e4);return t<120?`${t} min`:`${Math.round(t/6)/10} h`};function hi(e){switch(e.kind){case"loading":return"Loading\u2026";case"local":return ja;case"no-proxy":return"This host cannot reach the integration proxy on behalf of an app, so this app cannot import. Nothing was fetched.";case"not-connected":return"Not connected. Connect a Clockify account to import your completed time entries. Nothing is written to Clockify until you send a change.";case"connecting":return"Waiting for you to confirm the connection\u2026";case"failed":return`This app cannot run: ${e.message}`;case"setup":return e.busy==="options"?"Connected. Reading your Clockify workspaces\u2026":e.busy==="saving"?"Saving settings\u2026":e.error?`Setup failed: ${e.error}`:"Connected. Choose the workspace and how far back to import.";case"syncing":return`Importing the last ${e.settings.lookbackDays} days\u2026`;case"ready":{if(!e.last)return`Ready to import the last ${e.settings.lookbackDays} days of Clockify entries.`;if(!e.last.ok)return`Import failed: ${e.last.error}. Rows already in the table are kept.`;let{created:t,updated:n,unchanged:o,removed:r,warnings:i,log:s}=e.last.result;return`Last synced ${new Date(e.last.at).toLocaleTimeString()}: ${t} created, ${n} updated, ${o} unchanged, last ${e.settings.lookbackDays} days.`+(r?` ${r} removed (deleted in Clockify).`:"")+(s.candidates?` ${s.candidates} missing from Clockify's list, re-checked on the next sync.`:"")+(s.unknownMs?` ${Ra(s.unknownMs)} not loaded.`:"")+(e.last.result.account.forceProjects?" This workspace requires a project on every entry.":"")+(e.last.result.sendingElsewhereUntil?" Another open copy of this app is sending changes to Clockify.":"")+(i.length?` Warnings: ${i.join("; ")}`:"")}}}function wi(e,t,n,o){return mi(e,t,o)}function ki(e,t,n){return gi(e,t,n)}var Ea=6e4,vi=(e,t)=>e.unknown.map(n=>({from:Math.max(n.from,t.from),to:Math.min(n.to,t.to)})).filter(n=>n.to-n.from>=Ea);var xi={name:"Description",projectId:"Project",billable:"Billable",start:"Start",end:"End"},Fe=(e,t)=>new Date(ue(e,t)).toISOString().slice(0,16);function At(e,t){if(!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/.test(e))return;let n=Date.parse(`${e}:00Z`);if(Number.isFinite(n))return Re(n,t)[0]}function hn(e,t,n){switch(e){case"name":return t.name;case"projectId":return t.project??(t.projectId?t.projectId:"No project");case"billable":return t.billable?"Yes":"No";case"start":case"end":return`${H(_(t[e],n))} ${re(t[e],n)}`}}function Ta(e,t){return e.kind==="delete"?["Delete this entry in Clockify"]:e.kind==="create"?[`${e.copyOf?"Create the rest of the split entry":"Create a new entry"}: ${hn("start",e.desired,t)} \u2013 ${re(e.desired.end,t)}, ${hn("projectId",e.desired,t)}`]:e.fields.map(n=>`${xi[n]}: ${hn(n,e.base,t)} \u2192 ${hn(n,e.desired,t)}`)}var Pa={sent:"Sent",adjusted:"Sent; Clockify stored other values",already:"Clockify already had this",conflict:"Not sent: changed in Clockify, Clockify\u2019s values kept",refused:"Not sent",failed:"Failed",uncertain:"Unknown whether it arrived","not-sent":"Not sent (stopped after an earlier one)",changed:"Not sent: changed after review",gone:"Deleted in Clockify; row removed",bound:"Clockify already had it"};function Oa(e){return`${e.kind==="delete"?`Delete \u201C${e.title}\u201D`:`\u201C${e.title}\u201D`}: ${Pa[e.status]}${e.message?`. ${e.message}`:""}`}function Si(e,t,n,o,r){let{review:i,providerWon:s,recovered:a,outcomes:c,sending:l,error:d}=t;if(!i.length&&!s.length&&!a.length&&!c?.results.length&&!d)return null;let p=n.timeZone,y=i.filter(m=>!m.blockers.length),k=[];i.length&&k.push(e("p",null,e("strong",null,`${i.length} ${i.length===1?"change":"changes"} to send to Clockify`)," Made in this drive and not sent yet. Nothing is sent until you press Send."),e("ul",{class:"chg"},i.map(m=>e("li",{"data-entry":m.entryId},e("div",{class:"chg-head"},e("button",{type:"button",class:"link","data-open":m.entryId},m.title),N(e,"Discard",{variant:"ghost",key:`discard:${m.entryId}`,label:`Discard the change to ${m.title}`,disabled:r,onClick:()=>o.onDiscard(m.entryId)})),e("ul",null,Ta(m,p).map(b=>e("li",null,b))),m.blockers.length?e("p",{class:"chg-blocked"},`Cannot be sent: ${m.blockers.join(" ")}`):null))),e("div",{class:"row"},N(e,l?`Sending ${Math.min(l.done+1,l.total)} of ${l.total}\u2026`:`Send ${y.length} to Clockify`,{key:"send-changes",disabled:r||!y.length,onClick:o.onSend}))),s.length&&k.push(e("div",{class:"chg-notes",role:"note","aria-label":"Kept from Clockify"},e("strong",null,"Changed here and in Clockify: Clockify\u2019s values were kept."),e("ul",null,s.map(m=>e("li",null,`\u201C${m.title}\u201D: `,m.fields.map(b=>b.field==="delete"?"your deletion was dropped":`${xi[b.field]} is \u201C${String(b.clockify??"")}\u201D (yours was \u201C${String(b.yours??"")}\u201D)`).join("; ")))))),a.length&&k.push(e("p",{class:"muted"},a.map(m=>m.applied?`An interrupted send of \u201C${m.title}\u201D had arrived in Clockify.`:`An interrupted send of \u201C${m.title}\u201D had not arrived; it is listed again.`).join(" "))),c?.results.length&&k.push(e("div",{"aria-label":"Last send"},e("strong",null,"Last send"),e("ul",null,c.results.map(m=>e("li",{"data-status":m.status},Oa(m)))))),d&&k.push(de(e,{tone:"neg",icon:"err",lead:"Could not change this:",text:d,role:"alert"}));let f=e("section",{class:"changes","aria-label":"Changes to send"},...k);return f.addEventListener("click",m=>{let T=m.target.closest("[data-open]")?.getAttribute("data-open");T&&o.onOpen(T)}),f}var wn=(e,t)=>t?e("span",{class:"tag-pending"},t==="delete"?"Delete not sent":t==="create"?"New, not sent":"Not sent"):null;function Ci(e,t,n){let o=e("input",{id:"ed-desc",type:"text",class:"inp",value:t.description}),r=e("select",{id:"ed-proj",class:"sel"},n.projectRequired?null:e("option",{value:"",selected:!t.project},"No project"),...n.projects.map(y=>e("option",{value:y.id,selected:t.project?.id===y.id},y.name)),t.project&&!n.projects.some(y=>y.id===t.project.id)?e("option",{value:t.project.id,selected:!0},t.project.name??t.project.id):null),i=e("input",{id:"ed-bill",type:"checkbox",checked:t.billable}),s=e("input",{id:"ed-start",type:"datetime-local",class:"inp",step:60,value:Fe(t.start,n.timeZone)}),a=e("input",{id:"ed-end",type:"datetime-local",class:"inp",step:60,value:Fe(t.end,n.timeZone)}),c=e("p",{class:"chg-blocked",role:"alert",hidden:!0}),l=(y,k,f)=>e("div",{class:"field"},e("label",{for:y},k),f),d=()=>{let y=At(s.value,n.timeZone),k=At(a.value,n.timeZone);if(y===void 0||k===void 0||!(y{y.preventDefault(),d()}),{body:p,footer:[N(e,"Save",{key:"edit-save",onClick:d}),N(e,"Cancel",{variant:"ghost",key:"edit-cancel",onClick:n.onCancel})]}}var ve=(e,t)=>[e("span",{"aria-hidden":"true"},fe(t)),e("span",{class:"sr"},he(t))];function $t(e,t){return e("span",{class:`dot${t?"":" none"}`,style:t?.color?`background: ${t.color}`:void 0,"aria-hidden":"true"})}function yr(e,t){return e("div",{class:"proj"},$t(e,t),e("span",null,ke(t),t?.client?e("small",null,t.client):null))}function ji(e,{grid:t,week:n,onCell:o}){let r=Pe(n.days[0],n.days[6]),i=a=>[t.days[a].isToday?"today":"",t.days[a].isFuture?"future":"",t.days[a].inWindow?"":"out"].filter(Boolean).join(" ")||void 0,s=(a,c="")=>e("td",{class:[a===void 0?"":i(a),"z",c].filter(Boolean).join(" ")||void 0},e("span",{"aria-hidden":"true"},"\u2013"),e("span",{class:"sr"},"none"));return e("div",{class:"card gridwrap"},e("table",{class:"week"},e("caption",{class:"sr"},`Hours per project, ${r}`),e("thead",null,e("tr",null,e("th",{scope:"col"},"Project"),...t.days.map((a,c)=>e("th",{scope:"col",class:i(c),"aria-label":`${_e(a.key)} ${H(a.key)}${a.isToday?", today":""}${a.inWindow?"":", outside import window"}`},e("span",{class:"wd"},a.isToday?"Today":Ge(a.key)),e("span",{class:"dd"},String(Ut(a.key))))),e("th",{scope:"col",class:"tot"},"Total"))),e("tbody",null,...t.rows.map(a=>e("tr",null,e("th",{scope:"row"},yr(e,a.project)),...a.cells.map((c,l)=>{if(!c)return s(l);let d=e("button",{type:"button","data-k":`cell:${a.key}:${t.days[l].key}`},...ve(e,c));return d.addEventListener("click",()=>o(t.days[l].key,a.key)),e("td",{class:i(l)},d)}),e("td",{class:"tot"},...ve(e,a.total))))),e("tfoot",null,e("tr",null,e("th",{scope:"row"},"Day total"),...t.dayTotals.map((a,c)=>a?e("td",{class:i(c)},...ve(e,a)):s(c)),e("td",{class:"tot"},...ve(e,t.total))))))}function Ii(e,t,n){return e("div",{class:"foot"},e("span",null,"Billable ",e("b",null,fe(t.billable))),e("span",null,"Not billable ",e("b",null,fe(t.notBillable))),e("span",null,`Times in ${n}`))}function Ri(e,t){return t?e("div",{class:"note"},e("span",{class:"ring","aria-hidden":"true"}),t===1?"1 timer is running in Clockify. It appears here after you stop it and sync.":`${t} timers are running in Clockify. They appear here after you stop them and sync.`):null}var br="https://app.clockify.me/tracker";function tt(e,t){let n=e("h2",{id:"sheet-h",tabindex:"-1"},t.title),o=N(e,"Close",{variant:"ghost",icon:"x",iconOnly:!0,onClick:t.onClose}),r=e("div",{class:`drawer${t.full?" full":""}`,role:"dialog","aria-modal":"true","aria-labelledby":"sheet-h"},e("header",null,n,o),e("div",{class:"body"},...t.body),t.footer.length?e("footer",null,...t.footer):null),i=e("div",{class:"scrim"});i.addEventListener("click",t.onClose);let s=e("div",null,i,r);return s.addEventListener("keydown",a=>{if(a.key==="Escape"){a.preventDefault(),t.onClose();return}if(a.key!=="Tab")return;let c=[...r.querySelectorAll('button:not([disabled]), a[href], select, input, [tabindex="0"]')];if(!c.length)return;let l=c[0],d=c[c.length-1],p=e.doc.activeElement;a.shiftKey&&(p===l||p===n)?(a.preventDefault(),d.focus()):!a.shiftKey&&p===d&&(a.preventDefault(),l.focus())}),{node:s,focus:n}}function Ei(e,t,n){let o=n.edit,r=t.description||"(no description)";if(o?.mode==="edit"){let k=Ci(e,t,o.editor);return tt(e,{title:`Edit: ${r}`,full:n.full,onClose:o.editor.onCancel,body:[k.body],footer:k.footer})}let i=_(t.start,n.timeZone),s=t.end-t.start,a=k=>`${H(_(k,n.timeZone),!0)}, ${re(k,n.timeZone)}`,c=n.lastChecked?Date.parse(n.lastChecked):NaN,l=(k,f)=>[e("dt",null,k),e("dd",null,f)],d=!!o&&!o.blockers.length,p=o?.mode==="confirm-delete",y=o&&o.blockers.length?e("p",{class:"muted",style:"font-size: 12.5px; margin: 0"},`Not editable here: ${o.blockers.join(" ")}`):null;return tt(e,{title:r,full:n.full,onClose:n.onClose,body:[t.pending?e("p",{style:"margin: 0"},wn(e,t.pending),t.pending==="delete"?" Deleting it in Clockify is listed under \u201CChanges to send\u201D.":t.pending==="create"?" A new entry from a range edit, listed under \u201CChanges to send\u201D. It is created in Clockify only when you send it.":" Shown with your change, which is listed under \u201CChanges to send\u201D."):null,p&&o?e("div",{class:"confirm",role:"group","aria-label":"Delete entry"},e("p",null,"Delete this entry in Clockify? It is listed under \u201CChanges to send\u201D first, and deleted only when you send it."),e("div",{class:"row"},N(e,"Delete in Clockify",{variant:"danger",key:"confirm-delete",onClick:o.onConfirmDelete}),N(e,"Keep",{variant:"ghost",key:"cancel-delete",onClick:o.onCancelDelete}))):null,e("div",null,e("div",{class:"bigdur"},e("span",{"aria-hidden":"true"},fe(s)),e("span",{class:"sr"},he(s))),e("div",{class:"muted",style:"font-size: 12.5px; margin-top: 4px"},`${n.full?Ge(i):_e(i)} ${H(i,!n.full)} \xB7 ${re(t.start,n.timeZone)} \u2013 ${re(t.end,n.timeZone)}`)),e("dl",{class:"kv"},...l("Project",e("span",{class:"proj",style:"display: inline-flex"},$t(e,t.project),ke(t.project))),...t.project?.client?l("Client",t.project.client):[],...l("Billable",t.billable?"Yes":"No"),...t.member?l("Member",t.member):[],...l("Start",e("span",{class:"num"},a(t.start))),...l("End",e("span",{class:"num"},a(t.end)))),e("div",{class:"prov"},`Imported from Clockify${Number.isFinite(c)?`, last checked ${H(_(c,n.timeZone))} ${re(c,n.timeZone)}`:""}. ${o?"Edits are saved in this drive and reach Clockify only when you send them. If Clockify changes the same field, Clockify\u2019s value is kept.":"Changes made in Clockify replace this copy on the next sync."}`),y],footer:[d&&o&&!p&&t.pending!=="delete"?N(e,"Edit",{key:"edit",onClick:o.onEdit}):null,d&&o&&!p&&t.pending!=="delete"?N(e,"Delete entry\u2026",{variant:"danger",key:"delete",onClick:o.onDelete}):null,o&&t.pending?N(e,"Discard change",{variant:"sec",key:"discard",onClick:o.onDiscard}):null,n.openRow?N(e,"Open row in Atomic",{variant:"sec",key:"open-row",onClick:n.openRow}):null,gn(e,br,"Open Clockify","btn ghost",n.openExternal)]})}var hr=36e5,Ti="not-worked",Na="worked:";function Da(e){return e===Ti?{kind:"didNotWork"}:{kind:"worked",projectId:e.slice(7)||null}}function Pi(e,t){let n=Math.floor(t.now/hr)*hr,o=e("input",{id:"rg-from",type:"datetime-local",class:"inp",step:60,value:Fe(n-hr,t.timeZone)}),r=e("input",{id:"rg-to",type:"datetime-local",class:"inp",step:60,value:Fe(n,t.timeZone)}),i=e("select",{id:"rg-what",class:"sel"},...t.projects.map(d=>e("option",{value:`worked:${d.id}`},`Worked on ${d.name}`)),t.projectRequired?null:e("option",{value:Na},"Worked, no project"),e("option",{value:Ti},"Did not work")),s=e("p",{class:"chg-blocked",role:"alert",hidden:!t.error},t.error??""),a=(d,p,y)=>e("div",{class:"field"},e("label",{for:d},p),y),c=()=>{let d=At(o.value,t.timeZone),p=At(r.value,t.timeZone);if(d===void 0||p===void 0||!(d{d.preventDefault(),c()}),{body:l,footer:[N(e,"Plan changes",{key:"range-save",onClick:c}),N(e,"Cancel",{variant:"ghost",key:"range-cancel",onClick:t.onCancel})]}}var Oi=(e,t,n)=>e===t&&n?`Today, ${H(e)}`:`${_e(e)} ${H(e)}`;function Aa(e,t,n){let o=t.project?.id??fr,r=n.highlight&&n.highlight.projectKey===o&&n.highlight.day===_(t.start,n.timeZone),i=`${re(t.start,n.timeZone)} \u2013 ${re(t.end,n.timeZone)}`,s=ke(t.project),a=e("button",{type:"button",class:`entry${r?" hl":""}${t.pending==="delete"?" del":""}`,"data-k":`entry:${t.id}`,"data-entry":t.id},e("span",{class:`desc${t.description?"":" muted"}`},t.description||"(no description)",t.pending?[" ",wn(e,t.pending)]:null),e("span",{class:"pj"},$t(e,t.project),e("span",null,s,n.stack&&t.billable?[e("span",{"aria-hidden":"true"}," \xB7 $"),e("span",{class:"sr"},", billable")]:null)),e("span",{class:"bill"},t.billable?[e("span",{"aria-hidden":"true",title:"Billable"},"$"),e("span",{class:"sr"},"Billable")]:null),e("span",{class:"rng"},i),e("span",{class:"dur"},e("span",{"aria-hidden":"true"},fe(t.end-t.start)),e("span",{class:"sr"},he(t.end-t.start))));return a.addEventListener("click",()=>n.onOpen(t)),a}function wr(e,t,n){return e("section",{class:`card day${n.stack?" stack":""}`,"data-day":t.key,"aria-label":Oi(t.key,n.today,!1),...n.attrs??{}},e("div",{class:"dayhead"},e("h3",null,Oi(t.key,n.today,n.stack)),e("span",{class:"num"},...ve(e,t.total))),...t.entries.map(o=>Aa(e,o,n)))}function Ni(e,t,n){return t.length?t.map(o=>wr(e,o,n)):[e("p",{class:"muted",style:"margin: 8px 2px"},"No completed entries this week.")]}function Di(e,t,n,o,r){let i=t.map((a,c)=>{let l=e("button",{type:"button",role:"tab",id:`tab-${a.key}`,"aria-selected":a.key===o?"true":"false","aria-controls":"day-panel",tabindex:a.key===o?"0":"-1",disabled:a.isFuture,"data-k":`tab:${a.key}`,"aria-label":`${_e(a.key)} ${H(a.key)}, ${n[c]?he(n[c]):"no entries"}${a.inWindow?"":", outside import window"}`},e("span",{class:"wd","aria-hidden":"true"},Ge(a.key).slice(0,1)),e("span",{class:"dd","aria-hidden":"true"},String(Ut(a.key))),e("span",{class:"t","aria-hidden":"true"},n[c]?fe(n[c]):"\u2013"));return l.addEventListener("click",()=>r(a.key)),l}),s=e("div",{class:"strip",role:"tablist","aria-label":"Days"},...i);return s.addEventListener("keydown",a=>{let l={ArrowRight:1,ArrowLeft:-1}[a.key];if(!l)return;let d=t.filter(k=>!k.isFuture).map(k=>k.key),p=d.indexOf(o),y=d[(p+l+d.length)%d.length];y&&(a.preventDefault(),r(y))}),s}function Ai(e,t){let n=(o,r)=>e("div",null,e("small",null,o),e("strong",null,...ve(e,r)));return[e("div",{class:"sumline"},n("Total",t.total),n("Billable",t.billable),n("Not billable",t.notBillable)),e("ul",{class:"card",style:"list-style: none; margin: 0; padding: 0","aria-label":"Time per project"},...t.rows.map(o=>{let r=o.project?.color,i=r?`background: ${r}; `:"";return e("li",{class:"prow"},yr(e,o.project),e("div",{class:"track","aria-hidden":"true"},e("i",{class:"all",style:`${i}width: ${o.barPercent}%`}),o.billable?e("i",{style:`${i}width: ${o.billableBarPercent}%`}):null),e("span",{class:"num"},e("span",{"aria-hidden":"true"},fe(o.total)),e("span",{class:"sr"},`${he(o.total)}, of which ${he(o.billable)} billable, `)),e("span",{class:"num pct"},li(o.shareTenths)))})),e("div",{class:"legend","aria-hidden":"true"},e("span",null,e("i"),"Billable"),e("span",null,e("i",{class:"a"}),"Not billable"))]}function $i(e,t){let n=(o,r)=>e("li",null,je(e.doc,o?"check":"minus",o?"y":"n"),e("span",null,r));return et(e,"Bring your Clockify time into this drive",e("p",null,"Copies your completed time entries from the last 7 or 30 days, so you can see them by week and link them from your own pages."),e("ul",null,n(!0,"Description, project, client, start, end and billable status"),n(!0,"A Clockify API key, entered on the next page. This app never sees it."),n(!1,"Nothing is written to Clockify until you send a change you made. Running timers, tags and rates are not copied.")),e("div",null,N(e,"Connect Clockify",{key:"connect",onClick:t})),e("p",{class:"fine"},"Your API key is under Preferences \u2192 Manage API keys in Clockify."))}var Mi=e=>et(e,"Finish connecting in the bar above this app",e("p",{class:"muted"},"Your Atomic Server opened a Clockify connection prompt at the top of the page. Paste your API key there and choose Connect."),e("div",null,N(e,"Waiting\u2026",{disabled:!0}))),kn=(e,t)=>et(e,t,e("div",{class:"skel",style:"width: 60%"}));function kr(e,t,n){return et(e,"Could not read your Clockify workspaces",e("p",{class:"muted"},t),e("div",null,N(e,"Try again",{key:"setup-retry",onClick:n})))}function vr(e,t,n,o){let r=i=>{let s=e("button",{type:"button","aria-pressed":t===i?"true":"false","data-k":`window:${i}`},`Last ${i} days`);return s.addEventListener("click",()=>n(i)),s};return e("div",{class:"seg",role:"group","aria-labelledby":o},r(7),r(30))}function Li(e,t){let{choice:n}=t,r=t.options.workspaces.length>1?e("fieldset",{class:"field"},e("legend",{class:"lbl"},"Workspace"),e("div",{class:"opts"},...t.options.workspaces.map(i=>{let s=e("input",{type:"radio",name:"workspace",value:i.id,checked:i.id===n.workspaceId,"data-k":`ws:${i.id}`});return s.addEventListener("change",()=>t.onChange({...n,workspaceId:i.id})),e("label",{class:"opt"},s,e("span",null,i.name))}))):null;return et(e,"What should be imported?",r,e("div",{class:"field"},e("span",{class:"lbl",id:"win-l"},"Window"),vr(e,n.lookbackDays,i=>t.onChange({...n,lookbackDays:i}),"win-l"),e("span",{class:"hint"},`Recomputed on every sync: ${t.windowText(n.lookbackDays)} today.`)),t.error?e("p",{role:"alert"},t.error):null,e("div",null,N(e,t.saving?"Importing\u2026":"Import entries",{key:"import",disabled:t.saving||!n.workspaceId,onClick:t.onSubmit})))}function _i(e){let t=n=>e("div",{class:"skelgrid"},e("div",{class:"skel",style:"width: 60%"}),...Array.from({length:8},()=>e("div",{class:"skel",style:n?"opacity: 0.4":void 0})));return[e("div",{class:"card",style:"padding: 14px; display: grid; gap: 16px","aria-hidden":"true"},t(!1),t(!1),t(!0),t(!0)),e("p",{class:"muted",style:"margin: 0; font-size: 12.5px"},"The first import can take a minute: every entry is one save in your drive.")]}function Wi(e,t){let n=t.from.slice(0,7)===t.to.slice(0,7)?`${Number(t.from.slice(8))} and ${H(t.to)}`:`${H(t.from)} and ${H(t.to)}`;return fi(e,{lead:`No completed time entries between ${n}.`,text:"Entries appear here once they are stopped in Clockify. A running timer is not imported.",actions:[N(e,"Sync now",{key:"empty-sync",disabled:t.syncing,onClick:t.onSync}),t.lookbackDays===7?N(e,"Import 30 days instead",{variant:"sec",key:"widen",disabled:t.syncing,onClick:t.onWiden}):null],link:gn(e,br,"Open Clockify","link",t.openExternal)})}function Vi(e,t,n){let o={summary:"Details",text:t.detail},r=(i="sec")=>N(e,n.waitSeconds>0?`Try again (${n.waitSeconds} s)`:"Try again",{variant:i,key:"retry",disabled:n.waitSeconds>0||n.syncing,onClick:n.actions.retry});switch(t.kind){case"reauth":return de(e,{tone:"warn",icon:"warn",role:"alert",lead:"Clockify no longer accepts this connection.",text:"The API key may have been deleted or regenerated.",action:N(e,"Reconnect Clockify",{key:"reconnect",onClick:n.actions.reconnect}),details:o});case"forbidden":return de(e,{tone:"neg",icon:"err",role:"alert",lead:`This Clockify account cannot read time entries in ${n.workspaceName??"this workspace"}.`,action:N(e,"Choose another workspace",{variant:"sec",key:"choose-ws",onClick:n.actions.chooseWorkspace}),details:o});case"rate-limited":return de(e,{tone:"warn",icon:"warn",role:"alert",lead:"Clockify asked for fewer requests.",text:n.waitSeconds>0?`Try again in ${n.waitSeconds} seconds.`:"You can try again now.",action:r(),details:o});case"network":return de(e,{tone:"neg",icon:"err",role:"alert",lead:"Could not reach the integration proxy.",text:"Your imported entries are still here.",action:r(),details:o});case"too-many":return de(e,{tone:"neg",icon:"err",role:"alert",lead:"Clockify returned more than 10,000 entries for this window,",text:"the most this app imports at once.",action:n.lookbackDays===30?N(e,"Import 7 days instead",{variant:"sec",key:"narrow",onClick:n.actions.narrow}):r(),details:o});default:return de(e,{tone:"neg",icon:"err",role:"alert",lead:"The last sync failed.",text:"Your imported entries are still here.",action:r(),details:o})}}function Fi(e,t,n){let o=t.some(r=>/projects/.test(r));return de(e,{tone:"warn",icon:"warn",lead:o?"Project names could not be loaded,":"The last sync finished with warnings.",...o?{text:"so some entries show a project id."}:{},action:N(e,"Dismiss",{variant:"ghost",icon:"x",iconOnly:!0,key:"dismiss",onClick:n}),details:{summary:"Details",text:t.join(` +`)}})}var Ki=e=>de(e,{tone:"info",icon:"plug",lead:"This Atomic Server can't connect apps to Clockify yet.",text:"Entries imported earlier are still shown.",details:{summary:"Details for your admin",text:"The host does not provide store.proxy (the integration-proxy relay for plugin frames)."}}),Hi=(e,t)=>de(e,{tone:"info",icon:"info",lead:"Not synced with Clockify.",text:`\u201C${t}\u201D isn\u2019t this app\u2019s own table, and the app syncs only its own. Its time entries are shown here, read only.`});function zi(e,t){return e("div",{class:"banner info"},je(e.doc,"info"),e("p",null,"Before ",e("strong",null,H(t.windowStart)),` is outside your ${t.lookbackDays}-day import window. Only entries imported earlier are listed.`),t.lookbackDays===7?N(e,"Import 30 days",{variant:"sec",key:"widen-band",disabled:t.syncing,onClick:t.onWiden}):e("span"))}function Ji(e,t){let{user:n,workspaces:o}=t.options,r=e("select",{class:"sel",id:"set-ws","data-k":"set-ws"},...o.map(s=>e("option",{value:s.id,selected:s.id===t.choice.workspaceId},s.name)));r.addEventListener("change",()=>t.onChange({...t.choice,workspaceId:r.value}));let i=t.canDisconnect?t.confirming?e("div",{class:"confirm",role:"group","aria-label":"Disconnect Clockify?"},e("p",null,e("strong",null,"Disconnect Clockify?"),` Syncing stops. The ${t.entryCount} ${t.entryCount===1?"entry":"entries"} already imported stay in this drive.`),e("div",{class:"row"},N(e,"Disconnect",{variant:"danger",key:"disconnect-yes",onClick:t.onDisconnect}),N(e,"Cancel",{variant:"ghost",key:"disconnect-no",onClick:t.onKeepConnected}))):e("div",null,N(e,"Disconnect\u2026",{variant:"danger",key:"disconnect",onClick:t.onAskDisconnect})):e("div",{class:"field"},e("span",{class:"lbl"},"Connection"),e("span",{class:"hint"},"This Atomic Server can't disconnect an app from inside the app yet. Imported entries stay either way."));return tt(e,{title:"Settings",full:t.full,onClose:t.onCancel,body:[e("div",{class:"field"},e("span",{class:"lbl"},"Clockify account"),e("span",null,n.name??n.id,n.email?e("span",{class:"muted"},` \xB7 ${n.email}`):null)),e("div",{class:"field"},e("label",{for:"set-ws"},"Workspace"),r,e("span",{class:"hint"},"Changing it imports from the new workspace on the next sync. Entries from the old one stay in the drive.")),e("div",{class:"field"},e("span",{class:"lbl",id:"set-win"},"Window"),vr(e,t.choice.lookbackDays,s=>t.onChange({...t.choice,lookbackDays:s}),"set-win")),e("div",{class:"field"},e("span",{class:"lbl"},"Days are grouped in"),e("span",null,t.timeZone,e("span",{class:"muted"},t.zoneSource==="profile"?" (your Clockify profile)":" (this browser)"))),t.error?e("p",{role:"alert",style:"margin: 0"},t.error):null,i],footer:[N(e,t.saving?"Saving\u2026":"Save",{key:"settings-save",disabled:t.saving,onClick:t.onSave}),N(e,"Cancel",{variant:"ghost",key:"settings-cancel",onClick:t.onCancel})]})}var Zi=e=>e<560?"narrow":e<720?"mid":"wide",$a=864e5;function qi(e,t,n={}){let o=e.ownerDocument,r=di(o),i=n.now??Date.now,s={view:"week",settingsOpen:!1,confirming:!1},a=r("div",{role:"status",class:"sr"}),c=r("div",{class:"pl"});c.append(a);let l=r("div");c.append(l),e.append(c);let d=Zi(n.width??(e.clientWidth||1024)),p,y=!1,k;n.width===void 0&&typeof ResizeObserver=="function"&&(k=new ResizeObserver(()=>{let u=Zi(e.clientWidth||1024);u!==d&&(d=u,Q())}),k.observe(e));let f=u=>()=>{u(),Q()},m=()=>{t.sync()},b=n.colorScheme??"light",T=()=>t.canOpen().external&&t.state().kind!=="local"?u=>{t.openExternal(u)}:void 0,S=()=>{s.settingsOpen=!0,s.confirming=!1,t.openSettings()};function I(u){switch(u.kind){case"loading":return["idle","Loading\u2026"];case"local":return["idle","Not synced"];case"no-proxy":return["paused","Offline"];case"not-connected":return["idle","Not connected"];case"connecting":return["syncing","Connecting\u2026"];case"setup":return u.busy==="saving"?["syncing","Saving\u2026"]:["synced","Connected"];case"syncing":return["syncing","Syncing\u2026"];case"failed":return["error","Error"];case"ready":return u.last?u.last.ok?["synced",`Synced ${Hn(u.last.at,i())}`]:u.last.problem.kind==="reauth"?["reauth","Reconnect needed"]:["error","Sync failed"]:["idle","Not synced yet"]}}let v=u=>u.kind==="ready"&&u.last&&!u.last.ok?u.last:void 0,R=u=>{let h=v(u);if(h?.problem.kind!=="rate-limited")return 0;let A=h.at+(h.problem.retryAfterSeconds??60)*1e3;return Math.max(0,Math.ceil((A-i())/1e3))};function $(u,h){let[A,Z]=I(u),j=u.kind==="ready"||u.kind==="syncing"||u.kind==="setup"||u.kind==="no-proxy",q=t.names().workspaceName,M=q?`Clockify \xB7 ${q}`:"Clockify",W=(u.kind==="ready"||u.kind==="syncing")&&!C(u,h),V=v(u)?.problem.kind==="reauth";return ui(r,{title:"Timesheets",srPrefix:"Clockify ",mark:"clock",chip:j&&d!=="narrow"?{letter:"C",text:M}:void 0,pill:pi(r,A,Z),action:W?N(r,"Sync now",{icon:"sync",iconOnly:d!=="wide",key:"sync",variant:V?"sec":"primary",disabled:u.kind==="syncing"||R(u)>0,onClick:m}):null})}function oe(u,h){let{userName:A,workspaceName:Z}=t.names(),j=[],q=h?.window?Pe(_(h.window.from,h.timeZone),_(h.window.to,h.timeZone),!1):void 0;d==="narrow"?j.push(r("span",null,r("b",null,Z?`Clockify \xB7 ${Z}`:"Clockify"))):A&&j.push(r("span",null,"Connected as ",r("b",null,A)));let M=h?x(h):0,W=null;if(u.kind==="syncing"&&u.progress){let F=u.progress;F.phase==="fetch"?j.push(r("span",null,"Fetching time entries\u2026 ",r("b",null,`page ${F.page}`))):(j.push(r("span",null,`Saving ${F.total} ${F.total===1?"entry":"entries"}\u2026 `,r("b",null,`${F.done} of ${F.total}`))),W=r("span",{class:"progress","aria-hidden":"true"},r("i",{style:`width: ${F.total?Math.round(F.done/F.total*100):0}%`})))}if(v(u)&&h?.lastChecked?j.push(r("span",null,"Last synced ",r("b",null,Hn(Date.parse(h.lastChecked),i())))):q&&j.push(r("span",null,d==="narrow"?q:["Importing ",r("b",null,q)],d==="narrow"||u.kind==="syncing"?"":", your entries only")),h&&u.kind==="ready"&&d==="wide"&&j.push(r("span",null,`${M} ${M===1?"entry":"entries"}`)),u.kind==="ready"){let F=r("button",{type:"button",class:"link","data-k":"settings"},"Settings");F.addEventListener("click",S),j.push(F)}return j.length?r("div",{class:"conn"},...j,W):null}let ae=u=>no(i(),u.weekStart,u.timeZone);function g(u,h,A){let Z=ae(u),j=h.start>=Z.start,q=["week","entries","projects"].map(F=>{let ee=r("button",{type:"button",role:"tab","aria-selected":s.view===F?"true":"false","aria-controls":"view-panel",tabindex:s.view===F?"0":"-1","data-k":`view:${F}`},F[0].toUpperCase()+F.slice(1));return ee.addEventListener("click",f(()=>{s.view=F,s.highlight=void 0})),ee}),M=r("div",{class:"seg",role:"tablist","aria-label":"View"},...q);M.addEventListener("keydown",F=>{let ee={ArrowRight:1,ArrowLeft:-1}[F.key];if(!ee)return;F.preventDefault();let xe=["week","entries","projects"];s.view=xe[(xe.indexOf(s.view)+ee+3)%3],s.highlight=void 0,Q(),l.querySelector(`[data-k="view:${s.view}"]`)?.focus()});let W=s.view==="projects"?r("div",{class:"weeknav"},r("span",{class:"range"},u.window?Pe(_(u.window.from,u.timeZone),_(u.window.to,u.timeZone)):"Everything imported"),u.window?r("span",{class:"muted",style:"font-size: 12.5px"},"the whole import window"):null):r("div",{class:"weeknav"},N(r,"Previous week",{variant:"sec",icon:"left",iconOnly:!0,key:"prev",onClick:f(()=>w(Kn(h,-1)))}),r("span",{class:"range","aria-live":"polite"},Pe(h.days[0],h.days[6],d!=="narrow")),N(r,"Next week",{variant:"sec",icon:"right",iconOnly:!0,key:"next",disabled:j,onClick:f(()=>w(Kn(h,1)))}),d==="narrow"?null:N(r,"This week",{variant:"ghost",key:"this",disabled:j,onClick:f(()=>w(void 0))})),V=A===void 0?null:r("div",{class:"weektotal"},r("small",null,d==="narrow"?"Week":"Week total"),r("strong",null,...ve(r,A)));return d!=="wide"?r("div",{class:"bar"},W,V,M):r("div",{class:"bar"},W,M,V)}let w=u=>{s.week=u,s.highlight=void 0,s.day=void 0};function C(u,h){return!!h?.window&&u.kind==="ready"&&!!u.last?.ok&&!x(h)}function x(u){let h=u.window;return h?u.entries.filter(A=>A.start>=h.from&&A.start{t.send()},onDiscard:B=>{t.discard(B)},onOpen:B=>{s.entryId=B,s.editing=void 0,s.opener="send-changes",Q()}},u.kind!=="ready"||!!t.changes().sending));let xe=u.kind==="ready"&&!t.changes().sending;u.kind==="ready"&&h.window&&V.push(r("div",{class:"row"},N(r,"Edit a time range\u2026",{variant:"sec",key:"range-open",disabled:!xe,onClick:f(()=>{s.rangeOpen=!0,s.rangeError=void 0,s.opener="range-open"})}))),V.push(ki(r,h,u.kind==="ready"?{enabled:xe,projectRequired:t.projectChoices().required,onResolve:(B,rt)=>{t.resolveConflict(B,rt)}}:void 0)),u.kind==="no-proxy"&&V.push(Ki(r)),u.kind==="local"&&V.push(Hi(r,u.tableName)),F&&V.push(Vi(r,F.problem,{workspaceName:t.names().workspaceName,lookbackDays:M,waitSeconds:R(u),syncing:j,actions:{reconnect:()=>{t.reconnect()},chooseWorkspace:S,retry:m,narrow:()=>{t.setLookback(7)}}})),ee?.ok&&ee.result.warnings.length&&s.dismissed!==ee.at&&V.push(Fi(r,ee.result.warnings,f(()=>{s.dismissed=ee.at})));let xn=j&&!h.entries.length,Yi=C(u,h);if(xn)return{body:[J(A),r("div",{class:"content"},...V,..._i(r))]};if(Yi&&h.window)return{body:[r("div",{class:"content",style:"padding-top: 12px"},...V,Wi(r,{from:_(h.window.from,h.timeZone),to:_(h.window.to,h.timeZone),lookbackDays:M,syncing:!1,onSync:m,onWiden:()=>{t.setLookback(30)},openExternal:T()}))]};let xr=ro(A,h.timeZone),Sr=s.view!=="projects"&&h.window&&W.days.some(B=>!B.inWindow)?zi(r,{windowStart:_(h.window.from,h.timeZone),lookbackDays:M,syncing:j,onWiden:()=>{t.setLookback(30)}}):null,Cr=s.view!=="projects"?wi(r,h,xr,vi(h,xr)):null,jr={timeZone:h.timeZone,today:Z,stack:d==="narrow",highlight:s.highlight,onOpen:B=>{s.entryId=B.id,s.opener=`entry:${B.id}`,Q()}};if(s.view==="week")if(V.push(A.start===ae(h).start?Ri(r,h.running):null,Sr,Cr),d==="narrow"){let B=W.days.filter(pe=>!pe.isFuture).map(pe=>pe.key),rt=W.days.filter((pe,Xi)=>W.dayTotals[Xi]>0).map(pe=>pe.key),_t=s.day&&B.includes(s.day)?s.day:B.includes(Z)?Z:rt.at(-1)??B.at(-1)??A.days[0],Gi=gr(h.entries,A,h.timeZone).find(pe=>pe.key===_t)??{key:_t,total:0,entries:[]};V.push(Di(r,W.days,W.dayTotals,_t,pe=>{s.day=pe,Q(),Ke(`tab:${pe}`)?.focus()}),wr(r,Gi,{...jr,attrs:{role:"tabpanel",id:"day-panel","aria-labelledby":`tab-${_t}`}}))}else V.push(ji(r,{grid:W,week:A,onCell:(B,rt)=>{s.view="entries",s.highlight={day:B,projectKey:rt},s.scrollTo=B,Q()}}),Ii(r,W,h.timeZone));else s.view==="entries"?V.push(Sr,Cr,...Ni(r,gr(h.entries,A,h.timeZone),jr)):V.push(...Ai(r,ci(h.entries,h.window)));let nt=s.entryId?h.entries.find(B=>B.id===s.entryId):void 0;return s.entryId&&!nt&&(s.entryId=void 0),u.kind!=="ready"&&(s.rangeOpen=!1),{body:[g(h,A,s.view==="projects"?void 0:W.total),r("div",{class:"content",role:"tabpanel",id:"view-panel","aria-label":s.view},...V)],...nt?{overlay:Ei(r,nt,{timeZone:h.timeZone,full:d!=="wide",lastChecked:h.lastChecked,onClose:f(()=>{s.entryId=void 0,s.editing=void 0}),openExternal:T(),openRow:t.canOpen().resource?()=>{t.openRow(nt.id)}:void 0,edit:D(nt.id,h.timeZone)})}:s.rangeOpen?{overlay:E(h)}:{}}}function E(u){let h=f(()=>{s.rangeOpen=!1,s.rangeError=void 0}),{projects:A,required:Z}=t.projectChoices(),j=Pi(r,{timeZone:u.timeZone,projects:A,projectRequired:Z,now:i(),...s.rangeError?{error:s.rangeError}:{},onSave:q=>{t.editRange(q).then(M=>{M&&(s.rangeOpen=!1),s.rangeError=M?void 0:t.changes().error,Q()})},onCancel:h});return tt(r,{title:"Edit a time range",full:d!=="wide",body:[j.body],footer:j.footer,onClose:h})}function D(u,h){let A=t.state();if(A.kind!=="ready"&&A.kind!=="syncing")return;let{projects:Z,required:j}=t.projectChoices(),q=f(()=>{s.editing=void 0});return{blockers:t.editBlockers(u),mode:s.editing??"view",editor:{timeZone:h,projects:Z,projectRequired:j,onSave:M=>{s.editing=void 0,s.entryId=void 0,t.editEntry(u,M)},onCancel:q},onEdit:f(()=>{s.editing="edit"}),onDelete:f(()=>{s.editing="confirm-delete"}),onConfirmDelete:()=>{s.editing=void 0,s.entryId=void 0,t.deleteEntry(u)},onCancelDelete:q,onDiscard:()=>{t.discard(u)}}}function J(u){return r("div",{class:"bar"},r("div",{class:"weeknav"},r("span",{class:"range"},Pe(u.days[0],u.days[6],d!=="narrow"))))}function ie(u){let{options:h,draft:A}=u;return s.choice??={workspaceId:A.workspaceId??h?.user.activeWorkspace??h?.workspaces[0]?.id??"",lookbackDays:A.lookbackDays??30},h&&!h.workspaces.some(Z=>Z.id===s.choice.workspaceId)&&(s.choice.workspaceId=h.workspaces[0]?.id??""),s.choice}let me=u=>{let h=t.sheet(i())?.timeZone??"UTC";return Pe(_(i()-u*$a,h),_(i(),h),!1)},Ie=()=>{s.choice&&t.saveSettings(s.choice)};function Q(){let u=t.state(),h=t.sheet(i()),A=o.activeElement,Z=A?.closest?.("[data-k]")?.getAttribute("data-k"),j=!!A?.closest?.('[role="dialog"]');u.kind!=="setup"&&(s.settingsOpen=!1,s.choice=void 0,s.confirming=!1);let q=hi(u);a.textContent!==q&&(a.textContent=q),c.setAttribute("data-size",d),c.setAttribute("data-scheme",b);let M=[$(u,h)],W;switch(u.kind){case"loading":M.push(kn(r,"Loading\u2026"));break;case"not-connected":M.push($i(r,()=>{t.connect()}));break;case"connecting":M.push(Mi(r));break;case"failed":M.push(r("div",{class:"content",style:"padding-top: 16px"},Mt(u.message)));break;case"setup":{let V=s.settingsOpen&&h,F=ie(u);if(V){M.push(oe(u,h));let xe=P(u,h);M.push(...xe.body),u.error&&!u.options?W=Lt(u.error):u.options&&(W=Ji(r,{options:u.options,choice:F,timeZone:h.timeZone,zoneSource:t.names().timeZone?"profile":"browser",entryCount:x(h),full:d!=="wide",saving:u.busy==="saving",error:u.error,canDisconnect:t.canDisconnect(),confirming:s.confirming,onChange:xn=>{s.choice=xn,Q()},onSave:Ie,onCancel:()=>{t.cancelSettings(),s.opener="settings"},onAskDisconnect:f(()=>{s.confirming=!0}),onDisconnect:()=>{t.disconnect()},onKeepConnected:f(()=>{s.confirming=!1})}));break}let ee=u.options?.user;ee&&M.push(r("div",{class:"conn"},r("span",null,"Connected as ",r("b",null,ee.name??ee.email??ee.id)))),u.busy==="options"?M.push(kn(r,"Reading your Clockify workspaces\u2026")):u.options?M.push(Li(r,{options:u.options,draft:u.draft,saving:u.busy==="saving",error:u.error,choice:F,windowText:me,onChange:xe=>{s.choice=xe,Q()},onSubmit:Ie})):M.push(kr(r,u.error??"Unknown error",()=>{t.openSettings()}));break}case"local":case"no-proxy":case"ready":case"syncing":{if(!h){M.push(kn(r,"Loading\u2026"));break}M.push(oe(u,h));let V=P(u,h);M.push(...V.body),W=V.overlay;break}}if(l.replaceChildren(r("div",null,...M)),W&&l.append(W.node),W&&!y?W.focus.focus():!W&&y&&s.opener?(Ke(s.opener)?.focus(),s.opener=void 0):Z?Ke(Z)?.focus():j&&W&&W.focus.focus(),y=!!W,s.scrollTo){let V=l.querySelector(`[data-day="${s.scrollTo}"]`);V?.scrollIntoView?.({block:"start"}),V?.querySelector(".entry.hl")?.focus(),s.scrollTo=void 0}vn(u)}let Ke=u=>l.querySelector(`[data-k="${u.replace(/["\\]/g,"\\$&")}"]`);function Mt(u){return r("div",{class:"banner neg",role:"alert"},r("span"),r("p",null,r("strong",null,"This app cannot run."),` ${u}`),r("span"))}function Lt(u){let h=kr(r,u,()=>{t.openSettings()}),A=r("div",{role:"dialog","aria-modal":"true","aria-label":"Settings"},r("div",{class:"scrim"}),r("div",{class:"drawer full"},h,r("footer",null,N(r,"Close",{variant:"ghost",key:"settings-close",onClick:()=>{t.cancelSettings()}}))));return{node:A,focus:A.querySelector("button")??A}}function vn(u){if(p&&clearTimeout(p),p=void 0,s.settingsOpen||u.kind!=="ready")return;let h=R(u);p=setTimeout(Q,h>0?1e3:3e4)}return{render:Q,setColorScheme(u){b=u,Q()},destroy(){p&&clearTimeout(p),k?.disconnect()}}}var Ui=':root,body{margin:0;background:var(--t-color-bg-body, #fafafa)}.pl{--pl-bg: var(--t-color-bg-body, #fafafa);--pl-surface: var(--t-color-bg, #ffffff);--pl-subtle: var(--t-color-bg-1, #f2f2f2);--pl-border: var(--t-color-bg-2, #cccccc);--pl-hair: color-mix(in srgb, var(--pl-border) 55%, var(--pl-surface));--pl-text: var(--t-color-text, #000000);--pl-muted: var(--t-color-text-light, #666666);--pl-accent: var(--t-color-main, #1b50d8);--pl-accent-soft: var(--t-color-main-selected-bg, #f3f6fd);--pl-neg: var(--t-color-alert, #cf5b5b);--pl-warn: var(--t-color-warning, #f5a623);--pl-pos: var(--t-color-success, #2f8f5b);--pl-radius: var(--t-radius, 9px);--pl-font: var( --t-font-family, "Open Sans", "Helvetica Neue", "Segoe UI", system-ui, sans-serif );--pl-font-h: var( --t-font-family-header, "Montserrat", "Segoe UI", system-ui, sans-serif );--pl-shadow: 0 6px 24px rgba(0, 0, 0, .12);box-sizing:border-box;min-height:100vh;background:var(--pl-bg);color:var(--pl-text);font:14px/1.45 var(--pl-font)}.pl *,.pl *:before,.pl *:after{box-sizing:border-box}.pl *:focus-visible{outline:2px solid var(--pl-accent);outline-offset:2px}:where(.pl) button{font:inherit;color:inherit}.pl h1,.pl h2,.pl h3{font-family:var(--pl-font-h);margin:0}.pl .num{font-variant-numeric:tabular-nums}.pl .sr{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap}.pl .muted{color:var(--pl-muted)}.pl svg.i{width:16px;height:16px;flex:none;stroke:currentColor;fill:none;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}.hdr{display:flex;align-items:center;gap:10px;padding:10px 16px;background:var(--pl-surface);border-bottom:1px solid var(--pl-hair);flex-wrap:wrap}.mark{width:28px;height:28px;border-radius:7px;background:var(--pl-accent);color:#fff;display:grid;place-items:center;flex:none}.mark svg.i{width:17px;height:17px;stroke-width:2}.hdr h1{font-size:16px;font-weight:700;letter-spacing:-.01em}.chip{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;padding:2px 10px 2px 4px;border:1px solid var(--pl-hair);border-radius:999px;background:var(--pl-surface);white-space:nowrap}.chip .src{width:18px;height:18px;border-radius:50%;background:#03a9f4;color:#fff;font:700 10px/18px var(--pl-font);text-align:center}.spacer{flex:1}.pill{display:inline-flex;align-items:center;gap:6px;font-size:12.5px;padding:3px 10px;border-radius:999px;background:var(--pl-subtle);white-space:nowrap}.pill:before{content:"";width:8px;height:8px;border-radius:50%;background:var(--pl-muted)}.pill[data-state=synced]:before{background:var(--pl-pos)}.pill[data-state=syncing]:before{background:var(--pl-accent);animation:pl-pulse 1.2s ease-in-out infinite}.pill[data-state=error]:before{background:var(--pl-neg)}.pill[data-state=reauth]:before{background:var(--pl-warn)}@keyframes pl-pulse{50%{opacity:.25}}.btn{display:inline-flex;align-items:center;gap:6px;border:1px solid transparent;border-radius:var(--pl-radius);padding:6px 14px;font-weight:600;font-size:13.5px;cursor:pointer;white-space:nowrap;background:var(--pl-accent);color:#fff!important;text-decoration:none}.btn.sec{background:var(--pl-surface);border-color:var(--pl-border);color:var(--pl-text)!important}.btn.ghost{background:transparent;color:var(--pl-text)!important;padding-inline:8px}.btn.danger{background:transparent;color:color-mix(in srgb,var(--pl-neg) 70%,var(--pl-text))!important;border-color:color-mix(in srgb,var(--pl-neg) 50%,var(--pl-surface))}.btn[disabled]{opacity:.55;cursor:default}.btn.icon{padding:6px}.link{color:var(--pl-accent);text-decoration:underline;text-underline-offset:2px;background:none;border:0;padding:0;cursor:pointer;font:inherit}.conn{display:flex;flex-wrap:wrap;align-items:center;gap:4px 14px;padding:7px 16px;font-size:12.5px;color:var(--pl-muted);background:var(--pl-surface);border-bottom:1px solid var(--pl-hair)}.conn b{color:var(--pl-text);font-weight:600}.conn .progress{flex-basis:100%;height:3px;background:var(--pl-subtle);border-radius:2px;overflow:hidden}.conn .progress i{display:block;height:100%;background:var(--pl-accent);border-radius:2px}.bar{display:flex;flex-wrap:wrap;align-items:center;gap:10px 16px;padding:14px 16px 10px;max-width:1200px}.weeknav{display:flex;align-items:center;gap:4px}.weeknav .range{font-family:var(--pl-font-h);font-weight:700;font-size:15px;padding-inline:6px;white-space:nowrap}.seg{display:inline-flex;background:var(--pl-subtle);border-radius:var(--pl-radius);padding:3px;gap:2px}.seg button{border:0;background:transparent;border-radius:calc(var(--pl-radius) - 3px);padding:4px 12px;font-size:13px;cursor:pointer;color:var(--pl-muted)}.seg button[aria-selected=true],.seg button[aria-pressed=true]{background:var(--pl-surface);color:var(--pl-text);font-weight:600;box-shadow:0 1px 2px #0000001f}.weektotal{margin-left:auto;text-align:right;line-height:1.1}.weektotal small{display:block;font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:var(--pl-muted)}.weektotal strong{font-family:var(--pl-font-h);font-size:22px;font-variant-numeric:tabular-nums}.content{padding:0 16px 16px;display:grid;gap:10px;max-width:1200px}.card{background:var(--pl-surface);border:1px solid var(--pl-hair);border-radius:var(--pl-radius)}.gridwrap{overflow-x:auto}table.week{width:100%;border-collapse:collapse;font-size:13.5px}table.week caption{text-align:left}table.week th,table.week td{padding:9px 10px;border-bottom:1px solid var(--pl-hair)}table.week thead th{font-weight:600;text-align:right;vertical-align:bottom;white-space:nowrap}table.week thead th:first-child{text-align:left}table.week thead th .wd{display:block;font-size:10.5px;letter-spacing:.07em;text-transform:uppercase;color:var(--pl-muted);font-weight:600}table.week thead th .dd{font-size:14px}table.week td{text-align:right;font-variant-numeric:tabular-nums}table.week td.z{color:var(--pl-muted)}table.week .today{background:var(--pl-accent-soft)}table.week thead th.today .wd{color:var(--pl-accent)}table.week .future .wd,table.week .future .dd{color:var(--pl-muted);font-weight:500}table.week .tot{border-left:1px solid var(--pl-hair);font-weight:700}table.week tfoot td,table.week tfoot th{font-weight:700;border-bottom:0;border-top:1px solid var(--pl-border)}table.week tbody th,table.week tfoot th{text-align:left;font-weight:600}table.week tbody th{min-width:170px}table.week td button{border:0;background:none;padding:2px 4px;margin:-2px -4px;border-radius:5px;cursor:pointer;font:inherit;font-variant-numeric:tabular-nums}table.week td button:hover{background:var(--pl-subtle)}.proj{display:flex;gap:8px;align-items:flex-start}.dot{width:10px;height:10px;border-radius:50%;flex:none;margin-top:5px;box-shadow:0 0 0 1px var(--pl-hair);background:var(--pl-muted)}.dot.none{background:transparent;box-shadow:inset 0 0 0 1.5px var(--pl-muted)}.proj small{display:block;font-weight:400;font-size:12px;color:var(--pl-muted)}.out{background-image:repeating-linear-gradient(135deg,transparent 0 5px,color-mix(in srgb,var(--pl-border) 45%,transparent) 5px 6px)}.foot{display:flex;flex-wrap:wrap;gap:4px 18px;font-size:12.5px;color:var(--pl-muted);padding-inline:2px}.foot b{color:var(--pl-text);font-variant-numeric:tabular-nums}.note{display:flex;gap:8px;align-items:center;font-size:12.5px;color:var(--pl-muted)}.note .ring{width:10px;height:10px;border-radius:50%;border:2px solid var(--pl-accent);flex:none}.day{display:grid}.dayhead{display:flex;justify-content:space-between;align-items:baseline;padding:10px 14px 8px;border-bottom:1px solid var(--pl-hair)}.dayhead h3{font-size:14px}.dayhead .num{font-weight:700}.entry{display:grid;grid-template-columns:minmax(0,1fr) 190px 18px 104px 44px;align-items:center;gap:12px;padding:9px 14px;border:0;border-bottom:1px solid var(--pl-hair);background:none;text-align:left;width:100%;cursor:pointer;font-size:13.5px}.entry:last-child{border-bottom:0}.entry:hover{background:var(--pl-subtle)}.entry.hl{background:var(--pl-accent-soft)}.entry .desc{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.entry .pj{display:flex;gap:6px;align-items:center;color:var(--pl-muted);font-size:12.5px;min-width:0}.entry .pj .dot{margin-top:0;width:8px;height:8px}.entry .pj span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.entry .bill{font-weight:700;color:var(--pl-muted);text-align:center}.entry .rng{color:var(--pl-muted);font-variant-numeric:tabular-nums;font-size:12.5px;white-space:nowrap}.entry .dur{text-align:right;font-weight:600;font-variant-numeric:tabular-nums}.stack .entry{grid-template-columns:minmax(0,1fr) auto;row-gap:2px}.stack .entry .desc{grid-column:1}.stack .entry .dur{grid-column:2;grid-row:1}.stack .entry .pj{grid-column:1}.stack .entry .rng{grid-column:2;grid-row:2;text-align:right}.stack .entry .bill{display:none}.sumline{display:flex;flex-wrap:wrap;gap:6px 24px;padding:2px 2px 4px}.sumline div small{display:block;font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:var(--pl-muted)}.sumline div strong{font-family:var(--pl-font-h);font-size:20px;font-variant-numeric:tabular-nums}.prow{display:grid;grid-template-columns:210px minmax(0,1fr) 56px 52px;gap:14px;align-items:center;padding:10px 14px;border-bottom:1px solid var(--pl-hair);font-size:13.5px}.prow:last-child{border-bottom:0}.track{height:12px;background:var(--pl-subtle);border-radius:3px;position:relative;overflow:hidden}.track i{position:absolute;inset:0 auto 0 0;border-radius:3px;background:var(--pl-muted)}.track i.all{opacity:.35}.prow .num{text-align:right}.prow .pct{color:var(--pl-muted)}.legend{display:flex;gap:16px;font-size:12px;color:var(--pl-muted);align-items:center;padding-inline:2px}.legend i{display:inline-block;width:18px;height:8px;border-radius:2px;background:var(--pl-muted);vertical-align:middle;margin-right:6px}.legend i.a{opacity:.35}.scrim{position:fixed;inset:0;background:#00000047}.drawer{position:fixed;top:0;right:0;bottom:0;width:380px;max-width:100%;background:var(--pl-surface);box-shadow:var(--pl-shadow);border-left:1px solid var(--pl-hair);display:grid;grid-template-rows:auto 1fr auto;animation:pl-slide .16s ease-out}.drawer.full{width:auto;left:0;border-left:0}@keyframes pl-slide{0%{transform:translate(24px);opacity:0}}.drawer header{display:flex;align-items:flex-start;gap:10px;padding:16px;border-bottom:1px solid var(--pl-hair)}.drawer header h2{font-size:17px;line-height:1.3;flex:1;text-wrap:balance}.drawer header h2:focus{outline:none}.drawer .body{padding:16px;display:grid;gap:16px;align-content:start;overflow:auto}.drawer footer{padding:12px 16px;border-top:1px solid var(--pl-hair);display:flex;gap:8px;flex-wrap:wrap}dl.kv{display:grid;grid-template-columns:96px 1fr;gap:8px 12px;margin:0;font-size:13.5px}dl.kv dt{color:var(--pl-muted)}dl.kv dd{margin:0}.bigdur{font-family:var(--pl-font-h);font-size:28px;font-weight:700;font-variant-numeric:tabular-nums;line-height:1}.prov{font-size:12.5px;color:var(--pl-muted);background:var(--pl-subtle);border-radius:calc(var(--pl-radius) - 2px);padding:10px 12px}.field{display:grid;gap:6px;border:0;padding:0;margin:0;min-width:0}.field>label,.field>.lbl,.field>legend{font-weight:600;font-size:13px;padding:0}.field>.seg{justify-self:start}.field legend{margin-bottom:6px}.field .hint{font-size:12px;color:var(--pl-muted)}select.sel{font:inherit;font-size:13.5px;padding:7px 10px;border:1px solid var(--pl-border);border-radius:calc(var(--pl-radius) - 2px);background:var(--pl-surface);color:var(--pl-text)}.confirm{border:1px solid color-mix(in srgb,var(--pl-neg) 45%,var(--pl-surface));border-radius:calc(var(--pl-radius) - 2px);padding:12px;display:grid;gap:10px;font-size:13px}.confirm p{margin:0}.row{display:flex;gap:8px;flex-wrap:wrap;align-items:center}.centre{display:grid;place-items:center;padding:40px 16px 48px}.panel{width:100%;max-width:440px;background:var(--pl-surface);border:1px solid var(--pl-hair);border-radius:var(--pl-radius);padding:24px;display:grid;gap:14px}.panel h2{font-size:19px;line-height:1.25;text-wrap:balance}.panel p{margin:0}.panel ul{margin:0;padding:0;list-style:none;display:grid;gap:8px;font-size:13.5px}.panel li{display:flex;gap:10px;align-items:flex-start}.panel li svg.i{margin-top:2px}.panel li .y{color:var(--pl-pos)}.panel li .n{color:var(--pl-muted)}.panel .fine{font-size:12px;color:var(--pl-muted)}.empty{text-align:center;display:grid;gap:12px;justify-items:center;padding:44px 16px 52px;max-width:420px;margin:0 auto}.empty svg.i{width:36px;height:36px;stroke-width:1.4;color:var(--pl-muted)}.empty p{margin:0}.opts{display:grid;gap:8px}.opt{display:flex;gap:10px;align-items:flex-start;padding:10px 12px;border:1px solid var(--pl-border);border-radius:calc(var(--pl-radius) - 2px);font-size:13.5px;cursor:pointer}.opt:has(input:checked){border-color:var(--pl-accent);background:var(--pl-accent-soft)}.opt input{margin-top:3px;accent-color:var(--pl-accent)}.skel{background:var(--pl-subtle);border-radius:4px;height:12px;animation:pl-pulse 1.6s ease-in-out infinite}.skelgrid{display:grid;grid-template-columns:170px repeat(8,1fr);gap:14px}.banner{display:grid;grid-template-columns:auto 1fr auto;gap:4px 12px;align-items:start;padding:11px 14px;border-radius:var(--pl-radius);border:1px solid;font-size:13.5px}.banner>svg.i{margin-top:2px}.banner.warn{background:color-mix(in srgb,var(--pl-warn) 12%,var(--pl-surface));border-color:color-mix(in srgb,var(--pl-warn) 55%,var(--pl-surface))}.banner.warn>svg.i{color:color-mix(in srgb,var(--pl-warn) 70%,var(--pl-text))}.banner.neg{background:color-mix(in srgb,var(--pl-neg) 10%,var(--pl-surface));border-color:color-mix(in srgb,var(--pl-neg) 50%,var(--pl-surface))}.banner.neg>svg.i{color:var(--pl-neg)}.banner.info{background:var(--pl-subtle);border-color:var(--pl-hair)}.banner p{margin:0}.banner details{grid-column:2 / 4;font-size:12px;color:var(--pl-muted)}.banner details summary{cursor:pointer;width:max-content}.banner code{font:11.5px/1.5 ui-monospace,SFMono-Regular,Menlo,monospace;display:block;margin-top:4px;white-space:pre-wrap;word-break:break-word}.strip{display:grid;grid-template-columns:repeat(7,1fr);gap:4px}.strip button{display:grid;gap:1px;justify-items:center;padding:6px 0 7px;border:1px solid transparent;border-radius:calc(var(--pl-radius) - 3px);background:var(--pl-surface);cursor:pointer;font-size:11px}.strip button .wd{color:var(--pl-muted);font-weight:600;letter-spacing:.05em}.strip button .dd{font-weight:700;font-size:14px}.strip button .t{font-variant-numeric:tabular-nums;color:var(--pl-muted)}.strip button[aria-selected=true]{border-color:var(--pl-accent);background:var(--pl-accent-soft)}.strip button[aria-selected=true] .t{color:var(--pl-text);font-weight:600}.strip button[disabled]{opacity:.55;cursor:default}.pl[data-size=mid] table.week .proj small{display:none}.pl[data-size=mid] table.week tbody th{min-width:0}.pl[data-size=mid] table.week{font-size:12.5px}.pl[data-size=mid] .entry{grid-template-columns:minmax(0,1fr) 140px 14px 96px 40px;gap:10px}.pl[data-size=narrow] .bar{gap:10px}.pl[data-size=mid] .bar .seg{order:3}.pl[data-size=narrow] .weeknav .range{font-size:14px}.pl[data-size=narrow] .weektotal strong{font-size:18px}.pl[data-size=narrow] .bar .seg{width:100%}.pl[data-size=narrow] .bar .seg button{flex:1}.pl[data-size=narrow] .prow{grid-template-columns:minmax(0,1fr) auto auto;row-gap:6px}.pl[data-size=narrow] .prow .track{grid-column:1 / -1;grid-row:2}.unknown{padding:9px 12px;border-radius:var(--pl-radius);background:var(--pl-subtle);border:1px dashed var(--pl-border);font-size:12.5px;color:var(--pl-muted)}.unknown strong{color:var(--pl-text)}.conflicts{padding:11px 14px;border-radius:var(--pl-radius);border:1px solid color-mix(in srgb,var(--pl-warn) 55%,var(--pl-surface));background:color-mix(in srgb,var(--pl-warn) 12%,var(--pl-surface));font-size:13.5px}.conflicts p{margin:0 0 4px}.conflicts ul{margin:0;padding-left:18px}.changes{display:grid;gap:10px;padding:11px 14px;border-radius:var(--pl-radius);border:1px solid color-mix(in srgb,var(--pl-accent) 45%,var(--pl-surface));background:var(--pl-accent-soft);font-size:13.5px}.changes p{margin:0}.changes ul{margin:0;padding-left:18px}.changes ul.chg{padding:0;list-style:none;display:grid;gap:8px}.chg>li{background:var(--pl-surface);border:1px solid var(--pl-hair);border-radius:calc(var(--pl-radius) - 2px);padding:8px 10px}.chg-head{display:flex;justify-content:space-between;align-items:center;gap:8px;font-weight:600}.chg-blocked{color:color-mix(in srgb,var(--pl-neg) 75%,var(--pl-text));font-size:12.5px}.chg-notes{font-size:12.5px}.tag-pending{display:inline-block;font-size:11px;font-weight:600;padding:0 6px;border-radius:999px;border:1px dashed var(--pl-accent);color:var(--pl-text);white-space:nowrap}.entry.del .desc{text-decoration:line-through}form.edit{display:grid;gap:14px}input.inp{font:inherit;font-size:13.5px;padding:7px 10px;border:1px solid var(--pl-border);border-radius:calc(var(--pl-radius) - 2px);background:var(--pl-surface);color:var(--pl-text);min-width:0}label.check{display:inline-flex;align-items:center;gap:6px}.pl[data-scheme=dark]{color-scheme:dark;--pl-pos: var(--t-color-success, #4cc27a);--pl-shadow: 0 6px 24px rgba(0, 0, 0, .6)}.pl[data-scheme=dark] .btn:not(.sec):not(.ghost):not(.danger),.pl[data-scheme=dark] .mark{color:#000!important}@media(prefers-reduced-motion:reduce){.pill[data-state=syncing]:before,.skel,.drawer{animation:none!important}}';function Bi(e){let t=e.ownerDocument.createElement("style");return t.textContent=Ui,e.append(t),t}async function ap({root:e,store:t}){e.replaceChildren(),Bi(e);let n,o=bi(t,()=>n?.render()),r=t.getTheme?.().colorScheme;n=qi(e,o,r?{colorScheme:r}:{}),n.render(),t.onThemeChange?.(i=>n?.setColorScheme(i.colorScheme)),t.subscribe(await t.getApp(),()=>{o.appChanged()}),await o.load()}export{ap as view}; diff --git a/integrations/READINESS.md b/integrations/READINESS.md index 474bac663..c8dca78b2 100644 --- a/integrations/READINESS.md +++ b/integrations/READINESS.md @@ -74,20 +74,20 @@ read from the atomic-server source at the pin. ## Matrix -| Plugin (catalog id) | Runtime of the current code | Install entry point at the pin | Import / write scope (declared) | Evidence | Open blockers | -| ---------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Pets, drive app (`pets`) | Drive app `pets/app/`: iframe, `syncables/browser` over `store.proxy` | Integrations → Show experimental plugins → Drive apps → Install (`pets` 0.1.1, from GitHub Pages, integrity-checked). The host E2E installs this way, then updates from an older recorded version | Read-only. Pets from the mock `pets` platform into the app's own table | Unit; **Host E2E** (`pets` lane: catalog install and update, connect, 5 rows, datatypes) | None filed | -| Pets, static demo (`pets`) | Sandbox `pets/plugin.js`, no network | None. Its setup dialog was removed in `4bab16ee6` | Five static pets into a Pets table | Unit; `certify.mjs --layer js`. Historical: Rust sandbox test (removed from atomic-server in `4bab16ee6`) | None filed; the catalog card still describes this demo, not the drive app | -| Notion, drive app (`notion`) | Drive app `notion/app/`: iframe, `syncables/browser` + Devonian `AtomicLens` over `store.proxy`; the #89 UI (table, board and list views, side peek, sync details, Disconnect), and since 0.2.0 "Review changes" (compare on open, review, send) | Published (`notion` 0.2.0 on GitHub Pages) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | Every shared data source into one table; plain fields and select/status/multi-select options. Two-way for those fields on existing pages, after review (`PATCH /v1/pages/{id}`, baseline on the row); no page creation, no deletes | Unit; **Host E2E** (`notion` lane: catalog install, connect, 3 rows, column datatypes, formatted-text warning, the #89 states against the fixture's scenarios, an edit made in the host found on open and sent, a conflict resolved). No live run | [#8](https://github.com/ontola/atomic-plugins/issues/8) live evidence for writes; page creation; #177 Q9 (sync-status view only) | -| Notion, two-way pilot (no card; shares `notion`'s version) | Sandbox `notion/plugin.js` | None. `ConnectNotion` was removed in `4bab16ee6`. The `notion` catalog card now describes the drive app | Two-way on one data source: plain fields, property names, table/board view subset (`package.json` capabilities) | Unit; `certify.mjs --layer js`; `live` tier runs the installer against the pinned server with Notion stubbed. Historical: live UI import and title edits via `ConnectNotion` | Retire once the drive app's writes (0.2.0) have live evidence ([#8](https://github.com/ontola/atomic-plugins/issues/8)) | -| Clockify (`timesheets`) | Drive app `timesheets/app/`: iframe, own Clockify client over `store.proxy.request`. The #89 UI (week grid, entries, projects, read-only drawer, settings) over the #123 M1 observation log and M2 timeline | Published (`timesheets` 0.1.0 on GitHub Pages) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | Read-only. The user's own entries in one workspace, rolling 7- or 30-day look-back; completed entries as rows. Conflicts and not-loaded time shown read-only. No writes to Clockify yet | Unit (fake store; #123 M1 scenarios and fold property tests, M2 timeline incl. DST days); **Host E2E** (`timesheets` lane: catalog install, connect, setup, import, reload, changed entry, 7 → 30 days, 503 recovery, an M2 conflict and unknown time). The mock's Clockify endpoints follow API behaviour checked against a live account on 2026-09-24 (#123); the app itself has no live run | [#123](https://github.com/ontola/atomic-plugins/issues/123) M3/M4 (writes, resolving conflicts), [#97](https://github.com/ontola/atomic-plugins/issues/97) | -| Bank statements, importer (`money`) | Sandbox `money/plugin.js` (0.3.0), file handed over as `ctx.upload`, no network | Draft from a published release (Integrations → Community plugins → Create draft), then Set up and Import on the plugin page (atomic-server#1653's `accepts`/`destination`, in the pin). Publishing the bundle to a server is manual (#94). An importer set up before 0.3.0's `tables` pauses until Set up runs again | Import only. MT940 ≤ 512 KB, camt.053 ≤ 5 MB, ≤ 500 transactions per file, into Bank transactions plus one Imported statements row per statement (`destination.tables`, atomic-server#1768) | Unit; `certify.mjs --layer js`; host E2E `money/e2e/money.spec.ts` (synthetic MT940/camt.053: import with its statement row, reload, reimport, local edit, conflict, refused files). Historical: a real 272-transaction bunq MT940 export through `ImportMT940` (2026-09-11) | [#94](https://github.com/ontola/atomic-plugins/issues/94) | -| Money, drive app (`money`) | Drive app `money/app/`: iframe, a view of the importer's table (`store.getData()`), no `store.proxy`; imports through the importer (`store.importer.run`, atomic-server#1774) | Published (`money` 0.3.0 on GitHub Pages) but `enabled: false`. A catalog Install would not give a working app yet: it gets its own empty table with no importer, and the importer's table offers under Add view only apps rendering its class. The host E2E installs test-side and adds the Bank transaction class to the app's `renders` | Reads the importer's Bank transactions and Imported statements tables. Writes only `money-category` and `money-note` on a row, after the person allows row editing (atomic-server#1788) | Unit (fake store modelling a current and an older host); axe and screenshots (`app/harness/`); **Host E2E** (`money` lane, second test: Add view, import through the host's review, closing balance, category after Allow editing, in-app check). At pin `2567fc30b` the second test could fail on atomic-server#1846 ('New app' missing); fixed at pin `1432e244a`, where both tests passed once on 2026-09-29 | Install path above; [#179](https://github.com/ontola/atomic-plugins/pull/179) pin | -| Willow drop (`willow-drop`) | Sandbox `willow-drop/plugin.js`, drop file handed over as `ctx.upload` text and turned back into bytes, no network | As for Bank statements: draft from a published release, then Set up and Import on the plugin page. Publishing is manual (#94) | Import only. Willow'25 drops up to 5,000,000 bytes and 1,000 entries (declared); no delegated capabilities, no partial payloads | Unit (fixtures written by willow25 0.7.9); host E2E `willow-drop/e2e/willow-drop.spec.ts` (raw and base64 upload, reimport, refused drops) | [#139](https://github.com/ontola/atomic-plugins/issues/139) follow-ups: delegations, partial payloads | -| Google Calendar (`calendar`) | Drive app `calendar/app/`: iframe, `calendar/adapter.ts` through `app/relay.ts` over `store.proxy`. The #89 UI (agenda, week, drawer, review sheet; Month hands off to the table's Calendar view, which spans all-day ranges because rows use the host's `atomic-calendar-*` field names; from 0.2.0 the rows are the shared `event-v1` class of #177, and the app is offered under Add view on any `event-v1` table, where it shows the rows read only) | Published (`calendar` 0.2.0 committed for GitHub Pages; 0.1.0 wrote `day`/`all-day` and no end day; 0.1.4 removed the adapter's unused sandbox manifest and credential placeholder, and the relay enforces the declared scope of `app/operations.ts`; 0.2.0 moves an older install's table onto `event-v1` on first open) but `enabled: false` pending launch and the stable ontology domain, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | One calendar's single non-recurring events in (≤ 25,000 per scan); reviewed edits of five fields out with If-Match and `sendUpdates=none`; no creates or deletes in Google | Unit; **Host E2E** (`calendar` lane: catalog install, connect, import, refresh after a Google-side edit, review and send, 412 conflict, lost response, links/Month/Disconnect through the host, the host Calendar view spanning a three-day all-day event and placing a timed one, responsive and theme, the app as a view of a hand-made `event-v1` table; needs network access to the published ontology on GitHub Pages). Historical: live import (2026-09-09, proxy v39) through the retired LocalThought snapshot importer. No live run of the drive app | [#101](https://github.com/ontola/atomic-plugins/issues/101) live verification | -| Todoist (`devonian-todoist`) | Library only: `issue-tracker/todoist.ts` projection | None. Its host hook was removed in `f3efedf65` | Declared: read-only, active tasks and projects | Unit. Recorded-fixture tests skip until a recording exists | [#99](https://github.com/ontola/atomic-plugins/issues/99), [#46](https://github.com/ontola/atomic-plugins/issues/46) | -| GitHub issues (`issue-tracker`) | Drive app `issue-tracker/app/`: iframe, the Devonian bridge from `issue-tracker/devonian/github-issues/` (npm `devonian` 0.8.0) over `store.proxy`. The #89 board/list UI. The lens's sandbox `plugin.ts` has no host | Published (`issue-tracker` 0.1.1 on GitHub Pages; #206) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | Two-way for one repository: title, body, Todo/Doing/Done status, comments. Every GitHub write is held for review before send. An issue gone from GitHub: "Keep here only" or "Remove from board". An uncertain create has no in-app way out yet | Unit (incl. state 13); **Host E2E** (`issue-tracker` lane: catalog install, connect, repository picker, import, reload, reviewed status update, conflict review, keyboard move, comment). Opt-in lens `*.live.test.ts` (need `GITHUB_TOKEN`; not run in CI). Historical: live GitHub read (2026-09-09, proxy v38) via the retired server flow. No live run of the drive app | [#156](https://github.com/ontola/atomic-plugins/issues/156) "It landed", [#100](https://github.com/ontola/atomic-plugins/issues/100) | -| Moneybird (`moneybird`) | Drive app `money/moneybird/`: iframe, own Moneybird reader over `store.proxy.request` (contacts only) | None. The catalog entry is `enabled: false` with no `app-module` yet; the host E2E installs test-side (`New app` + source) | Read-only. Contacts of one administration into a typed table | Unit; **Host E2E** on a SYNTHETIC fixture (`money` lane, `moneybird.spec.ts`: connect, choose an administration, 5 typed rows, failed refresh keeps rows, resync). Nothing verified against real Moneybird | [#102](https://github.com/ontola/atomic-plugins/issues/102) (a real recording needs a Moneybird account) | +| Plugin (catalog id) | Runtime of the current code | Install entry point at the pin | Import / write scope (declared) | Evidence | Open blockers | +| ---------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------- | +| Pets, drive app (`pets`) | Drive app `pets/app/`: iframe, `syncables/browser` over `store.proxy` | Integrations → Show experimental plugins → Drive apps → Install (`pets` 0.1.1, from GitHub Pages, integrity-checked). The host E2E installs this way, then updates from an older recorded version | Read-only. Pets from the mock `pets` platform into the app's own table | Unit; **Host E2E** (`pets` lane: catalog install and update, connect, 5 rows, datatypes) | None filed | +| Pets, static demo (`pets`) | Sandbox `pets/plugin.js`, no network | None. Its setup dialog was removed in `4bab16ee6` | Five static pets into a Pets table | Unit; `certify.mjs --layer js`. Historical: Rust sandbox test (removed from atomic-server in `4bab16ee6`) | None filed; the catalog card still describes this demo, not the drive app | +| Notion, drive app (`notion`) | Drive app `notion/app/`: iframe, `syncables/browser` + Devonian `AtomicLens` over `store.proxy`; the #89 UI (table, board and list views, side peek, sync details, Disconnect), and since 0.2.0 "Review changes" (compare on open, review, send) | Published (`notion` 0.2.0 on GitHub Pages) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | Every shared data source into one table; plain fields and select/status/multi-select options. Two-way for those fields on existing pages, after review (`PATCH /v1/pages/{id}`, baseline on the row); no page creation, no deletes | Unit; **Host E2E** (`notion` lane: catalog install, connect, 3 rows, column datatypes, formatted-text warning, the #89 states against the fixture's scenarios, an edit made in the host found on open and sent, a conflict resolved). No live run | [#8](https://github.com/ontola/atomic-plugins/issues/8) live evidence for writes; page creation; #177 Q9 (sync-status view only) | +| Notion, two-way pilot (no card; shares `notion`'s version) | Sandbox `notion/plugin.js` | None. `ConnectNotion` was removed in `4bab16ee6`. The `notion` catalog card now describes the drive app | Two-way on one data source: plain fields, property names, table/board view subset (`package.json` capabilities) | Unit; `certify.mjs --layer js`; `live` tier runs the installer against the pinned server with Notion stubbed. Historical: live UI import and title edits via `ConnectNotion` | Retire once the drive app's writes (0.2.0) have live evidence ([#8](https://github.com/ontola/atomic-plugins/issues/8)) | +| Clockify (`timesheets`) | Drive app `timesheets/app/`: iframe, own Clockify client over `store.proxy.request`. The #89 UI (week grid, entries, projects, drawer, settings, "Changes to send", range edits) over the #123 M1 observation log and M2 timeline; from 0.5.0 the rows are the shared `time-entry-v1` class of #177, linked to rows of the app's own Projects and People tables (`work-project-v1`, `work-person-v1`), and the app is offered under Add view on any `time-entry-v1` table, where it shows the rows read only | Published (`timesheets` 0.5.0 committed for GitHub Pages; 0.5.0 moves an older install's table onto `time-entry-v1` in place on first open, unsent edits kept) but `enabled: false` pending launch and the stable ontology domain, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | The user's own entries in one workspace, rolling 7- or 30-day look-back; completed entries as rows. Reviewed edits, range edits and conflict resolutions written back (#123 M3–M5), declared, not verified: mock-tested only | Unit (fake store; #123 M1–M5 scenarios, fold and planner property tests, the first-open move onto `time-entry-v1`); **Host E2E** (`timesheets` lane: catalog install, connect, setup, import as `time-entry-v1` rows with project and person links, reload, changed entry, 7 → 30 days, 503 recovery, an M2 conflict and unknown time, an edit, a range edit and a resolution sent after review, the app as a view of a hand-made `time-entry-v1` table; needs network access to the published ontology on GitHub Pages). The mock's Clockify endpoints follow API behaviour checked against a live account on 2026-09-24 (#123); the app itself has no live run | [#123](https://github.com/ontola/atomic-plugins/issues/123) live verification, [#97](https://github.com/ontola/atomic-plugins/issues/97) | +| Bank statements, importer (`money`) | Sandbox `money/plugin.js` (0.3.0), file handed over as `ctx.upload`, no network | Draft from a published release (Integrations → Community plugins → Create draft), then Set up and Import on the plugin page (atomic-server#1653's `accepts`/`destination`, in the pin). Publishing the bundle to a server is manual (#94). An importer set up before 0.3.0's `tables` pauses until Set up runs again | Import only. MT940 ≤ 512 KB, camt.053 ≤ 5 MB, ≤ 500 transactions per file, into Bank transactions plus one Imported statements row per statement (`destination.tables`, atomic-server#1768) | Unit; `certify.mjs --layer js`; host E2E `money/e2e/money.spec.ts` (synthetic MT940/camt.053: import with its statement row, reload, reimport, local edit, conflict, refused files). Historical: a real 272-transaction bunq MT940 export through `ImportMT940` (2026-09-11) | [#94](https://github.com/ontola/atomic-plugins/issues/94) | +| Money, drive app (`money`) | Drive app `money/app/`: iframe, a view of the importer's table (`store.getData()`), no `store.proxy`; imports through the importer (`store.importer.run`, atomic-server#1774) | Published (`money` 0.3.0 on GitHub Pages) but `enabled: false`. A catalog Install would not give a working app yet: it gets its own empty table with no importer, and the importer's table offers under Add view only apps rendering its class. The host E2E installs test-side and adds the Bank transaction class to the app's `renders` | Reads the importer's Bank transactions and Imported statements tables. Writes only `money-category` and `money-note` on a row, after the person allows row editing (atomic-server#1788) | Unit (fake store modelling a current and an older host); axe and screenshots (`app/harness/`); **Host E2E** (`money` lane, second test: Add view, import through the host's review, closing balance, category after Allow editing, in-app check). At pin `2567fc30b` the second test could fail on atomic-server#1846 ('New app' missing); fixed at pin `1432e244a`, where both tests passed once on 2026-09-29 | Install path above; [#179](https://github.com/ontola/atomic-plugins/pull/179) pin | +| Willow drop (`willow-drop`) | Sandbox `willow-drop/plugin.js`, drop file handed over as `ctx.upload` text and turned back into bytes, no network | As for Bank statements: draft from a published release, then Set up and Import on the plugin page. Publishing is manual (#94) | Import only. Willow'25 drops up to 5,000,000 bytes and 1,000 entries (declared); no delegated capabilities, no partial payloads | Unit (fixtures written by willow25 0.7.9); host E2E `willow-drop/e2e/willow-drop.spec.ts` (raw and base64 upload, reimport, refused drops) | [#139](https://github.com/ontola/atomic-plugins/issues/139) follow-ups: delegations, partial payloads | +| Google Calendar (`calendar`) | Drive app `calendar/app/`: iframe, `calendar/adapter.ts` through `app/relay.ts` over `store.proxy`. The #89 UI (agenda, week, drawer, review sheet; Month hands off to the table's Calendar view, which spans all-day ranges because rows use the host's `atomic-calendar-*` field names; from 0.2.0 the rows are the shared `event-v1` class of #177, and the app is offered under Add view on any `event-v1` table, where it shows the rows read only) | Published (`calendar` 0.2.0 committed for GitHub Pages; 0.1.0 wrote `day`/`all-day` and no end day; 0.1.4 removed the adapter's unused sandbox manifest and credential placeholder, and the relay enforces the declared scope of `app/operations.ts`; 0.2.0 moves an older install's table onto `event-v1` on first open) but `enabled: false` pending launch and the stable ontology domain, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | One calendar's single non-recurring events in (≤ 25,000 per scan); reviewed edits of five fields out with If-Match and `sendUpdates=none`; no creates or deletes in Google | Unit; **Host E2E** (`calendar` lane: catalog install, connect, import, refresh after a Google-side edit, review and send, 412 conflict, lost response, links/Month/Disconnect through the host, the host Calendar view spanning a three-day all-day event and placing a timed one, responsive and theme, the app as a view of a hand-made `event-v1` table; needs network access to the published ontology on GitHub Pages). Historical: live import (2026-09-09, proxy v39) through the retired LocalThought snapshot importer. No live run of the drive app | [#101](https://github.com/ontola/atomic-plugins/issues/101) live verification | +| Todoist (`devonian-todoist`) | Library only: `issue-tracker/todoist.ts` projection | None. Its host hook was removed in `f3efedf65` | Declared: read-only, active tasks and projects | Unit. Recorded-fixture tests skip until a recording exists | [#99](https://github.com/ontola/atomic-plugins/issues/99), [#46](https://github.com/ontola/atomic-plugins/issues/46) | +| GitHub issues (`issue-tracker`) | Drive app `issue-tracker/app/`: iframe, the Devonian bridge from `issue-tracker/devonian/github-issues/` (npm `devonian` 0.8.0) over `store.proxy`. The #89 board/list UI. The lens's sandbox `plugin.ts` has no host | Published (`issue-tracker` 0.1.1 on GitHub Pages; #206) but `enabled: false` pending launch, so Drive apps does not offer it. The host E2E installs it through Drive apps, with the lanes' dev-server serving the entry enabled | Two-way for one repository: title, body, Todo/Doing/Done status, comments. Every GitHub write is held for review before send. An issue gone from GitHub: "Keep here only" or "Remove from board". An uncertain create has no in-app way out yet | Unit (incl. state 13); **Host E2E** (`issue-tracker` lane: catalog install, connect, repository picker, import, reload, reviewed status update, conflict review, keyboard move, comment). Opt-in lens `*.live.test.ts` (need `GITHUB_TOKEN`; not run in CI). Historical: live GitHub read (2026-09-09, proxy v38) via the retired server flow. No live run of the drive app | [#156](https://github.com/ontola/atomic-plugins/issues/156) "It landed", [#100](https://github.com/ontola/atomic-plugins/issues/100) | +| Moneybird (`moneybird`) | Drive app `money/moneybird/`: iframe, own Moneybird reader over `store.proxy.request` (contacts only) | None. The catalog entry is `enabled: false` with no `app-module` yet; the host E2E installs test-side (`New app` + source) | Read-only. Contacts of one administration into a typed table | Unit; **Host E2E** on a SYNTHETIC fixture (`money` lane, `moneybird.spec.ts`: connect, choose an administration, 5 typed rows, failed refresh keeps rows, resync). Nothing verified against real Moneybird | [#102](https://github.com/ontola/atomic-plugins/issues/102) (a real recording needs a Moneybird account) | `integrations/localthought/` is shared tooling, not a user-facing plugin: the shared mock proxy every E2E lane uses (`mock-proxy.mjs`, which speaks diff --git a/integrations/catalog.json b/integrations/catalog.json index d4ff50d6d..ecab81223 100644 --- a/integrations/catalog.json +++ b/integrations/catalog.json @@ -229,15 +229,15 @@ "https://atomicdata.dev/properties/name": "Clockify", "https://atomicdata.dev/properties/emoji": "⏱️", "https://atomicdata.dev/properties/description": "A drive app that brings your Clockify time entries into a week view and a table of its own, and sends edits you review back to Clockify.", - "https://atomicdata.dev/integrations/properties/capabilities": "Reads your own time entries in one workspace over a rolling 7- or 30-day look-back, keeps what each read saw in an observation log in the drive, and shows a week grid, the entries by day and hours per project. Completed entries become rows in the app's table (start, end, project, billable). A timeline shows overlapping entries and work over a break as conflicts, and time no read has covered as not loaded, never as not worked. An entry's description, project, billable flag, start and end can be edited in the app or in the table, or the entry deleted; a time range can be marked as worked on a project or as not worked, which trims, splits, extends or creates entries over exactly that range; and a conflict can be resolved by keeping one project, marking it not worked, or removing a duplicate. Each change is listed under Changes to send and written to Clockify only when sent, after a fresh read, and confirmed by a read afterwards. If Clockify changed the same field, Clockify's value is kept; a new entry is not created where Clockify has time by then. With the app open on two devices or in two tabs, one sends at a time, and range edits made on each without seeing the other's are shown as a conflict between your edits and held until one is chosen.", + "https://atomicdata.dev/integrations/properties/capabilities": "Reads your own time entries in one workspace over a rolling 7- or 30-day look-back, keeps what each read saw in an observation log in the drive, and shows a week grid, the entries by day and hours per project. Completed entries become rows in the app's table, as the shared Time entry class (time-entry-v1, ontola/atomic-plugins#177): start, end, billable, and project and person as links to rows of the app's own Projects and People tables. Added as a view of another Time entry table, it shows that table's entries, read only, and syncs nothing. A timeline shows overlapping entries and work over a break as conflicts, and time no read has covered as not loaded, never as not worked. An entry's description, project, billable flag, start and end can be edited in the app or in the table, or the entry deleted; a time range can be marked as worked on a project or as not worked, which trims, splits, extends or creates entries over exactly that range; and a conflict can be resolved by keeping one project, marking it not worked, or removing a duplicate. Each change is listed under Changes to send and written to Clockify only when sent, after a fresh read, and confirmed by a read afterwards. If Clockify changed the same field, Clockify's value is kept; a new entry is not created where Clockify has time by then. With the app open on two devices or in two tabs, one sends at a time, and range edits made on each without seeing the other's are shown as a conflict between your edits and held until one is chosen.", "https://atomicdata.dev/integrations/properties/events": "Install from Drive apps, connect Clockify through the host's consent bar (the API key is entered at the integration proxy, never in the drive), then choose a workspace and a look-back. It syncs when opened and on Sync now; nothing runs while the app is closed.", - "https://atomicdata.dev/integrations/properties/limitation": "Write-back is declared, not verified: it is tested against the mock proxy only, and no write has been made to a live Clockify account through the app. Changes are found only while the app is open; a row deleted in the table is not noticed. Running timers, locked entries, breaks and entries with custom field values cannot be edited. Coordination between two open copies is advisory (the drive has no compare-and-swap), so two copies starting to send in the same moment can still both send, at worst creating a duplicate that the app then offers to remove; it has been tested with simulated devices only, not with two real browsers. The same field edited directly on two devices keeps the later edit. No tags, tasks, rates or custom fields. Tested against a mock proxy modelled on Clockify behaviour checked against a live account (2026-09-24); the app itself has not run against a live account or the real integration proxy.", + "https://atomicdata.dev/integrations/properties/limitation": "Write-back is declared, not verified: it is tested against the mock proxy only, and no write has been made to a live Clockify account through the app. Changes are found only while the app is open; a row deleted in the table is not noticed. Running timers, locked entries, breaks and entries with custom field values cannot be edited. Coordination between two open copies is advisory (the drive has no compare-and-swap), so two copies starting to send in the same moment can still both send, at worst creating a duplicate that the app then offers to remove; it has been tested with simulated devices only, not with two real browsers. The same field edited directly on two devices keeps the later edit. No tags, tasks, rates or custom fields. Tested against a mock proxy modelled on Clockify behaviour checked against a live account (2026-09-24); the app itself has not run against a live account or the real integration proxy. Only the app's own table is synced. Waits for the stable ontology domain.", "https://atomicdata.dev/integrations/properties/keywords": "clockify time tracking timesheet week hours projects conflicts drive app", - "https://atomicdata.dev/integrations/properties/version": "0.4.0", + "https://atomicdata.dev/integrations/properties/version": "0.5.0", "https://atomicdata.dev/integrations/properties/app-row-name": "Time entry", "https://atomicdata.dev/integrations/properties/app-row-name-plural": "Time entries", - "https://atomicdata.dev/integrations/properties/app-module": "https://ontola.github.io/atomic-plugins/apps/timesheets/0.4.0/ui.js", - "https://atomicdata.dev/integrations/properties/app-module-integrity": "sha384-1vg5yfFSuTK8b++5NRFH8tNkdwSOfFWJSFj5YdBfv80frvmEqr6xJVB8+p4zhBTT" + "https://atomicdata.dev/integrations/properties/app-module": "https://ontola.github.io/atomic-plugins/apps/timesheets/0.5.0/ui.js", + "https://atomicdata.dev/integrations/properties/app-module-integrity": "sha384-ojhlPi5dUE+b4rvYhkDIjjP/aeznkcPg8jHFVMqblLpvS7B3x6xRG6HUelgyRn9X" }, { "@id": "https://atomicdata.dev/integrations/catalog/notion", diff --git a/integrations/lanes.json b/integrations/lanes.json index f1cc8060a..0ebff7a6c 100644 --- a/integrations/lanes.json +++ b/integrations/lanes.json @@ -175,7 +175,8 @@ "index": 6, "platforms": ["clockify"], "tiers": ["typecheck", "unit", "e2e"], - "note": "The e2e installs the timesheets drive app from the catalog (Integrations, Drive apps; the committed apps/timesheets//ui.js) and drives it in its plugin iframe: connect through the host's consent bar and the mock proxy, set up workspace and look-back in the frame, then import, reload, refresh and recover from a proxy failure through the host relay (atomic-server#1657; the pin has it). Provider changes and failures go through the mock proxy's local-only fixture driver (POST /__fixture/clockify). It also checks an M2 conflict and not-loaded time in the #89 views. The old upstream Clockify tests were deleted in atomic-server 4bab16ee6 with the UI they drove (#44).", + "paths": ["ontology/**", "ontology-kit/**"], + "note": "paths: the app bundles ontology-kit/terms.mjs and resolver.mjs and syncs into the shared time-entry-v1, work-project-v1 and work-person-v1 classes (#177), so an ontology change runs this lane too. The rows use the published GitHub Pages subjects, which the server and browser fetch themselves, so the e2e needs network access to ontola.github.io; it first checks Pages serves the three classes and their properties with the committed bytes (ontology-kit/served.mjs). One test adds the app as a view of a hand-made time-entry-v1 table through Add view. The e2e installs the timesheets drive app from the catalog (Integrations, Drive apps; the committed apps/timesheets//ui.js) and drives it in its plugin iframe: connect through the host's consent bar and the mock proxy, set up workspace and look-back in the frame, then import, reload, refresh and recover from a proxy failure through the host relay (atomic-server#1657; the pin has it). Provider changes and failures go through the mock proxy's local-only fixture driver (POST /__fixture/clockify). It also checks an M2 conflict and not-loaded time in the #89 views. The old upstream Clockify tests were deleted in atomic-server 4bab16ee6 with the UI they drove (#44).", "e2e": ["integrations/timesheets/e2e/clockify.spec.ts"] }, { diff --git a/integrations/timesheets/README.md b/integrations/timesheets/README.md index 68dbf8f36..07e01c789 100644 --- a/integrations/timesheets/README.md +++ b/integrations/timesheets/README.md @@ -10,7 +10,10 @@ it writes reviewed edits back to Clockify (#123 M3, below), since 0.3.0 range edits and conflict resolutions (#123 M4), and since 0.4.0 it coordinates two open copies (#123 M5: the send lease, range edits made apart, two devices compacting the log); all are mock-tested only, so those -capabilities are declared, not verified. The first sections describe the Clockify +capabilities are declared, not verified. Since 0.5.0 its rows are the +shared `time-entry-v1` class, linked to rows of its own Projects and People +tables (#177 item 7, below), which keeps its catalog entry disabled until +the ontology moves to a stable domain. The first sections describe the Clockify lens and the LocalThought extension flow it was written for; the pinned host no longer has that flow. @@ -60,7 +63,7 @@ Live account data must never be checked into fixtures. `app/` is the replacement for the LocalThought extension path above: Clockify as an Atomic **App** ("drive plugin"). `app/build.mjs` bundles it -into one minified ES module (`app/dist/ui.js`, about 144 KB, no imports) that +into one minified ES module (`app/dist/ui.js`, about 161 KB, no imports) that exports only `view({ root, store })`; the host stores it as the App's entry-point source and runs it in a null-origin, `allow-scripts`-only iframe (`plugin_ui.rs`). Plain DOM, no framework; one `