ezship 0.1.15 → 0.1.16
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/access.d.mts +5 -1
- package/access.mjs +69 -29
- package/commands.d.mts +19 -0
- package/commands.mjs +318 -60
- package/editor-types.json.gz +0 -0
- package/ez.mjs +2 -2
- package/package.json +1 -1
- package/schema.d.mts +8 -0
- package/schema.mjs +28 -3
- package/update-check.mjs +0 -9
package/access.d.mts
CHANGED
|
@@ -92,7 +92,11 @@ export function lookupSelect(
|
|
|
92
92
|
me: string,
|
|
93
93
|
instance: string,
|
|
94
94
|
): { sql: string; binds: (string | number | null)[] };
|
|
95
|
-
|
|
95
|
+
/** The rules with every atom that reads a column the App Database lacks replaced by what NULL gives it. */
|
|
96
|
+
export function storedAccess(
|
|
97
|
+
access: Access,
|
|
98
|
+
live: { tables: Record<string, { columns: Record<string, unknown> }> },
|
|
99
|
+
): { access: Access; pending: boolean };
|
|
96
100
|
export function printScope(access: Access | null | undefined): string | null;
|
|
97
101
|
export function printCondition(cond: Condition): string;
|
|
98
102
|
export function printRule(rule: Rule): string;
|
package/access.mjs
CHANGED
|
@@ -793,10 +793,11 @@ export function compileCondition(
|
|
|
793
793
|
/** @param {Condition} c @returns {string} */
|
|
794
794
|
const walk = (c) => {
|
|
795
795
|
switch (c.kind) {
|
|
796
|
+
// No items: what `storedAccess` folds an atom to, never and always.
|
|
796
797
|
case "or":
|
|
797
|
-
return `(${c.items.map(walk).join(" OR ")})
|
|
798
|
+
return c.items.length ? `(${c.items.map(walk).join(" OR ")})` : "0";
|
|
798
799
|
case "and":
|
|
799
|
-
return `(${c.items.map(walk).join(" AND ")})
|
|
800
|
+
return c.items.length ? `(${c.items.map(walk).join(" AND ")})` : "1";
|
|
800
801
|
case "group":
|
|
801
802
|
return viewer.groups.includes(c.name) ? "1" : "0";
|
|
802
803
|
case "owner":
|
|
@@ -872,39 +873,78 @@ export function conditionColumns(cond) {
|
|
|
872
873
|
return [...out];
|
|
873
874
|
}
|
|
874
875
|
|
|
876
|
+
/** The columns every stored Table has, which no declaration lists. */
|
|
877
|
+
const ALWAYS_STORED = ["id", "created_at", "created_by", "updated_at", "updated_by"];
|
|
878
|
+
|
|
875
879
|
/**
|
|
876
|
-
*
|
|
877
|
-
*
|
|
878
|
-
*
|
|
880
|
+
* The rules as the App Database can answer them now (docs/adr/0156). A column no Preview or Deploy has added
|
|
881
|
+
* yet holds NULL in every row, so an atom that reads one is replaced by what NULL gives it: `IS NULL` always
|
|
882
|
+
* passes (an AND of nothing), every other test never does (an OR of nothing), and a lookup through a missing
|
|
883
|
+
* Table or column finds no value. A scope whose lookup cannot be read yet is left out: it only narrows.
|
|
884
|
+
* `pending` says something was replaced, so the caller asks again once the App Database has grown.
|
|
885
|
+
* @type {typeof import("./access.d.mts").storedAccess}
|
|
879
886
|
*/
|
|
880
|
-
export function
|
|
881
|
-
|
|
882
|
-
const
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
+
export function storedAccess(access, live) {
|
|
888
|
+
let pending = false;
|
|
889
|
+
const has = (/** @type {string} */ table, /** @type {string} */ column) => {
|
|
890
|
+
const stored = live.tables[table];
|
|
891
|
+
return !!stored && (ALWAYS_STORED.includes(column) || Object.hasOwn(stored.columns, column));
|
|
892
|
+
};
|
|
893
|
+
/** @returns {Condition} */
|
|
894
|
+
const constant = (/** @type {boolean} */ passes) => {
|
|
895
|
+
pending = true;
|
|
896
|
+
return passes ? { kind: "and", items: [] } : { kind: "or", items: [] };
|
|
887
897
|
};
|
|
888
|
-
/** @param {
|
|
889
|
-
const
|
|
890
|
-
if (c.
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
+
/** @param {Extract<Condition, { kind: "my" }>} c @returns {Extract<Condition, { kind: "my" }> | null} */
|
|
899
|
+
const lookup = (c) => {
|
|
900
|
+
if (!has(c.table, c.select) || !has(c.table, c.member)) return null;
|
|
901
|
+
/** @type {LookupCondition[]} */
|
|
902
|
+
const where = [];
|
|
903
|
+
for (const w of c.where) {
|
|
904
|
+
if (has(c.table, w.column)) where.push(w);
|
|
905
|
+
else if (w.kind !== "null" || w.not) return null;
|
|
906
|
+
}
|
|
907
|
+
if (where.length !== c.where.length) pending = true;
|
|
908
|
+
return { ...c, where };
|
|
898
909
|
};
|
|
899
|
-
|
|
900
|
-
|
|
910
|
+
/** @param {string} table @param {Condition} c @returns {Condition} */
|
|
911
|
+
const fold = (table, c) => {
|
|
912
|
+
switch (c.kind) {
|
|
913
|
+
case "or":
|
|
914
|
+
case "and":
|
|
915
|
+
return { kind: c.kind, items: c.items.map((item) => fold(table, item)) };
|
|
916
|
+
case "group":
|
|
917
|
+
return c;
|
|
918
|
+
case "owner":
|
|
919
|
+
return has(table, "created_by") ? c : constant(false);
|
|
920
|
+
case "me":
|
|
921
|
+
case "eq":
|
|
922
|
+
return has(table, c.column) ? c : constant(false);
|
|
923
|
+
case "null":
|
|
924
|
+
return has(table, c.column) ? c : constant(!c.not);
|
|
925
|
+
case "my": {
|
|
926
|
+
const found = has(table, c.column) ? lookup(c) : null;
|
|
927
|
+
return found ?? constant(false);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
};
|
|
931
|
+
/** @type {Access} */
|
|
932
|
+
const out = { tables: {}, ...(access.groups ? { groups: access.groups } : {}) };
|
|
933
|
+
for (const [table, ops] of Object.entries(access.tables)) {
|
|
934
|
+
out.tables[table] = {};
|
|
935
|
+
for (const op of /** @type {const} */ (["read", "write"])) {
|
|
936
|
+
const rule = ops[op];
|
|
937
|
+
if (rule)
|
|
938
|
+
out.tables[table][op] =
|
|
939
|
+
rule.kind === "where" ? { kind: "where", cond: fold(table, rule.cond) } : rule;
|
|
940
|
+
}
|
|
941
|
+
}
|
|
901
942
|
if (access.scope) {
|
|
902
|
-
const
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
for (const w of lookup.where) add(lookup.table, w.column);
|
|
943
|
+
const found = lookup(access.scope.lookup);
|
|
944
|
+
if (found) out.scope = { ...access.scope, lookup: found };
|
|
945
|
+
else pending = true;
|
|
906
946
|
}
|
|
907
|
-
return
|
|
947
|
+
return { access: out, pending };
|
|
908
948
|
}
|
|
909
949
|
|
|
910
950
|
/**
|
package/commands.d.mts
CHANGED
|
@@ -676,6 +676,25 @@ export type Recipe = {
|
|
|
676
676
|
notes: string;
|
|
677
677
|
};
|
|
678
678
|
export const RECIPES: readonly Recipe[];
|
|
679
|
+
/** A help topic's code block, checked by the Pipeline's tests as `before + code + after` in the file `path`. */
|
|
680
|
+
export type HelpSnippet = {
|
|
681
|
+
name: string;
|
|
682
|
+
/** The help topic that prints `code`. */
|
|
683
|
+
topic: string;
|
|
684
|
+
/** The Working Copy `path` is in: a Site unless "global". */
|
|
685
|
+
tree?: "global";
|
|
686
|
+
path: string;
|
|
687
|
+
/** What the topic prints. */
|
|
688
|
+
code: string;
|
|
689
|
+
/** What the check adds around `code` to make the file; never printed. */
|
|
690
|
+
before?: string;
|
|
691
|
+
after?: string;
|
|
692
|
+
/** Other Site files the block needs, by path; never printed. */
|
|
693
|
+
files?: Readonly<Record<string, string>>;
|
|
694
|
+
};
|
|
695
|
+
export const HELP_SNIPPETS: readonly HelpSnippet[];
|
|
696
|
+
/** The Tables the snippets are checked against. */
|
|
697
|
+
export const HELP_SNIPPET_SCHEMA: string;
|
|
679
698
|
|
|
680
699
|
export function describeCommand(argv: string[]): string;
|
|
681
700
|
export function runCommand(ws: Workspace, argv: string[], stdin?: string): Promise<string>;
|
package/commands.mjs
CHANGED
|
@@ -3072,10 +3072,16 @@ export const CHECK_RULES = Object.freeze(
|
|
|
3072
3072
|
"an eslint-disable or oxlint-disable comment: Site code has no escape hatch, so it turns nothing off (docs/adr/0121)",
|
|
3073
3073
|
"fix the finding it meant to hide, and delete the comment",
|
|
3074
3074
|
],
|
|
3075
|
+
[
|
|
3076
|
+
"@typescript-eslint/switch-exhaustiveness-check",
|
|
3077
|
+
"warning",
|
|
3078
|
+
"a switch over a union (a CHECK list's values, a workflow's states) that names neither every member nor a default (docs/adr/0154)",
|
|
3079
|
+
"add a case for each value the message lists, or a default (an empty column's null need not be named)",
|
|
3080
|
+
],
|
|
3075
3081
|
[
|
|
3076
3082
|
"floating-write",
|
|
3077
3083
|
"warning",
|
|
3078
|
-
"a db write or server-function call whose promise nobody awaits (
|
|
3084
|
+
"a db write or server-function call whose promise nobody awaits (one handed to a component whose prop takes a promise passes, docs/adr/0154)",
|
|
3079
3085
|
"one click: onClick={() => run(() => db.update(...))}; a form: await it in useActionState(attempt(async () => ...), null)",
|
|
3080
3086
|
],
|
|
3081
3087
|
[
|
|
@@ -3099,8 +3105,8 @@ export const CHECK_RULES = Object.freeze(
|
|
|
3099
3105
|
[
|
|
3100
3106
|
"ne-nullable",
|
|
3101
3107
|
"warning",
|
|
3102
|
-
"{ col: { ne: x } } on a nullable column: it also drops rows where col is NULL",
|
|
3103
|
-
"{ nin: [x] } keeps the NULL rows;
|
|
3108
|
+
"{ col: { ne: x } } on a nullable column: it also drops rows where col is NULL (a type error too on a Table named in the code, docs/adr/0154)",
|
|
3109
|
+
"{ nin: [x] } keeps the NULL rows, { nin: [x], null: false } drops them; ne only on id and created_at",
|
|
3104
3110
|
],
|
|
3105
3111
|
[
|
|
3106
3112
|
"reduce-rows",
|
|
@@ -3123,14 +3129,14 @@ export const CHECK_RULES = Object.freeze(
|
|
|
3123
3129
|
[
|
|
3124
3130
|
"fn-op-budget",
|
|
3125
3131
|
"warning",
|
|
3126
|
-
"a write inside a loop
|
|
3127
|
-
"a call has
|
|
3132
|
+
"a write inside a loop that is unbounded or may run more than 250 times (900 if it reads Date.now()) in a server function or job",
|
|
3133
|
+
"a call has 5 seconds of database time and 1,000 database operations: use insertMany, updateMany or deleteMany with a limit (ez help functions), bound the loop, or write in chunks from several calls",
|
|
3128
3134
|
],
|
|
3129
3135
|
[
|
|
3130
3136
|
"redundant-transaction",
|
|
3131
3137
|
"warning",
|
|
3132
3138
|
"a server function or job handler that returns db.transaction(...): every call is already one transaction",
|
|
3133
|
-
"write the callback's body in the handler, with db for tx (the
|
|
3139
|
+
"write the callback's body in the handler, with db for tx (the message shows it)",
|
|
3134
3140
|
],
|
|
3135
3141
|
[
|
|
3136
3142
|
"server-locale",
|
|
@@ -3195,8 +3201,9 @@ export function helpRules() {
|
|
|
3195
3201
|
.map((r) => ` ${r.id.padEnd(width)} ${r.summary}\n ${" ".repeat(width)} fix: ${r.fix}`)
|
|
3196
3202
|
.join("\n");
|
|
3197
3203
|
return `The rules \`ez check\` runs (the same ones Push, Preview and Deploy run). Each problem names its rule id,
|
|
3198
|
-
a file and a line; \`ez check --json\` prints them as
|
|
3199
|
-
|
|
3204
|
+
a file and a line, and its message says what to write instead; \`ez check --json\` prints them as
|
|
3205
|
+
[{ file, line, column, rule, severity, message }]. No rule sends an edit to apply: make the change the
|
|
3206
|
+
message names. Errors fail the check; warnings never do.
|
|
3200
3207
|
Warnings become errors only in a platform release on or after ${WARNINGS_UNTIL}, announced here.
|
|
3201
3208
|
|
|
3202
3209
|
Errors:
|
|
@@ -4428,8 +4435,9 @@ Restrictions, each with its replacement:
|
|
|
4428
4435
|
[check] Name an Integration with a string literal. (integration-literal)
|
|
4429
4436
|
[runtime] Row queries return 100 rows by default and 1000 at most: totals come from useLive.count and
|
|
4430
4437
|
aggregates, never from reducing rows.
|
|
4431
|
-
[runtime] A server function or job call:
|
|
4432
|
-
no network but Integrations, no locales (no Intl).
|
|
4438
|
+
[runtime] A server function or job call: 10 seconds, 5 seconds holding the database (ez help functions), 32 MB
|
|
4439
|
+
heap, 1,000 database operations, 256 KB in and out, no network but Integrations, no locales (no Intl).
|
|
4440
|
+
One transaction per call, which runs as if it were alone; each db call from a page is its own.
|
|
4433
4441
|
[runtime] Preview data is production data: every Preview write is real.
|
|
4434
4442
|
[advice] Await every write; key list items by the row's id; use errorMessage(e), never \`e as Error\`;
|
|
4435
4443
|
call hooks at the top of a component. (ez check warns on each: fix warnings too.)
|
|
@@ -4453,7 +4461,7 @@ How to work
|
|
|
4453
4461
|
a component before the page that imports it, a function before its caller. \`ez help recipes\` has
|
|
4454
4462
|
complete examples of the common pieces.
|
|
4455
4463
|
5. \`ez check\` after each change and fix what it reports, errors and warnings, before you say a change is
|
|
4456
|
-
done; \`ez check --json\` gives each problem as data
|
|
4464
|
+
done; \`ez check --json\` gives each problem as data, its message naming the change to make.
|
|
4457
4465
|
\`ez format\` lays out the code in ezship's one style; run it before you push.
|
|
4458
4466
|
6. \`ez preview\` (or \`ez dev\`, which keeps it current) and give the user \`ez link --preview <name>\`;
|
|
4459
4467
|
a successful preview is also a check. Its data is the live data.
|
|
@@ -4503,6 +4511,238 @@ notice danger, badge, table.data, stack, row, muted, ...) come first. [check] CS
|
|
|
4503
4511
|
only through Assets: asset("logo") is the URL of an image an Admin uploaded with \`ez asset add\` (\`ez asset
|
|
4504
4512
|
ls\`). [advice] Move a style={{ ... }} of literals into a class (inline-style warns).`;
|
|
4505
4513
|
|
|
4514
|
+
/**
|
|
4515
|
+
* The code blocks of the help topics, as data (docs/adr/0153): a topic prints `code`, and the Pipeline's
|
|
4516
|
+
* `help.test.ts` checks `before + code + after` as the file `path`, with no warnings, against the starter
|
|
4517
|
+
* Global Workspace and `HELP_SNIPPET_SCHEMA`. Change a block only to code that checks clean.
|
|
4518
|
+
* @type {readonly import("./commands.d.mts").HelpSnippet[]}
|
|
4519
|
+
*/
|
|
4520
|
+
export const HELP_SNIPPETS = Object.freeze([
|
|
4521
|
+
{
|
|
4522
|
+
name: "chart",
|
|
4523
|
+
topic: "data",
|
|
4524
|
+
path: "pages/chart.tsx",
|
|
4525
|
+
before: `import { useLive } from "@ezship/react";
|
|
4526
|
+
import { Bar, BarChart, ResponsiveContainer, Tooltip, XAxis } from "recharts";
|
|
4527
|
+
|
|
4528
|
+
/** Order totals by status. */
|
|
4529
|
+
export default function Chart() {
|
|
4530
|
+
const stats = useLive.aggregate("orders", { group: ["status"], sum: ["amount"] });
|
|
4531
|
+
return (
|
|
4532
|
+
`,
|
|
4533
|
+
code: `<ResponsiveContainer height={240}><BarChart data={stats.rows}>
|
|
4534
|
+
<XAxis dataKey="group.status" /><Tooltip /><Bar dataKey="sum.amount" /></BarChart></ResponsiveContainer>
|
|
4535
|
+
`,
|
|
4536
|
+
after: ` );
|
|
4537
|
+
}
|
|
4538
|
+
`,
|
|
4539
|
+
},
|
|
4540
|
+
{
|
|
4541
|
+
name: "relations",
|
|
4542
|
+
topic: "data",
|
|
4543
|
+
path: "components/Analyses.tsx",
|
|
4544
|
+
before: `import { useLive } from "@ezship/react";
|
|
4545
|
+
|
|
4546
|
+
/** Analyses of received samples, with what each references. */
|
|
4547
|
+
export default function Analyses({ like }: { like: string }) {
|
|
4548
|
+
`,
|
|
4549
|
+
code: `const { rows } = useLive.query("analysis", {
|
|
4550
|
+
where: { "sample_id.status": "received", or: [{ code: { like } }, { ref: { like } }] }, // paths filter before paging
|
|
4551
|
+
include: { sample_id: ["code"], "sample_id.client_id": ["name"], analyst: ["name"], method_instrument: { instrument_id: ["title"] } },
|
|
4552
|
+
order: ["sort_key nulls last"],
|
|
4553
|
+
});
|
|
4554
|
+
`,
|
|
4555
|
+
after: ` return (
|
|
4556
|
+
<ul>
|
|
4557
|
+
{rows.map((row) => (
|
|
4558
|
+
<li key={row.id}>
|
|
4559
|
+
{row.sample?.code} {row.sample?.client?.name} {row.analyst_row?.name}{" "}
|
|
4560
|
+
{row.method_instrument.map((m) => m.instrument?.title).join(", ")}
|
|
4561
|
+
</li>
|
|
4562
|
+
))}
|
|
4563
|
+
</ul>
|
|
4564
|
+
);
|
|
4565
|
+
}
|
|
4566
|
+
`,
|
|
4567
|
+
},
|
|
4568
|
+
{
|
|
4569
|
+
name: "action",
|
|
4570
|
+
topic: "forms",
|
|
4571
|
+
path: "components/HoursDialog.tsx",
|
|
4572
|
+
files: {
|
|
4573
|
+
"functions/saveHours.ts": `import { serverFunction, z } from "@ezship/react/server";
|
|
4574
|
+
|
|
4575
|
+
/** Records the hours worked on an item. */
|
|
4576
|
+
export default serverFunction(
|
|
4577
|
+
z.object({ itemId: z.string(), hours: z.number() }),
|
|
4578
|
+
async ({ db }, input) => {
|
|
4579
|
+
await db.update("items", input.itemId, { hours: input.hours });
|
|
4580
|
+
},
|
|
4581
|
+
);
|
|
4582
|
+
`,
|
|
4583
|
+
},
|
|
4584
|
+
before: `import { startTransition, useActionState, useState } from "react";
|
|
4585
|
+
import { attempt } from "@ezship/react";
|
|
4586
|
+
import saveHours from "../functions/saveHours";
|
|
4587
|
+
|
|
4588
|
+
/** A dialog's body that saves the hours worked on an item. */
|
|
4589
|
+
export default function HoursDialog({
|
|
4590
|
+
item,
|
|
4591
|
+
onClose,
|
|
4592
|
+
}: {
|
|
4593
|
+
item: { id: string };
|
|
4594
|
+
onClose: () => void;
|
|
4595
|
+
}) {
|
|
4596
|
+
`,
|
|
4597
|
+
code: `const [hours, setHours] = useState("");
|
|
4598
|
+
const [error, save, saving] = useActionState(attempt(async () => {
|
|
4599
|
+
const h = parseFloat(hours);
|
|
4600
|
+
if (isNaN(h) || h < 0) throw new Error("Enter a valid number of hours.");
|
|
4601
|
+
await saveHours({ itemId: item.id, hours: h }); // or db.update(...); a failure becomes the error
|
|
4602
|
+
onClose();
|
|
4603
|
+
}), null);
|
|
4604
|
+
return (
|
|
4605
|
+
<>
|
|
4606
|
+
{error ? <div className="notice danger">{error}</div> : null}
|
|
4607
|
+
<input value={hours} onChange={(e) => setHours(e.target.value)} />
|
|
4608
|
+
<button type="button" disabled={saving} onClick={() => startTransition(save)}>Save</button>
|
|
4609
|
+
</>
|
|
4610
|
+
);
|
|
4611
|
+
`,
|
|
4612
|
+
after: `}
|
|
4613
|
+
`,
|
|
4614
|
+
},
|
|
4615
|
+
{
|
|
4616
|
+
name: "session",
|
|
4617
|
+
topic: "frame",
|
|
4618
|
+
tree: "global",
|
|
4619
|
+
path: "session.ts",
|
|
4620
|
+
code: `import type { DateString } from "@ezship/react";
|
|
4621
|
+
import type { Company } from "global/db/types";
|
|
4622
|
+
export type Provided = { company: Company; roles: string[]; isAdmin: boolean }; // what the Shell provides
|
|
4623
|
+
export type Saved = { activeCompanyId: string | null; favorites: string[] }; // kept across sign-outs and devices
|
|
4624
|
+
export type SignedIn = { range: { from: DateString; to: DateString } | null }; // cleared when the viewer signs out
|
|
4625
|
+
export const defaults: Saved & SignedIn = { activeCompanyId: null, favorites: [], range: null };
|
|
4626
|
+
`,
|
|
4627
|
+
},
|
|
4628
|
+
{
|
|
4629
|
+
name: "hook",
|
|
4630
|
+
topic: "frame",
|
|
4631
|
+
path: "hooks/useOpenOrders.ts",
|
|
4632
|
+
before: `/** A customer's open orders and their total. */
|
|
4633
|
+
`,
|
|
4634
|
+
code: `import { useLive } from "@ezship/react";
|
|
4635
|
+
export default function useOpenOrders(customerId: string) {
|
|
4636
|
+
const orders = useLive("orders", { where: { customer_id: customerId, status: "open" } });
|
|
4637
|
+
const total = useLive.aggregate("orders", { where: { customer_id: customerId, status: "open" }, sum: ["amount"] });
|
|
4638
|
+
return { orders, total: total.rows[0]?.sum.amount ?? 0 };
|
|
4639
|
+
}
|
|
4640
|
+
`,
|
|
4641
|
+
},
|
|
4642
|
+
{
|
|
4643
|
+
name: "function",
|
|
4644
|
+
topic: "functions",
|
|
4645
|
+
path: "functions/save.ts",
|
|
4646
|
+
before: `/** Saves a new order. */
|
|
4647
|
+
`,
|
|
4648
|
+
code: `import { serverFunction, z } from "@ezship/react/server";
|
|
4649
|
+
export default serverFunction(z.object({ title: z.string().min(1) }), async ({ db }, input) => {
|
|
4650
|
+
return db.insert("orders", input);
|
|
4651
|
+
});
|
|
4652
|
+
`,
|
|
4653
|
+
},
|
|
4654
|
+
{
|
|
4655
|
+
name: "many-rows",
|
|
4656
|
+
topic: "functions",
|
|
4657
|
+
path: "functions/syncPage.ts",
|
|
4658
|
+
before: `import { serverFunction, z } from "@ezship/react/server";
|
|
4659
|
+
|
|
4660
|
+
/** Marks one page of items synced and says whether more remain. */
|
|
4661
|
+
export default serverFunction(z.object({}), async ({ db }) => {
|
|
4662
|
+
`,
|
|
4663
|
+
code: `const { more } = await db.updateMany("items", { where: { synced: 0 }, limit: 100 }, { synced: 1 });
|
|
4664
|
+
return { more };
|
|
4665
|
+
`,
|
|
4666
|
+
after: `});
|
|
4667
|
+
`,
|
|
4668
|
+
},
|
|
4669
|
+
{
|
|
4670
|
+
name: "timed-loop",
|
|
4671
|
+
topic: "functions",
|
|
4672
|
+
path: "functions/syncSome.ts",
|
|
4673
|
+
before: `import { serverFunction, z } from "@ezship/react/server";
|
|
4674
|
+
|
|
4675
|
+
/** Marks items synced one by one for as long as the call has time. */
|
|
4676
|
+
export default serverFunction(z.object({}), async ({ db }) => {
|
|
4677
|
+
`,
|
|
4678
|
+
code: `const from = Date.now(); // in code that calls an integration, take it just before the first write
|
|
4679
|
+
const rows = await db.list("items", { where: { synced: 0 }, limit: 900 });
|
|
4680
|
+
for (const row of rows) {
|
|
4681
|
+
if (Date.now() - from > 4000) break;
|
|
4682
|
+
await db.update("items", row.id, { synced: 1 });
|
|
4683
|
+
}
|
|
4684
|
+
`,
|
|
4685
|
+
after: `});
|
|
4686
|
+
`,
|
|
4687
|
+
},
|
|
4688
|
+
{
|
|
4689
|
+
name: "lib",
|
|
4690
|
+
topic: "functions",
|
|
4691
|
+
tree: "global",
|
|
4692
|
+
path: "lib/accounting.ts",
|
|
4693
|
+
before: `/** Guards the accounting periods share. */
|
|
4694
|
+
`,
|
|
4695
|
+
code: `import type { Database } from "@ezship/react/server";
|
|
4696
|
+
export async function periodGuard(db: Database, date: string) {
|
|
4697
|
+
const [closed] = await db.list("accounting_periods", { where: { closed: 1, ends_on: { gte: date } }, limit: 1 });
|
|
4698
|
+
if (closed) throw new Error(\`The period ending \${closed.ends_on} is closed.\`);
|
|
4699
|
+
}
|
|
4700
|
+
`,
|
|
4701
|
+
},
|
|
4702
|
+
]);
|
|
4703
|
+
|
|
4704
|
+
/** The Tables `HELP_SNIPPETS` are checked against; no topic prints it. */
|
|
4705
|
+
export const HELP_SNIPPET_SCHEMA = `CREATE TABLE companies (name TEXT);
|
|
4706
|
+
CREATE TABLE orders (
|
|
4707
|
+
title TEXT,
|
|
4708
|
+
customer_id TEXT,
|
|
4709
|
+
status TEXT CHECK (status IN ('open', 'shipped', 'paid')),
|
|
4710
|
+
amount MONEY
|
|
4711
|
+
);
|
|
4712
|
+
CREATE TABLE items (title TEXT, hours REAL, synced INTEGER);
|
|
4713
|
+
CREATE TABLE accounting_periods (ends_on DATE, closed INTEGER);
|
|
4714
|
+
CREATE TABLE client (name TEXT);
|
|
4715
|
+
CREATE TABLE sample (
|
|
4716
|
+
code TEXT,
|
|
4717
|
+
status TEXT CHECK (status IN ('due', 'received')),
|
|
4718
|
+
client_id REFERENCES client
|
|
4719
|
+
);
|
|
4720
|
+
CREATE TABLE instrument (title TEXT);
|
|
4721
|
+
CREATE TABLE analysis (
|
|
4722
|
+
code TEXT,
|
|
4723
|
+
ref TEXT,
|
|
4724
|
+
sort_key INTEGER,
|
|
4725
|
+
sample_id REFERENCES sample,
|
|
4726
|
+
analyst MEMBER
|
|
4727
|
+
);
|
|
4728
|
+
CREATE TABLE method_instrument (
|
|
4729
|
+
analysis_id REFERENCES analysis,
|
|
4730
|
+
instrument_id REFERENCES instrument
|
|
4731
|
+
);
|
|
4732
|
+
CREATE INDEX ON method_instrument (analysis_id);
|
|
4733
|
+
`;
|
|
4734
|
+
|
|
4735
|
+
/** A topic's block as it prints: `HELP_SNIPPETS`' code, indented under the sentence that introduces it. @param {string} name */
|
|
4736
|
+
function snippet(name) {
|
|
4737
|
+
const found = HELP_SNIPPETS.find((s) => s.name === name);
|
|
4738
|
+
if (!found) throw new Error(`No help snippet "${name}"`);
|
|
4739
|
+
return found.code
|
|
4740
|
+
.trimEnd()
|
|
4741
|
+
.split("\n")
|
|
4742
|
+
.map((l) => ` ${l}`)
|
|
4743
|
+
.join("\n");
|
|
4744
|
+
}
|
|
4745
|
+
|
|
4506
4746
|
/** `ez help data`: reading and writing the App Database from pages. */
|
|
4507
4747
|
const DATA_TOPIC = `Data: reading and writing the App Database from pages, components and hooks (all from @ezship/react).
|
|
4508
4748
|
Tables belong to the Instance: every Site shares them. Declare them in global/db/schema.sql (\`ez help db\`);
|
|
@@ -4512,8 +4752,8 @@ types come from \`import type { Order } from "global/db/types"\`, and rows are R
|
|
|
4512
4752
|
useLive.query(table, query) / db.query(table, query) -> { rows, truncated } (live queries add loading)
|
|
4513
4753
|
useLive.count("orders", { where: { status: "shipped" } }) -> the complete count, undefined while loading
|
|
4514
4754
|
useLive.aggregate("orders", { group: ["status"], sum: ["amount"] }) -> { rows: [{ group, count, sum }], truncated, loading, version }
|
|
4515
|
-
|
|
4516
|
-
|
|
4755
|
+
Charts are recharts (ADR 0114), fed an aggregate's rows (stats = the useLive.aggregate above):
|
|
4756
|
+
${snippet("chart")}
|
|
4517
4757
|
db.list(table, query) / db.get(table, id) / db.count(table, { where }) / db.aggregate(table, query) -> one-shot, in event handlers
|
|
4518
4758
|
db.insert("orders", { customer, status: "new" }); db.update("orders", id, { status: "ready" }); db.delete("orders", id)
|
|
4519
4759
|
db.update("orders", id, { status: "paid" }, { why: "Invoice paid by card" }) -> the reason lands in that write's History row
|
|
@@ -4526,18 +4766,19 @@ types come from \`import type { Order } from "global/db/types"\`, and rows are R
|
|
|
4526
4766
|
toCents("1,234.50"), toCents(12.5), fromCents(cents) -> MONEY values (whole cents; null when unreadable)
|
|
4527
4767
|
where: { col: value } is equality ({ col: null } is IS NULL); { col: { gte: 2 } } uses eq ne lt lte gt gte in
|
|
4528
4768
|
nin like null has; or: [{ ... }, { ... }]; and: [{ or: [...] }, { or: [...] }] for several ors. { in: [] }
|
|
4529
|
-
matches nothing. ne
|
|
4769
|
+
matches nothing. [check] ne is typed only for a column no row leaves empty (id, created_at): anywhere else it
|
|
4770
|
+
would also drop the NULL rows, so say which you mean: { nin: [x] } keeps them, { nin: [x], null: false }
|
|
4771
|
+
drops them (types, ne-nullable).
|
|
4772
|
+
[runtime] like matches the whole value: % is any run of characters and _ is one, and it ignores case for ASCII
|
|
4773
|
+
letters only (A and a match; É and é do not).
|
|
4530
4774
|
[runtime] Row queries default to 100 rows and cap at 1000. [check, warning] Never compute a total or count
|
|
4531
4775
|
from rows, by reduce or by a loop (reduce-rows): use count and aggregate, which are complete. Never search,
|
|
4532
4776
|
filter or page loaded rows by what the user typed or picked (filter-rows): put it in where and limit/offset,
|
|
4533
4777
|
and show useLive.query's truncated. Aggregate filters apply before grouping; limit/offset page the groups,
|
|
4534
4778
|
which can be truncated too. Ungrouped empty input counts zero.
|
|
4535
4779
|
Relations (ADR 0102): [advice] never join in the browser or build id maps; one query follows REFERENCES.
|
|
4536
|
-
|
|
4537
|
-
|
|
4538
|
-
include: { sample_id: ["code"], "sample_id.client_id": ["name"], analyst: ["name"], method_instrument: { instrument_id: ["title"] } },
|
|
4539
|
-
order: ["sort_key nulls last"],
|
|
4540
|
-
}) -> row.sample?.code, row.sample?.client?.name, row.analyst_row?.name (an actor), row.method_instrument[i].instrument?.title
|
|
4780
|
+
${snippet("relations")}
|
|
4781
|
+
-> row.sample?.code, row.sample?.client?.name, row.analyst_row?.name (an actor), row.method_instrument[i].instrument?.title
|
|
4541
4782
|
A <name>_id include lands on row.<name>, <name>_ids (an id list) on row.<name> as an array, any other column c
|
|
4542
4783
|
on row.c_row; a child Table on row.<child> (up to 100, oldest first; truncatedChildren says more exist; its
|
|
4543
4784
|
column needs an index). Unreadable rows are null or left out. { ids: { has: id } } tests an id list.
|
|
@@ -4573,17 +4814,7 @@ the error state and the try/catch/finally around the write. attempt() makes the
|
|
|
4573
4814
|
show: null on success, otherwise errorMessage of what it threw (a failed check, a refused write, a server
|
|
4574
4815
|
function's rejection). The dialog stays open with the message; the action closes it on success. Keep the
|
|
4575
4816
|
fields in useState and read them in the action; server functions take their typed input, never FormData.
|
|
4576
|
-
|
|
4577
|
-
const [error, save, saving] = useActionState(attempt(async () => {
|
|
4578
|
-
const h = parseFloat(hours);
|
|
4579
|
-
if (isNaN(h) || h < 0) throw new Error("Enter a valid number of hours.");
|
|
4580
|
-
await saveHours({ itemId: item.id, hours: h }); // or db.update(...); a failure becomes the error
|
|
4581
|
-
onClose();
|
|
4582
|
-
}), null);
|
|
4583
|
-
...
|
|
4584
|
-
{error ? <div className="notice danger">{error}</div> : null}
|
|
4585
|
-
<input value={hours} onChange={(e) => setHours(e.target.value)} />
|
|
4586
|
-
<button type="button" disabled={saving} onClick={() => startTransition(save)}>Save</button>
|
|
4817
|
+
${snippet("action")}
|
|
4587
4818
|
Dispatch the action from onClick={() => startTransition(save)} (both from react), or from a form: <form
|
|
4588
4819
|
id="hours" action={save} noValidate> around the fields and a Save button with form="hours" (it may sit in a
|
|
4589
4820
|
footer outside the form). A form submits on Enter, but every <button> inside it without type="button" submits
|
|
@@ -4605,12 +4836,7 @@ Pick by what the value is:
|
|
|
4605
4836
|
[advice] Never pass the frame's values down as props; read useProvided() where they are needed.
|
|
4606
4837
|
global/session.ts declares them (all four exports; each type may be {}; Admins push it, and it takes effect at
|
|
4607
4838
|
once for every Site, ez help lifecycle):
|
|
4608
|
-
|
|
4609
|
-
import type { Company } from "global/db/types";
|
|
4610
|
-
export type Provided = { company: Company; roles: string[]; isAdmin: boolean }; // what the Shell provides
|
|
4611
|
-
export type Saved = { activeCompanyId: string | null; favorites: string[] }; // kept across sign-outs and devices
|
|
4612
|
-
export type SignedIn = { range: { from: DateString; to: DateString } | null }; // cleared when the viewer signs out
|
|
4613
|
-
export const defaults: Saved & SignedIn = { activeCompanyId: null, favorites: [], range: null };
|
|
4839
|
+
${snippet("session")}
|
|
4614
4840
|
[check] Saved and SignedIn are written like a JSON TYPE (string, number, boolean, null, DateString, EpochMs,
|
|
4615
4841
|
literals, { ... }, T[], Record<string, T>; no named types), every key camelCase and required (session-shape).
|
|
4616
4842
|
[runtime] The Host checks every write against them; a value is at most 4 KB of JSON, 32 keys per Instance.
|
|
@@ -4635,12 +4861,7 @@ Custom hooks (ADR 0091): when a second page or component needs the same live que
|
|
|
4635
4861
|
values, move them into \`hooks/use<Name>.ts\` (or \`global/hooks/use<Name>.ts\` when several Sites share it,
|
|
4636
4862
|
imported as "global/hooks/use<Name>") rather than copying them. A hook has a component's imports and rules,
|
|
4637
4863
|
calls hooks at its top level and returns values, never markup:
|
|
4638
|
-
|
|
4639
|
-
export default function useOpenOrders(customerId: string) {
|
|
4640
|
-
const orders = useLive("orders", { where: { customer_id: customerId, status: "open" } });
|
|
4641
|
-
const total = useLive.aggregate("orders", { where: { customer_id: customerId, status: "open" }, sum: ["amount"] });
|
|
4642
|
-
return { orders, total: total.rows[0]?.sum.amount ?? 0 };
|
|
4643
|
-
}
|
|
4864
|
+
${snippet("hook")}
|
|
4644
4865
|
[check, warning] Call hooks at the top of a component, never in a loop, a callback or a condition (react-hooks/rules-of-hooks, hooks-order).
|
|
4645
4866
|
A hook is for React state and live data; logic that needs neither belongs in global/lib (ez help functions).
|
|
4646
4867
|
The Shell and navigation: App.tsx renders the Site's links once in <Nav>{links}</Nav>; the global Shell draws
|
|
@@ -4654,10 +4875,7 @@ signIn() and signOut() are their own imports, not fields of useAuth().`;
|
|
|
4654
4875
|
/** `ez help functions`: server functions, useCall and Global lib modules (ADRs 0041, 0077). */
|
|
4655
4876
|
const FUNCTIONS_TOPIC = `Server functions, useCall and shared logic.
|
|
4656
4877
|
Server functions belong to this Site's Version and deploy with its UI. In functions/save.ts:
|
|
4657
|
-
|
|
4658
|
-
export default serverFunction(z.object({ title: z.string().min(1) }), async ({ db }, input) => {
|
|
4659
|
-
return db.insert("orders", input);
|
|
4660
|
-
});
|
|
4878
|
+
${snippet("function")}
|
|
4661
4879
|
UI imports ./functions/save (../functions/save from a page or component) and calls save({ title }) from an
|
|
4662
4880
|
event handler or an action, or useCall(summary, { from, to }) -> { result, loading, error, refresh } to run
|
|
4663
4881
|
one when the page opens. useCall takes any async function of its input, so a report too big for a function's
|
|
@@ -4665,15 +4883,52 @@ limits can load from the page: useCall(({ companyId }) => computeAging(db, compa
|
|
|
4665
4883
|
computeAging a global/lib function given the page's db; its db calls are separate requests under the same
|
|
4666
4884
|
access rules, so prefer aggregates to loops. Neither form is live: refresh() reloads it.
|
|
4667
4885
|
The handler's context: { db, user, session, documents, integration, members } (ez help integrations, access,
|
|
4668
|
-
documents). The db has the caller's access rules and list/query/aggregate/count/get/insert/update/delete
|
|
4669
|
-
typed; user is the validated caller.
|
|
4886
|
+
documents). The db has the caller's access rules and list/query/aggregate/count/get/insert/update/delete and
|
|
4887
|
+
insertMany/updateMany/deleteMany (below), typed; user is the validated caller.
|
|
4670
4888
|
[runtime] Each call is one transaction: all writes and History commit together or all roll back, so never wrap
|
|
4671
4889
|
a handler's body in db.transaction (redundant-transaction warns); one inside a try still fails the call when
|
|
4672
4890
|
its failure is caught. A repeated unique key rolls the call back: check before you insert. Await database calls.
|
|
4673
|
-
[runtime]
|
|
4674
|
-
|
|
4891
|
+
[runtime] A call runs as if it were alone: no other write lands between what it reads and what it writes, so a
|
|
4892
|
+
check then a write holds, and a value read and written back never loses an update. To keep this the Host may run
|
|
4893
|
+
a call twice; the first run leaves nothing and the caller gets one answer. Code that calls an integration has
|
|
4894
|
+
this only from its first write or inside db.transaction (ez help integrations). A page has none of it across
|
|
4895
|
+
calls: each db call from a page is its own transaction, so a check that must hold when the write lands belongs in
|
|
4896
|
+
a function, a Table rule or a workflow action, which run inside the write.
|
|
4897
|
+
[runtime] Limits per call: 10-second deadline, 5-second database deadline (below), 32-MB JS heap, 1,000 database
|
|
4898
|
+
operations, 256-KB JSON input and output. No files, network (but Integrations), packages, timers
|
|
4675
4899
|
or locales: there is no Intl, and toLocale*String and localeCompare ignore locales and time zones, so return
|
|
4676
4900
|
numbers and ISO dates and format in the page (server-locale warns). A stale browser call asks for a reload.
|
|
4901
|
+
[runtime] The database deadline is usually the first limit a call meets. From its first database operation
|
|
4902
|
+
until it returns, reads, computation and the commit included, a call has 5 seconds, and one database step 2 seconds;
|
|
4903
|
+
past either, the whole call rolls back ("Function database deadline exceeded"). Code that calls an integration
|
|
4904
|
+
counts from its first write instead (ez help integrations). So does a call the Host has not yet seen write, so
|
|
4905
|
+
a function can pass once and fail the next time: plan for the first operation. A write takes from about 1 ms on
|
|
4906
|
+
an idle Host to 15 ms or more, by its Table and the Host's load, so the 1,000 operations may not fit: plan on 250
|
|
4907
|
+
writes per call. (fn-op-budget warns on a write loop that is unbounded or may run more than 250 times.) Other
|
|
4908
|
+
writes wait while a call holds the database, so keep what people wait on short.
|
|
4909
|
+
[runtime] On a Host that several Instances share, an Instance's calls share 1 second of execution and 250 ms of
|
|
4910
|
+
database time a second, with bursts of 60 s and 20 s; past either, a call is refused with 429 and Retry-After. A
|
|
4911
|
+
Host with one customer has no such budget; code that must run on both retries a 429.
|
|
4912
|
+
[runtime] Many rows at once, in server code only (not a page, a Table rule or a lib module's Database):
|
|
4913
|
+
db.insertMany(table, rows, { why, action }) writes up to 1,000 rows and answers { count, ids };
|
|
4914
|
+
db.updateMany(table, { where, limit }, patch, { why }) and db.deleteMany(table, { where, limit }, { why }) take up
|
|
4915
|
+
to limit rows (1,000 at most and by default) in id order and answer { count, more }, where more says where matched
|
|
4916
|
+
others. Each is one database operation and means exactly that many single writes: access rules, defaults, Table
|
|
4917
|
+
rules, workflows (the status column is refused as in an update), unique keys and a History row each. A refusal
|
|
4918
|
+
rolls the call back, so none of its rows stand: that includes a row where matches that the caller may read but not
|
|
4919
|
+
write (403, naming the row), so narrow where to rows it may write. The 256-KB limit holds for what you pass.
|
|
4920
|
+
[advice] Move bulk work in pages, one per call, and let the next call continue while more is true:
|
|
4921
|
+
${snippet("many-rows")}
|
|
4922
|
+
Page by a condition the write changes: a patch that leaves where true matches the same rows again. The database
|
|
4923
|
+
deadline still holds for the whole operation, and past it the call rolls back: 1,000 rows take about half a second
|
|
4924
|
+
on an idle Host, or about 2.5 seconds on a Table with rules, and longer on a busy one, so on a Table with rules
|
|
4925
|
+
choose a limit well inside 1,000.
|
|
4926
|
+
[advice] To adapt to a busy Host, write row by row and stop by time with Date.now(): it is the Host's clock and
|
|
4927
|
+
keeps moving while a call waits. Stop at about 4 seconds, which leaves room for the last write and the commit, and
|
|
4928
|
+
stay under the 1,000 operations too, since a fast Host reaches them first (fn-op-budget allows up to 900 items in a
|
|
4929
|
+
loop that reads Date.now()):
|
|
4930
|
+
${snippet("timed-loop")}
|
|
4931
|
+
What it wrote commits when the handler returns; the next call picks up the rest.
|
|
4677
4932
|
[check] Each function file is one default serverFunction(...) call; keep private helpers inside that file, or in
|
|
4678
4933
|
a global/lib module once a second file needs them. Options are literals: serverFunction(input, handler,
|
|
4679
4934
|
{ access: "group(payroll)", authority: "site" }) (ez help access); { api: true } also lets an API Key call it
|
|
@@ -4687,11 +4942,7 @@ workflows import them by name (\`import { periodGuard } from "global/lib/account
|
|
|
4687
4942
|
the Site rules (no packages, network, timers, storage, DOM or classes). It runs in server functions too, so
|
|
4688
4943
|
format for display in pages, not in lib. Whatever reads or writes takes the database as its first argument,
|
|
4689
4944
|
typed \`Database\` (\`Row\`, \`Query\`, \`TableName\` and the other data types come from the same module):
|
|
4690
|
-
|
|
4691
|
-
export async function periodGuard(db: Database, date: string) {
|
|
4692
|
-
const [closed] = await db.list("accounting_periods", { where: { closed: 1, ends_on: { gte: date } }, limit: 1 });
|
|
4693
|
-
if (closed) throw new Error(\`The period ending \${closed.ends_on} is closed.\`);
|
|
4694
|
-
}
|
|
4945
|
+
${snippet("lib")}
|
|
4695
4946
|
A page passes \`db\` from @ezship/react, a server function its \`db\`, so one guard runs in both and, inside a
|
|
4696
4947
|
function, in its transaction. [advice] Move code to lib when a second file needs it rather than copying it.
|
|
4697
4948
|
\`ez global check\` checks lib against every Site; a Site's \`ez check\` and \`ez preview\` use the lib in your
|
|
@@ -4723,6 +4974,9 @@ takes the writer at once (no integration call inside or after it). A rollback ne
|
|
|
4723
4974
|
the service an idempotency key where it takes one, and remember a timed-out POST may have happened.
|
|
4724
4975
|
[runtime] Per call: 5 requests, each within the integration's timeout (default 10 s, at most 30), 60 s in all,
|
|
4725
4976
|
256 KB each way, no redirects followed.
|
|
4977
|
+
[runtime] While a service answers, the call's 10-second deadline pauses and it holds no database, so neither its
|
|
4978
|
+
requests nor its reads before the first write count toward the 5-second database deadline (ez help functions).
|
|
4979
|
+
That deadline starts at the first write or db.transaction: the writes and whatever follows them must fit in it.
|
|
4726
4980
|
An Admin can also give a binding values (\`ez integration value stripe --header Stripe-Version 2024-06-20\`,
|
|
4727
4981
|
or \`--secret\` for a second key, read like the credential): headers and parameters the Host adds to every
|
|
4728
4982
|
request. [runtime] Code cannot set or override a header or parameter the binding sets. Values belong on the
|
|
@@ -4753,8 +5007,11 @@ logic it shares with a Site goes in global/lib and its constants in global/const
|
|
|
4753
5007
|
[runtime] \`ez global push\` activates the schedules and the jobs at once ("Takes effect now"); only Admins
|
|
4754
5008
|
change schedules.json. Previews never run them. A job sees the Tables and columns a Preview or Deploy has
|
|
4755
5009
|
created: push alone creates none. Each due time runs at most once; after the Host was down, only the latest
|
|
4756
|
-
missed time runs. One run has a function's
|
|
4757
|
-
|
|
5010
|
+
missed time runs. One run has a function's limits, the 5-second database deadline included (ez help functions),
|
|
5011
|
+
and a run past one rolls back whole and is not retried: a long job is several short runs, each writing a bounded
|
|
5012
|
+
batch the next continues from, with updateMany's limit and more (ez help functions) or a Date.now() bound; take
|
|
5013
|
+
what it stores or keys on from run.due.
|
|
5014
|
+
\`ez schedule list\` shows each schedule's next due time and last run, \`ez schedule runs <name>\` its recent runs and errors,
|
|
4758
5015
|
and \`ez schedule run <name>\` runs it now (writes are real). \`ez schedule pause <name>\` stops its due times
|
|
4759
5016
|
with no push; \`ez schedule resume <name>\` starts them again from now, skipping the times missed while paused.
|
|
4760
5017
|
Listeners receive webhooks: other services post events to the Site, verified with the secret the service
|
|
@@ -5307,7 +5564,8 @@ ${RECIPES.map(recipeText).join("\n\n")}`;
|
|
|
5307
5564
|
const accessTopic =
|
|
5308
5565
|
() => `Access: who opens a Site, who reads and writes which rows, who runs which code.
|
|
5309
5566
|
Every Site and Preview requires a signed-in active Member; Builders are Members too. An Admin may restrict a
|
|
5310
|
-
Site to allow-lists and groups (\`ez site access\`)
|
|
5567
|
+
Site to allow-lists and groups (\`ez site access\`); the Admin who restricts it stays on its lists, so
|
|
5568
|
+
\`ez site access restrict\` alone makes an app theirs only. Sign-in is the platform's: never build a login page.
|
|
5311
5569
|
Rows: global/db/access.sql is the one place that says who reads and writes which rows. [runtime] The Host
|
|
5312
5570
|
applies it to every page, function, job and attachment request, for deployed Sites and Previews alike, from
|
|
5313
5571
|
the moment an Admin pushes it (ez help lifecycle); a row a Member may not read is "Not found".
|
|
@@ -5530,7 +5788,7 @@ export const COMMANDS = [
|
|
|
5530
5788
|
},
|
|
5531
5789
|
{
|
|
5532
5790
|
usage: "ez check [--json]",
|
|
5533
|
-
help: "the rules, the types and a build dry run on the host, without serving anything; errors fail it, warnings do not (`ez help rules`); --json prints [{ file, line, column, rule, severity, message
|
|
5791
|
+
help: "the rules, the types and a build dry run on the host, without serving anything; errors fail it, warnings do not (`ez help rules`); --json prints [{ file, line, column, rule, severity, message }]; run it before you say a change is done (a successful ez preview is also a check)",
|
|
5534
5792
|
},
|
|
5535
5793
|
{
|
|
5536
5794
|
usage: "ez format [--check]",
|
|
@@ -5591,7 +5849,7 @@ export const COMMANDS = [
|
|
|
5591
5849
|
},
|
|
5592
5850
|
{
|
|
5593
5851
|
usage: "ez site access restrict|open",
|
|
5594
|
-
help: "admins: switch between the allow-lists and everyone in the instance",
|
|
5852
|
+
help: "admins: switch between the allow-lists and everyone in the instance; whoever restricts a site stays on its lists",
|
|
5595
5853
|
},
|
|
5596
5854
|
{
|
|
5597
5855
|
usage: "ez site access add|remove|rm builder|user <who>",
|
package/editor-types.json.gz
CHANGED
|
Binary file
|
package/ez.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// Instance-connected terminal adapter (ADR 0026). The shared command contract lives in commands.mjs.
|
|
3
3
|
import { localFetch } from "./local-fetch.mjs";
|
|
4
|
-
import { checkForUpdate
|
|
4
|
+
import { checkForUpdate } from "./update-check.mjs";
|
|
5
5
|
import { editorExports, ensureEditor } from "./editor.mjs";
|
|
6
6
|
import {
|
|
7
7
|
adoptBinding,
|
|
@@ -1276,7 +1276,7 @@ async function updateCheck() {
|
|
|
1276
1276
|
const pkg = JSON.parse(await readFile(new URL("./package.json", import.meta.url), "utf8"));
|
|
1277
1277
|
return await checkForUpdate({
|
|
1278
1278
|
current: pkg.version,
|
|
1279
|
-
name:
|
|
1279
|
+
name: pkg.name,
|
|
1280
1280
|
file: join(CRED_DIR, "update-check.json"),
|
|
1281
1281
|
env: process.env,
|
|
1282
1282
|
fetch: globalThis.fetch,
|
package/package.json
CHANGED
package/schema.d.mts
CHANGED
|
@@ -85,6 +85,14 @@ export const DATABASE_OPERATIONS: Readonly<
|
|
|
85
85
|
>;
|
|
86
86
|
/** One of `DATABASE_OPERATIONS`: a method every `db` has, in a page and on the Host. */
|
|
87
87
|
export type DatabaseOperation = keyof typeof DATABASE_OPERATIONS;
|
|
88
|
+
/** What server code's `db` has beyond `DATABASE_OPERATIONS` (docs/adr/0104), with the argument counts it accepts. */
|
|
89
|
+
export const SERVER_DATABASE_OPERATIONS: Readonly<
|
|
90
|
+
Record<"insertMany" | "updateMany" | "deleteMany", readonly number[]>
|
|
91
|
+
>;
|
|
92
|
+
/** One of `SERVER_DATABASE_OPERATIONS`: many rows in one database operation. */
|
|
93
|
+
export type ServerDatabaseOperation = keyof typeof SERVER_DATABASE_OPERATIONS;
|
|
94
|
+
/** The most rows one many-row operation writes (docs/adr/0104). */
|
|
95
|
+
export const MANY_ROWS: 1000;
|
|
88
96
|
/** The longest Push message and write reason (docs/adr/0093), in characters. */
|
|
89
97
|
export const MAX_MESSAGE_CHARS: 500;
|
|
90
98
|
/** A Push message or write reason as stored: trimmed, null when absent or blank. */
|
package/schema.mjs
CHANGED
|
@@ -39,6 +39,24 @@ export const DATABASE_OPERATIONS = Object.freeze({
|
|
|
39
39
|
// A workflow action on a row (docs/adr/0103): table, id, action, then an optional patch and options.
|
|
40
40
|
transition: Object.freeze([3, 4, 5]),
|
|
41
41
|
});
|
|
42
|
+
/**
|
|
43
|
+
* What server code's `db` has beyond `DATABASE_OPERATIONS` (docs/adr/0104), with the argument counts the Host
|
|
44
|
+
* accepts: many rows in one database operation. Never a page's, a Table rule's or the `Database` a lib module takes.
|
|
45
|
+
* @type {typeof import("./schema.d.mts").SERVER_DATABASE_OPERATIONS}
|
|
46
|
+
*/
|
|
47
|
+
export const SERVER_DATABASE_OPERATIONS = Object.freeze({
|
|
48
|
+
// table, rows, then optional options
|
|
49
|
+
insertMany: Object.freeze([2, 3]),
|
|
50
|
+
// table, { where, limit? }, patch, then optional options
|
|
51
|
+
updateMany: Object.freeze([3, 4]),
|
|
52
|
+
// table, { where, limit? }, then optional options
|
|
53
|
+
deleteMany: Object.freeze([2, 3]),
|
|
54
|
+
});
|
|
55
|
+
/**
|
|
56
|
+
* The most rows one many-row operation writes (docs/adr/0104).
|
|
57
|
+
* @type {typeof import("./schema.d.mts").MANY_ROWS}
|
|
58
|
+
*/
|
|
59
|
+
export const MANY_ROWS = 1000;
|
|
42
60
|
/**
|
|
43
61
|
* The longest Push message and write reason (docs/adr/0093), in characters.
|
|
44
62
|
* @type {typeof import("./schema.d.mts").MAX_MESSAGE_CHARS}
|
|
@@ -1461,7 +1479,8 @@ export function planSchema(schema, mine, instance, siteId) {
|
|
|
1461
1479
|
/**
|
|
1462
1480
|
* The unique indexes a Declaration adds to Tables that already exist (docs/adr/0046): the ones whose rows the
|
|
1463
1481
|
* platform checks for duplicates before a Push, a Preview or a Deploy. Sequence columns count, since each
|
|
1464
|
-
* carries a unique index.
|
|
1482
|
+
* carries a unique index. An index over a column not stored yet is left out: the column will hold NULL on every
|
|
1483
|
+
* row, NULLs are distinct, and there is nothing to read it from until the artifact batch adds it.
|
|
1465
1484
|
* @type {typeof import("./schema.d.mts").newUniqueIndexes}
|
|
1466
1485
|
*/
|
|
1467
1486
|
export function newUniqueIndexes(live, decl) {
|
|
@@ -1470,8 +1489,12 @@ export function newUniqueIndexes(live, decl) {
|
|
|
1470
1489
|
const existing = live.tables[table];
|
|
1471
1490
|
if (!existing) continue;
|
|
1472
1491
|
const have = new Set((existing.unique ?? []).map(indexKey));
|
|
1473
|
-
for (const columns of [...(def.unique ?? []), ...sequenceColumns(def).map((c) => [c])])
|
|
1474
|
-
if (
|
|
1492
|
+
for (const columns of [...(def.unique ?? []), ...sequenceColumns(def).map((c) => [c])]) {
|
|
1493
|
+
if (have.has(indexKey(columns))) continue;
|
|
1494
|
+
// A live Table's `columns` omit the system columns, which every Table stores.
|
|
1495
|
+
if (columns.every((c) => c in existing.columns || SYSTEM_COLUMNS.includes(c)))
|
|
1496
|
+
out.push({ table, columns });
|
|
1497
|
+
}
|
|
1475
1498
|
}
|
|
1476
1499
|
return out;
|
|
1477
1500
|
}
|
|
@@ -2514,6 +2537,8 @@ owner), and a my() Table must be WRITE BY functions, BY none or WHERE group(...)
|
|
|
2514
2537
|
themselves rows. Reads, counts, aggregates, Histories and attachments see only admitted rows; a row outside
|
|
2515
2538
|
them is "Not found". Members' groups: ez user group add <who> <name>. Check what someone sees with
|
|
2516
2539
|
\`ez db query <table> --as <who>\`; \`ez global push --dry-run\` reports what a change does to each Member.
|
|
2540
|
+
A rule goes in the push that declares the Table or column it reads: until a Preview or Deploy has added a
|
|
2541
|
+
new column the rule reads it as NULL, which is what every row then holds.
|
|
2517
2542
|
READ lookup, department, sample_type WHERE group(staff); one rule for several Tables
|
|
2518
2543
|
GROUP analyst; a group server code may assign (docs/adr/0101)
|
|
2519
2544
|
GROUP lab-manager IMPLIES analyst, verifier; holding it confers those too, wherever groups are tested
|
package/update-check.mjs
CHANGED
|
@@ -38,15 +38,6 @@ export function isNewer(current, latest) {
|
|
|
38
38
|
export const updateNotice = (current, latest, name) =>
|
|
39
39
|
`A newer ez is available: ${current} → ${latest}. Upgrade with: npm install -g ${name}@latest`;
|
|
40
40
|
|
|
41
|
-
/**
|
|
42
|
-
* The package `ez` runs as: the `ezship` alias when its bin started it, else `@ezship/cli`.
|
|
43
|
-
* @param {string | undefined} bin process.argv[1]
|
|
44
|
-
*/
|
|
45
|
-
export const installedAs = (bin) =>
|
|
46
|
-
bin && /[\\/]node_modules[\\/]ezship[\\/]/.test(bin) && !/[\\/]@ezship[\\/]cli[\\/]/.test(bin)
|
|
47
|
-
? "ezship"
|
|
48
|
-
: "@ezship/cli";
|
|
49
|
-
|
|
50
41
|
/**
|
|
51
42
|
* @typedef {{ checkedAt?: number, latest?: string, notifiedAt?: number }} UpdateState
|
|
52
43
|
* @typedef {{
|