@zenera/cli 1.3.20 → 1.3.22
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/assets/chat.html +920 -835
- package/package.json +6 -6
- package/templates/editor/.github/skills/zen-cli/references/projects.md +2 -2
- package/templates/editor/.github/skills/zen-review/SKILL.md +3 -1
- package/templates/editor/.github/skills/zen-review/scripts/check-paths.sh +6 -1
- package/templates/project/SPECIFICATION.md.tmpl +3 -2
- package/templates/project/agents/prompts/default.md.tmpl +4 -2
- package/templates/project/agents/skills/data-analysis/SKILL.md +1 -1
- package/templates/project/agents/skills/html-page/SKILL.md +147 -0
- package/templates/project/agents/skills/html-page/assets/api.js +87 -0
- package/templates/project/agents/skills/html-page/assets/app/api/items.api.py +84 -0
- package/templates/project/agents/skills/html-page/assets/app/index.html +278 -0
- package/templates/project/agents/skills/{html-dashboard/assets/template.html → html-page/assets/dashboard.html} +2 -0
- package/templates/project/agents/skills/html-page/references/charts-and-tables.md +71 -0
- package/templates/project/agents/skills/html-page/references/python-functions.md +203 -0
- package/templates/project/agents.yaml.tmpl +2 -1
- package/templates/project/agents/skills/html-dashboard/SKILL.md +0 -163
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@zenera/cli",
|
|
3
|
-
"version": "1.3.
|
|
3
|
+
"version": "1.3.22",
|
|
4
4
|
"description": "Command-line front end for @zenera/neo: agentic projects you can run, share and commit.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"agents",
|
|
@@ -56,11 +56,11 @@
|
|
|
56
56
|
"@google/genai": "^2.30.0",
|
|
57
57
|
"@inkjs/ui": "^2.0.0",
|
|
58
58
|
"@openrouter/sdk": "^1.4.25",
|
|
59
|
-
"@zenera/engine": "^1.3.
|
|
60
|
-
"@zenera/neo": "^1.3.
|
|
61
|
-
"@zenera/sandbox": "^1.3.
|
|
62
|
-
"@zenera/server": "^1.3.
|
|
63
|
-
"@zenera/view": "^1.3.
|
|
59
|
+
"@zenera/engine": "^1.3.22",
|
|
60
|
+
"@zenera/neo": "^1.3.22",
|
|
61
|
+
"@zenera/sandbox": "^1.3.22",
|
|
62
|
+
"@zenera/server": "^1.3.22",
|
|
63
|
+
"@zenera/view": "^1.3.22",
|
|
64
64
|
"google-auth-library": "^10.0.0",
|
|
65
65
|
"ink": "^7.1.1",
|
|
66
66
|
"openai": "^6.0.0",
|
|
@@ -38,8 +38,8 @@ agents/mcp-memory-instructions.md the same, for those that also have memory
|
|
|
38
38
|
agents/memory-instructions.md more of them, for agents with the memory store
|
|
39
39
|
agents/tools-instructions.md more of them, about how tools are called
|
|
40
40
|
agents/prompts/default.md the default agent's prompt: a general-purpose assistant
|
|
41
|
-
agents/skills/ a2ui, a2ui-charts, data-analysis, html-
|
|
42
|
-
with an Exa key, mcp with the mcp tools; and yours
|
|
41
|
+
agents/skills/ a2ui, a2ui-charts, data-analysis, html-page;
|
|
42
|
+
web-research with an Exa key, mcp with the mcp tools; and yours
|
|
43
43
|
assets/README.md
|
|
44
44
|
sandbox/Dockerfile the image the sandbox builds
|
|
45
45
|
sessions/ empty
|
|
@@ -220,7 +220,9 @@ emptied or explained rather than skimmed. It strips urls before tokenising, skip
|
|
|
220
220
|
a handful of English constructions that contain a slash, and leaves the four
|
|
221
221
|
copies `zen` ships (`agents/{files,fork,memory,tools}-instructions.md`) out
|
|
222
222
|
entirely - they are worked examples by design, and `zen check` keeps them
|
|
223
|
-
byte-identical (`rules.stale`).
|
|
223
|
+
byte-identical (`rules.stale`). The `html-page` skill is left out as well: its
|
|
224
|
+
paths are urls relative to the page (`api('api/orders')`), not files the agent
|
|
225
|
+
opens.
|
|
224
226
|
|
|
225
227
|
Everything it does print is either noise the script has not learned yet or a
|
|
226
228
|
real finding. There is no third case. A candidate that is genuinely noise is a
|
|
@@ -52,6 +52,10 @@ strip_urls() {
|
|
|
52
52
|
# are left out on purpose. They are full of worked examples, so they fail this
|
|
53
53
|
# sweep by design, and the project cannot edit them anyway: `zen check` reports
|
|
54
54
|
# any byte that differs as `rules.stale`.
|
|
55
|
+
#
|
|
56
|
+
# The html-page skill is left out too. Its paths are the page's own urls,
|
|
57
|
+
# relative to the page (`api('api/orders')`, `../api.js`), and to this sweep
|
|
58
|
+
# they look exactly like files the agent cannot open.
|
|
55
59
|
files() {
|
|
56
60
|
{
|
|
57
61
|
if [ -d agents/prompts ]; then find agents/prompts -type f -name '*.md'; fi
|
|
@@ -60,7 +64,8 @@ files() {
|
|
|
60
64
|
if [ -f "$file" ]; then echo "$file"; fi
|
|
61
65
|
done
|
|
62
66
|
} | grep -Ev '^agents/(a2ui|files|fork|markdown|mcp|mcp-memory|memory|tools)-instructions\.md$' |
|
|
63
|
-
grep -Ev '^agents/skills/(a2ui|a2ui-charts)/SKILL\.md$' |
|
|
67
|
+
grep -Ev '^agents/skills/(a2ui|a2ui-charts)/SKILL\.md$' |
|
|
68
|
+
grep -Ev '^agents/skills/html-page/' | sort -u
|
|
64
69
|
}
|
|
65
70
|
|
|
66
71
|
# Every token in those files, urls removed first, and a sentence's full stop
|
|
@@ -61,8 +61,9 @@ data in it — and report what was done in enough detail to be checked.
|
|
|
61
61
|
{{/if}}
|
|
62
62
|
- Skills — guides in `agents/skills`, loaded when a request needs one:
|
|
63
63
|
- `data-analysis` — calculations, tables and statistics over data, in Python.
|
|
64
|
-
- `html-
|
|
65
|
-
tables and filters
|
|
64
|
+
- `html-page` — interactive HTML pages: dashboards and reports with charts,
|
|
65
|
+
tables and filters, and small apps whose page calls Python functions to
|
|
66
|
+
read and change data.
|
|
66
67
|
- `a2ui` — forms, cards and tables in the chat.
|
|
67
68
|
- `a2ui-charts` — charts, together with `a2ui`.
|
|
68
69
|
{{#if web}}
|
|
@@ -50,8 +50,10 @@ Your skill index lists detailed guides. Load the one that covers a task before
|
|
|
50
50
|
you start it:
|
|
51
51
|
|
|
52
52
|
- `data-analysis` — calculations, tables and statistics over data, in Python.
|
|
53
|
-
- `html-
|
|
54
|
-
answer has several charts or tables, or data to filter and explore
|
|
53
|
+
- `html-page` — an interactive HTML page: a dashboard or report when an
|
|
54
|
+
answer has several charts or tables, or data to filter and explore; a
|
|
55
|
+
small app (the page calls Python functions) when the user wants something
|
|
56
|
+
to use and change.
|
|
55
57
|
- `a2ui` — forms, cards and tables in the chat; always before any A2UI.
|
|
56
58
|
- `a2ui-charts` — charts, together with `a2ui`.
|
|
57
59
|
{{#if web}}
|
|
@@ -77,7 +77,7 @@ the real file. If the data cannot answer the question, say what is missing.
|
|
|
77
77
|
one finding it shows.
|
|
78
78
|
- A complex report - several related charts, tables and breakdowns, or data
|
|
79
79
|
the user will want to filter, sort or drill into - is an interactive HTML
|
|
80
|
-
dashboard, not a long reply: load the `html-
|
|
80
|
+
dashboard, not a long reply: load the `html-page` skill. Its page shows
|
|
81
81
|
only numbers your script wrote to its `data.json`.
|
|
82
82
|
- When the result is a file the user will keep (a cleaned CSV, a report),
|
|
83
83
|
write it to the workspace and name it in the answer.
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: html-page
|
|
3
|
+
description: Building an interactive HTML page the user opens from the chat - a dashboard or report with charts, tables, filters and headline numbers, or a small app whose page calls Python functions to read and change data (a tracker, a CRUD tool, a form that saves, a page that queries a database each time it opens). Where to write it, how it gets its data, the layout that works in the chat's side panel and full page, and how to check it. Load when an answer has more than one chart or table, data the user will want to filter or explore, or the user wants something to use and change.
|
|
4
|
+
tags: [html, dashboard, report, app, charts, api, python, ui]
|
|
5
|
+
version: 1.0.0
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
# Interactive HTML pages
|
|
9
|
+
|
|
10
|
+
A page is the answer when a reply would be too long or too static: several
|
|
11
|
+
related charts and tables, a breakdown to filter, sort or drill into, or
|
|
12
|
+
something the user will use and change (add items, edit records, run a
|
|
13
|
+
query). One chart or a short table is better inline in the chat (load `a2ui`
|
|
14
|
+
and `a2ui-charts`).
|
|
15
|
+
|
|
16
|
+
## First: where its data comes from
|
|
17
|
+
|
|
18
|
+
| The page | Its data | Read next |
|
|
19
|
+
| ------------------------------------------------------------- | ---------------------------------------------------------- | ------------------------------------------------------------------ |
|
|
20
|
+
| Shows numbers you compute now (a report, a dashboard) | `data.json` beside the page, written by your script | `references/charts-and-tables.md` |
|
|
21
|
+
| Shows live data (queried each time it opens) or saves changes | Python functions in `*.api.py` files, called from the page | `references/python-functions.md`, and charts-and-tables for charts |
|
|
22
|
+
|
|
23
|
+
Read the reference before writing the page: `cat /skills/html-page/references/<file>`.
|
|
24
|
+
Functions also know who is signed in (`zenera.identity()`: id, name, email,
|
|
25
|
+
role), for per-user data and permissions - python-functions.md, "Who is
|
|
26
|
+
calling".
|
|
27
|
+
|
|
28
|
+
Static data first when it will do: it opens at once and needs no code at
|
|
29
|
+
view time. A page that only shows numbers never invents, estimates or
|
|
30
|
+
hard-codes one: compute it first (load `data-analysis`).
|
|
31
|
+
|
|
32
|
+
## Where it goes
|
|
33
|
+
|
|
34
|
+
One folder per page, under `/workspace/pages/`:
|
|
35
|
+
|
|
36
|
+
```
|
|
37
|
+
/workspace/pages/sales-q1/
|
|
38
|
+
├── index.html the page
|
|
39
|
+
├── data.json data it shows, written by your script (static data)
|
|
40
|
+
├── api.js calls the functions - copied, never edited (functions)
|
|
41
|
+
└── api/
|
|
42
|
+
├── orders.api.py functions the page calls
|
|
43
|
+
├── db.py helpers they import (not callable from the page)
|
|
44
|
+
└── .data/ the page's own data (SQLite); never downloadable
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
- Name the folder after the content (`sales-q1`, `expense-tracker`),
|
|
48
|
+
lowercase with dashes. Rewriting a page keeps its folder, its link and its
|
|
49
|
+
data.
|
|
50
|
+
- A script that builds `data.json` goes under `/workspace/.tmp/`, so the page
|
|
51
|
+
can be refreshed by running it again.
|
|
52
|
+
- More pages of one app are more `.html` files in the folder.
|
|
53
|
+
|
|
54
|
+
## Start from a template
|
|
55
|
+
|
|
56
|
+
Copy one and edit it rather than writing a page from scratch:
|
|
57
|
+
|
|
58
|
+
```sh
|
|
59
|
+
# a dashboard or report: charts, KPIs, filters, table
|
|
60
|
+
mkdir -p /workspace/pages/sales-q1
|
|
61
|
+
cp /skills/html-page/assets/dashboard.html /workspace/pages/sales-q1/index.html
|
|
62
|
+
|
|
63
|
+
# an app: a list kept in SQLite, with add, check off, filter and delete
|
|
64
|
+
cp -r /skills/html-page/assets/app /workspace/pages/todo
|
|
65
|
+
cp /skills/html-page/assets/api.js /workspace/pages/todo/
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
Keep the templates' layout, theme and helpers; replace the part marked
|
|
69
|
+
`The page: replace from here`. A dashboard with live data is the dashboard
|
|
70
|
+
template plus `api.js` and an `*.api.py`: its `loadData()` says what to
|
|
71
|
+
change.
|
|
72
|
+
|
|
73
|
+
## How it is shown, and what that allows
|
|
74
|
+
|
|
75
|
+
The chat opens the page in a side panel next to the conversation (often 400 -
|
|
76
|
+
600 px wide) or in a full browser tab. Either way it runs sandboxed:
|
|
77
|
+
|
|
78
|
+
- It reaches files and functions of its folder **by a path relative to the
|
|
79
|
+
page**: `fetch('data.json')`, `<img src="logo.png">`, `api('api/orders')`,
|
|
80
|
+
and `..` to go up. Never `file:///`, `/workspace/...`, `http://localhost`
|
|
81
|
+
or an `.api.py` name in the page.
|
|
82
|
+
- Scripts, styles and fonts load only from `cdn.jsdelivr.net`, `unpkg.com`
|
|
83
|
+
and `cdnjs.cloudflare.com`. Any other host is blocked - no external APIs,
|
|
84
|
+
images, map tiles or analytics from the page. A page that needs an outside
|
|
85
|
+
service calls a Python function that does.
|
|
86
|
+
- No `localStorage`, `sessionStorage`, cookies or `IndexedDB` (the page has
|
|
87
|
+
no origin of its own; touching them throws). Keep view state in variables
|
|
88
|
+
or `location.hash`, and anything to keep in the database.
|
|
89
|
+
- No `<form>` submission: use inputs, buttons and `click` / `change`
|
|
90
|
+
listeners. No `alert`, `confirm` or `prompt` (blocked): confirm a delete
|
|
91
|
+
with a second click, as the app template does.
|
|
92
|
+
- Links to other sites need `target="_blank" rel="noopener"`.
|
|
93
|
+
- The page cannot call the agent or any tool.
|
|
94
|
+
|
|
95
|
+
## Layout - always adaptive
|
|
96
|
+
|
|
97
|
+
Every page must work at 360 px (narrow panel) and 1600 px (wide tab) without
|
|
98
|
+
horizontal scrolling. The templates do this; keep to their rules:
|
|
99
|
+
|
|
100
|
+
- `<meta name="viewport" content="width=device-width, initial-scale=1">`.
|
|
101
|
+
- No fixed widths: CSS grid that reflows
|
|
102
|
+
(`repeat(auto-fit, minmax(min(100%, 420px), 1fr))`), flex rows that wrap.
|
|
103
|
+
- Every grid or flex child gets `min-width: 0` (the templates' `.card` has
|
|
104
|
+
it), or a chart, table or long text pushes the page wider than the panel.
|
|
105
|
+
- Let the page scroll; do not lock the body to `100vh`.
|
|
106
|
+
- Light and dark: colours come from the CSS variables in `:root`, switched by
|
|
107
|
+
`prefers-color-scheme`. Use `var(--fg)`, `var(--muted)` and the rest - no
|
|
108
|
+
hard-coded colours in new elements.
|
|
109
|
+
- Controls in one wrapping row at the top; then headline numbers; then
|
|
110
|
+
charts or the list; the detailed table last.
|
|
111
|
+
|
|
112
|
+
## Page code
|
|
113
|
+
|
|
114
|
+
- One `state` object and one `render()` that draws everything from it; every
|
|
115
|
+
control only changes `state` and calls `render()` (or reloads first). The
|
|
116
|
+
numbers, charts and lists then always agree.
|
|
117
|
+
- Show "Loading…", an empty state ("No orders yet", "No data for these
|
|
118
|
+
filters") and errors in a box on the page - never fail silently.
|
|
119
|
+
- Put values from data into the page with `textContent` (or the templates'
|
|
120
|
+
`esc()`), never raw into `innerHTML`.
|
|
121
|
+
- Libraries: ECharts for charts, Tabulator for tables, from the CDN URLs in
|
|
122
|
+
`dashboard.html`. No CSS frameworks, React or Vue (no build step here).
|
|
123
|
+
|
|
124
|
+
## Check before you link it
|
|
125
|
+
|
|
126
|
+
```sh
|
|
127
|
+
cd /workspace/pages/sales-q1
|
|
128
|
+
grep -nE "file://|/workspace|localhost|localStorage|sessionStorage|<form|alert\(|confirm\(|prompt\(" *.html || echo "paths ok"
|
|
129
|
+
grep -noE "(src|href)=\"https?://[^\"]+" *.html | grep -vE "cdn.jsdelivr.net|unpkg.com|cdnjs.cloudflare.com" || echo "hosts ok"
|
|
130
|
+
[ ! -f data.json ] || python3 -c "import json; json.load(open('data.json'))" && echo "data ok"
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
Confirm every relative file the page loads exists in its folder. A page with
|
|
134
|
+
functions: call each of them from the shell first (`python-functions.md`,
|
|
135
|
+
"Test before you link it").
|
|
136
|
+
|
|
137
|
+
## Hand it over
|
|
138
|
+
|
|
139
|
+
- The main findings with their numbers in two to four sentences, or for an
|
|
140
|
+
app what it does - the reply must stand on its own for someone who never
|
|
141
|
+
opens the page.
|
|
142
|
+
- Then the page as a link, alone in its own paragraph:
|
|
143
|
+
|
|
144
|
+
[Sales Q1 dashboard](file:///workspace/pages/sales-q1/index.html)
|
|
145
|
+
|
|
146
|
+
- Say what the user can do there ("filter by region", "add and check off
|
|
147
|
+
items"), where an app keeps its data, and what is left out.
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Calls the functions of this app's *.api.py files from the page. Keep this file as it is.
|
|
3
|
+
*
|
|
4
|
+
* const items = api('api/items'); // api/items.api.py, relative to the page
|
|
5
|
+
* const list = await items.list_items(); // list_items()
|
|
6
|
+
* await items.add_item({ title: 'Milk' }); // add_item(title="Milk")
|
|
7
|
+
*
|
|
8
|
+
* Each call is a POST of the arguments as JSON to `<file>/<function>`. It resolves with what the
|
|
9
|
+
* function returned, or rejects with an ApiError: `.status` (0 when the server could not be
|
|
10
|
+
* reached) and `.message` (the function's HttpError message, or what went wrong).
|
|
11
|
+
* A server still starting (503) or busy (429) is waited for and asked again, up to 3 times.
|
|
12
|
+
*/
|
|
13
|
+
(function () {
|
|
14
|
+
class ApiError extends Error {
|
|
15
|
+
constructor(message, status, body) {
|
|
16
|
+
super(message);
|
|
17
|
+
this.name = 'ApiError';
|
|
18
|
+
this.status = status;
|
|
19
|
+
this.body = body;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const sleep = (ms) => new Promise((done) => setTimeout(done, ms));
|
|
24
|
+
|
|
25
|
+
async function call(file, name, args) {
|
|
26
|
+
const url = `${String(file).replace(/\/+$/, '')}/${encodeURIComponent(name)}`;
|
|
27
|
+
for (let attempt = 0; ; attempt++) {
|
|
28
|
+
let res;
|
|
29
|
+
try {
|
|
30
|
+
// text/plain keeps this a "simple" request: the sandboxed page has no origin, and a
|
|
31
|
+
// JSON content type would need a CORS preflight the app's host does not answer.
|
|
32
|
+
res = await fetch(url, {
|
|
33
|
+
method: 'POST',
|
|
34
|
+
headers: {
|
|
35
|
+
'content-type': 'text/plain;charset=UTF-8',
|
|
36
|
+
accept: 'application/json',
|
|
37
|
+
},
|
|
38
|
+
body: JSON.stringify(args ?? {}),
|
|
39
|
+
});
|
|
40
|
+
} catch (err) {
|
|
41
|
+
throw new ApiError(`${name}: the app's server could not be reached`, 0, err);
|
|
42
|
+
}
|
|
43
|
+
if ((res.status === 503 || res.status === 429) && attempt < 3) {
|
|
44
|
+
const seconds = Number(res.headers.get('retry-after')) || 2 * (attempt + 1);
|
|
45
|
+
await sleep(Math.min(seconds, 10) * 1000);
|
|
46
|
+
continue;
|
|
47
|
+
}
|
|
48
|
+
const text = await res.text();
|
|
49
|
+
let body = null;
|
|
50
|
+
if (text) {
|
|
51
|
+
try {
|
|
52
|
+
body = JSON.parse(text);
|
|
53
|
+
} catch {
|
|
54
|
+
body = text;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (!res.ok) {
|
|
58
|
+
const message =
|
|
59
|
+
body && typeof body === 'object' && body.error
|
|
60
|
+
? body.error
|
|
61
|
+
: typeof body === 'string' && body
|
|
62
|
+
? body.slice(0, 300)
|
|
63
|
+
: `${name} failed (${res.status})`;
|
|
64
|
+
throw new ApiError(message, res.status, body);
|
|
65
|
+
}
|
|
66
|
+
return body;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The functions of one .api.py file, by its path relative to the page without `.api.py`. */
|
|
71
|
+
function api(file) {
|
|
72
|
+
return new Proxy(
|
|
73
|
+
{},
|
|
74
|
+
{
|
|
75
|
+
get(_, name) {
|
|
76
|
+
// `then` too: an object returned from an async function must not look like a promise.
|
|
77
|
+
if (typeof name !== 'string' || name === 'then') return undefined;
|
|
78
|
+
return (args) => call(file, name, args);
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
api.call = call;
|
|
85
|
+
window.api = api;
|
|
86
|
+
window.ApiError = ApiError;
|
|
87
|
+
})();
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""The app's API: every public function here can be called from index.html.
|
|
2
|
+
|
|
3
|
+
const items = api('api/items');
|
|
4
|
+
await items.add_item({ title: 'Milk' }) -> add_item(title="Milk")
|
|
5
|
+
|
|
6
|
+
Names starting with `_` and anything imported are not callable from the page.
|
|
7
|
+
Try them from a shell before linking the app:
|
|
8
|
+
|
|
9
|
+
python3 -m zenera.api api/items.api.py
|
|
10
|
+
python3 -m zenera.api api/items.api.py add_item '{"title": "Milk"}'
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import zenera
|
|
14
|
+
from zenera.api import HttpError, connect
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _db():
|
|
18
|
+
db = connect("app.sqlite")
|
|
19
|
+
db.execute(
|
|
20
|
+
"""CREATE TABLE IF NOT EXISTS items (
|
|
21
|
+
id INTEGER PRIMARY KEY,
|
|
22
|
+
title TEXT NOT NULL,
|
|
23
|
+
done INTEGER NOT NULL DEFAULT 0,
|
|
24
|
+
created TEXT NOT NULL DEFAULT (datetime('now'))
|
|
25
|
+
)"""
|
|
26
|
+
)
|
|
27
|
+
return db
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _item(db, item_id: int):
|
|
31
|
+
row = db.execute("SELECT id, title, done, created FROM items WHERE id = ?", (item_id,)).fetchone()
|
|
32
|
+
if row is None:
|
|
33
|
+
raise HttpError(404, f"no item {item_id}")
|
|
34
|
+
return {**row, "done": bool(row["done"])}
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def me():
|
|
38
|
+
"""Who is using the page, for its header; None when nobody is signed in."""
|
|
39
|
+
u = zenera.identity()
|
|
40
|
+
if u is None:
|
|
41
|
+
return None
|
|
42
|
+
return {"id": u.id, "name": u.name or u.email or u.id, "role": u.role}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def list_items(show: str = "all"):
|
|
46
|
+
"""All items, or only the open or done ones (show: all | open | done)."""
|
|
47
|
+
where = {"all": "", "open": " WHERE done = 0", "done": " WHERE done = 1"}
|
|
48
|
+
if show not in where:
|
|
49
|
+
raise HttpError(400, "show must be all, open or done")
|
|
50
|
+
rows = _db().execute(f"SELECT id, title, done, created FROM items{where[show]} ORDER BY id").fetchall()
|
|
51
|
+
return [{**r, "done": bool(r["done"])} for r in rows]
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def add_item(title: str):
|
|
55
|
+
"""Adds an item and returns it."""
|
|
56
|
+
title = (title or "").strip()
|
|
57
|
+
if not title:
|
|
58
|
+
raise HttpError(400, "the title is empty")
|
|
59
|
+
if len(title) > 200:
|
|
60
|
+
raise HttpError(400, "the title is longer than 200 characters")
|
|
61
|
+
db = _db()
|
|
62
|
+
with db:
|
|
63
|
+
cur = db.execute("INSERT INTO items (title) VALUES (?)", (title,))
|
|
64
|
+
return _item(db, cur.lastrowid)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def set_done(id: int, done: bool):
|
|
68
|
+
"""Marks an item done or open, and returns it."""
|
|
69
|
+
db = _db()
|
|
70
|
+
with db:
|
|
71
|
+
cur = db.execute("UPDATE items SET done = ? WHERE id = ?", (1 if done else 0, id))
|
|
72
|
+
if cur.rowcount == 0:
|
|
73
|
+
raise HttpError(404, f"no item {id}")
|
|
74
|
+
return _item(db, id)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def remove_item(id: int):
|
|
78
|
+
"""Deletes an item."""
|
|
79
|
+
db = _db()
|
|
80
|
+
with db:
|
|
81
|
+
cur = db.execute("DELETE FROM items WHERE id = ?", (id,))
|
|
82
|
+
if cur.rowcount == 0:
|
|
83
|
+
raise HttpError(404, f"no item {id}")
|
|
84
|
+
return {"removed": id}
|