@feltdb/feltkit 0.3.18 → 0.3.19
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/dist/app.d.ts +57 -14
- package/dist/app.js +71 -9
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.d.ts +25 -0
- package/dist/appboundry/build.js +10 -1
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/guest.js +18 -2
- package/dist/appboundry/guest.js.map +1 -1
- package/dist/appboundry/host.js +3 -0
- package/dist/appboundry/host.js.map +1 -1
- package/dist/cli/compose.d.ts +31 -0
- package/dist/cli/compose.js +274 -0
- package/dist/cli/compose.js.map +1 -0
- package/dist/cli/create.d.ts +201 -0
- package/dist/cli/create.js +1139 -0
- package/dist/cli/create.js.map +1 -0
- package/dist/cli/deploy.d.ts +1 -0
- package/dist/cli/deploy.js +66 -6
- package/dist/cli/deploy.js.map +1 -1
- package/dist/cli/domain.d.ts +174 -0
- package/dist/cli/domain.js +1119 -0
- package/dist/cli/domain.js.map +1 -0
- package/dist/cli/main.d.ts +2 -0
- package/dist/cli/main.js +135 -6
- package/dist/cli/main.js.map +1 -1
- package/dist/cli/shell.d.ts +7 -0
- package/dist/cli/shell.js +59 -0
- package/dist/cli/shell.js.map +1 -0
- package/dist/component.d.ts +174 -0
- package/dist/component.js +77 -0
- package/dist/component.js.map +1 -0
- package/dist/composition/catalog.d.ts +3 -0
- package/dist/composition/catalog.js +217 -0
- package/dist/composition/catalog.js.map +1 -0
- package/dist/composition/contract.d.ts +165 -0
- package/dist/composition/contract.js +12 -0
- package/dist/composition/contract.js.map +1 -0
- package/dist/composition/execute.d.ts +110 -0
- package/dist/composition/execute.js +350 -0
- package/dist/composition/execute.js.map +1 -0
- package/dist/composition/generate.d.ts +105 -0
- package/dist/composition/generate.js +274 -0
- package/dist/composition/generate.js.map +1 -0
- package/dist/composition/plan.d.ts +131 -0
- package/dist/composition/plan.js +558 -0
- package/dist/composition/plan.js.map +1 -0
- package/dist/composition/profiles.d.ts +20 -0
- package/dist/composition/profiles.js +81 -0
- package/dist/composition/profiles.js.map +1 -0
- package/dist/composition/reconcile.d.ts +153 -0
- package/dist/composition/reconcile.js +282 -0
- package/dist/composition/reconcile.js.map +1 -0
- package/dist/composition/recover.d.ts +89 -0
- package/dist/composition/recover.js +407 -0
- package/dist/composition/recover.js.map +1 -0
- package/dist/composition/resolve.d.ts +2 -0
- package/dist/composition/resolve.js +208 -0
- package/dist/composition/resolve.js.map +1 -0
- package/dist/dashboard/assets/{index-DnIOVGF-.js → index-BrC1AtZ1.js} +5 -5
- package/dist/dashboard/index.html +1 -1
- package/dist/docs.d.ts +1 -1
- package/dist/docs.js +1 -0
- package/dist/docs.js.map +1 -1
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/runtime/activity.d.ts +8 -1
- package/dist/runtime/activity.js.map +1 -1
- package/dist/runtime/audit.d.ts +43 -0
- package/dist/runtime/audit.js +52 -0
- package/dist/runtime/audit.js.map +1 -0
- package/dist/runtime/claims.d.ts +76 -0
- package/dist/runtime/claims.js +100 -0
- package/dist/runtime/claims.js.map +1 -0
- package/dist/runtime/context.d.ts +6 -5
- package/dist/runtime/contract.js +4 -1
- package/dist/runtime/contract.js.map +1 -1
- package/dist/runtime/data.d.ts +14 -2
- package/dist/runtime/data.js +62 -23
- package/dist/runtime/data.js.map +1 -1
- package/dist/runtime/escape-hatch.d.ts +37 -0
- package/dist/runtime/escape-hatch.js +76 -0
- package/dist/runtime/escape-hatch.js.map +1 -0
- package/dist/runtime/instance.js +2 -1
- package/dist/runtime/instance.js.map +1 -1
- package/dist/runtime/outbox.js +3 -0
- package/dist/runtime/outbox.js.map +1 -1
- package/dist/runtime/runtime.d.ts +33 -0
- package/dist/runtime/runtime.js +127 -12
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/services-rules.d.ts +12 -0
- package/dist/runtime/services-rules.js +8 -0
- package/dist/runtime/services-rules.js.map +1 -0
- package/dist/runtime/services.js +5 -3
- package/dist/runtime/services.js.map +1 -1
- package/dist/runtime/tenancy.d.ts +13 -4
- package/dist/runtime/tenancy.js +30 -9
- package/dist/runtime/tenancy.js.map +1 -1
- package/dist/runtime/transactions.d.ts +38 -1
- package/dist/runtime/transactions.js +20 -5
- package/dist/runtime/transactions.js.map +1 -1
- package/dist/server/admin.js +52 -0
- package/dist/server/admin.js.map +1 -1
- package/dist/server/components.d.ts +44 -0
- package/dist/server/components.js +212 -0
- package/dist/server/components.js.map +1 -0
- package/dist/server/index.d.ts +2 -0
- package/dist/server/index.js +24 -5
- package/dist/server/index.js.map +1 -1
- package/dist/server/project.d.ts +27 -0
- package/dist/server/project.js +63 -0
- package/dist/server/project.js.map +1 -1
- package/dist/server/public.d.ts +2 -0
- package/dist/server/public.js +2 -0
- package/dist/server/public.js.map +1 -1
- package/dist/testing/index.d.ts +12 -0
- package/dist/testing/index.js +15 -0
- package/dist/testing/index.js.map +1 -1
- package/docs/ARCHITECTURE.md +1 -1
- package/docs/AUTH.md +8 -3
- package/docs/COMPONENTS.md +91 -0
- package/docs/GUARANTEES.md +24 -4
- package/docs/README.md +3 -2
- package/docs/RESOLVER.md +4 -2
- package/docs/SECURITY.md +2 -2
- package/docs/TRANSACTIONS.md +1 -1
- package/package.json +14 -12
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +1 -1
- package/skills/feltkit-services/SKILL.md +1 -1
|
@@ -0,0 +1,1119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The composer's domain model (M8): entities with typed fields, relationships, ownership, scope and
|
|
3
|
+
* constraints, as a developer states them, compiled to what the SDK really supports: `app.collection`
|
|
4
|
+
* shapes (`s.string`, `s.number`, `s.boolean`, `s.enum`, `s.optional`, `s.ref`), `{ tenant: true }`,
|
|
5
|
+
* `unique`, and one function module per entity (list, get, create, update, remove) whose permissions
|
|
6
|
+
* are named and whose ownership rule is explicit. Every line emitted here is application-owned code,
|
|
7
|
+
* written once at creation; the generated tests exercise it for real (permissions, isolation,
|
|
8
|
+
* ownership, uniqueness, references).
|
|
9
|
+
*
|
|
10
|
+
* Nothing here is a schema feature the SDK lacks: references are enforced by FeltDB when the
|
|
11
|
+
* application's schema is active (s.ref), uniqueness at commit, tenancy on every read and write.
|
|
12
|
+
*/
|
|
13
|
+
import { CLAIM_TYPES, claimSpecProblem } from "../runtime/claims.js";
|
|
14
|
+
export const IDENT = /^[a-z][a-zA-Z0-9]{0,40}$/;
|
|
15
|
+
/** Fields the generator adds or FeltKit reserves. */
|
|
16
|
+
export const RESERVED_FIELDS = new Set(["id", "__version", "tenantId", "createdBy", "createdAt", "updatedAt"]);
|
|
17
|
+
export class DomainError extends Error {
|
|
18
|
+
hint;
|
|
19
|
+
constructor(message, hint) {
|
|
20
|
+
super(message);
|
|
21
|
+
this.hint = hint;
|
|
22
|
+
this.name = "DomainError";
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/** `title:string, done:boolean, due:number?, status:enum(open|closed)` */
|
|
26
|
+
export function parseFields(text) {
|
|
27
|
+
const out = [];
|
|
28
|
+
for (const part of text.split(",").map((p) => p.trim()).filter(Boolean)) {
|
|
29
|
+
const m = /^([a-zA-Z][a-zA-Z0-9]*)\s*:\s*(string|number|boolean|enum\(([^)]*)\))\s*(\?)?$/.exec(part);
|
|
30
|
+
if (!m)
|
|
31
|
+
throw new DomainError(`"${part}" is not a field.`, "Fields are name:type, with type string, number, boolean or enum(a|b|c); a trailing ? makes it optional: title:string, done:boolean, due:number?, status:enum(open|closed)");
|
|
32
|
+
const [, name, typeText, enumValues, optional] = m;
|
|
33
|
+
if (!IDENT.test(name))
|
|
34
|
+
throw new DomainError(`Field "${name}" must be a lower-case identifier.`, "Like title, dueDate, isDone.");
|
|
35
|
+
if (RESERVED_FIELDS.has(name))
|
|
36
|
+
throw new DomainError(`Field "${name}" is added by FeltKit or the composer; do not declare it.`, `Reserved: ${[...RESERVED_FIELDS].join(", ")}.`);
|
|
37
|
+
if (out.some((f) => f.name === name))
|
|
38
|
+
throw new DomainError(`Field "${name}" is declared twice.`, "Each field once.");
|
|
39
|
+
const type = (typeText.startsWith("enum") ? "enum" : typeText);
|
|
40
|
+
const values = type === "enum" ? enumValues.split("|").map((v) => v.trim()).filter(Boolean) : undefined;
|
|
41
|
+
if (type === "enum" && (!values?.length || values.some((v) => !/^[a-zA-Z0-9_-]+$/.test(v))))
|
|
42
|
+
throw new DomainError(`enum "${name}" needs values like enum(open|closed).`, "Values are words separated by |.");
|
|
43
|
+
out.push({ name: name, type, required: !optional, ...(values ? { values } : {}) });
|
|
44
|
+
}
|
|
45
|
+
return out;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Membership claims as plain data: `plan:enum(free|pro), seats:integer=1, region:string` → claim specs
|
|
49
|
+
* (workspace.tenancy.claims). Types: string, number, integer, boolean, enum(a|b); `=value` is the declaration's default.
|
|
50
|
+
*/
|
|
51
|
+
export function parseClaims(text) {
|
|
52
|
+
const out = {};
|
|
53
|
+
for (const part of text.split(",").map((p) => p.trim()).filter(Boolean)) {
|
|
54
|
+
const m = /^([a-zA-Z][a-zA-Z0-9]*)\s*:\s*(string|number|integer|boolean|enum\(([^)]*)\))\s*(?:=\s*(.+))?$/.exec(part);
|
|
55
|
+
if (!m)
|
|
56
|
+
throw new DomainError(`"${part}" is not a claim.`, "Claims are name:type, with type string, number, integer, boolean or enum(a|b); =value gives a default: plan:enum(free|pro), seats:integer=1");
|
|
57
|
+
const [, name, typeText, enumValues, defaultText] = m;
|
|
58
|
+
if (name in out)
|
|
59
|
+
throw new DomainError(`Claim "${name}" is declared twice.`, "Each claim once.");
|
|
60
|
+
const type = (typeText.startsWith("enum") ? "enum" : typeText);
|
|
61
|
+
const spec = { type };
|
|
62
|
+
if (type === "enum")
|
|
63
|
+
spec.values = enumValues.split("|").map((v) => v.trim()).filter(Boolean);
|
|
64
|
+
if (defaultText !== undefined) {
|
|
65
|
+
const raw = defaultText.trim();
|
|
66
|
+
spec.default = type === "boolean" ? (raw === "true" ? true : raw === "false" ? false : raw) : type === "number" || type === "integer" ? (raw === "" || Number.isNaN(Number(raw)) ? raw : Number(raw)) : raw;
|
|
67
|
+
}
|
|
68
|
+
const problem = claimSpecProblem(name, spec);
|
|
69
|
+
if (problem)
|
|
70
|
+
throw new DomainError(`Claim "${name}": ${problem}.`, "For example plan:enum(free|pro), seats:integer=1, region:string.");
|
|
71
|
+
out[name] = spec;
|
|
72
|
+
}
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
/** `plan=pro|enterprise` against the declared claims → a gate, its values typed by the claim's declaration. */
|
|
76
|
+
export function parseRequire(text, claims) {
|
|
77
|
+
const m = /^([a-zA-Z][a-zA-Z0-9]*)\s*=\s*(.+)$/.exec(text.trim());
|
|
78
|
+
if (!m)
|
|
79
|
+
throw new DomainError(`"${text}" is not a claim requirement.`, "A requirement is claim=value or claim=value|value: plan=pro, plan=pro|enterprise, verified=true.");
|
|
80
|
+
const [, claim, valuesText] = m;
|
|
81
|
+
const spec = claims[claim];
|
|
82
|
+
if (!spec)
|
|
83
|
+
throw new DomainError(`Requirement names "${claim}", which is not a declared claim (${Object.keys(claims).join(", ") || "none declared"}).`, "Declare it first: --claim <name>:<type> (or the claims question in the interview).");
|
|
84
|
+
const values = valuesText.split("|").map((v) => v.trim()).filter(Boolean).map((raw) => {
|
|
85
|
+
if (spec.type === "boolean") {
|
|
86
|
+
if (raw !== "true" && raw !== "false")
|
|
87
|
+
throw new DomainError(`Requirement ${claim}=${raw}: ${claim} is a boolean claim (true or false).`, "For example verified=true.");
|
|
88
|
+
return raw === "true";
|
|
89
|
+
}
|
|
90
|
+
if (spec.type === "number" || spec.type === "integer") {
|
|
91
|
+
if (Number.isNaN(Number(raw)) || (spec.type === "integer" && !Number.isInteger(Number(raw))))
|
|
92
|
+
throw new DomainError(`Requirement ${claim}=${raw}: ${claim} is ${spec.type === "integer" ? "an integer" : "a number"} claim.`, "For example seats=5.");
|
|
93
|
+
return Number(raw);
|
|
94
|
+
}
|
|
95
|
+
if (spec.type === "enum" && !spec.values.includes(raw))
|
|
96
|
+
throw new DomainError(`Requirement ${claim}=${raw}: ${claim} is one of ${spec.values.join(", ")}.`, `For example ${claim}=${spec.values[0]}.`);
|
|
97
|
+
return raw;
|
|
98
|
+
});
|
|
99
|
+
if (!values.length)
|
|
100
|
+
throw new DomainError(`Requirement ${claim}= names no value.`, "A requirement is claim=value or claim=value|value.");
|
|
101
|
+
return { claim: claim, values };
|
|
102
|
+
}
|
|
103
|
+
/** `project -> projects, assignee -> people?` */
|
|
104
|
+
export function parseRelations(text) {
|
|
105
|
+
const out = [];
|
|
106
|
+
for (const part of text.split(",").map((p) => p.trim()).filter(Boolean)) {
|
|
107
|
+
const m = /^([a-zA-Z][a-zA-Z0-9]*)\s*->\s*([a-zA-Z][a-zA-Z0-9]*)\s*(\?)?$/.exec(part);
|
|
108
|
+
if (!m)
|
|
109
|
+
throw new DomainError(`"${part}" is not a relationship.`, "Relationships are field -> entity, with a trailing ? when optional: project -> projects, assignee -> people?");
|
|
110
|
+
const [, field, target, optional] = m;
|
|
111
|
+
const fieldName = field.endsWith("Id") ? field : `${field}Id`;
|
|
112
|
+
if (RESERVED_FIELDS.has(fieldName))
|
|
113
|
+
throw new DomainError(`"${fieldName}" is reserved.`, `Reserved: ${[...RESERVED_FIELDS].join(", ")}.`);
|
|
114
|
+
if (out.some((r) => r.field === fieldName))
|
|
115
|
+
throw new DomainError(`Relationship field "${fieldName}" is declared twice.`, "Each once.");
|
|
116
|
+
out.push({ field: fieldName, target: target, required: !optional });
|
|
117
|
+
}
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
/** `name; projectId,title` → [["name"], ["projectId","title"]] */
|
|
121
|
+
export function parseUnique(text) {
|
|
122
|
+
return text.split(";").map((group) => group.split(",").map((f) => f.trim()).filter(Boolean)).filter((g) => g.length);
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Consistency across entities: every scope exists in the foundation, every relationship targets a declared
|
|
126
|
+
* entity and does not reach from wider to narrower data, every unique field exists, names are distinct.
|
|
127
|
+
*/
|
|
128
|
+
export function validateEntities(entities, tenancy = "workspaces", claims = {}) {
|
|
129
|
+
const names = new Set();
|
|
130
|
+
for (const e of entities) {
|
|
131
|
+
if (e.requires) {
|
|
132
|
+
if (tenancy === "individuals")
|
|
133
|
+
throw new DomainError(`${e.name} requires a membership claim, but this application has no workspaces.`, "Claims belong to workspace memberships. Without workspaces, authority is the account's roles; choose workspaces if people join organizations.");
|
|
134
|
+
if (e.scope !== "workspace")
|
|
135
|
+
throw new DomainError(`${e.name} requires a membership claim, but it is ${e.scope}.`, "A shared entity is reached without a workspace, so no membership is there to judge. Only a workspace-scoped entity can require a claim.");
|
|
136
|
+
if (!(e.requires.claim in claims))
|
|
137
|
+
throw new DomainError(`${e.name} requires the claim "${e.requires.claim}", which is not declared (${Object.keys(claims).join(", ") || "no claims declared"}).`, "Declare it in workspace.tenancy.claims first (--claim <name>:<type>).");
|
|
138
|
+
}
|
|
139
|
+
if (!IDENT.test(e.name))
|
|
140
|
+
throw new DomainError(`Entity "${e.name}" must be a lower-case identifier.`, "Like notes, projects, lineItems.");
|
|
141
|
+
if (names.has(e.name))
|
|
142
|
+
throw new DomainError(`Entity "${e.name}" is declared twice.`, "Each entity once.");
|
|
143
|
+
names.add(e.name);
|
|
144
|
+
if (e.scope === "workspace" && tenancy === "individuals")
|
|
145
|
+
throw new DomainError(`${e.name} is workspace-scoped, but this application has no workspaces.`, "Without workspaces an entity is personal (each person's own records) or shared. Choose workspaces for the application if its data belongs to organizations.");
|
|
146
|
+
if (e.scope === "personal" && tenancy === "workspaces")
|
|
147
|
+
throw new DomainError(`${e.name} is personal, but this application groups people in workspaces.`, "In a workspace application an entity belongs to a workspace or is shared; creator ownership (owned) keeps changes to the creator.");
|
|
148
|
+
if (e.scope === "personal" && !e.owned)
|
|
149
|
+
throw new DomainError(`${e.name} is personal, so it is owned by its creator.`, "A personal entity is always owned: say so, or make it shared.");
|
|
150
|
+
if (e.public && e.scope !== "shared")
|
|
151
|
+
throw new DomainError(`${e.name} is ${e.scope === "workspace" ? "workspace-scoped" : "personal"}, so it cannot be read publicly.`, e.scope === "workspace" ? "A workspace record is read in a workspace, by a member; an anonymous caller has none. Only a shared entity can be public." : "Personal records are the creator's alone. Only a shared entity can be public.");
|
|
152
|
+
}
|
|
153
|
+
for (const e of entities) {
|
|
154
|
+
for (const r of e.relations) {
|
|
155
|
+
if (!names.has(r.target))
|
|
156
|
+
throw new DomainError(`${e.name}.${r.field} refers to "${r.target}", which is not one of the entities (${[...names].join(", ")}).`, "Name the related entity among the entities, or drop the relationship.");
|
|
157
|
+
if (e.fields.some((f) => f.name === r.field))
|
|
158
|
+
throw new DomainError(`${e.name}.${r.field} is both a field and a relationship.`, "Use one.");
|
|
159
|
+
const target = entities.find((x) => x.name === r.target);
|
|
160
|
+
if (e.scope === "workspace" && target.scope === "shared") {
|
|
161
|
+
// Allowed: a workspace record may point at a shared one. The reverse would leak a workspace id into shared data.
|
|
162
|
+
}
|
|
163
|
+
else if (e.scope === "shared" && target.scope === "workspace")
|
|
164
|
+
throw new DomainError(`${e.name} is shared but ${e.name}.${r.field} refers to ${r.target}, which belongs to a workspace.`, "A shared record cannot point at workspace-scoped data (it would reach across workspaces). Make the relationship the other way, or scope both the same.");
|
|
165
|
+
else if (e.scope === "shared" && target.scope === "personal")
|
|
166
|
+
throw new DomainError(`${e.name} is shared but ${e.name}.${r.field} refers to ${r.target}, which is personal.`, "A shared record cannot point at one person's data (everyone would see the reference). Make the relationship the other way, or scope both the same.");
|
|
167
|
+
}
|
|
168
|
+
for (const group of e.unique) {
|
|
169
|
+
for (const f of group)
|
|
170
|
+
if (!e.fields.some((x) => x.name === f) && !e.relations.some((r) => r.field === f))
|
|
171
|
+
throw new DomainError(`${e.name} unique constraint names "${f}", which is not a field or relationship of ${e.name}.`, `Fields: ${[...e.fields.map((f) => f.name), ...e.relations.map((r) => r.field)].join(", ") || "none"}.`);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
/** Entities ordered so that a relationship's target comes before the entity that refers to it (for tests that create records). */
|
|
176
|
+
export function creationOrder(entities) {
|
|
177
|
+
const done = [];
|
|
178
|
+
const pending = [...entities];
|
|
179
|
+
let guard = 0;
|
|
180
|
+
while (pending.length && guard++ < 100) {
|
|
181
|
+
const next = pending.find((e) => e.relations.every((r) => r.target === e.name || done.some((d) => d.name === r.target)));
|
|
182
|
+
if (!next) {
|
|
183
|
+
// A cycle: emit the rest in declaration order; their required references cannot all be satisfied at creation, which the tests then state.
|
|
184
|
+
done.push(...pending);
|
|
185
|
+
break;
|
|
186
|
+
}
|
|
187
|
+
done.push(next);
|
|
188
|
+
pending.splice(pending.indexOf(next), 1);
|
|
189
|
+
}
|
|
190
|
+
return done;
|
|
191
|
+
}
|
|
192
|
+
const cap = (s) => s[0].toUpperCase() + s.slice(1);
|
|
193
|
+
const singular = (name) => (name.endsWith("ies") ? `${name.slice(0, -3)}y` : name.endsWith("s") ? name.slice(0, -1) : name);
|
|
194
|
+
function fieldSchema(f) {
|
|
195
|
+
const base = f.type === "string" ? "s.string({ maxLength: 4000 })" : f.type === "number" ? "s.number()" : f.type === "boolean" ? "s.boolean()" : `s.enum([${f.values.map((v) => JSON.stringify(v)).join(", ")}])`;
|
|
196
|
+
return f.required ? base : `s.optional(${base})`;
|
|
197
|
+
}
|
|
198
|
+
/** The `app.collection(...)` declaration for an entity, for feltkit/app.ts. */
|
|
199
|
+
export function renderCollection(e, noun, tenancy = "workspaces") {
|
|
200
|
+
const lines = [];
|
|
201
|
+
lines.push(`/**`);
|
|
202
|
+
const about = e.scope === "workspace" ? `Belongs to a ${noun}: FeltKit scopes every read and write to the caller's current ${noun}.` : e.scope === "personal" ? `Personal: each person's own records; feltkit/${e.name}.ts shows a caller only what they created.` : tenancy === "workspaces" ? `Shared across ${noun}s: every signed-in caller with the permission sees the same records.` : `Shared: every signed-in caller with the permission sees the same records.`;
|
|
203
|
+
lines.push(` * ${cap(e.name)}${e.description ? `: ${e.description}` : ""}. ${about}`);
|
|
204
|
+
if (e.owned && e.scope !== "personal")
|
|
205
|
+
lines.push(` * Owned: createdBy is the creating principal; only the creator or a managing role may update or remove a record (feltkit/${e.name}.ts).`);
|
|
206
|
+
if (e.scope === "personal")
|
|
207
|
+
lines.push(` * createdBy is the creating principal, and the only key to a record: nobody else lists, reads, changes or removes it (feltkit/${e.name}.ts).`);
|
|
208
|
+
if (e.public)
|
|
209
|
+
lines.push(` * Public: list and get are open to anyone, signed in or not (access: "public" in feltkit/${e.name}.ts); writes need their permission.`);
|
|
210
|
+
if (e.requires)
|
|
211
|
+
lines.push(` * Requires the membership claim ${e.requires.claim} = ${e.requires.values.map((v) => JSON.stringify(v)).join(" | ")} on every function (app.requireClaim in feltkit/${e.name}.ts); a permission alone is not enough.`);
|
|
212
|
+
for (const r of e.relations)
|
|
213
|
+
lines.push(` * ${r.field} refers to a ${singular(r.target)}; FeltDB refuses a value that names no record and refuses to delete a referenced ${singular(r.target)}.`);
|
|
214
|
+
lines.push(` */`);
|
|
215
|
+
lines.push(`export const ${e.name} = app.collection(`);
|
|
216
|
+
lines.push(` ${JSON.stringify(e.name)},`);
|
|
217
|
+
lines.push(` {`);
|
|
218
|
+
for (const f of e.fields)
|
|
219
|
+
lines.push(` ${f.name}: ${fieldSchema(f)},`);
|
|
220
|
+
for (const r of e.relations)
|
|
221
|
+
lines.push(` ${r.field}: ${r.required ? `s.ref(${JSON.stringify(r.target)})` : `s.optional(s.ref(${JSON.stringify(r.target)}))`},`);
|
|
222
|
+
if (e.owned)
|
|
223
|
+
lines.push(` createdBy: s.string(),`);
|
|
224
|
+
lines.push(` createdAt: s.number(),`);
|
|
225
|
+
lines.push(` updatedAt: s.number(),`);
|
|
226
|
+
lines.push(` },`);
|
|
227
|
+
const options = [];
|
|
228
|
+
if (e.scope === "workspace")
|
|
229
|
+
options.push("tenant: true");
|
|
230
|
+
else if (e.scope === "personal")
|
|
231
|
+
options.push(`description: "personal: each person's own records", indexes: [{ fields: ["createdBy"] }]`);
|
|
232
|
+
else
|
|
233
|
+
options.push(`description: ${JSON.stringify(tenancy === "workspaces" ? `shared across ${noun}s` : "shared by every signed-in person")}`);
|
|
234
|
+
if (e.unique.length)
|
|
235
|
+
options.push(`unique: [${e.unique.map((g) => `{ fields: [${g.map((f) => JSON.stringify(f)).join(", ")}] }`).join(", ")}]`);
|
|
236
|
+
lines.push(` { ${options.join(", ")} },`);
|
|
237
|
+
lines.push(`);`);
|
|
238
|
+
return lines;
|
|
239
|
+
}
|
|
240
|
+
/** The permissions an entity's functions name: <entity>.read, .create, .update, .delete. */
|
|
241
|
+
export const PERMISSIONS = ["read", "create", "update", "delete"];
|
|
242
|
+
/**
|
|
243
|
+
* The roles that may change another member's owned record.
|
|
244
|
+
*
|
|
245
|
+
* With workspaces the top role always manages: the composition's `workspace.tenancy.managers` names the roles that
|
|
246
|
+
* manage *besides* the top one (the interview asks "which roles manage members without being the <top>"), so the
|
|
247
|
+
* effective set is the top role followed by the declared managers. With individuals there is no implicit manager and
|
|
248
|
+
* only the declared roles manage.
|
|
249
|
+
*
|
|
250
|
+
* One function, called by the entity modules and by the generated tests, because when those two derive the set
|
|
251
|
+
* separately they can disagree: they did, and the generated application's own test suite failed for a single-role
|
|
252
|
+
* workspace with no declared manager — the module let the sole role change anyone's record while the test asserted
|
|
253
|
+
* FORBIDDEN (Level B case `c_004a8472da66a7`).
|
|
254
|
+
*/
|
|
255
|
+
export function managingRoles(roles, declaredManagers, tenancy = "workspaces") {
|
|
256
|
+
if (tenancy === "individuals")
|
|
257
|
+
return [...declaredManagers];
|
|
258
|
+
const top = roles[0];
|
|
259
|
+
return top === undefined ? [...declaredManagers] : [top, ...declaredManagers.filter((r) => r !== top)];
|
|
260
|
+
}
|
|
261
|
+
/**
|
|
262
|
+
* One function module per entity: list, get, create, update, remove, each naming its permission.
|
|
263
|
+
* `managers` are the roles that may update or remove any record of an owned entity that is not personal:
|
|
264
|
+
* workspace roles (judged on the caller's membership) with workspaces, the account's own roles otherwise. Callers
|
|
265
|
+
* derive it with `managingRoles`, never by hand, so the modules and the generated tests cannot disagree.
|
|
266
|
+
* A personal entity is the creator's alone: every function sees only the caller's own records.
|
|
267
|
+
*/
|
|
268
|
+
export function renderEntityModule(e, noun, managers, tenancy = "workspaces") {
|
|
269
|
+
// Managers reach owned records of the entity kind that has a membership to judge: workspace-scoped with workspaces
|
|
270
|
+
// (the caller's role in the workspace), shared with individuals (the account's roles). A shared entity in a workspace
|
|
271
|
+
// application is the creator's alone, as before.
|
|
272
|
+
const managed = e.owned && managers.length > 0 && (tenancy === "workspaces" ? e.scope === "workspace" : e.scope === "shared");
|
|
273
|
+
const personal = e.scope === "personal";
|
|
274
|
+
const writable = [...e.fields.map((f) => f.name), ...e.relations.map((r) => r.field)];
|
|
275
|
+
const argOf = (name, optional) => {
|
|
276
|
+
const f = e.fields.find((x) => x.name === name);
|
|
277
|
+
if (f)
|
|
278
|
+
return optional ? `s.optional(${fieldSchema({ ...f, required: true })})` : fieldSchema(f);
|
|
279
|
+
const r = e.relations.find((x) => x.field === name);
|
|
280
|
+
const base = `s.ref(${JSON.stringify(r.target)})`;
|
|
281
|
+
return optional || !r.required ? `s.optional(${base})` : base;
|
|
282
|
+
};
|
|
283
|
+
const lines = [];
|
|
284
|
+
lines.push(`/**`);
|
|
285
|
+
lines.push(` * ${cap(e.name)}: list, get, create, update, remove. Each function names the permission it needs`);
|
|
286
|
+
lines.push(` * (${PERMISSIONS.map((p) => `${e.name}.${p}`).join(", ")}); roles grant them in feltkit/app.ts.${e.scope === "workspace" ? ` Every call is scoped to the caller's ${noun}.` : personal ? " Every call sees only the caller's own records." : ""}`);
|
|
287
|
+
if (e.public)
|
|
288
|
+
lines.push(` * Public reads: list and get are access: "public" (anyone, signed in or not); create, update and remove need their permission.`);
|
|
289
|
+
if (e.owned && !personal)
|
|
290
|
+
lines.push(` * Ownership: createdBy is the creator; update and remove are allowed to the creator${managed ? ` or to ${managers.map((m) => `"${m}"`).join(" / ")}` : ""}.`);
|
|
291
|
+
if (personal)
|
|
292
|
+
lines.push(` * Ownership: createdBy is the creator, and another person's record does not exist for the caller (NOT_FOUND), whatever their role.`);
|
|
293
|
+
if (e.attachments)
|
|
294
|
+
lines.push(` * Attachments: files, download (reading the record), attach, attachLink, detach (changing it). A file is bound to its record by the`);
|
|
295
|
+
if (e.attachments)
|
|
296
|
+
lines.push(` * metadata fixed at upload ({ entity, recordId }) and checked on every read; a file of another record does not exist here (NOT_FOUND).`);
|
|
297
|
+
if (e.attachments)
|
|
298
|
+
lines.push(` * The roles that read this entity hold files.read; the roles that change it hold files.write and files.delete (feltkit/app.ts).${e.public ? " Public reads do not extend to files: the Files service needs a signed-in caller." : ""}`);
|
|
299
|
+
if (e.requires)
|
|
300
|
+
lines.push(` * Claim gate: every function first requires the caller's membership claim ${e.requires.claim} to be ${e.requires.values.map((v) => JSON.stringify(v)).join(" or ")} (app.requireClaim):`);
|
|
301
|
+
if (e.requires)
|
|
302
|
+
lines.push(` * set through the server (a member manager or an invitation), valid under the declaration now; a permission without it is FORBIDDEN.`);
|
|
303
|
+
lines.push(` * Composed by \`feltkit create\`; this file is yours.`);
|
|
304
|
+
lines.push(` */`);
|
|
305
|
+
lines.push(`import { fail, s } from "@feltdb/feltkit";`);
|
|
306
|
+
lines.push(`import { app, ${e.name} } from "./app.js";`);
|
|
307
|
+
lines.push(``);
|
|
308
|
+
// Personal: the caller's own record, or NOT_FOUND (another person's does not exist for them), inline in get, update and remove.
|
|
309
|
+
const own = ` if (!record || record.createdBy !== ctx.auth.requirePrincipal().id) fail("NOT_FOUND", ${JSON.stringify(`No such ${singular(e.name)}.`)});`;
|
|
310
|
+
/** The metadata that binds a file to one record of this entity. */
|
|
311
|
+
const binding = (idExpr) => `{ entity: ${JSON.stringify(e.name)}, recordId: ${idExpr} }`;
|
|
312
|
+
if (e.owned && !personal) {
|
|
313
|
+
lines.push(`/** The creator, ${managed ? (tenancy === "workspaces" ? `or a ${noun} role that manages ${e.name} (${managers.join(", ")})` : `or an account holding a role that manages ${e.name} (${managers.join(", ")})`) : "and nobody else"}. */`);
|
|
314
|
+
lines.push(`function mayChange(ctx: { auth: { requirePrincipal(): { id: string${tenancy === "individuals" ? "; roles: readonly string[]" : ""} }; tenant: { role: string } | null } }, record: { createdBy: string }): boolean {`);
|
|
315
|
+
lines.push(` if (record.createdBy === ctx.auth.requirePrincipal().id) return true;`);
|
|
316
|
+
if (managed && tenancy === "workspaces")
|
|
317
|
+
lines.push(` const role = app.requireTenant(ctx as never).role;`);
|
|
318
|
+
if (managed && tenancy === "workspaces")
|
|
319
|
+
lines.push(` return [${managers.map((m) => JSON.stringify(m)).join(", ")}].includes(role);`);
|
|
320
|
+
else if (managed)
|
|
321
|
+
lines.push(` return ctx.auth.requirePrincipal().roles.some((role) => [${managers.map((m) => JSON.stringify(m)).join(", ")}].includes(role));`);
|
|
322
|
+
else
|
|
323
|
+
lines.push(` return false;`);
|
|
324
|
+
lines.push(`}`);
|
|
325
|
+
lines.push(``);
|
|
326
|
+
}
|
|
327
|
+
// list
|
|
328
|
+
const filterArgs = e.relations.map((r) => `${r.field}: s.optional(s.string())`);
|
|
329
|
+
lines.push(`/** ${cap(e.name)}${e.scope === "workspace" ? ` of the current ${noun}` : personal ? " of the caller" : ""}, newest first${e.relations.length ? `; optionally only those of one ${e.relations.map((r) => singular(r.target)).join(" or ")}` : ""}. */`);
|
|
330
|
+
const readAccess = e.public ? "public" : `${e.name}.read`;
|
|
331
|
+
lines.push(`export const list = app.query({`);
|
|
332
|
+
lines.push(` access: ${JSON.stringify(readAccess)},`);
|
|
333
|
+
lines.push(` args: { ${filterArgs.join(", ")} },`);
|
|
334
|
+
lines.push(` handler: async (ctx${e.relations.length ? ", filter" : ""}) => {`);
|
|
335
|
+
if (e.relations.length)
|
|
336
|
+
lines.push(` const where = Object.fromEntries(Object.entries(filter).filter(([, v]) => v !== undefined));`);
|
|
337
|
+
if (personal)
|
|
338
|
+
lines.push(` return ctx.db.find(${e.name}, { ${e.relations.length ? "...where, " : ""}createdBy: ctx.auth.requirePrincipal().id }, { orderBy: [{ field: "createdAt", direction: "desc" }] });`);
|
|
339
|
+
else
|
|
340
|
+
lines.push(` return ctx.db.find(${e.name}, ${e.relations.length ? "where" : "{}"}, { orderBy: [{ field: "createdAt", direction: "desc" }] });`);
|
|
341
|
+
lines.push(` },`);
|
|
342
|
+
lines.push(`});`);
|
|
343
|
+
lines.push(``);
|
|
344
|
+
// get
|
|
345
|
+
lines.push(`export const get = app.query({`);
|
|
346
|
+
lines.push(` access: ${JSON.stringify(readAccess)},`);
|
|
347
|
+
lines.push(` args: { id: s.string() },`);
|
|
348
|
+
lines.push(` handler: async (ctx, { id }) => {`);
|
|
349
|
+
lines.push(` const record = await ctx.db.get(${e.name}, id);`);
|
|
350
|
+
lines.push(personal ? own : ` if (!record) fail("NOT_FOUND", ${JSON.stringify(`No such ${singular(e.name)}.`)});`);
|
|
351
|
+
lines.push(` return record;`);
|
|
352
|
+
lines.push(` },`);
|
|
353
|
+
lines.push(`});`);
|
|
354
|
+
lines.push(``);
|
|
355
|
+
// create
|
|
356
|
+
lines.push(`export const create = app.mutation({`);
|
|
357
|
+
lines.push(` access: ${JSON.stringify(`${e.name}.create`)},`);
|
|
358
|
+
lines.push(` args: { ${writable.map((n) => `${n}: ${argOf(n, false)}`).join(", ")} },`);
|
|
359
|
+
lines.push(` handler: async (ctx, input) => {`);
|
|
360
|
+
lines.push(` const now = Date.now();`);
|
|
361
|
+
lines.push(` return ctx.db.insert(${e.name}, { ...input, ${e.owned ? "createdBy: ctx.auth.requirePrincipal().id, " : ""}createdAt: now, updatedAt: now });`);
|
|
362
|
+
lines.push(` },`);
|
|
363
|
+
lines.push(`});`);
|
|
364
|
+
lines.push(``);
|
|
365
|
+
// update
|
|
366
|
+
lines.push(`export const update = app.mutation({`);
|
|
367
|
+
lines.push(` access: ${JSON.stringify(`${e.name}.update`)},`);
|
|
368
|
+
lines.push(` args: { id: s.string()${writable.length ? ", " : ""}${writable.map((n) => `${n}: ${argOf(n, true)}`).join(", ")} },`);
|
|
369
|
+
lines.push(` handler: async (ctx, { id, ...changes }) => {`);
|
|
370
|
+
lines.push(` const record = await ctx.db.get(${e.name}, id);`);
|
|
371
|
+
lines.push(personal ? own : ` if (!record) fail("NOT_FOUND", ${JSON.stringify(`No such ${singular(e.name)}.`)});`);
|
|
372
|
+
if (e.owned && !personal)
|
|
373
|
+
lines.push(` if (!mayChange(ctx, record)) fail("FORBIDDEN", ${JSON.stringify(`Only the creator${managed ? ` or a ${managers.join("/")}` : ""} can change this ${singular(e.name)}.`)});`);
|
|
374
|
+
lines.push(` const patch = Object.fromEntries(Object.entries(changes).filter(([, v]) => v !== undefined));`);
|
|
375
|
+
lines.push(` await ctx.db.patch(${e.name}, id, { ...patch, updatedAt: Date.now() });`);
|
|
376
|
+
lines.push(` },`);
|
|
377
|
+
lines.push(`});`);
|
|
378
|
+
lines.push(``);
|
|
379
|
+
// remove
|
|
380
|
+
lines.push(`export const remove = app.mutation({`);
|
|
381
|
+
lines.push(` access: ${JSON.stringify(`${e.name}.delete`)},`);
|
|
382
|
+
lines.push(` args: { id: s.string() },`);
|
|
383
|
+
lines.push(` handler: async (ctx, { id }) => {`);
|
|
384
|
+
lines.push(` const record = await ctx.db.get(${e.name}, id);`);
|
|
385
|
+
lines.push(personal ? own : ` if (!record) fail("NOT_FOUND", ${JSON.stringify(`No such ${singular(e.name)}.`)});`);
|
|
386
|
+
if (e.owned && !personal)
|
|
387
|
+
lines.push(` if (!mayChange(ctx, record)) fail("FORBIDDEN", ${JSON.stringify(`Only the creator${managed ? ` or a ${managers.join("/")}` : ""} can remove this ${singular(e.name)}.`)});`);
|
|
388
|
+
if (e.attachments)
|
|
389
|
+
lines.push(` // Its files go with it: nothing is left behind that no record binds.`);
|
|
390
|
+
if (e.attachments)
|
|
391
|
+
lines.push(` for (const file of await ctx.services.files.list({ metadata: ${binding("id")} })) await ctx.services.files.remove(file.id);`);
|
|
392
|
+
lines.push(` await ctx.db.delete(${e.name}, id);`);
|
|
393
|
+
lines.push(` },`);
|
|
394
|
+
lines.push(`});`);
|
|
395
|
+
lines.push(``);
|
|
396
|
+
// The Files service needs a signed-in caller, so a public entity's files are read by its roles, not by anyone.
|
|
397
|
+
if (e.attachments)
|
|
398
|
+
lines.push(...renderAttachments(e, { readAccess: `${e.name}.read`, personal, own, managed, managers, binding }));
|
|
399
|
+
const module = lines.join("\n");
|
|
400
|
+
// The claim gate is the first line of every handler: before any record is read or written.
|
|
401
|
+
return e.requires ? module.replace(/^( handler: async \(ctx[^\n]*\n)/gm, `$1 app.requireClaim(ctx, ${JSON.stringify(e.requires.claim)}, ${JSON.stringify([...e.requires.values])});\n`) : module;
|
|
402
|
+
}
|
|
403
|
+
/**
|
|
404
|
+
* The attachment functions of an entity: files and download read the record first (the caller sees the record, or
|
|
405
|
+
* NOT_FOUND); attach, attachLink and detach change it (the record's own rule: ownership, scope). Every file carries the
|
|
406
|
+
* binding metadata; a file whose binding names another record does not exist for this one. The service's own permissions
|
|
407
|
+
* (files.read, files.write, files.delete) are checked by the runtime on top of the entity's.
|
|
408
|
+
*/
|
|
409
|
+
function renderAttachments(e, c) {
|
|
410
|
+
const one = singular(e.name);
|
|
411
|
+
const lines = [];
|
|
412
|
+
const seeRecord = [` const record = await ctx.db.get(${e.name}, id);`, c.personal ? c.own : ` if (!record) fail("NOT_FOUND", ${JSON.stringify(`No such ${one}.`)});`];
|
|
413
|
+
const changeRecord = [...seeRecord, ...(e.owned && !c.personal ? [` if (!mayChange(ctx, record)) fail("FORBIDDEN", ${JSON.stringify(`Only the creator${c.managed ? ` or a ${c.managers.join("/")}` : ""} can change this ${one}'s files.`)});`] : [])];
|
|
414
|
+
const bound = (what) => [
|
|
415
|
+
` const file = await ctx.services.files.get(fileId).catch(() => null);`,
|
|
416
|
+
` if (!file || file.metadata.entity !== ${JSON.stringify(e.name)} || file.metadata.recordId !== id) fail("NOT_FOUND", ${JSON.stringify(`No such file on this ${one}.`)});`,
|
|
417
|
+
...(what ? [what] : []),
|
|
418
|
+
];
|
|
419
|
+
lines.push(`/** Files attached to one ${one}, oldest first. Seeing them is seeing the ${one}. */`);
|
|
420
|
+
lines.push(`export const files = app.query({`);
|
|
421
|
+
lines.push(` access: ${JSON.stringify(c.readAccess)},`);
|
|
422
|
+
lines.push(` args: { id: s.string() },`);
|
|
423
|
+
lines.push(` handler: async (ctx, { id }) => {`);
|
|
424
|
+
lines.push(...seeRecord);
|
|
425
|
+
lines.push(` return ctx.services.files.list({ metadata: ${c.binding("id")} });`);
|
|
426
|
+
lines.push(` },`);
|
|
427
|
+
lines.push(`});`);
|
|
428
|
+
lines.push(``);
|
|
429
|
+
lines.push(`/** A short-lived download link for one attached file: the file must belong to this ${one}, which the caller must see. */`);
|
|
430
|
+
lines.push(`export const download = app.query({`);
|
|
431
|
+
lines.push(` access: ${JSON.stringify(c.readAccess)},`);
|
|
432
|
+
lines.push(` args: { id: s.string(), fileId: s.string() },`);
|
|
433
|
+
lines.push(` handler: async (ctx, { id, fileId }) => {`);
|
|
434
|
+
lines.push(...seeRecord);
|
|
435
|
+
lines.push(...bound(` return ctx.services.files.link(fileId);`));
|
|
436
|
+
lines.push(` },`);
|
|
437
|
+
lines.push(`});`);
|
|
438
|
+
lines.push(``);
|
|
439
|
+
lines.push(`/** Attach a text file to a ${one} (binary uploads: attachLink). Attaching is changing the ${one}: its rule applies. */`);
|
|
440
|
+
lines.push(`export const attach = app.mutation({`);
|
|
441
|
+
lines.push(` access: ${JSON.stringify(`${e.name}.update`)},`);
|
|
442
|
+
lines.push(` args: { id: s.string(), name: s.string({ maxLength: 200 }), contentType: s.optional(s.string({ maxLength: 100 })), content: s.string() },`);
|
|
443
|
+
lines.push(` handler: async (ctx, { id, name, contentType, content }) => {`);
|
|
444
|
+
lines.push(...changeRecord);
|
|
445
|
+
lines.push(` const file = await ctx.services.files.upload({ name, ...(contentType ? { contentType } : {}), content, metadata: ${c.binding("id")} });`);
|
|
446
|
+
lines.push(` await ctx.db.patch(${e.name}, id, { updatedAt: Date.now() });`);
|
|
447
|
+
lines.push(` return file.id;`);
|
|
448
|
+
lines.push(` },`);
|
|
449
|
+
lines.push(`});`);
|
|
450
|
+
lines.push(``);
|
|
451
|
+
lines.push(`/** A single-use upload link bound to this ${one}: the browser PUTs the bytes to its url; the file is created as the caller, bound to the ${one}. */`);
|
|
452
|
+
lines.push(`export const attachLink = app.mutation({`);
|
|
453
|
+
lines.push(` access: ${JSON.stringify(`${e.name}.update`)},`);
|
|
454
|
+
lines.push(` args: { id: s.string(), name: s.optional(s.string({ maxLength: 200 })), contentType: s.optional(s.string({ maxLength: 100 })) },`);
|
|
455
|
+
lines.push(` handler: async (ctx, { id, name, contentType }) => {`);
|
|
456
|
+
lines.push(...changeRecord);
|
|
457
|
+
lines.push(` return ctx.services.files.uploadLink({ ...(name ? { name } : {}), ...(contentType ? { contentType } : {}), metadata: ${c.binding("id")} });`);
|
|
458
|
+
lines.push(` },`);
|
|
459
|
+
lines.push(`});`);
|
|
460
|
+
lines.push(``);
|
|
461
|
+
lines.push(`/** Remove one attached file. Detaching is changing the ${one}: its rule applies. */`);
|
|
462
|
+
lines.push(`export const detach = app.mutation({`);
|
|
463
|
+
lines.push(` access: ${JSON.stringify(`${e.name}.update`)},`);
|
|
464
|
+
lines.push(` args: { id: s.string(), fileId: s.string() },`);
|
|
465
|
+
lines.push(` handler: async (ctx, { id, fileId }) => {`);
|
|
466
|
+
lines.push(...changeRecord);
|
|
467
|
+
lines.push(...bound(` await ctx.services.files.remove(fileId);`));
|
|
468
|
+
lines.push(` await ctx.db.patch(${e.name}, id, { updatedAt: Date.now() });`);
|
|
469
|
+
lines.push(` },`);
|
|
470
|
+
lines.push(`});`);
|
|
471
|
+
lines.push(``);
|
|
472
|
+
return lines;
|
|
473
|
+
}
|
|
474
|
+
/** feltkit/_generated/api.ts for the app module plus one module per entity (what `feltkit codegen` would write). */
|
|
475
|
+
export function renderApi(entityNames) {
|
|
476
|
+
const modules = ["app", ...entityNames];
|
|
477
|
+
return [
|
|
478
|
+
"/* Generated by `feltkit dev` / `feltkit codegen`. Do not edit; it is rewritten when feltkit/ changes. */",
|
|
479
|
+
"/* eslint-disable */",
|
|
480
|
+
'import { createApi } from "@feltdb/feltkit/client";',
|
|
481
|
+
...modules.map((m) => `import type * as ${m}_module from "../${m}.js";`),
|
|
482
|
+
"",
|
|
483
|
+
"/** Typed references to every query and mutation. Type-only imports: no backend code reaches the browser. */",
|
|
484
|
+
`export const api = createApi<{ ${modules.map((m) => `${JSON.stringify(m)}: typeof ${m}_module`).join("; ")} }>();`,
|
|
485
|
+
"",
|
|
486
|
+
].join("\n");
|
|
487
|
+
}
|
|
488
|
+
/** A sample value for a field, for the generated tests. */
|
|
489
|
+
function sample(f, n = 1) {
|
|
490
|
+
switch (f.type) {
|
|
491
|
+
case "string":
|
|
492
|
+
return JSON.stringify(`${f.name} ${n}`);
|
|
493
|
+
case "number":
|
|
494
|
+
return String(n);
|
|
495
|
+
case "boolean":
|
|
496
|
+
return "false";
|
|
497
|
+
case "enum":
|
|
498
|
+
return JSON.stringify(f.values[0]);
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* The permissions test, for both foundations: every function names its access (a permission, or "public" only on the
|
|
503
|
+
* read functions of an entity declared public); an anonymous caller is UNAUTHORIZED on every non-public function and a
|
|
504
|
+
* signed-in caller holding no permission is FORBIDDEN on every one; public reads work for an anonymous caller and
|
|
505
|
+
* public entities' writes still need their permission. Negative first: a test that only shows an allowed call is not proof.
|
|
506
|
+
*/
|
|
507
|
+
function renderPermissionsTest(entities, tenancy) {
|
|
508
|
+
const ordered = creationOrder(entities);
|
|
509
|
+
const publicReads = ordered.filter((e) => e.public).flatMap((e) => [`${e.name}:list`, `${e.name}:get`]);
|
|
510
|
+
const lines = [];
|
|
511
|
+
lines.push(`test("deny by default: every function names its access; an anonymous caller is refused everywhere${publicReads.length ? " but the public reads" : ""}; a signed-in caller with no permission is refused everywhere${tenancy === "none" ? "; no workspace exists" : ""}", async () => {`);
|
|
512
|
+
lines.push(` const t = await createTestApp();`);
|
|
513
|
+
lines.push(` try {`);
|
|
514
|
+
lines.push(` const publicReads: string[] = ${JSON.stringify(publicReads)};`);
|
|
515
|
+
lines.push(` for (const [name, fn] of t.runtime.project.functions) {`);
|
|
516
|
+
lines.push(` assert.notEqual(fn.access, "authenticated", \`\${name} names its permission\`);`);
|
|
517
|
+
lines.push(` assert.equal(fn.access === "public", publicReads.includes(name), \`\${name} is public only when declared so\`);`);
|
|
518
|
+
lines.push(` }`);
|
|
519
|
+
if (tenancy === "none")
|
|
520
|
+
lines.push(` assert.equal(t.tenancy, null, "no tenancy: nothing to join, nobody to invite");`);
|
|
521
|
+
lines.push(` // Anonymous: UNAUTHORIZED on every function that is not public; a public read answers (empty).`);
|
|
522
|
+
lines.push(` const nobody = { id: "nobody", type: "user" as const, roles: [] as string[] };`);
|
|
523
|
+
lines.push(` for (const [name, fn] of t.runtime.project.functions) {`);
|
|
524
|
+
lines.push(` const call = (who: typeof nobody | null) => t.runtime.call(name, name.endsWith(":list") ? {} : { id: "none" }, { principal: who, via: "test" });`);
|
|
525
|
+
lines.push(` const anonymous = await call(null);`);
|
|
526
|
+
lines.push(` if (fn.access === "public") assert.ok(anonymous.ok || anonymous.error.code === "NOT_FOUND", \`\${name} is public: an anonymous call is answered\`);`);
|
|
527
|
+
lines.push(` else assert.equal(anonymous.ok ? "allowed" : anonymous.error.code, "UNAUTHORIZED", \`\${name}: anonymous is refused\`);`);
|
|
528
|
+
lines.push(` // Signed in, holding no permission: FORBIDDEN on every function that needs one (public reads apart).`);
|
|
529
|
+
lines.push(` const none = await call(nobody);`);
|
|
530
|
+
lines.push(` if (fn.access !== "public") assert.equal(none.ok ? "allowed" : none.error.code, "FORBIDDEN", \`\${name}: a signed-in caller with no permission is refused\`);`);
|
|
531
|
+
lines.push(` }`);
|
|
532
|
+
lines.push(` } finally {`);
|
|
533
|
+
lines.push(` await t.close();`);
|
|
534
|
+
lines.push(` }`);
|
|
535
|
+
lines.push(`});`);
|
|
536
|
+
lines.push(``);
|
|
537
|
+
return lines;
|
|
538
|
+
}
|
|
539
|
+
/**
|
|
540
|
+
* What a member without a configured claim meets at a gate: no value (CLAIM_UNAVAILABLE), the declaration's default outside
|
|
541
|
+
* the allowed values (CLAIM_NOT_ALLOWED), or a default the gate accepts (null: there is no refusal to show).
|
|
542
|
+
*/
|
|
543
|
+
function gateRefusal(gate, claims) {
|
|
544
|
+
const spec = claims?.[gate.claim];
|
|
545
|
+
if (!spec || spec.default === undefined)
|
|
546
|
+
return "CLAIM_UNAVAILABLE";
|
|
547
|
+
return gate.values.includes(spec.default) ? null : "CLAIM_NOT_ALLOWED";
|
|
548
|
+
}
|
|
549
|
+
/**
|
|
550
|
+
* tests/domain.test.ts: for every entity, the permissions, isolation, ownership, uniqueness and
|
|
551
|
+
* references the composition claims, driven through the real runtime. Application-owned once written.
|
|
552
|
+
*/
|
|
553
|
+
export function renderDomainTests(entities, context) {
|
|
554
|
+
if (context.tenancy === "individuals")
|
|
555
|
+
return renderIndividualDomainTests(entities, context);
|
|
556
|
+
const ordered = creationOrder(entities);
|
|
557
|
+
const top = context.roles[0];
|
|
558
|
+
const reader = context.roles.length > 1 ? context.roles[context.roles.length - 1] : null;
|
|
559
|
+
// The manager the test exercises: a declared one when there is one, so the declared role is covered; otherwise the
|
|
560
|
+
// top role, which manages by itself. `context.managers` is `managingRoles(...)`, the set the modules enforce.
|
|
561
|
+
const manager = context.managers.find((r) => r !== top) ?? context.managers[0] ?? null;
|
|
562
|
+
const lines = [];
|
|
563
|
+
lines.push(`/**`);
|
|
564
|
+
lines.push(` * The domain the composition declared, as executable guarantees: every function names its permission; a`);
|
|
565
|
+
lines.push(` * reader role reads and cannot write; workspace data is invisible from another ${context.noun}; owned records`);
|
|
566
|
+
lines.push(` * change only through their creator${manager ? ` or a ${manager}` : ""}; unique constraints and references are`);
|
|
567
|
+
lines.push(` * enforced by FeltDB. Composed by \`feltkit create\`; add your own tests beside it. Run with \`npm test\`.`);
|
|
568
|
+
lines.push(` */`);
|
|
569
|
+
lines.push(`import { test } from "node:test";`);
|
|
570
|
+
lines.push(`import assert from "node:assert/strict";`);
|
|
571
|
+
lines.push(`import { createTestApp, type TestApp } from "@feltdb/feltkit/testing";`);
|
|
572
|
+
lines.push(`import { api } from "../feltkit/_generated/api.js";`);
|
|
573
|
+
lines.push(``);
|
|
574
|
+
lines.push(`type Who = { id: string; type: "user"; displayName?: string; roles: string[] };`);
|
|
575
|
+
lines.push(`const person = (id: string): Who => ({ id, type: "user", displayName: id, roles: [] });`);
|
|
576
|
+
lines.push(``);
|
|
577
|
+
lines.push(`/** A ${context.noun} created by \`creator\` (its ${top}); the other members join the way people do, by accepting an invitation. */`);
|
|
578
|
+
lines.push(`async function workspace(t: TestApp, name: string, creator: Who, members: Array<[Who, string]> = []) {`);
|
|
579
|
+
if (context.create === "none")
|
|
580
|
+
lines.push(` // This application does not create ${context.noun}s (create: "none"): they are provisioned outside it. The test harness provisions one the same way.`);
|
|
581
|
+
lines.push(context.create === "none" ? ` const tenant = await t.provisionTenant(name, { ...creator, email: \`\${creator.id}@example.com\` });` : ` const tenant = await t.tenancy!.create(name, { ...creator, email: \`\${creator.id}@example.com\` });`);
|
|
582
|
+
lines.push(` const actor = { ...(await t.tenancy!.context(tenant.id, creator.id))!, principalId: creator.id, displayName: creator.id };`);
|
|
583
|
+
lines.push(` for (const [who, role] of members) {`);
|
|
584
|
+
lines.push(` const { token } = await t.tenancy!.invite(actor, { email: \`\${who.id}@example.com\`, role });`);
|
|
585
|
+
lines.push(` await t.tenancy!.accept(token, { ...who, email: \`\${who.id}@example.com\`, emailVerified: true });`);
|
|
586
|
+
lines.push(` }`);
|
|
587
|
+
lines.push(` return tenant.id;`);
|
|
588
|
+
lines.push(`}`);
|
|
589
|
+
if (ordered.some((e) => e.requires)) {
|
|
590
|
+
lines.push(``);
|
|
591
|
+
lines.push(`/** Set members' claims the way the application does: through the server, by a member who manages members (the creator here). */`);
|
|
592
|
+
lines.push(`async function setClaims(t: TestApp, ws: string, manager: string, members: readonly string[], claims: Record<string, unknown>) {`);
|
|
593
|
+
lines.push(` const actor = { ...(await t.tenancy!.context(ws, manager))!, principalId: manager };`);
|
|
594
|
+
lines.push(` for (const who of members) await t.tenancy!.setClaims(actor, who, claims);`);
|
|
595
|
+
lines.push(`}`);
|
|
596
|
+
}
|
|
597
|
+
lines.push(``);
|
|
598
|
+
const sampleArgs = (e, n, refs) => {
|
|
599
|
+
const parts = e.fields.map((f) => `${f.name}: ${sample(f, n)}`);
|
|
600
|
+
for (const r of e.relations)
|
|
601
|
+
parts.push(`${r.field}: ${refs}[${JSON.stringify(r.target)}]`);
|
|
602
|
+
return `{ ${parts.join(", ")} }`;
|
|
603
|
+
};
|
|
604
|
+
lines.push(...renderPermissionsTest(entities, "ws"));
|
|
605
|
+
for (const e of ordered) {
|
|
606
|
+
const deps = creationOrder(entities).filter((d) => d.name !== e.name && e.relations.some((r) => r.target === d.name));
|
|
607
|
+
const workspaceScoped = e.scope === "workspace";
|
|
608
|
+
lines.push(`test(${JSON.stringify(`${e.name}: create, list, get, update, remove${reader ? `; a ${reader} reads but cannot write` : ""}${workspaceScoped ? `; another ${context.noun} sees nothing` : ""}${e.owned ? `; owned by the creator${manager && workspaceScoped ? ` (a ${manager} may change)` : ""}` : ""}${e.unique.length ? "; unique" : ""}${e.relations.length ? "; references enforced" : ""}`)}, async () => {`);
|
|
609
|
+
lines.push(` const t = await createTestApp();`);
|
|
610
|
+
lines.push(` try {`);
|
|
611
|
+
lines.push(` const ada = person("ada");`);
|
|
612
|
+
lines.push(` const bob = person("bob");`);
|
|
613
|
+
lines.push(` const eve = person("eve");`);
|
|
614
|
+
if (workspaceScoped) {
|
|
615
|
+
lines.push(` const ws = await workspace(t, "acme", ada, [[bob, ${JSON.stringify(manager ?? (context.roles[1] ?? top))}]${reader ? `, [eve, ${JSON.stringify(reader)}]` : ""}]);`);
|
|
616
|
+
lines.push(` const other = await workspace(t, "other", person("zed"));`);
|
|
617
|
+
lines.push(` const asAda = t.as(ada, { tenant: ws });`);
|
|
618
|
+
lines.push(` const asBob = t.as(bob, { tenant: ws });`);
|
|
619
|
+
if (reader)
|
|
620
|
+
lines.push(` const asEve = t.as(eve, { tenant: ws });`);
|
|
621
|
+
lines.push(` const asZed = t.as(person("zed"), { tenant: other });`);
|
|
622
|
+
}
|
|
623
|
+
else {
|
|
624
|
+
// Shared: roles come from the principal's own roles.
|
|
625
|
+
lines.push(` const asAda = t.as({ ...ada, roles: [${JSON.stringify(top)}] });`);
|
|
626
|
+
lines.push(` const asBob = t.as({ ...bob, roles: [${JSON.stringify(manager ?? top)}] });`);
|
|
627
|
+
if (reader)
|
|
628
|
+
lines.push(` const asEve = t.as({ ...eve, roles: [${JSON.stringify(reader)}] });`);
|
|
629
|
+
}
|
|
630
|
+
// Referenced records first.
|
|
631
|
+
lines.push(` const refs: Record<string, string> = {};`);
|
|
632
|
+
for (const d of deps) {
|
|
633
|
+
if (d.requires)
|
|
634
|
+
lines.push(` await setClaims(t, ws, "ada", ["ada"], { ${JSON.stringify(d.requires.claim)}: ${JSON.stringify(d.requires.values[0])} });`);
|
|
635
|
+
lines.push(` refs[${JSON.stringify(d.name)}] = await asAda.mutation(api.${d.name}.create, ${sampleArgs(d, 9, "refs")});`);
|
|
636
|
+
}
|
|
637
|
+
if (e.requires && workspaceScoped) {
|
|
638
|
+
const gate = e.requires;
|
|
639
|
+
const allowed = JSON.stringify(gate.values[0]);
|
|
640
|
+
const refusal = gateRefusal(gate, context.claims);
|
|
641
|
+
if (refusal) {
|
|
642
|
+
lines.push(` // Claim gate (${gate.claim} = ${gate.values.map((v) => JSON.stringify(v)).join(" | ")}): the ${top}, holding every permission, is refused until the membership carries an allowed value${refusal === "CLAIM_NOT_ALLOWED" ? " (the declaration's default is not one)" : ""}.`);
|
|
643
|
+
lines.push(` await assert.rejects(asAda.mutation(api.${e.name}.create, ${sampleArgs(e, 1, "refs")}), (error: { code: string; hint?: string }) => error.code === "FORBIDDEN" && error.hint === ${JSON.stringify(refusal)});`);
|
|
644
|
+
lines.push(` await assert.rejects(asAda.query(api.${e.name}.list, {}), { code: "FORBIDDEN" }, "reads are gated too");`);
|
|
645
|
+
}
|
|
646
|
+
else {
|
|
647
|
+
lines.push(` // Claim gate (${gate.claim} = ${gate.values.map((v) => JSON.stringify(v)).join(" | ")}): the declaration's default already satisfies it, so a member passes without configuration.`);
|
|
648
|
+
}
|
|
649
|
+
lines.push(` // A claim is never a request field: a claim sent as an argument is refused as an unknown argument, and satisfies nothing.`);
|
|
650
|
+
lines.push(` await assert.rejects(asAda.query(api.${e.name}.list, { ${gate.claim}: ${allowed} } as never), (error: { code: string }) => error.code === "INVALID_ARGUMENT" || error.code === "FORBIDDEN");`);
|
|
651
|
+
lines.push(` await setClaims(t, ws, "ada", [${["ada", "bob", ...(reader ? ["eve"] : [])].map((w) => JSON.stringify(w)).join(", ")}], { ${JSON.stringify(gate.claim)}: ${allowed} });`);
|
|
652
|
+
lines.push(` await setClaims(t, other, "zed", ["zed"], { ${JSON.stringify(gate.claim)}: ${allowed} });`);
|
|
653
|
+
}
|
|
654
|
+
lines.push(` const id = await asAda.mutation(api.${e.name}.create, ${sampleArgs(e, 1, "refs")});`);
|
|
655
|
+
lines.push(` assert.ok(typeof id === "string" && id, "create returns the id");`);
|
|
656
|
+
lines.push(` const listed = await asAda.query(api.${e.name}.list, {});`);
|
|
657
|
+
lines.push(` assert.equal(listed.length, 1);`);
|
|
658
|
+
lines.push(` const got = await asAda.query(api.${e.name}.get, { id });`);
|
|
659
|
+
if (e.fields.length)
|
|
660
|
+
lines.push(` assert.equal(got.${e.fields[0].name}, ${sample(e.fields[0], 1)});`);
|
|
661
|
+
if (e.owned)
|
|
662
|
+
lines.push(` assert.equal(got.createdBy, "ada", "the creator is stamped");`);
|
|
663
|
+
if (e.unique.length) {
|
|
664
|
+
const group = e.unique[0];
|
|
665
|
+
// Right after creation, before any update: a second record repeating the unique values is refused at commit.
|
|
666
|
+
const dupArgs = (n) => {
|
|
667
|
+
const parts = e.fields.map((f) => `${f.name}: ${group.includes(f.name) ? sample(f, 1) : sample(f, n)}`);
|
|
668
|
+
for (const r of e.relations)
|
|
669
|
+
parts.push(`${r.field}: refs[${JSON.stringify(r.target)}]`);
|
|
670
|
+
return `{ ${parts.join(", ")} }`;
|
|
671
|
+
};
|
|
672
|
+
lines.push(` // Unique (${group.join(", ")}): a second record with the same value is refused at commit.`);
|
|
673
|
+
lines.push(` await assert.rejects(asAda.mutation(api.${e.name}.create, ${dupArgs(6)}), { code: "CONFLICT" });`);
|
|
674
|
+
}
|
|
675
|
+
if (workspaceScoped)
|
|
676
|
+
lines.push(` assert.equal((got as { tenantId?: string }).tenantId, ws, "the record belongs to the ${context.noun}");`);
|
|
677
|
+
if (e.fields.length) {
|
|
678
|
+
lines.push(` await asAda.mutation(api.${e.name}.update, { id, ${e.fields[0].name}: ${sample(e.fields[0], 2)} });`);
|
|
679
|
+
lines.push(` assert.equal((await asAda.query(api.${e.name}.get, { id })).${e.fields[0].name}, ${sample(e.fields[0], 2)});`);
|
|
680
|
+
}
|
|
681
|
+
if (reader) {
|
|
682
|
+
lines.push(` // A ${reader} reads, and is refused every write.`);
|
|
683
|
+
lines.push(` assert.equal((await asEve.query(api.${e.name}.list, {})).length, 1);`);
|
|
684
|
+
lines.push(` await assert.rejects(asEve.mutation(api.${e.name}.create, ${sampleArgs(e, 3, "refs")}), { code: "FORBIDDEN" });`);
|
|
685
|
+
lines.push(` await assert.rejects(asEve.mutation(api.${e.name}.remove, { id }), { code: "FORBIDDEN" });`);
|
|
686
|
+
}
|
|
687
|
+
if (workspaceScoped) {
|
|
688
|
+
lines.push(` // Another ${context.noun}: the record does not exist there.`);
|
|
689
|
+
lines.push(` assert.equal((await asZed.query(api.${e.name}.list, {})).length, 0);`);
|
|
690
|
+
lines.push(` await assert.rejects(asZed.query(api.${e.name}.get, { id }), { code: "NOT_FOUND" });`);
|
|
691
|
+
}
|
|
692
|
+
if (e.owned) {
|
|
693
|
+
if (workspaceScoped && manager) {
|
|
694
|
+
lines.push(` // Owned: bob (a ${manager}) may change ada's record; a non-manager member may not change bob's.`);
|
|
695
|
+
lines.push(` await asBob.mutation(api.${e.name}.update, { id${e.fields.length ? `, ${e.fields[0].name}: ${sample(e.fields[0], 4)}` : ""} });`);
|
|
696
|
+
lines.push(` const bobs = await asBob.mutation(api.${e.name}.create, ${sampleArgs(e, 5, "refs")});`);
|
|
697
|
+
if (reader) {
|
|
698
|
+
// eve is a reader: cannot write at all; use a plain member if one exists between manager and reader
|
|
699
|
+
const member = context.roles.find((r) => r !== top && !context.managers.includes(r) && r !== reader);
|
|
700
|
+
if (member) {
|
|
701
|
+
lines.push(` const cal = person("cal");`);
|
|
702
|
+
lines.push(` {`);
|
|
703
|
+
lines.push(` const actor = { ...(await t.tenancy!.context(ws, "ada"))!, principalId: "ada", displayName: "ada" };`);
|
|
704
|
+
lines.push(` const { token } = await t.tenancy!.invite(actor, { email: "cal@example.com", role: ${JSON.stringify(member)} });`);
|
|
705
|
+
lines.push(` await t.tenancy!.accept(token, { ...cal, email: "cal@example.com", emailVerified: true });`);
|
|
706
|
+
lines.push(` }`);
|
|
707
|
+
lines.push(` await assert.rejects(t.as(cal, { tenant: ws }).mutation(api.${e.name}.remove, { id: bobs }), { code: "FORBIDDEN" }, "a ${member} is not the creator and not a manager");`);
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
lines.push(` await asAda.mutation(api.${e.name}.remove, { id: bobs });`);
|
|
711
|
+
}
|
|
712
|
+
else {
|
|
713
|
+
lines.push(` // Owned: only the creator changes it.`);
|
|
714
|
+
lines.push(` await assert.rejects(asBob.mutation(api.${e.name}.update, { id${e.fields.length ? `, ${e.fields[0].name}: ${sample(e.fields[0], 4)}` : ""} }), { code: "FORBIDDEN" });`);
|
|
715
|
+
}
|
|
716
|
+
}
|
|
717
|
+
if (e.relations.length) {
|
|
718
|
+
const r = e.relations[0];
|
|
719
|
+
lines.push(` // References: a value naming no ${singular(r.target)} is refused.`);
|
|
720
|
+
lines.push(` await assert.rejects(asAda.mutation(api.${e.name}.create, { ${[...e.fields.map((f) => `${f.name}: ${sample(f, 7)}`), ...e.relations.map((x) => `${x.field}: ${x.field === r.field ? '"no-such-record"' : `refs[${JSON.stringify(x.target)}]`}`)].join(", ")} }));`);
|
|
721
|
+
}
|
|
722
|
+
lines.push(` await asAda.mutation(api.${e.name}.remove, { id });`);
|
|
723
|
+
lines.push(` assert.equal((await asAda.query(api.${e.name}.list, {})).length, 0);`);
|
|
724
|
+
lines.push(` } finally {`);
|
|
725
|
+
lines.push(` await t.close();`);
|
|
726
|
+
lines.push(` }`);
|
|
727
|
+
lines.push(`});`);
|
|
728
|
+
lines.push(``);
|
|
729
|
+
}
|
|
730
|
+
return lines.join("\n");
|
|
731
|
+
}
|
|
732
|
+
/**
|
|
733
|
+
* tests/domain.test.ts for the individual-accounts foundation: no workspace exists; people are accounts holding
|
|
734
|
+
* the base role (and, when granted, an application role). A personal entity is invisible to everyone but its
|
|
735
|
+
* creator, whatever their role; a shared entity is read by everyone with the permission and changed by its
|
|
736
|
+
* creator or a manager; permissions, uniqueness and references as with workspaces.
|
|
737
|
+
*/
|
|
738
|
+
function renderIndividualDomainTests(entities, context) {
|
|
739
|
+
const ordered = creationOrder(entities);
|
|
740
|
+
const base = context.baseRole ?? "person";
|
|
741
|
+
const manager = context.managers[0] ?? null;
|
|
742
|
+
const lines = [];
|
|
743
|
+
lines.push(`/**`);
|
|
744
|
+
lines.push(` * The domain the composition declared, as executable guarantees: every function names its permission; a`);
|
|
745
|
+
lines.push(` * personal record is seen and changed only by its creator (another ${base}${manager ? `, even a ${manager},` : ""} finds nothing);`);
|
|
746
|
+
lines.push(` * a shared record is read by every ${base} and changed by its creator${manager ? ` or a ${manager}` : ""}; unique constraints and`);
|
|
747
|
+
lines.push(` * references are enforced by FeltDB. No workspace exists. Composed by \`feltkit create\`; add your own tests beside it.`);
|
|
748
|
+
lines.push(` */`);
|
|
749
|
+
lines.push(`import { test } from "node:test";`);
|
|
750
|
+
lines.push(`import assert from "node:assert/strict";`);
|
|
751
|
+
lines.push(`import { createTestApp } from "@feltdb/feltkit/testing";`);
|
|
752
|
+
lines.push(`import { api } from "../feltkit/_generated/api.js";`);
|
|
753
|
+
lines.push(``);
|
|
754
|
+
lines.push(`type Who = { id: string; type: "user"; displayName?: string; roles: string[] };`);
|
|
755
|
+
lines.push(`/** An account holding the base role ${JSON.stringify(base)}, and optionally an application role it was granted (accounts.setRoles). */`);
|
|
756
|
+
lines.push(`const person = (id: string, ...roles: string[]): Who => ({ id, type: "user", displayName: id, roles: [${JSON.stringify(base)}, ...roles] });`);
|
|
757
|
+
lines.push(``);
|
|
758
|
+
const sampleArgs = (e, n, refs) => {
|
|
759
|
+
const parts = e.fields.map((f) => `${f.name}: ${sample(f, n)}`);
|
|
760
|
+
for (const r of e.relations)
|
|
761
|
+
parts.push(`${r.field}: ${refs}[${JSON.stringify(r.target)}]`);
|
|
762
|
+
return `{ ${parts.join(", ")} }`;
|
|
763
|
+
};
|
|
764
|
+
lines.push(...renderPermissionsTest(entities, "none"));
|
|
765
|
+
for (const e of ordered) {
|
|
766
|
+
const deps = ordered.filter((d) => d.name !== e.name && e.relations.some((r) => r.target === d.name));
|
|
767
|
+
const personal = e.scope === "personal";
|
|
768
|
+
lines.push(`test(${JSON.stringify(`${e.name}: create, list, get, update, remove${personal ? `; another ${base}${manager ? ` or a ${manager}` : ""} sees nothing` : `; every ${base} reads${e.owned ? `; only the creator${manager ? ` or a ${manager}` : ""} changes` : manager ? `; only a ${manager} writes` : ""}`}${e.unique.length ? "; unique" : ""}${e.relations.length ? "; references enforced" : ""}`)}, async () => {`);
|
|
769
|
+
lines.push(` const t = await createTestApp();`);
|
|
770
|
+
lines.push(` try {`);
|
|
771
|
+
lines.push(` const ada = person("ada"${!personal && !e.owned && manager ? `, ${JSON.stringify(manager)}` : ""});`);
|
|
772
|
+
lines.push(` const bob = person("bob");`);
|
|
773
|
+
if (manager)
|
|
774
|
+
lines.push(` const meg = person("meg", ${JSON.stringify(manager)});`);
|
|
775
|
+
lines.push(` const asAda = t.as(ada);`);
|
|
776
|
+
lines.push(` const asBob = t.as(bob);`);
|
|
777
|
+
if (manager)
|
|
778
|
+
lines.push(` const asMeg = t.as(meg);`);
|
|
779
|
+
lines.push(` const refs: Record<string, string> = {};`);
|
|
780
|
+
// Referenced records first, by whoever may create them (a shared record nobody owns is the manager's to write).
|
|
781
|
+
for (const d of deps)
|
|
782
|
+
lines.push(` refs[${JSON.stringify(d.name)}] = await ${!d.owned && d.scope === "shared" && manager ? "asMeg" : "asAda"}.mutation(api.${d.name}.create, ${sampleArgs(d, 9, "refs")});`);
|
|
783
|
+
lines.push(` const id = await asAda.mutation(api.${e.name}.create, ${sampleArgs(e, 1, "refs")});`);
|
|
784
|
+
lines.push(` assert.ok(typeof id === "string" && id, "create returns the id");`);
|
|
785
|
+
lines.push(` assert.equal((await asAda.query(api.${e.name}.list, {})).length, 1);`);
|
|
786
|
+
lines.push(` const got = await asAda.query(api.${e.name}.get, { id });`);
|
|
787
|
+
if (e.fields.length)
|
|
788
|
+
lines.push(` assert.equal(got.${e.fields[0].name}, ${sample(e.fields[0], 1)});`);
|
|
789
|
+
if (e.owned)
|
|
790
|
+
lines.push(` assert.equal(got.createdBy, "ada", "the creator is stamped");`);
|
|
791
|
+
lines.push(` assert.equal((got as { tenantId?: string }).tenantId, undefined, "no workspace id: the record belongs to no tenant");`);
|
|
792
|
+
if (e.unique.length) {
|
|
793
|
+
const group = e.unique[0];
|
|
794
|
+
const dupArgs = (n) => {
|
|
795
|
+
const parts = e.fields.map((f) => `${f.name}: ${group.includes(f.name) ? sample(f, 1) : sample(f, n)}`);
|
|
796
|
+
for (const r of e.relations)
|
|
797
|
+
parts.push(`${r.field}: refs[${JSON.stringify(r.target)}]`);
|
|
798
|
+
return `{ ${parts.join(", ")} }`;
|
|
799
|
+
};
|
|
800
|
+
lines.push(` // Unique (${group.join(", ")}): a second record with the same value is refused at commit.`);
|
|
801
|
+
lines.push(` await assert.rejects(asAda.mutation(api.${e.name}.create, ${dupArgs(6)}), { code: "CONFLICT" });`);
|
|
802
|
+
}
|
|
803
|
+
if (e.fields.length) {
|
|
804
|
+
lines.push(` await asAda.mutation(api.${e.name}.update, { id, ${e.fields[0].name}: ${sample(e.fields[0], 2)} });`);
|
|
805
|
+
lines.push(` assert.equal((await asAda.query(api.${e.name}.get, { id })).${e.fields[0].name}, ${sample(e.fields[0], 2)});`);
|
|
806
|
+
}
|
|
807
|
+
if (personal) {
|
|
808
|
+
lines.push(` // Personal: for bob${manager ? ` and for meg (a ${manager})` : ""} ada's record does not exist.`);
|
|
809
|
+
lines.push(` assert.equal((await asBob.query(api.${e.name}.list, {})).length, 0);`);
|
|
810
|
+
lines.push(` await assert.rejects(asBob.query(api.${e.name}.get, { id }), { code: "NOT_FOUND" });`);
|
|
811
|
+
lines.push(` await assert.rejects(asBob.mutation(api.${e.name}.update, { id${e.fields.length ? `, ${e.fields[0].name}: ${sample(e.fields[0], 4)}` : ""} }), { code: "NOT_FOUND" });`);
|
|
812
|
+
lines.push(` await assert.rejects(asBob.mutation(api.${e.name}.remove, { id }), { code: "NOT_FOUND" });`);
|
|
813
|
+
if (manager)
|
|
814
|
+
lines.push(` await assert.rejects(asMeg.query(api.${e.name}.get, { id }), { code: "NOT_FOUND" });`);
|
|
815
|
+
lines.push(` // bob's own records are his: one each, invisible to the other.`);
|
|
816
|
+
lines.push(` const bobs = await asBob.mutation(api.${e.name}.create, ${sampleArgs(e, 5, "refs")});`);
|
|
817
|
+
lines.push(` assert.equal((await asBob.query(api.${e.name}.list, {})).length, 1);`);
|
|
818
|
+
lines.push(` assert.equal((await asAda.query(api.${e.name}.list, {})).length, 1);`);
|
|
819
|
+
lines.push(` await asBob.mutation(api.${e.name}.remove, { id: bobs });`);
|
|
820
|
+
}
|
|
821
|
+
else {
|
|
822
|
+
lines.push(` // Shared: bob reads it too.`);
|
|
823
|
+
lines.push(` assert.equal((await asBob.query(api.${e.name}.list, {})).length, 1);`);
|
|
824
|
+
lines.push(` assert.equal((await asBob.query(api.${e.name}.get, { id })).id, id);`);
|
|
825
|
+
if (e.owned) {
|
|
826
|
+
lines.push(` // Owned: bob is not the creator${manager ? ` and not a ${manager}` : ""}.`);
|
|
827
|
+
lines.push(` await assert.rejects(asBob.mutation(api.${e.name}.update, { id${e.fields.length ? `, ${e.fields[0].name}: ${sample(e.fields[0], 4)}` : ""} }), { code: "FORBIDDEN" });`);
|
|
828
|
+
lines.push(` await assert.rejects(asBob.mutation(api.${e.name}.remove, { id }), { code: "FORBIDDEN" });`);
|
|
829
|
+
if (manager) {
|
|
830
|
+
lines.push(` // A ${manager} may change anyone's.`);
|
|
831
|
+
lines.push(` await asMeg.mutation(api.${e.name}.update, { id${e.fields.length ? `, ${e.fields[0].name}: ${sample(e.fields[0], 4)}` : ""} });`);
|
|
832
|
+
}
|
|
833
|
+
}
|
|
834
|
+
else if (manager) {
|
|
835
|
+
lines.push(` // Not owned: a ${base} reads; writing is the ${manager}'s.`);
|
|
836
|
+
lines.push(` await assert.rejects(asBob.mutation(api.${e.name}.create, ${sampleArgs(e, 3, "refs")}), { code: "FORBIDDEN" });`);
|
|
837
|
+
lines.push(` await assert.rejects(asBob.mutation(api.${e.name}.remove, { id }), { code: "FORBIDDEN" });`);
|
|
838
|
+
}
|
|
839
|
+
}
|
|
840
|
+
if (e.relations.length) {
|
|
841
|
+
const r = e.relations[0];
|
|
842
|
+
lines.push(` // References: a value naming no ${singular(r.target)} is refused.`);
|
|
843
|
+
lines.push(` await assert.rejects(asAda.mutation(api.${e.name}.create, { ${[...e.fields.map((f) => `${f.name}: ${sample(f, 7)}`), ...e.relations.map((x) => `${x.field}: ${x.field === r.field ? '"no-such-record"' : `refs[${JSON.stringify(x.target)}]`}`)].join(", ")} }));`);
|
|
844
|
+
}
|
|
845
|
+
lines.push(` await asAda.mutation(api.${e.name}.remove, { id });`);
|
|
846
|
+
lines.push(` assert.equal((await asAda.query(api.${e.name}.list, {})).length, 0);`);
|
|
847
|
+
lines.push(` } finally {`);
|
|
848
|
+
lines.push(` await t.close();`);
|
|
849
|
+
lines.push(` }`);
|
|
850
|
+
lines.push(`});`);
|
|
851
|
+
lines.push(``);
|
|
852
|
+
}
|
|
853
|
+
return lines.join("\n");
|
|
854
|
+
}
|
|
855
|
+
/**
|
|
856
|
+
* tests/foundation.test.ts, from the composition itself: what the accounts and workspace selections
|
|
857
|
+
* guarantee (open or closed sign-up, who may create a workspace, the declared roles), as executable
|
|
858
|
+
* checks against the real runtime. Application-owned once written.
|
|
859
|
+
*/
|
|
860
|
+
export function renderFoundationTests(c) {
|
|
861
|
+
if (c.tenancy === "individuals")
|
|
862
|
+
return renderIndividualFoundationTests(c);
|
|
863
|
+
const lines = [];
|
|
864
|
+
lines.push(`/**`);
|
|
865
|
+
lines.push(` * The composed foundation, as executable guarantees: ${c.signUp ? "anyone may sign up" : "sign-up is closed (people are invited)"}, ${c.create === "anyone" ? `any signed-in account may create a ${c.noun}` : `${c.noun}s are not created through the application`},`);
|
|
866
|
+
lines.push(` * and every declared ${c.noun} role is a role of the application. Composed by \`feltkit create\`; add your own tests beside this one. Run with \`npm test\`.`);
|
|
867
|
+
lines.push(` */`);
|
|
868
|
+
lines.push(`import { test } from "node:test";`);
|
|
869
|
+
lines.push(`import assert from "node:assert/strict";`);
|
|
870
|
+
lines.push(`import { createTestApp } from "@feltdb/feltkit/testing";`);
|
|
871
|
+
lines.push(``);
|
|
872
|
+
lines.push(`test("the foundation: accounts (${c.signUp ? "open" : "invitation-only"} sign-up), ${c.noun}s (${c.create === "anyone" ? "created by members" : "not created through the application"}), and the declared roles", async () => {`);
|
|
873
|
+
lines.push(` const t = await createTestApp();`);
|
|
874
|
+
lines.push(` try {`);
|
|
875
|
+
lines.push(` const runtime = t.runtime;`);
|
|
876
|
+
lines.push(` assert.ok(runtime.accounts, "accounts are part of the foundation");`);
|
|
877
|
+
if (c.signUp) {
|
|
878
|
+
lines.push(` const created = await runtime.accounts!.signUp({ email: "owner@example.com", password: "a-long-password-1", name: "Owner" });`);
|
|
879
|
+
lines.push(` await runtime.accounts!.markVerified(created.id);`);
|
|
880
|
+
lines.push(` assert.ok((await runtime.accounts!.signIn({ email: "owner@example.com", password: "a-long-password-1" })).id, "a person signs up and signs in");`);
|
|
881
|
+
}
|
|
882
|
+
else {
|
|
883
|
+
lines.push(` await assert.rejects(runtime.accounts!.signUp({ email: "stranger@example.com", password: "a-long-password-1", name: "Stranger" }), { code: "FORBIDDEN" }, "sign-up is closed: people join by invitation");`);
|
|
884
|
+
}
|
|
885
|
+
lines.push(` assert.ok(t.tenancy, "${c.noun}s are part of the foundation");`);
|
|
886
|
+
lines.push(` const options = runtime.project.app.options as unknown as { roles: Record<string, string[]>; auth: { accounts: { magicLink?: boolean; signUp?: boolean }; tenant: { roles: string[]; create?: string } } };`);
|
|
887
|
+
lines.push(` assert.deepEqual(options.auth.tenant.roles, ${JSON.stringify([...c.roles])}, "the declared ${c.noun} roles");`);
|
|
888
|
+
lines.push(` for (const role of options.auth.tenant.roles) assert.ok(role in options.roles, \`role \${role} is declared\`);`);
|
|
889
|
+
lines.push(` assert.equal(options.auth.accounts.magicLink ?? false, ${c.magicLink}, "sign-in links ${c.magicLink ? "on" : "off"}");`);
|
|
890
|
+
lines.push(` assert.equal(options.auth.accounts.signUp ?? true, ${c.signUp}, "sign-up ${c.signUp ? "open" : "closed"}");`);
|
|
891
|
+
if (c.create === "anyone") {
|
|
892
|
+
lines.push(` const ws = await t.tenancy!.create("acme", { id: "ada", type: "user", roles: [], email: "ada@example.com" });`);
|
|
893
|
+
lines.push(` assert.equal((await t.tenancy!.context(ws.id, "ada"))?.role, ${JSON.stringify(c.roles[0])}, "the creator holds the top role");`);
|
|
894
|
+
}
|
|
895
|
+
else {
|
|
896
|
+
lines.push(` assert.equal(options.auth.tenant.create, "none", "${c.noun}s are not created through the application");`);
|
|
897
|
+
}
|
|
898
|
+
lines.push(` } finally {`);
|
|
899
|
+
lines.push(` await t.close();`);
|
|
900
|
+
lines.push(` }`);
|
|
901
|
+
lines.push(`});`);
|
|
902
|
+
lines.push(``);
|
|
903
|
+
return lines.join("\n");
|
|
904
|
+
}
|
|
905
|
+
/**
|
|
906
|
+
* tests/foundation.test.ts for the individual-accounts foundation: accounts exist and sign-up is open; there is
|
|
907
|
+
* no tenancy, no membership and no invitation; every account holds the base role and nothing else until an
|
|
908
|
+
* operator grants it an application role, which its sessions then carry.
|
|
909
|
+
*/
|
|
910
|
+
function renderIndividualFoundationTests(c) {
|
|
911
|
+
const base = c.baseRole ?? "person";
|
|
912
|
+
const granted = c.roles[0] ?? null;
|
|
913
|
+
const lines = [];
|
|
914
|
+
lines.push(`/**`);
|
|
915
|
+
lines.push(` * The composed foundation, as executable guarantees: anyone may sign up and sign in; there are no workspaces,`);
|
|
916
|
+
lines.push(` * memberships or invitations; a new account holds the base role ${JSON.stringify(base)}${granted ? `; an application role (${c.roles.join(", ")}) is held once granted (accounts.setRoles)` : ""}.`);
|
|
917
|
+
lines.push(` * Composed by \`feltkit create\`; add your own tests beside this one. Run with \`npm test\`.`);
|
|
918
|
+
lines.push(` */`);
|
|
919
|
+
lines.push(`import { test } from "node:test";`);
|
|
920
|
+
lines.push(`import assert from "node:assert/strict";`);
|
|
921
|
+
lines.push(`import { createTestApp } from "@feltdb/feltkit/testing";`);
|
|
922
|
+
lines.push(``);
|
|
923
|
+
lines.push(`test("the foundation: accounts (open sign-up), no workspaces, the base role${granted ? " and granted application roles" : ""}", async () => {`);
|
|
924
|
+
lines.push(` const t = await createTestApp();`);
|
|
925
|
+
lines.push(` try {`);
|
|
926
|
+
lines.push(` const runtime = t.runtime;`);
|
|
927
|
+
lines.push(` assert.ok(runtime.accounts, "accounts are part of the foundation");`);
|
|
928
|
+
lines.push(` assert.equal(t.tenancy, null, "no tenancy: there is nothing to join and nobody to invite");`);
|
|
929
|
+
lines.push(` const options = runtime.project.app.options as unknown as { roles: Record<string, string[]>; auth: { accounts: { roles: string[]; magicLink?: boolean; signUp?: boolean }; tenant?: unknown } };`);
|
|
930
|
+
lines.push(` assert.equal(options.auth.tenant, undefined, "the declaration has no auth.tenant");`);
|
|
931
|
+
lines.push(` assert.deepEqual(options.auth.accounts.roles, [${JSON.stringify(base)}], "every new account holds the base role");`);
|
|
932
|
+
lines.push(` for (const role of ${JSON.stringify([base, ...c.roles])}) assert.ok(role in options.roles, \`role \${role} is declared\`);`);
|
|
933
|
+
lines.push(` assert.equal(options.auth.accounts.magicLink ?? false, ${c.magicLink}, "sign-in links ${c.magicLink ? "on" : "off"}");`);
|
|
934
|
+
lines.push(` assert.equal(options.auth.accounts.signUp ?? true, true, "sign-up open");`);
|
|
935
|
+
lines.push(` const created = await runtime.accounts!.signUp({ email: "ada@example.com", password: "a-long-password-1", name: "Ada" });`);
|
|
936
|
+
lines.push(` await runtime.accounts!.markVerified(created.id);`);
|
|
937
|
+
lines.push(` assert.ok((await runtime.accounts!.signIn({ email: "ada@example.com", password: "a-long-password-1" })).id, "a person signs up and signs in");`);
|
|
938
|
+
lines.push(` const session = await runtime.issueSession({ id: created.id, type: "user", roles: [...created.roles] }, { kind: "account", via: "test" });`);
|
|
939
|
+
lines.push(` assert.deepEqual((await runtime.principalForToken(session.token))?.roles, [${JSON.stringify(base)}], "a new account's session holds the base role only");`);
|
|
940
|
+
if (granted) {
|
|
941
|
+
lines.push(` // An application role is granted (accounts.setRoles): the account's next request carries it.`);
|
|
942
|
+
lines.push(` await runtime.accounts!.setRoles(created.id, [${JSON.stringify(base)}, ${JSON.stringify(granted)}]);`);
|
|
943
|
+
lines.push(` assert.deepEqual((await runtime.principalForToken(session.token))?.roles, [${JSON.stringify(base)}, ${JSON.stringify(granted)}]);`);
|
|
944
|
+
}
|
|
945
|
+
lines.push(` } finally {`);
|
|
946
|
+
lines.push(` await t.close();`);
|
|
947
|
+
lines.push(` }`);
|
|
948
|
+
lines.push(`});`);
|
|
949
|
+
lines.push(``);
|
|
950
|
+
return lines.join("\n");
|
|
951
|
+
}
|
|
952
|
+
/**
|
|
953
|
+
* tests/files.test.ts: for every entity with attachments, the file boundary follows the record boundary, through the
|
|
954
|
+
* real runtime and the real Files service: the creator attaches, lists and gets a download link; a caller who cannot
|
|
955
|
+
* see the record (another workspace, another person) gets NOT_FOUND from files and download; a file of another record
|
|
956
|
+
* does not exist on this one; a reader role lists and cannot attach or detach; an anonymous caller is UNAUTHORIZED
|
|
957
|
+
* (unless the entity is public, when reads are open and writes still refused); detaching removes the file; removing the
|
|
958
|
+
* record removes its files. Application-owned once written.
|
|
959
|
+
*/
|
|
960
|
+
export function renderFilesTests(entities, context) {
|
|
961
|
+
const withFiles = creationOrder(entities).filter((e) => e.attachments);
|
|
962
|
+
const individuals = context.tenancy === "individuals";
|
|
963
|
+
const base = context.baseRole ?? "person";
|
|
964
|
+
const top = context.roles[0] ?? base;
|
|
965
|
+
const reader = !individuals && context.roles.length > 1 ? context.roles[context.roles.length - 1] : null;
|
|
966
|
+
const manager = (individuals ? context.managers[0] : context.managers.find((r) => r !== top) ?? context.managers[0]) ?? null;
|
|
967
|
+
const lines = [];
|
|
968
|
+
lines.push(`/**`);
|
|
969
|
+
lines.push(` * Files follow their records: a file attached to a ${individuals ? "record" : context.noun + " record"} is seen only by whoever sees the record and changed only by`);
|
|
970
|
+
lines.push(` * whoever may change it; a file of another record does not exist here; anonymous callers are refused. Driven through the`);
|
|
971
|
+
lines.push(` * real runtime and the real Files service. Composed by \`feltkit create\`; add your own tests beside it. Run with \`npm test\`.`);
|
|
972
|
+
lines.push(` */`);
|
|
973
|
+
lines.push(`import { test } from "node:test";`);
|
|
974
|
+
lines.push(`import assert from "node:assert/strict";`);
|
|
975
|
+
lines.push(`import { createTestApp${individuals ? "" : ", type TestApp"} } from "@feltdb/feltkit/testing";`);
|
|
976
|
+
lines.push(`import { api } from "../feltkit/_generated/api.js";`);
|
|
977
|
+
lines.push(``);
|
|
978
|
+
lines.push(`type Who = { id: string; type: "user"; displayName?: string; roles: string[] };`);
|
|
979
|
+
if (individuals)
|
|
980
|
+
lines.push(`const person = (id: string, ...roles: string[]): Who => ({ id, type: "user", displayName: id, roles: [${JSON.stringify(base)}, ...roles] });`);
|
|
981
|
+
else {
|
|
982
|
+
lines.push(`const person = (id: string): Who => ({ id, type: "user", displayName: id, roles: [] });`);
|
|
983
|
+
lines.push(``);
|
|
984
|
+
lines.push(`async function workspace(t: TestApp, name: string, creator: Who, members: Array<[Who, string]> = []) {`);
|
|
985
|
+
if (context.create === "none")
|
|
986
|
+
lines.push(` // This application does not create ${context.noun}s (create: "none"): they are provisioned outside it. The test harness provisions one the same way.`);
|
|
987
|
+
lines.push(context.create === "none" ? ` const tenant = await t.provisionTenant(name, { ...creator, email: \`\${creator.id}@example.com\` });` : ` const tenant = await t.tenancy!.create(name, { ...creator, email: \`\${creator.id}@example.com\` });`);
|
|
988
|
+
lines.push(` const actor = { ...(await t.tenancy!.context(tenant.id, creator.id))!, principalId: creator.id, displayName: creator.id };`);
|
|
989
|
+
lines.push(` for (const [who, role] of members) {`);
|
|
990
|
+
lines.push(` const { token } = await t.tenancy!.invite(actor, { email: \`\${who.id}@example.com\`, role });`);
|
|
991
|
+
lines.push(` await t.tenancy!.accept(token, { ...who, email: \`\${who.id}@example.com\`, emailVerified: true });`);
|
|
992
|
+
lines.push(` }`);
|
|
993
|
+
lines.push(` return tenant.id;`);
|
|
994
|
+
lines.push(`}`);
|
|
995
|
+
if (entities.some((e) => e.requires)) {
|
|
996
|
+
lines.push(``);
|
|
997
|
+
lines.push(`/** Set members' claims the way the application does: through the server, by a member who manages members (the creator here). */`);
|
|
998
|
+
lines.push(`async function setClaims(t: TestApp, ws: string, manager: string, members: readonly string[], claims: Record<string, unknown>) {`);
|
|
999
|
+
lines.push(` const actor = { ...(await t.tenancy!.context(ws, manager))!, principalId: manager };`);
|
|
1000
|
+
lines.push(` for (const who of members) await t.tenancy!.setClaims(actor, who, claims);`);
|
|
1001
|
+
lines.push(`}`);
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
lines.push(``);
|
|
1005
|
+
const sampleArgs = (e, n) => {
|
|
1006
|
+
const parts = e.fields.map((f) => `${f.name}: ${sample(f, n)}`);
|
|
1007
|
+
for (const r of e.relations)
|
|
1008
|
+
parts.push(`${r.field}: refs[${JSON.stringify(r.target)}]`);
|
|
1009
|
+
return `{ ${parts.join(", ")} }`;
|
|
1010
|
+
};
|
|
1011
|
+
for (const e of withFiles) {
|
|
1012
|
+
const deps = creationOrder(entities).filter((d) => d.name !== e.name && e.relations.some((r) => r.target === d.name));
|
|
1013
|
+
const personal = e.scope === "personal";
|
|
1014
|
+
const workspaceScoped = e.scope === "workspace";
|
|
1015
|
+
const outsider = individuals ? `another ${base}${manager ? ` or a ${manager}` : ""}` : `another ${context.noun}`;
|
|
1016
|
+
lines.push(`test(${JSON.stringify(`${e.name} files: attach, list, download, detach; ${personal || workspaceScoped ? `${outsider} finds nothing` : "shared: everyone lists, only those who may change the record attach"}; a file of another record does not exist; anonymous is refused${e.public ? " (public reads do not extend to files)" : ""}; removing the record removes its files`)}, async () => {`);
|
|
1017
|
+
lines.push(` const t = await createTestApp();`);
|
|
1018
|
+
lines.push(` try {`);
|
|
1019
|
+
lines.push(` const ada = person("ada"${individuals && !e.owned && manager ? `, ${JSON.stringify(manager)}` : ""});`);
|
|
1020
|
+
lines.push(` const bob = person("bob");`);
|
|
1021
|
+
if (individuals) {
|
|
1022
|
+
if (manager)
|
|
1023
|
+
lines.push(` const meg = person("meg", ${JSON.stringify(manager)});`);
|
|
1024
|
+
lines.push(` const asAda = t.as(ada);`);
|
|
1025
|
+
lines.push(` const asBob = t.as(bob);`);
|
|
1026
|
+
if (manager)
|
|
1027
|
+
lines.push(` const asMeg = t.as(meg);`);
|
|
1028
|
+
}
|
|
1029
|
+
else {
|
|
1030
|
+
lines.push(` const eve = person("eve");`);
|
|
1031
|
+
lines.push(` const ws = await workspace(t, "acme", ada, [[bob, ${JSON.stringify(manager ?? context.roles[1] ?? top)}]${reader ? `, [eve, ${JSON.stringify(reader)}]` : ""}]);`);
|
|
1032
|
+
lines.push(` const other = await workspace(t, "other", person("zed"));`);
|
|
1033
|
+
lines.push(` const asAda = t.as(ada, { tenant: ws });`);
|
|
1034
|
+
lines.push(` const asBob = t.as(bob, { tenant: ws });`);
|
|
1035
|
+
if (reader)
|
|
1036
|
+
lines.push(` const asEve = t.as(eve, { tenant: ws });`);
|
|
1037
|
+
lines.push(` const asZed = t.as(person("zed"), { tenant: other });`);
|
|
1038
|
+
// Claim gates: the entity's and its dependencies'. The record boundary is what this test is about; the gate has its own test.
|
|
1039
|
+
const gates = [...new Map([e, ...deps].filter((x) => x.requires).map((x) => [x.requires.claim, x.requires.values[0]])).entries()];
|
|
1040
|
+
if (gates.length) {
|
|
1041
|
+
lines.push(` // Membership claims the entity (or what it refers to) requires: set through the server, as the application does.`);
|
|
1042
|
+
lines.push(` await setClaims(t, ws, "ada", [${["ada", "bob", ...(reader ? ["eve"] : [])].map((w) => JSON.stringify(w)).join(", ")}], { ${gates.map(([k, v]) => `${JSON.stringify(k)}: ${JSON.stringify(v)}`).join(", ")} });`);
|
|
1043
|
+
lines.push(` await setClaims(t, other, "zed", ["zed"], { ${gates.map(([k, v]) => `${JSON.stringify(k)}: ${JSON.stringify(v)}`).join(", ")} });`);
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
lines.push(` const refs: Record<string, string> = {};`);
|
|
1047
|
+
for (const d of deps)
|
|
1048
|
+
lines.push(` refs[${JSON.stringify(d.name)}] = await ${individuals && !d.owned && d.scope === "shared" && manager ? "asMeg" : "asAda"}.mutation(api.${d.name}.create, ${sampleArgs(d, 9)});`);
|
|
1049
|
+
lines.push(` const id = await asAda.mutation(api.${e.name}.create, ${sampleArgs(e, 1)});`);
|
|
1050
|
+
lines.push(` const fileId = await asAda.mutation(api.${e.name}.attach, { id, name: "notes.txt", contentType: "text/plain", content: "hello" });`);
|
|
1051
|
+
lines.push(` assert.ok(typeof fileId === "string" && fileId, "attach returns the file id");`);
|
|
1052
|
+
lines.push(` const listed = await asAda.query(api.${e.name}.files, { id });`);
|
|
1053
|
+
lines.push(` assert.equal(listed.length, 1);`);
|
|
1054
|
+
lines.push(` assert.equal(listed[0]!.metadata.recordId, id, "the file is bound to its record");`);
|
|
1055
|
+
lines.push(` const link = await asAda.query(api.${e.name}.download, { id, fileId });`);
|
|
1056
|
+
lines.push(` assert.match(link.url, /^\\/api\\/files\\//);`);
|
|
1057
|
+
lines.push(` const uploadLink = await asAda.mutation(api.${e.name}.attachLink, { id, name: "photo.png", contentType: "image/png" });`);
|
|
1058
|
+
lines.push(` assert.match(uploadLink.url, /^\\/api\\/files\\//);`);
|
|
1059
|
+
lines.push(` // A file of another record does not exist on this one, even for the creator.`);
|
|
1060
|
+
lines.push(` const second = await asAda.mutation(api.${e.name}.create, ${sampleArgs(e, 2)});`);
|
|
1061
|
+
lines.push(` await assert.rejects(asAda.query(api.${e.name}.download, { id: second, fileId }), { code: "NOT_FOUND" });`);
|
|
1062
|
+
lines.push(` await assert.rejects(asAda.mutation(api.${e.name}.detach, { id: second, fileId }), { code: "NOT_FOUND" });`);
|
|
1063
|
+
// Outsiders.
|
|
1064
|
+
if (workspaceScoped) {
|
|
1065
|
+
lines.push(` // Another ${context.noun}: the record, and so its files, do not exist.`);
|
|
1066
|
+
lines.push(` await assert.rejects(asZed.query(api.${e.name}.files, { id }), { code: "NOT_FOUND" });`);
|
|
1067
|
+
lines.push(` await assert.rejects(asZed.query(api.${e.name}.download, { id, fileId }), { code: "NOT_FOUND" });`);
|
|
1068
|
+
lines.push(` await assert.rejects(asZed.mutation(api.${e.name}.detach, { id, fileId }), { code: "NOT_FOUND" });`);
|
|
1069
|
+
}
|
|
1070
|
+
else if (personal) {
|
|
1071
|
+
lines.push(` // Another person${manager ? `, even a ${manager},` : ""}: the record, and so its files, do not exist.`);
|
|
1072
|
+
for (const who of ["asBob", ...(manager ? ["asMeg"] : [])]) {
|
|
1073
|
+
lines.push(` await assert.rejects(${who}.query(api.${e.name}.files, { id }), { code: "NOT_FOUND" });`);
|
|
1074
|
+
lines.push(` await assert.rejects(${who}.query(api.${e.name}.download, { id, fileId }), { code: "NOT_FOUND" });`);
|
|
1075
|
+
lines.push(` await assert.rejects(${who}.mutation(api.${e.name}.attach, { id, name: "x.txt", content: "x" }), { code: "NOT_FOUND" });`);
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
else {
|
|
1079
|
+
// shared
|
|
1080
|
+
lines.push(` // Shared: bob lists and downloads${e.owned ? "; not the creator, he may not attach or detach" : individuals && manager ? "; not a manager, he may not attach" : ""}.`);
|
|
1081
|
+
lines.push(` assert.equal((await asBob.query(api.${e.name}.files, { id })).length, 1);`);
|
|
1082
|
+
lines.push(` assert.match((await asBob.query(api.${e.name}.download, { id, fileId })).url, /^\\/api\\/files\\//);`);
|
|
1083
|
+
if (e.owned) {
|
|
1084
|
+
lines.push(` await assert.rejects(asBob.mutation(api.${e.name}.attach, { id, name: "x.txt", content: "x" }), { code: "FORBIDDEN" });`);
|
|
1085
|
+
lines.push(` await assert.rejects(asBob.mutation(api.${e.name}.detach, { id, fileId }), { code: "FORBIDDEN" });`);
|
|
1086
|
+
if (individuals && manager)
|
|
1087
|
+
lines.push(` await asMeg.mutation(api.${e.name}.attach, { id, name: "m.txt", content: "m" });`);
|
|
1088
|
+
}
|
|
1089
|
+
else if (individuals && manager) {
|
|
1090
|
+
lines.push(` await assert.rejects(asBob.mutation(api.${e.name}.attach, { id, name: "x.txt", content: "x" }), { code: "FORBIDDEN" });`);
|
|
1091
|
+
lines.push(` await asMeg.mutation(api.${e.name}.attach, { id, name: "m.txt", content: "m" });`);
|
|
1092
|
+
}
|
|
1093
|
+
}
|
|
1094
|
+
if (reader && !individuals) {
|
|
1095
|
+
lines.push(` // A ${reader} ${workspaceScoped || e.scope === "shared" ? "lists and downloads, and" : ""} cannot attach or detach.`);
|
|
1096
|
+
lines.push(` assert.equal((await asEve.query(api.${e.name}.files, { id })).length, ${e.scope === "shared" || workspaceScoped ? "1" : "1"});`);
|
|
1097
|
+
lines.push(` await assert.rejects(asEve.mutation(api.${e.name}.attach, { id, name: "x.txt", content: "x" }), { code: "FORBIDDEN" });`);
|
|
1098
|
+
lines.push(` await assert.rejects(asEve.mutation(api.${e.name}.detach, { id, fileId }), { code: "FORBIDDEN" });`);
|
|
1099
|
+
}
|
|
1100
|
+
lines.push(` // Anonymous: refused everywhere${e.public ? " (the entity's public reads do not extend to files: the Files service needs a signed-in caller)" : ""}.`);
|
|
1101
|
+
lines.push(` await assert.rejects(t.query(api.${e.name}.files, { id }), { code: "UNAUTHORIZED" });`);
|
|
1102
|
+
lines.push(` await assert.rejects(t.query(api.${e.name}.download, { id, fileId }), { code: "UNAUTHORIZED" });`);
|
|
1103
|
+
lines.push(` await assert.rejects(t.mutation(api.${e.name}.attach, { id, name: "x.txt", content: "x" }), { code: "UNAUTHORIZED" });`);
|
|
1104
|
+
lines.push(` await assert.rejects(t.mutation(api.${e.name}.detach, { id, fileId }), { code: "UNAUTHORIZED" });`);
|
|
1105
|
+
lines.push(` // Detach removes the file; removing the record removes the rest.`);
|
|
1106
|
+
lines.push(` await asAda.mutation(api.${e.name}.detach, { id, fileId });`);
|
|
1107
|
+
lines.push(` await assert.rejects(asAda.query(api.${e.name}.download, { id, fileId }), { code: "NOT_FOUND" });`);
|
|
1108
|
+
lines.push(` const again = await asAda.mutation(api.${e.name}.attach, { id, name: "again.txt", content: "again" });`);
|
|
1109
|
+
lines.push(` await asAda.mutation(api.${e.name}.remove, { id });`);
|
|
1110
|
+
lines.push(` await assert.rejects(asAda.query(api.${e.name}.download, { id, fileId: again }), { code: "NOT_FOUND" });`);
|
|
1111
|
+
lines.push(` } finally {`);
|
|
1112
|
+
lines.push(` await t.close();`);
|
|
1113
|
+
lines.push(` }`);
|
|
1114
|
+
lines.push(`});`);
|
|
1115
|
+
lines.push(``);
|
|
1116
|
+
}
|
|
1117
|
+
return lines.join("\n");
|
|
1118
|
+
}
|
|
1119
|
+
//# sourceMappingURL=domain.js.map
|