@unbase-app/layer 0.0.0-stage → 2.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +400 -2
- package/bin/unbase-layer.mjs +28 -0
- package/cli/artifact-style.mjs +89 -0
- package/cli/fetch.mjs +142 -0
- package/cli/lib.mjs +160 -0
- package/cli/live.mjs +35 -0
- package/cli/overview-artifact.mjs +142 -0
- package/cli/plan-artifact.mjs +337 -0
- package/cli/post.mjs +309 -0
- package/cli/redispatch.mjs +99 -0
- package/cli/screenshot.mjs +189 -0
- package/cli/status.mjs +50 -0
- package/cli/store.mjs +143 -0
- package/dist/client/start.d.ts +4 -0
- package/dist/client/start.js +12888 -0
- package/package.json +119 -4
- package/skills/build-comment/SKILL.md +61 -0
- package/skills/get-comments/SKILL.md +127 -0
- package/skills/process-comments/SKILL.md +115 -0
- package/skills/propose-comment/SKILL.md +79 -0
- package/src/astro/component-marker.mjs +161 -0
- package/src/astro/content-map-extra.mjs +192 -0
- package/src/astro/content-map.mjs +584 -0
- package/src/astro/deploy-context.mjs +66 -0
- package/src/astro/index.d.ts +97 -0
- package/src/astro/index.mjs +277 -0
- package/src/astro/pages.mjs +192 -0
- package/src/astro/version.mjs +13 -0
- package/src/edit/index.d.mts +178 -0
- package/src/edit/index.mjs +1002 -0
- package/src/page/index.d.mts +71 -0
- package/src/page/index.mjs +216 -0
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// ============================================================================
|
|
3
|
+
// Offers a choice under a pin to operator-dispatch again, so it still becomes
|
|
4
|
+
// a build run (a PR under the pin).
|
|
5
|
+
//
|
|
6
|
+
// npx unbase-layer redispatch --nr 33 [--dry]
|
|
7
|
+
//
|
|
8
|
+
// Why: the trigger (unbase.dispatch_operator) only fires on an insert. A
|
|
9
|
+
// choice ("Keuze: B · …", the button) whose dispatch got lost never comes
|
|
10
|
+
// back by itself — and the buttons are gone once chosen. This takes the
|
|
11
|
+
// latest choice by the team under pin N and sends its id to operator-dispatch
|
|
12
|
+
// exactly the way the trigger does (pg_net, with the URL and secret from the
|
|
13
|
+
// vault), so operator-dispatch applies all its own rules: team only, after a
|
|
14
|
+
// proposal, the daily limit, one active run per pin.
|
|
15
|
+
//
|
|
16
|
+
// Stops when the pin already has a build run that did not fail;
|
|
17
|
+
// operator-dispatch refuses the same choice twice as well.
|
|
18
|
+
//
|
|
19
|
+
// Local only (the Supabase CLI, logged in on this machine): it needs the
|
|
20
|
+
// vault, which operator-api never hands out.
|
|
21
|
+
// ============================================================================
|
|
22
|
+
|
|
23
|
+
import { args, lit, localProjectId, PROJECT_KEY, sql } from "./lib.mjs";
|
|
24
|
+
|
|
25
|
+
const o = args();
|
|
26
|
+
const nr = Number(o.nr);
|
|
27
|
+
if (!Number.isInteger(nr) || nr < 1) {
|
|
28
|
+
console.error("Usage: comment-modus redispatch --nr <pin number> [--dry]");
|
|
29
|
+
process.exit(1);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const project = localProjectId();
|
|
33
|
+
const [pin] = sql(`select id, nr, status from unbase.comments where parent_id is null and project_id = ${lit(project)} and nr = ${nr}`);
|
|
34
|
+
if (!pin) throw new Error(`No pin #${nr} on ${PROJECT_KEY}`);
|
|
35
|
+
if (pin.status !== "open") throw new Error(`Pin #${nr} is resolved; operator-dispatch would not start anything`);
|
|
36
|
+
|
|
37
|
+
const [choice] = sql(`
|
|
38
|
+
select c.id, c.body, c.created_at, a.name
|
|
39
|
+
from unbase.comments c
|
|
40
|
+
join unbase.accounts a on a.id = c.author_id
|
|
41
|
+
where c.parent_id = '${pin.id}'
|
|
42
|
+
and a.kind = 'person'
|
|
43
|
+
and unbase.is_team_account(c.project_id, c.author_id)
|
|
44
|
+
and c.body ~* '^\\s*(keuze|choice)\\s*:'
|
|
45
|
+
order by c.created_at desc
|
|
46
|
+
limit 1
|
|
47
|
+
`);
|
|
48
|
+
if (!choice) throw new Error(`No choice ("Keuze: …" / "Choice: …") by the team under #${nr}`);
|
|
49
|
+
|
|
50
|
+
const runs = sql(`
|
|
51
|
+
select id, status, created_at from unbase.operator_runs
|
|
52
|
+
where pin_id = '${pin.id}' and kind = 'build' and status <> 'failed'
|
|
53
|
+
order by created_at desc
|
|
54
|
+
`);
|
|
55
|
+
if (runs.length) {
|
|
56
|
+
console.log(`#${nr} already has a build run (${runs[0].status}, ${runs[0].created_at}); nothing to do.`);
|
|
57
|
+
process.exit(0);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
console.log(`#${nr}: ${choice.name}, ${choice.created_at}\n ${choice.body.split("\n")[0].slice(0, 160)}`);
|
|
61
|
+
if (o.dry) {
|
|
62
|
+
console.log("--dry: not sent.");
|
|
63
|
+
process.exit(0);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// The same secrets as the trigger: the new names first, the old ones while
|
|
67
|
+
// the vault still holds them (migration 032 renames them).
|
|
68
|
+
const [{ request_id }] = sql(`
|
|
69
|
+
with target as (
|
|
70
|
+
select decrypted_secret as url from vault.decrypted_secrets
|
|
71
|
+
where name in ('operator_dispatch_url', 'cm_dispatch_url')
|
|
72
|
+
order by name = 'operator_dispatch_url' desc limit 1
|
|
73
|
+
),
|
|
74
|
+
secret as (
|
|
75
|
+
select decrypted_secret as value from vault.decrypted_secrets
|
|
76
|
+
where name in ('operator_dispatch_secret', 'cm_dispatch_secret')
|
|
77
|
+
order by name = 'operator_dispatch_secret' desc limit 1
|
|
78
|
+
)
|
|
79
|
+
select net.http_post(
|
|
80
|
+
url := replace((select url from target), '/functions/v1/cm-dispatch', '/functions/v1/operator-dispatch'),
|
|
81
|
+
body := jsonb_build_object('comment_id', '${choice.id}'),
|
|
82
|
+
headers := jsonb_build_object(
|
|
83
|
+
'content-type', 'application/json',
|
|
84
|
+
'x-operator-secret', (select value from secret),
|
|
85
|
+
'x-cm-secret', (select value from secret)
|
|
86
|
+
)
|
|
87
|
+
) as request_id
|
|
88
|
+
`);
|
|
89
|
+
|
|
90
|
+
// pg_net sends in the background; wait briefly for operator-dispatch's answer.
|
|
91
|
+
for (let i = 0; i < 10; i++) {
|
|
92
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
93
|
+
const [res] = sql(`select status_code, content, error_msg from net._http_response where id = ${Number(request_id)}`);
|
|
94
|
+
if (!res) continue;
|
|
95
|
+
if (res.error_msg) throw new Error(`operator-dispatch not reached: ${res.error_msg}`);
|
|
96
|
+
console.log(`operator-dispatch ${res.status_code}: ${res.content}`);
|
|
97
|
+
process.exit(res.status_code === 200 ? 0 : 1);
|
|
98
|
+
}
|
|
99
|
+
console.log(`Sent (pg_net request ${request_id}); no answer yet. Watch the pin.`);
|
|
@@ -0,0 +1,189 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// ============================================================================
|
|
3
|
+
// A screenshot of the spot of a comment, the way the reviewer saw it.
|
|
4
|
+
//
|
|
5
|
+
// npx unbase-layer screenshot --nr 8 --out before.png [--base http://localhost:4330]
|
|
6
|
+
// [--mobile] [--no-pin] [--hover] [--comments comments.json] [--debug]
|
|
7
|
+
// [--selector <css>] [--mode path|jump|element]
|
|
8
|
+
//
|
|
9
|
+
// Before/after of a change that alters the structure (a wrapper removed, a
|
|
10
|
+
// shorter page): the reviewer's selector no longer matches and the click point
|
|
11
|
+
// is elsewhere. Then pass the same --selector and --mode element for both, so
|
|
12
|
+
// before and after frame the same thing.
|
|
13
|
+
//
|
|
14
|
+
// --nr looks the comment up in --comments (the output of `fetch`) or else live
|
|
15
|
+
// in the database. Desktop: the reviewer's window (viewport width × height),
|
|
16
|
+
// scrolled to where they clicked (page_x/page_y), so a block that sticks while
|
|
17
|
+
// scrolling is in the same state. --mobile: 390 × 844, touch, the element
|
|
18
|
+
// centred.
|
|
19
|
+
//
|
|
20
|
+
// --base is the site: the live site by default (the "before"); for the
|
|
21
|
+
// "after", the dev server of the worktree. Same window and same scroll for
|
|
22
|
+
// both, so the before/after slider lays them exactly on top of each other.
|
|
23
|
+
// The pin (red, with the number) is drawn on top unless --no-pin.
|
|
24
|
+
//
|
|
25
|
+
// Output: a png, and on stdout { file, width, height, found, hit, mode }.
|
|
26
|
+
// ============================================================================
|
|
27
|
+
|
|
28
|
+
import { readFileSync } from "node:fs";
|
|
29
|
+
import { chromium } from "playwright-core";
|
|
30
|
+
import { args, CHROME, COOKIE_BUTTON, LIVE, lit, localProjectId, sql } from "./lib.mjs";
|
|
31
|
+
|
|
32
|
+
const o = args();
|
|
33
|
+
if (!o.nr || !o.out) {
|
|
34
|
+
console.error("Usage: --nr <n> --out <file.png> [--base <url>] [--mobile] [--no-pin] [--comments comments.json]");
|
|
35
|
+
process.exit(1);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function find(nr) {
|
|
39
|
+
if (o.comments) {
|
|
40
|
+
const d = JSON.parse(readFileSync(o.comments, "utf8"));
|
|
41
|
+
const x = d.comments.find((m) => m.nr === Number(nr));
|
|
42
|
+
if (x) return x;
|
|
43
|
+
}
|
|
44
|
+
const [r] = sql(`select to_jsonb(c) as c from unbase.comments c where c.project_id = ${lit(localProjectId())} and c.nr = ${Number(nr)}`);
|
|
45
|
+
if (!r) throw new Error(`Comment #${nr} does not exist`);
|
|
46
|
+
const c = r.c;
|
|
47
|
+
return {
|
|
48
|
+
nr: c.nr,
|
|
49
|
+
page: { path: c.page_path },
|
|
50
|
+
element: { selector: c.selector, x_pct: c.x_pct, y_pct: c.y_pct, page_x: c.page_x, page_y: c.page_y },
|
|
51
|
+
viewport: { width: c.viewport_w, height: c.viewport_h },
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const m = find(o.nr);
|
|
56
|
+
if (o.selector) m.element = { ...m.element, selector: o.selector };
|
|
57
|
+
const mobile = Boolean(o.mobile);
|
|
58
|
+
const viewport = mobile
|
|
59
|
+
? { width: 390, height: 844 }
|
|
60
|
+
: { width: m.viewport.width || 1440, height: m.viewport.height || 900 };
|
|
61
|
+
const base = String(o.base || LIVE).replace(/\/$/, "");
|
|
62
|
+
|
|
63
|
+
const browser = await chromium.launch({ executablePath: CHROME });
|
|
64
|
+
const ctx = await browser.newContext({
|
|
65
|
+
viewport,
|
|
66
|
+
deviceScaleFactor: mobile ? 2 : 1,
|
|
67
|
+
isMobile: mobile,
|
|
68
|
+
hasTouch: mobile,
|
|
69
|
+
// No reduced motion: blocks that stick while scrolling switch their scroll
|
|
70
|
+
// behaviour off under it, and that is not what the reviewer saw. Instead,
|
|
71
|
+
// wait for reveal animations to finish.
|
|
72
|
+
});
|
|
73
|
+
const p = await ctx.newPage();
|
|
74
|
+
// Where the pin goes. Desktop: page_x/page_y is the click point on the page.
|
|
75
|
+
// But how long the page is depends on how the reviewer got there: blocks that
|
|
76
|
+
// stick while scrolling only grow when you scroll past them, and correct a
|
|
77
|
+
// jump with scrollBy. Someone who arrived through an anchor link never grew
|
|
78
|
+
// them. Hence three modes, and the first one where the element really sits
|
|
79
|
+
// under the pin (elementFromPoint) wins:
|
|
80
|
+
// path from the top in small steps to the click point, like reading
|
|
81
|
+
// jump page reloaded, straight to the click point (anchor link)
|
|
82
|
+
// element the element centred, pin at x/y_pct
|
|
83
|
+
// Mobile has no click point (different layout): "element" right away.
|
|
84
|
+
async function place(mode) {
|
|
85
|
+
return p.evaluate(
|
|
86
|
+
async ({ el, mode }) => {
|
|
87
|
+
const wait = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
88
|
+
const target = el.selector ? document.querySelector(el.selector) : null;
|
|
89
|
+
const hit = (x, y) => {
|
|
90
|
+
const h = document.elementFromPoint(x, y);
|
|
91
|
+
return Boolean(target && h && (target === h || target.contains(h) || h.contains(target)));
|
|
92
|
+
};
|
|
93
|
+
if (mode === "path" || mode === "jump") {
|
|
94
|
+
const goal = Math.max(0, el.page_y - innerHeight / 2);
|
|
95
|
+
if (mode === "path") {
|
|
96
|
+
for (let y = 0; y < goal; y += 300) {
|
|
97
|
+
scrollTo(0, y);
|
|
98
|
+
await wait(70);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
for (let i = 0; i < 4 && Math.abs(scrollY - goal) > 2; i++) {
|
|
102
|
+
scrollTo(0, goal);
|
|
103
|
+
await wait(400);
|
|
104
|
+
}
|
|
105
|
+
const x = el.page_x - scrollX;
|
|
106
|
+
const y = el.page_y - scrollY;
|
|
107
|
+
return { mode, hit: hit(x, y), found: Boolean(target), x, y };
|
|
108
|
+
}
|
|
109
|
+
if (!target) return { mode, hit: false, found: false, x: innerWidth / 2, y: innerHeight / 2 };
|
|
110
|
+
// Here too in steps, so sticky blocks above have already grown.
|
|
111
|
+
for (let i = 0; i < 6; i++) {
|
|
112
|
+
const r = target.getBoundingClientRect();
|
|
113
|
+
const goal = Math.max(0, r.top + scrollY + (r.height * (el.y_pct ?? 50)) / 100 - innerHeight / 2);
|
|
114
|
+
if (Math.abs(scrollY - goal) < 2) break;
|
|
115
|
+
for (let y = scrollY; y < goal; y += 300) {
|
|
116
|
+
scrollTo(0, y);
|
|
117
|
+
await wait(70);
|
|
118
|
+
}
|
|
119
|
+
scrollTo(0, goal);
|
|
120
|
+
await wait(400);
|
|
121
|
+
}
|
|
122
|
+
const r = target.getBoundingClientRect();
|
|
123
|
+
const x = r.left + (r.width * (el.x_pct ?? 50)) / 100;
|
|
124
|
+
const y = Math.min(Math.max(r.top + (r.height * (el.y_pct ?? 50)) / 100, 40), innerHeight - 8);
|
|
125
|
+
return { mode, hit: hit(x, y), found: true, x, y };
|
|
126
|
+
},
|
|
127
|
+
{ el: m.element, mode },
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const url = base + (m.page.path || "/");
|
|
132
|
+
async function load() {
|
|
133
|
+
await p.goto(url, { waitUntil: "networkidle", timeout: 60_000 });
|
|
134
|
+
// Cookie banner away with JS (a mouse click leaves :hover behind; the button
|
|
135
|
+
// text is cookieButton in comment-modus.json), Astro's dev toolbar hidden.
|
|
136
|
+
if (COOKIE_BUTTON) await p.evaluate((t) => [...document.querySelectorAll("button")].find((b) => b.textContent.trim() === t)?.click(), COOKIE_BUTTON);
|
|
137
|
+
await p.addStyleTag({ content: "astro-dev-toolbar{display:none!important}" });
|
|
138
|
+
// A fresh dev server serves the fonts only after the first requests; without
|
|
139
|
+
// this the "after" renders in a fallback font and the whole layout shifts.
|
|
140
|
+
await p.evaluate(() => document.fonts.ready);
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
await load();
|
|
144
|
+
const hasPoint = !mobile && m.element.page_y != null && m.element.page_x != null;
|
|
145
|
+
const modes = o.mode ? [o.mode] : hasPoint ? ["path", "jump", "element"] : ["element"];
|
|
146
|
+
let spot;
|
|
147
|
+
for (const [i, mode] of modes.entries()) {
|
|
148
|
+
if (i > 0) await load();
|
|
149
|
+
spot = await place(mode);
|
|
150
|
+
if (spot.hit) break;
|
|
151
|
+
}
|
|
152
|
+
await p.waitForTimeout(1200);
|
|
153
|
+
|
|
154
|
+
// --hover: the mouse on the element, for comments about a hover state.
|
|
155
|
+
if (o.hover && m.element.selector) {
|
|
156
|
+
await p.hover(m.element.selector, { timeout: 5000 }).catch(() => console.error("hover: element not reachable"));
|
|
157
|
+
await p.waitForTimeout(500);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (!o["no-pin"]) {
|
|
161
|
+
await p.evaluate(
|
|
162
|
+
({ x, y, nr }) => {
|
|
163
|
+
const pin = document.createElement("div");
|
|
164
|
+
pin.textContent = String(nr);
|
|
165
|
+
Object.assign(pin.style, {
|
|
166
|
+
// The pin's point is bottom-left; just under the top edge (a click on
|
|
167
|
+
// the navigation) it would fall above the viewport.
|
|
168
|
+
position: "fixed", left: `${x}px`, top: `${Math.max(y, 32)}px`, transform: "translate(0, -100%)", zIndex: "99999",
|
|
169
|
+
width: "28px", height: "28px", display: "grid", placeItems: "center",
|
|
170
|
+
// The same pin as in the layer (tokens.ts): signal red with a white edge.
|
|
171
|
+
background: "#F73737", color: "#FFFFFF",
|
|
172
|
+
border: "2px solid #FFFFFF", borderRadius: "50% 50% 50% 0",
|
|
173
|
+
font: "700 12px/1 Inter, system-ui, sans-serif",
|
|
174
|
+
boxShadow: "0 4px 14px rgba(0,0,0,.35)",
|
|
175
|
+
});
|
|
176
|
+
document.body.append(pin);
|
|
177
|
+
},
|
|
178
|
+
{ ...spot, nr: m.nr },
|
|
179
|
+
);
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// --debug: where the scroll and the pin ended up (a pin that falls outside the
|
|
183
|
+
// image, or a block that sits differently than expected).
|
|
184
|
+
if (o.debug) console.error(JSON.stringify({ spot, scrollY: await p.evaluate(() => scrollY) }));
|
|
185
|
+
await p.screenshot({ path: o.out });
|
|
186
|
+
await browser.close();
|
|
187
|
+
// hit: the element really sits under the pin. If not, the page has changed
|
|
188
|
+
// since the comment; go by element.text and say so.
|
|
189
|
+
console.log(JSON.stringify({ file: o.out, width: viewport.width, height: viewport.height, scale: mobile ? 2 : 1, found: spot.found, hit: spot.hit, mode: spot.mode }));
|
package/cli/status.mjs
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// ============================================================================
|
|
3
|
+
// Reports how far a run of the Operator is, so the layer can show it under
|
|
4
|
+
// the pin ("Operator is making screenshots …").
|
|
5
|
+
//
|
|
6
|
+
// npx unbase-layer status --run <id> --status running --step recording [--url <run url>] [--pr-url <pr url>]
|
|
7
|
+
//
|
|
8
|
+
// status: running | done | failed | skipped. step: a key the layer translates
|
|
9
|
+
// (recording, posting, building, checking, pr, starting, answering, expired).
|
|
10
|
+
// The Dutch values from before 1.0 (bezig, klaar, mislukt, overgeslagen;
|
|
11
|
+
// --stap opnames, plaatsen …) are still accepted and sent in English
|
|
12
|
+
// (LEGACY-NL: agendavoorhethart's workflow comment-operator.yml passes them).
|
|
13
|
+
// Only in CI, through operator-api (CM_OPERATOR_KEY). Without --run it does
|
|
14
|
+
// nothing: a run started by hand has no row in operator_runs.
|
|
15
|
+
// ============================================================================
|
|
16
|
+
|
|
17
|
+
import { args } from "./lib.mjs";
|
|
18
|
+
import { setRunStatus } from "./store.mjs";
|
|
19
|
+
|
|
20
|
+
// LEGACY-NL: the Dutch status and step names from before 1.0 (the keys), each mapped to the English
|
|
21
|
+
// value operator-api takes. agendavoorhethart's .github/workflows/comment-operator.yml still passes
|
|
22
|
+
// `--status bezig --stap …`; English values pass through as they are.
|
|
23
|
+
const STATUSES = { bezig: "running", klaar: "done", mislukt: "failed", overgeslagen: "skipped" };
|
|
24
|
+
const STEPS = {
|
|
25
|
+
opnames: "recording", plaatsen: "posting", bouwen: "building", controleren: "checking",
|
|
26
|
+
pr: "pr", starten: "starting", antwoorden: "answering", verlopen: "expired",
|
|
27
|
+
};
|
|
28
|
+
const english = (map, value) => (value in map ? map[value] : Object.values(map).includes(value) ? value : null);
|
|
29
|
+
|
|
30
|
+
const o = args();
|
|
31
|
+
if (!o.run) {
|
|
32
|
+
console.log("No --run: nothing to report.");
|
|
33
|
+
process.exit(0);
|
|
34
|
+
}
|
|
35
|
+
const status = english(STATUSES, o.status);
|
|
36
|
+
if (!status) {
|
|
37
|
+
console.error(`--status ${o.status}: use ${Object.values(STATUSES).join(", ")}.`);
|
|
38
|
+
process.exit(1);
|
|
39
|
+
}
|
|
40
|
+
// LEGACY-NL: --stap is --step's name from before 1.0.
|
|
41
|
+
const given = o.step ?? o.stap;
|
|
42
|
+
// A step the layer does not know yet still goes through (operator-api takes
|
|
43
|
+
// any key of [a-z-]); the layer then shows its generic "working on it".
|
|
44
|
+
const step = given === undefined || given === true ? undefined : (english(STEPS, given) ?? (/^[a-z-]{1,40}$/.test(given) ? given : null));
|
|
45
|
+
if (given !== undefined && !step) {
|
|
46
|
+
console.error(`--step ${given}: use ${Object.values(STEPS).join(", ")}.`);
|
|
47
|
+
process.exit(1);
|
|
48
|
+
}
|
|
49
|
+
const r = await setRunStatus({ runId: o.run, status, step, url: o.url ?? undefined, prUrl: o["pr-url"] ?? undefined });
|
|
50
|
+
console.log(`Run ${r.id}: ${r.status}${step ? ` (${step})` : ""}`);
|
package/cli/store.mjs
ADDED
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// ============================================================================
|
|
2
|
+
// Where fetch and post read and write: two roads to the same database.
|
|
3
|
+
//
|
|
4
|
+
// local the Supabase CLI, logged in on this machine (`sql`, `upload` in
|
|
5
|
+
// lib.mjs). Full access to the Unbase project: for a session on
|
|
6
|
+
// the owner's Mac.
|
|
7
|
+
// CI the Edge Function operator-api, with CM_OPERATOR_KEY (one key per
|
|
8
|
+
// project, made in Unbase and stored hashed in operator_keys). It
|
|
9
|
+
// can do exactly this: read this project's comments, post a
|
|
10
|
+
// team-only reply as the Operator, upload an image for that reply,
|
|
11
|
+
// and report the progress of a run and of a deploy. No resolving,
|
|
12
|
+
// no public replies, no SQL.
|
|
13
|
+
//
|
|
14
|
+
// The road is chosen by the environment: CM_OPERATOR_KEY set → CI.
|
|
15
|
+
// CM_OPERATOR_URL overrides the address (default: the function in the
|
|
16
|
+
// project of comment-modus.json).
|
|
17
|
+
// ============================================================================
|
|
18
|
+
|
|
19
|
+
import { readFileSync } from "node:fs";
|
|
20
|
+
import { PROJECT_KEY, PROJECT_REF, jsonLit, lit, localProjectId, sql, upload as cliUpload } from "./lib.mjs";
|
|
21
|
+
|
|
22
|
+
const KEY = process.env.CM_OPERATOR_KEY || null;
|
|
23
|
+
const URL_ = process.env.CM_OPERATOR_URL || `https://${PROJECT_REF}.supabase.co/functions/v1/operator-api`;
|
|
24
|
+
|
|
25
|
+
/** true when this run goes through operator-api (CI). */
|
|
26
|
+
export const VIA_OPERATOR = Boolean(KEY);
|
|
27
|
+
|
|
28
|
+
/** operator-api takes the project as a uuid (`project`) or, for a key from
|
|
29
|
+
* before Unbase, as the old site key (`site`); a slug it does not take. The
|
|
30
|
+
* key itself decides the project: naming another one is refused. */
|
|
31
|
+
const NAMED = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(PROJECT_KEY)
|
|
32
|
+
? { project: PROJECT_KEY.toLowerCase() }
|
|
33
|
+
: { site: PROJECT_KEY };
|
|
34
|
+
|
|
35
|
+
async function call(action, body = {}) {
|
|
36
|
+
const res = await fetch(URL_, {
|
|
37
|
+
method: "POST",
|
|
38
|
+
// x-operator-key is operator-api's header; x-cm-key is the one it still
|
|
39
|
+
// accepts from before the rename.
|
|
40
|
+
headers: { "content-type": "application/json", "x-operator-key": KEY, "x-cm-key": KEY },
|
|
41
|
+
body: JSON.stringify({ ...NAMED, action, ...body }),
|
|
42
|
+
});
|
|
43
|
+
const text = await res.text();
|
|
44
|
+
let data;
|
|
45
|
+
try {
|
|
46
|
+
data = JSON.parse(text);
|
|
47
|
+
} catch {
|
|
48
|
+
data = { error: text.slice(0, 500) };
|
|
49
|
+
}
|
|
50
|
+
if (!res.ok) throw new Error(`operator-api ${action}: ${res.status} ${data.error ?? text.slice(0, 500)}`);
|
|
51
|
+
return data;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The project's uuid, when it is known without asking operator-api: always
|
|
55
|
+
* locally, in CI only when comment-modus.json holds the uuid itself. */
|
|
56
|
+
export function knownProjectId() {
|
|
57
|
+
if (!VIA_OPERATOR) return localProjectId();
|
|
58
|
+
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(PROJECT_KEY) ? PROJECT_KEY.toLowerCase() : null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Every comment of this project with its author: [{ c, author: { name, team, operator } }].
|
|
62
|
+
* team: owner, admin or editor on the project, or its Operator. */
|
|
63
|
+
export async function commentRows() {
|
|
64
|
+
if (VIA_OPERATOR) return (await call("comments")).rows;
|
|
65
|
+
const project = localProjectId();
|
|
66
|
+
return sql(`
|
|
67
|
+
select to_jsonb(c) as c,
|
|
68
|
+
jsonb_build_object(
|
|
69
|
+
'name', a.name,
|
|
70
|
+
'team', c.author_id is not null and unbase.is_team_account(c.project_id, c.author_id),
|
|
71
|
+
'operator', coalesce(a.kind = 'operator', false)
|
|
72
|
+
) as author
|
|
73
|
+
from unbase.comments c
|
|
74
|
+
left join unbase.accounts a on a.id = c.author_id
|
|
75
|
+
where c.project_id = ${lit(project)}
|
|
76
|
+
order by c.created_at
|
|
77
|
+
`);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** The project's Operator account: { id, name }, or null when there is none. */
|
|
81
|
+
export async function operatorProfile() {
|
|
82
|
+
if (VIA_OPERATOR) return (await call("operator")).operator;
|
|
83
|
+
const [row] = sql(`
|
|
84
|
+
select a.id, a.name
|
|
85
|
+
from unbase.projects p
|
|
86
|
+
join unbase.accounts a on a.id = p.operator_account_id
|
|
87
|
+
where p.id = ${lit(localProjectId())}
|
|
88
|
+
`);
|
|
89
|
+
return row ?? null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Pins (not replies) of this project by number: Map nr → { id, nr, status }. */
|
|
93
|
+
export async function pinsByNr(nrs) {
|
|
94
|
+
const list = VIA_OPERATOR
|
|
95
|
+
? (await call("pins", { nrs })).pins
|
|
96
|
+
: sql(
|
|
97
|
+
`select id, nr, status from unbase.comments where parent_id is null and project_id = ${lit(localProjectId())} and nr in (${nrs.map(Number).join(",")})`,
|
|
98
|
+
);
|
|
99
|
+
return new Map(list.map((p) => [p.nr, p]));
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** An image for reply `id`. `path` is "<id>/<name>"; returns where it was
|
|
103
|
+
* stored in the bucket: "<project id>/<id>/<name>" (in CI as operator-api
|
|
104
|
+
* reports it). */
|
|
105
|
+
export async function uploadImage(file, path) {
|
|
106
|
+
if (!VIA_OPERATOR) {
|
|
107
|
+
const stored = `${localProjectId()}/${path}`;
|
|
108
|
+
cliUpload(file, stored);
|
|
109
|
+
return stored;
|
|
110
|
+
}
|
|
111
|
+
const [id, name] = path.split("/");
|
|
112
|
+
const r = await call("upload", { id, name, data: readFileSync(file).toString("base64") });
|
|
113
|
+
return r.path ?? path;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** A reply under a pin, as the Operator. operator-api only takes team-only
|
|
117
|
+
* replies and never resolves; locally both are possible. */
|
|
118
|
+
export async function insertReply({ id, pin, operatorId, text, teamOnly, attachment, resolve }) {
|
|
119
|
+
if (VIA_OPERATOR) {
|
|
120
|
+
if (!teamOnly) throw new Error("Through operator-api a reply is always team-only (--team-only).");
|
|
121
|
+
if (resolve) throw new Error("Through operator-api the Operator never resolves a pin.");
|
|
122
|
+
await call("reply", { id, pin: pin.nr, text, attachment });
|
|
123
|
+
return;
|
|
124
|
+
}
|
|
125
|
+
const project = localProjectId();
|
|
126
|
+
sql(`
|
|
127
|
+
insert into unbase.comments (id, project_id, parent_id, author_id, body, team_only, attachment)
|
|
128
|
+
values ('${id}', ${lit(project)}, '${pin.id}', '${operatorId}', ${lit(text)}, ${teamOnly ? "true" : "false"}, ${attachment ? jsonLit(attachment) : "null"});
|
|
129
|
+
${resolve ? `update unbase.comments set status = 'resolved', resolved_by = '${operatorId}', resolved_at = now() where id = '${pin.id}';` : ""}
|
|
130
|
+
`);
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
/** Progress of a run (unbase.operator_runs): only through operator-api, the
|
|
134
|
+
* workflow is the only one that reports it. */
|
|
135
|
+
export async function setRunStatus({ runId, status, step, url, prUrl }) {
|
|
136
|
+
if (!VIA_OPERATOR) throw new Error("status goes through operator-api: set CM_OPERATOR_KEY.");
|
|
137
|
+
return call("status", { run_id: runId, status, step, run_url: url, pr_url: prUrl });
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function reportLive({ sha, status, url }) {
|
|
141
|
+
if (!VIA_OPERATOR) throw new Error("live goes through operator-api: set CM_OPERATOR_KEY.");
|
|
142
|
+
return call("live", { sha, status, url });
|
|
143
|
+
}
|