@feltdb/feltkit 0.3.17 → 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 +246 -13
- package/dist/app.js +215 -6
- package/dist/app.js.map +1 -1
- package/dist/appboundry/build.d.ts +70 -0
- package/dist/appboundry/build.js +62 -2
- package/dist/appboundry/build.js.map +1 -1
- package/dist/appboundry/guest.js +57 -3
- package/dist/appboundry/guest.js.map +1 -1
- package/dist/appboundry/host.js +7 -0
- package/dist/appboundry/host.js.map +1 -1
- package/dist/authorize.js +1 -0
- package/dist/authorize.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-appboundry-self-hosted.d.ts +2 -0
- package/dist/cli/deploy-appboundry-self-hosted.js +1 -1
- package/dist/cli/deploy-appboundry-self-hosted.js.map +1 -1
- package/dist/cli/deploy-appboundry.js +3 -0
- package/dist/cli/deploy-appboundry.js.map +1 -1
- 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 +141 -7
- 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/client/index.d.ts +192 -5
- package/dist/client/index.js +301 -28
- package/dist/client/index.js.map +1 -1
- 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 +2 -0
- package/dist/docs.js.map +1 -1
- package/dist/index.d.ts +7 -3
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/react/auth.d.ts +131 -0
- package/dist/react/auth.js +830 -0
- package/dist/react/auth.js.map +1 -0
- package/dist/react/context.d.ts +8 -0
- package/dist/react/context.js +14 -0
- package/dist/react/context.js.map +1 -0
- package/dist/react/index.d.ts +3 -18
- package/dist/react/index.js +5 -13
- package/dist/react/index.js.map +1 -1
- package/dist/runtime/accounts.d.ts +33 -2
- package/dist/runtime/accounts.js +167 -27
- package/dist/runtime/accounts.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/authority.d.ts +8 -1
- package/dist/runtime/authority.js +11 -2
- package/dist/runtime/authority.js.map +1 -1
- package/dist/runtime/challenges.d.ts +51 -0
- package/dist/runtime/challenges.js +121 -0
- package/dist/runtime/challenges.js.map +1 -0
- package/dist/runtime/changes.d.ts +22 -0
- package/dist/runtime/changes.js +51 -3
- package/dist/runtime/changes.js.map +1 -1
- 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 +47 -5
- package/dist/runtime/contract.js +17 -3
- package/dist/runtime/contract.js.map +1 -1
- package/dist/runtime/data.d.ts +50 -4
- package/dist/runtime/data.js +113 -35
- 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/live.d.ts +48 -0
- package/dist/runtime/live.js +154 -0
- package/dist/runtime/live.js.map +1 -0
- package/dist/runtime/outbox.js +6 -0
- package/dist/runtime/outbox.js.map +1 -1
- package/dist/runtime/runtime.d.ts +103 -5
- package/dist/runtime/runtime.js +411 -41
- package/dist/runtime/runtime.js.map +1 -1
- package/dist/runtime/search.d.ts +54 -0
- package/dist/runtime/search.js +66 -0
- package/dist/runtime/search.js.map +1 -0
- 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/sessions.d.ts +16 -2
- package/dist/runtime/sessions.js +40 -4
- package/dist/runtime/sessions.js.map +1 -1
- package/dist/runtime/tenancy.d.ts +198 -0
- package/dist/runtime/tenancy.js +397 -0
- package/dist/runtime/tenancy.js.map +1 -0
- package/dist/runtime/tenant-scope.d.ts +9 -0
- package/dist/runtime/tenant-scope.js +127 -0
- package/dist/runtime/tenant-scope.js.map +1 -0
- package/dist/runtime/transactions.d.ts +83 -3
- package/dist/runtime/transactions.js +53 -11
- 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 +4 -1
- package/dist/server/index.js +324 -63
- package/dist/server/index.js.map +1 -1
- package/dist/server/mcp.js +6 -3
- package/dist/server/mcp.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/server/session-http.d.ts +48 -0
- package/dist/server/session-http.js +116 -0
- package/dist/server/session-http.js.map +1 -0
- package/dist/server/tenancy.d.ts +40 -0
- package/dist/server/tenancy.js +191 -0
- package/dist/server/tenancy.js.map +1 -0
- package/dist/testing/index.d.ts +19 -0
- package/dist/testing/index.js +22 -2
- package/dist/testing/index.js.map +1 -1
- package/docs/AGENT-OPERATIONS.md +1 -0
- package/docs/APPBOUNDRY.md +11 -1
- package/docs/ARCHITECTURE.md +5 -3
- package/docs/AUTH.md +267 -0
- package/docs/COMPONENTS.md +91 -0
- package/docs/GUARANTEES.md +74 -7
- package/docs/README.md +4 -2
- package/docs/RESOLVER.md +4 -2
- package/docs/SECURITY.md +5 -4
- package/docs/TRANSACTIONS.md +98 -1
- package/docs/UPSTREAM-GAPS.md +2 -0
- package/package.json +15 -12
- package/skills/.claude-plugin/marketplace.json +1 -1
- package/skills/.claude-plugin/plugin.json +1 -1
- package/skills/feltkit-data/SKILL.md +6 -0
- package/skills/feltkit-services/SKILL.md +1 -1
- package/dist/runtime/account-links.d.ts +0 -19
- package/dist/runtime/account-links.js +0 -45
- package/dist/runtime/account-links.js.map +0 -1
|
@@ -0,0 +1,1139 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `feltkit create`: the interactive composer. A developer selects what the application needs, in
|
|
3
|
+
* application language; FeltKit translates the selections into a profile and the catalog's capabilities (M1):
|
|
4
|
+
* an application whose data belongs to organizations its people join gets the collaborative-workspace
|
|
5
|
+
* foundation (accounts, workspaces, invitations); one whose people have their own accounts and their own
|
|
6
|
+
* records gets individual-accounts (accounts, nothing of workspaces). The requirement decides, never a
|
|
7
|
+
* profile flag. FeltKit
|
|
8
|
+
* shows the resolved composition (the resolver's own output), and, once confirmed, scaffolds the
|
|
9
|
+
* project and composes its foundation with the same generator `feltkit compose` uses (M2). Nothing
|
|
10
|
+
* here resolves, generates, checks or writes on its own: the catalog, the resolver, the generator and
|
|
11
|
+
* the integrity check are the ones that exist. Inside an existing application the composer never
|
|
12
|
+
* writes: it reconciles (M3), plans (M4) and hands the exact `feltkit compose apply --approve <id>`
|
|
13
|
+
* command to the developer (M5).
|
|
14
|
+
*/
|
|
15
|
+
import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { basename, join, relative, resolve } from "node:path";
|
|
17
|
+
import { createInterface } from "node:readline";
|
|
18
|
+
import { scaffold, ScaffoldError, toAppName } from "create-feltkit";
|
|
19
|
+
import { CATALOG } from "../composition/catalog.js";
|
|
20
|
+
import { DECLARATION_PATH, GENERATED_PATHS, LOCK_PATH, RECORD_PATH, canonical, checkFoundation, generateFoundation } from "../composition/generate.js";
|
|
21
|
+
import { planComposition } from "../composition/plan.js";
|
|
22
|
+
import { COLLABORATIVE_WORKSPACE, INDIVIDUAL_ACCOUNTS } from "../composition/profiles.js";
|
|
23
|
+
import { readGeneratedState, reconcile } from "../composition/reconcile.js";
|
|
24
|
+
import { FeltKitError } from "../errors.js";
|
|
25
|
+
import { compose, parseParams } from "./compose.js";
|
|
26
|
+
import { DomainError, PERMISSIONS, creationOrder, managingRoles, parseClaims, parseFields, parseRelations, parseRequire, parseUnique, renderApi, renderCollection, renderDomainTests, renderEntityModule, renderFilesTests, renderFoundationTests, validateEntities } from "./domain.js";
|
|
27
|
+
import { c, line, setOutput, symbols } from "./output.js";
|
|
28
|
+
import { INDIVIDUAL_APP_SHELL } from "./shell.js";
|
|
29
|
+
/** `workspaces`: the kind's data belongs to organizations people join (the default answer); `individuals`: to each person. */
|
|
30
|
+
export const APP_KINDS = [
|
|
31
|
+
{ value: "collaboration", label: "Collaboration application", hint: "people work together in shared workspaces", tenancy: "workspaces" },
|
|
32
|
+
{ value: "business", label: "Business application", hint: "an organization's own records and processes, per organization", tenancy: "workspaces" },
|
|
33
|
+
{ value: "portal", label: "Customer portal", hint: "each customer sees and manages their own account", tenancy: "workspaces" },
|
|
34
|
+
{ value: "marketplace", label: "Marketplace", hint: "several parties, each in their own space, meeting through the application", tenancy: "workspaces" },
|
|
35
|
+
{ value: "operations", label: "Internal operations application", hint: "staff tooling, with operators configuring it", tenancy: "workspaces" },
|
|
36
|
+
{ value: "personal", label: "Personal application", hint: "each person signs up and works with their own records; no organization to join", tenancy: "individuals" },
|
|
37
|
+
{ value: "custom", label: "Custom application", hint: "none of the above; select the pieces directly", tenancy: "workspaces" },
|
|
38
|
+
];
|
|
39
|
+
/** `needs`: a participant that exists only with workspaces (membership, invitation into one). */
|
|
40
|
+
export const PARTICIPANTS = [
|
|
41
|
+
{ value: "customers", label: "Customers", hint: "sign up on their own, work in their own space" },
|
|
42
|
+
{ value: "staff", label: "Internal staff", hint: "your people, usually invited" },
|
|
43
|
+
{ value: "administrators", label: "Administrators", hint: "manage members and configure the application" },
|
|
44
|
+
{ value: "partners", label: "External partners", hint: "invited into specific workspaces", needs: "workspaces" },
|
|
45
|
+
{ value: "collaborators", label: "Human collaborators", hint: "people working together on shared data" },
|
|
46
|
+
{ value: "agents", label: "AI agents", hint: "join workspaces as members with their own permissions", needs: "workspaces" },
|
|
47
|
+
];
|
|
48
|
+
/** The two foundations, as the requirement a developer states. The profile follows from the answer; nothing else selects it. */
|
|
49
|
+
export const TENANCIES = [
|
|
50
|
+
{ value: "workspaces", label: "Organizations people join (workspaces, teams, accounts): data belongs to the organization, invisible to the others", hint: `foundation ${COLLABORATIVE_WORKSPACE.id}: accounts, workspaces with roles, invitations`, profile: COLLABORATIVE_WORKSPACE },
|
|
51
|
+
{ value: "individuals", label: "Individuals: each person has their own account and their own records; no organization to join", hint: `foundation ${INDIVIDUAL_ACCOUNTS.id}: accounts only; no workspaces, memberships or invitations`, profile: INDIVIDUAL_ACCOUNTS },
|
|
52
|
+
];
|
|
53
|
+
export const CAPABILITY_GUIDE = [
|
|
54
|
+
{ id: "identity.accounts", label: "Accounts and authentication", provides: "sign-up and sign-in with an e-mail address: password, optionally an e-mailed sign-in link, verification, password reset, sessions", addresses: "people need their own identity in the application", constraints: "account e-mail (links, invitations) needs a sender address; delivered through Mailerport", applicationOwned: "nothing: FeltKit's screens and routes do it" },
|
|
55
|
+
{ id: "workspace.tenancy", label: "Organizations and tenancy (workspaces, roles, isolation)", provides: "workspaces people belong to with a role each; collections marked { tenant: true } are scoped to the current workspace on every read and write", addresses: "data that belongs to a team, an organization or a customer, invisible to the others", constraints: "every role is an ordinary FeltKit role; the top role holds every workspace permission", applicationOwned: "which of your collections are workspace-scoped, and what each role may do with your data" },
|
|
56
|
+
{ id: "workspace.invitations", label: "Invitations and membership", provides: "invite by e-mail with a role, accept once with the invited address, change roles, remove, leave", addresses: "bringing the right people into a workspace", constraints: "needs accounts and workspaces; invitation e-mail needs the sender address", applicationOwned: "nothing" },
|
|
57
|
+
{ id: "agents.membership", label: "Agent capabilities (agents as workspace members)", provides: "an agent role whose holders join workspaces directly, without an invitation", addresses: "AI agents acting inside workspaces", constraints: "the role grants nothing by itself", applicationOwned: "the agent (app.agent) and the permissions you give its role", offeredFor: ["agents"] },
|
|
58
|
+
{ id: "ops.operator", label: "Operator role (production Studio)", provides: "a role for operating the application in production: models, credentials, configuration, API keys, webhooks, jobs, schedules", addresses: "administrators configuring the running application, apart from workspace roles", constraints: "operators are granted through `feltkit operator grant`", applicationOwned: "nothing", offeredFor: ["administrators", "staff"] },
|
|
59
|
+
{ id: "services.files", label: "Files and documents", provides: "file upload, download and deletion with permissions, stored in the application's FeltDB; files attach to the entities you choose, and follow their records' rules", addresses: "attachments and documents", constraints: "one size limit for every file (FeltKit's default is 1 MiB); the service itself is application-wide (any files.read reads any file), so the per-record binding is in the generated functions", applicationOwned: "the screens that upload (PUT to attachLink's url) and show files; any rule beyond the record's" },
|
|
60
|
+
{ id: "services.notifications", label: "Notifications", provides: "in-application notifications a person reads, marks and dismisses, sent after a change commits", addresses: "telling people what happened", constraints: "notification types are names you choose", applicationOwned: "when to send one (ctx.afterCommit in your functions)" },
|
|
61
|
+
{ id: "services.jobs", label: "Background jobs", provides: "durable jobs queued from your functions, run by the runtime with retries, inspectable in Studio", addresses: "work that must happen after a request, reliably", constraints: "handlers are your functions, named in the declaration", applicationOwned: "the handlers, and when to queue a job" },
|
|
62
|
+
{ id: "services.schedules", label: "Scheduled work", provides: "jobs that run on a schedule", addresses: "recurring work", constraints: "requires background jobs", applicationOwned: "the schedules and their handlers" },
|
|
63
|
+
];
|
|
64
|
+
/** Needs people ask for that no catalog capability composes today. Each line is what the SDK offers instead, verified in source. */
|
|
65
|
+
export const NOT_COMPOSABLE = [
|
|
66
|
+
{ id: "webhooks", label: "Webhooks and integrations", status: "the SDK has webhooks (services.webhooks in feltkit({...}), permissions webhooks.*); not a catalog capability yet, so it is declared by hand in feltkit/app.ts" },
|
|
67
|
+
{ id: "realtime", label: "Real-time collaboration", status: "every query is live (useQueryState updates when data changes); presence and co-editing are not platform capabilities" },
|
|
68
|
+
{ id: "search", label: "Search", status: "FeltDB queries and indexes exist; there is no composable search capability" },
|
|
69
|
+
{ id: "sso", label: "Single sign-on / external identity providers", status: "the SDK accepts auth.providers (OIDC); not a catalog capability yet, so it is declared by hand in feltkit/app.ts" },
|
|
70
|
+
];
|
|
71
|
+
/** The profile the answers select: a function of the stated requirement, not of a flag. */
|
|
72
|
+
export function profileFor(a) {
|
|
73
|
+
return TENANCIES.find((t) => t.value === a.tenancy).profile;
|
|
74
|
+
}
|
|
75
|
+
export class Cancelled extends Error {
|
|
76
|
+
constructor() {
|
|
77
|
+
super("cancelled");
|
|
78
|
+
this.name = "Cancelled";
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/**
|
|
82
|
+
* The terminal prompter: numbered choices, comma-separated multiple choices, y/n; an empty required
|
|
83
|
+
* answer asks again; "q" cancels; end of input cancels. Lines are queued as they arrive, so answers
|
|
84
|
+
* piped in all at once (a script, a test) are not lost between questions.
|
|
85
|
+
*/
|
|
86
|
+
export function terminalPrompter(input = process.stdin, output = process.stdout) {
|
|
87
|
+
const rl = createInterface({ input, terminal: false });
|
|
88
|
+
const queue = [];
|
|
89
|
+
let waiting = null;
|
|
90
|
+
let closed = false;
|
|
91
|
+
rl.on("line", (l) => (waiting ? (waiting(l), (waiting = null)) : queue.push(l)));
|
|
92
|
+
rl.on("close", () => {
|
|
93
|
+
closed = true;
|
|
94
|
+
waiting?.(null);
|
|
95
|
+
waiting = null;
|
|
96
|
+
});
|
|
97
|
+
const next = () => (queue.length ? Promise.resolve(queue.shift()) : closed ? Promise.resolve(null) : new Promise((r) => (waiting = r)));
|
|
98
|
+
const ask = async (q) => {
|
|
99
|
+
output.write(q);
|
|
100
|
+
const raw = await next();
|
|
101
|
+
if (raw === null) {
|
|
102
|
+
output.write("\n");
|
|
103
|
+
throw new Cancelled();
|
|
104
|
+
}
|
|
105
|
+
const answer = raw.trim();
|
|
106
|
+
if (!output.isTTY)
|
|
107
|
+
output.write(`${answer}\n`);
|
|
108
|
+
if (answer === "q" || answer === "quit")
|
|
109
|
+
throw new Cancelled();
|
|
110
|
+
return answer;
|
|
111
|
+
};
|
|
112
|
+
return {
|
|
113
|
+
say: (text) => line(text),
|
|
114
|
+
close: () => rl.close(),
|
|
115
|
+
async text(prompt, options = {}) {
|
|
116
|
+
for (;;) {
|
|
117
|
+
const answer = await ask(`${prompt}${options.default !== undefined ? c.dim(` [${options.default}]`) : ""}: `);
|
|
118
|
+
const value = answer || options.default || "";
|
|
119
|
+
if (!value && options.required) {
|
|
120
|
+
line(c.dim(" An answer is needed (q to cancel)."));
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const problem = value && options.validate ? options.validate(value) : null;
|
|
124
|
+
if (problem) {
|
|
125
|
+
line(c.dim(` ${problem}`));
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
return value;
|
|
129
|
+
}
|
|
130
|
+
},
|
|
131
|
+
async choose(prompt, choices, options = {}) {
|
|
132
|
+
line(prompt);
|
|
133
|
+
choices.forEach((ch, i) => line(` ${i + 1}. ${ch.label}${ch.hint ? c.dim(` ${ch.hint}`) : ""}`));
|
|
134
|
+
const def = options.default ? choices.findIndex((ch) => ch.value === options.default) + 1 : 0;
|
|
135
|
+
for (;;) {
|
|
136
|
+
const answer = await ask(`Choose 1-${choices.length}${def ? c.dim(` [${def}]`) : ""}: `);
|
|
137
|
+
const n = answer ? Number(answer) : def;
|
|
138
|
+
if (Number.isInteger(n) && n >= 1 && n <= choices.length)
|
|
139
|
+
return choices[n - 1].value;
|
|
140
|
+
const byValue = choices.find((ch) => ch.value === answer);
|
|
141
|
+
if (byValue)
|
|
142
|
+
return byValue.value;
|
|
143
|
+
line(c.dim(` Choose a number from 1 to ${choices.length} (q to cancel).`));
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
async multi(prompt, choices, options = {}) {
|
|
147
|
+
line(prompt);
|
|
148
|
+
const selectable = choices.filter((ch) => !ch.locked);
|
|
149
|
+
for (const ch of choices.filter((ch) => ch.locked))
|
|
150
|
+
line(` ${symbols.ok} ${ch.label}${c.dim(" (always included)")}${ch.hint ? c.dim(` ${ch.hint}`) : ""}`);
|
|
151
|
+
selectable.forEach((ch, i) => line(` ${i + 1}. ${ch.label}${ch.hint ? c.dim(` ${ch.hint}`) : ""}`));
|
|
152
|
+
const def = (options.default ?? []).filter((v) => selectable.some((ch) => ch.value === v));
|
|
153
|
+
for (;;) {
|
|
154
|
+
const answer = await ask(`Numbers, comma-separated, or none${def.length ? c.dim(` [${def.map((v) => selectable.findIndex((ch) => ch.value === v) + 1).join(",")}]`) : ""}: `);
|
|
155
|
+
if (!answer)
|
|
156
|
+
return [...def];
|
|
157
|
+
if (answer === "none")
|
|
158
|
+
return [];
|
|
159
|
+
const parts = answer.split(",").map((p) => p.trim()).filter(Boolean);
|
|
160
|
+
const picked = parts.map((p) => (Number.isInteger(Number(p)) ? selectable[Number(p) - 1]?.value : selectable.find((ch) => ch.value === p)?.value));
|
|
161
|
+
if (picked.every((v) => typeof v === "string"))
|
|
162
|
+
return [...new Set(picked)];
|
|
163
|
+
line(c.dim(` Use numbers from 1 to ${selectable.length}, comma-separated, or none (q to cancel).`));
|
|
164
|
+
}
|
|
165
|
+
},
|
|
166
|
+
async confirm(prompt, defaultValue) {
|
|
167
|
+
for (;;) {
|
|
168
|
+
const answer = (await ask(`${prompt} ${c.dim(defaultValue ? "[Y/n]" : "[y/N]")} `)).toLowerCase();
|
|
169
|
+
if (!answer)
|
|
170
|
+
return defaultValue;
|
|
171
|
+
if (answer === "y" || answer === "yes")
|
|
172
|
+
return true;
|
|
173
|
+
if (answer === "n" || answer === "no")
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
},
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
// ── The interview ────────────────────────────────────────────────────────────
|
|
180
|
+
const NAME = /^[a-z][a-z0-9-]{0,62}$/;
|
|
181
|
+
const IDENT = /^[a-z][a-zA-Z0-9]{0,40}$/;
|
|
182
|
+
const PERMISSION = /^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9*]+)+$/;
|
|
183
|
+
const guideFor = (id) => CAPABILITY_GUIDE.find((g) => g.id === id);
|
|
184
|
+
const isCapability = (id) => CATALOG.has(id);
|
|
185
|
+
export function defaultAnswers(dir, name) {
|
|
186
|
+
return { dir, name, description: "", kind: "collaboration", participants: ["collaborators", "administrators"], include: [], params: {}, entities: [], workflows: [], notComposable: [], agentPermissions: [], tenancy: "workspaces", roles: [], managers: [] };
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Ask, section by section, adapting to earlier answers. Returns the answers, or throws Cancelled.
|
|
190
|
+
* `sections` limits a pass to what the developer wants to change (the review loop).
|
|
191
|
+
*/
|
|
192
|
+
export async function interview(io, start, sections = ["basics", "kind", "participants", "capabilities", "details", "data"]) {
|
|
193
|
+
const a = { ...start, participants: [...start.participants], include: [...start.include], params: JSON.parse(JSON.stringify(start.params)), entities: [...start.entities], workflows: [...start.workflows], notComposable: [...start.notComposable], agentPermissions: [...start.agentPermissions], roles: [...start.roles], managers: [...start.managers] };
|
|
194
|
+
const param = (cap, key) => a.params[cap]?.[key];
|
|
195
|
+
const setParam = (cap, key, value) => {
|
|
196
|
+
(a.params[cap] ??= {})[key] = value;
|
|
197
|
+
};
|
|
198
|
+
if (sections.includes("basics")) {
|
|
199
|
+
a.name = await io.text("Application name (lower-case, digits, dashes)", { default: a.name, required: true, validate: (v) => (NAME.test(v) ? null : "Use lower-case letters, digits and dashes, starting with a letter.") });
|
|
200
|
+
a.description = await io.text("One line about what it does", { default: a.description || undefined });
|
|
201
|
+
}
|
|
202
|
+
if (sections.includes("kind")) {
|
|
203
|
+
const previousKind = a.kind;
|
|
204
|
+
a.kind = (await io.choose("What kind of application are you building?", APP_KINDS, { default: a.kind }));
|
|
205
|
+
// The foundation follows from one requirement: whether data belongs to organizations people join. The kind only suggests the answer.
|
|
206
|
+
const suggested = a.kind === previousKind ? a.tenancy : APP_KINDS.find((k) => k.value === a.kind).tenancy;
|
|
207
|
+
a.tenancy = (await io.choose("Who does the data belong to?", TENANCIES, { default: suggested }));
|
|
208
|
+
const profile = profileFor(a);
|
|
209
|
+
io.say(c.dim(` Foundation: ${profile.id} (${profile.required.join(", ")}). ${a.tenancy === "workspaces" ? "Workspaces and invitations are included because the data belongs to organizations." : "No workspace, membership or invitation is included: people have their own accounts and their own records."}`));
|
|
210
|
+
// Selections that exist only with workspaces leave with them.
|
|
211
|
+
if (a.tenancy === "individuals") {
|
|
212
|
+
const dropped = a.participants.filter((p) => PARTICIPANTS.find((q) => q.value === p)?.needs === "workspaces");
|
|
213
|
+
if (dropped.length)
|
|
214
|
+
io.say(c.dim(` Not without workspaces: ${dropped.map((p) => PARTICIPANTS.find((q) => q.value === p).label).join(", ")}.`));
|
|
215
|
+
a.participants = a.participants.filter((p) => !dropped.includes(p));
|
|
216
|
+
a.include = a.include.filter((id) => profile.optional.includes(id));
|
|
217
|
+
a.entities = a.entities.map((e) => (e.scope === "workspace" ? { ...e, scope: "personal", owned: true } : e));
|
|
218
|
+
delete a.params["workspace.tenancy"];
|
|
219
|
+
delete a.params["workspace.invitations"];
|
|
220
|
+
delete a.params["agents.membership"];
|
|
221
|
+
}
|
|
222
|
+
else {
|
|
223
|
+
a.entities = a.entities.map((e) => (e.scope === "personal" ? { ...e, scope: "workspace" } : e));
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
const profile = profileFor(a);
|
|
227
|
+
if (sections.includes("participants")) {
|
|
228
|
+
const fitting = PARTICIPANTS.filter((p) => !p.needs || p.needs === a.tenancy);
|
|
229
|
+
const defaults = (a.participants.length ? a.participants : a.kind === "portal" || a.kind === "marketplace" ? ["customers", "administrators"] : a.kind === "operations" ? ["staff", "administrators"] : a.kind === "personal" ? ["customers"] : ["collaborators", "administrators"]).filter((p) => fitting.some((f) => f.value === p));
|
|
230
|
+
a.participants = (await io.multi("Who uses it?", fitting, { default: defaults }));
|
|
231
|
+
if (fitting.length < PARTICIPANTS.length)
|
|
232
|
+
io.say(c.dim(` Not offered without workspaces: ${PARTICIPANTS.filter((p) => p.needs && p.needs !== a.tenancy).map((p) => `${p.label} (${p.hint})`).join("; ")}.`));
|
|
233
|
+
}
|
|
234
|
+
if (sections.includes("capabilities")) {
|
|
235
|
+
// Every capability the profile allows is offered. `offeredFor` says who a capability is usually for, which belongs
|
|
236
|
+
// in its hint: using it to remove the choice made the interview less expressive than the flags, so a composition
|
|
237
|
+
// the resolver accepts and `--include` produces could not be reached by answering questions at all (Level B case
|
|
238
|
+
// c_041f766abb22ef: individual accounts, collaborators only, ops.operator). The profile bounds what may be
|
|
239
|
+
// included; the participants only say what is usual.
|
|
240
|
+
const offered = CAPABILITY_GUIDE.filter((g) => profile.optional.includes(g.id));
|
|
241
|
+
const usual = (g) => !g.offeredFor || g.offeredFor.some((p) => a.participants.includes(p));
|
|
242
|
+
const notInProfile = CAPABILITY_GUIDE.filter((g) => !profile.optional.includes(g.id) && !profile.required.includes(g.id));
|
|
243
|
+
const choices = [
|
|
244
|
+
...CAPABILITY_GUIDE.filter((g) => profile.required.includes(g.id)).map((g) => ({ value: g.id, label: g.label, hint: g.provides, locked: true })),
|
|
245
|
+
...offered.map((g) => ({
|
|
246
|
+
value: g.id,
|
|
247
|
+
label: g.label,
|
|
248
|
+
hint: `${g.provides}${CATALOG.get(g.id).requires.length ? ` (needs ${CATALOG.get(g.id).requires.join(", ")})` : ""}${usual(g) ? "" : ` (usually for ${g.offeredFor.join(", ")})`}`,
|
|
249
|
+
})),
|
|
250
|
+
];
|
|
251
|
+
const picked = await io.multi("Which capabilities does it need? Each is a real platform capability; its constraints and what stays yours are shown in the review.", choices, { default: a.include.filter((id) => offered.some((g) => g.id === id)) });
|
|
252
|
+
a.include = picked.filter(isCapability);
|
|
253
|
+
// A dependency is included explicitly here, with the reason, never silently.
|
|
254
|
+
for (const id of [...a.include]) {
|
|
255
|
+
for (const dep of CATALOG.get(id).requires) {
|
|
256
|
+
if (!profile.required.includes(dep) && !a.include.includes(dep)) {
|
|
257
|
+
io.say(` ${symbols.ok} ${guideFor(dep)?.label ?? dep} is included because ${guideFor(id)?.label ?? id} requires it.`);
|
|
258
|
+
a.include.push(dep);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
const unusual = offered.filter((g) => !usual(g));
|
|
263
|
+
if (unusual.length)
|
|
264
|
+
io.say(c.dim(` Offered, though usually for other participants: ${unusual.map((g) => `${g.label} (for ${g.offeredFor.join(", ")})`).join("; ")}.`));
|
|
265
|
+
if (notInProfile.length)
|
|
266
|
+
io.say(c.dim(` Not part of the ${profile.id} foundation: ${notInProfile.map((g) => g.label).join("; ")}.`));
|
|
267
|
+
a.notComposable = await io.multi("Anything else it needs? These are not composable yet; they are recorded as work the application owns, with what the SDK offers instead.", NOT_COMPOSABLE.map((n) => ({ value: n.id, label: n.label, hint: n.status })), { default: a.notComposable });
|
|
268
|
+
}
|
|
269
|
+
if (sections.includes("details")) {
|
|
270
|
+
// Accounts (required by both profiles). With workspaces the sender is required (invitations are e-mailed); without, it is optional.
|
|
271
|
+
if (a.tenancy === "workspaces") {
|
|
272
|
+
setParam("identity.accounts", "emailFrom", await io.text("Sender address for account e-mail (verification, sign-in links, invitations)", { default: param("identity.accounts", "emailFrom"), required: true, validate: (v) => (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) ? null : "An e-mail address, like auth@example.com.") }));
|
|
273
|
+
setParam("identity.accounts", "magicLink", await io.confirm("E-mailed sign-in links (with a code) besides passwords?", param("identity.accounts", "magicLink") ?? true));
|
|
274
|
+
setParam("identity.accounts", "signUp", (await io.choose("Who may create an account?", [{ value: "open", label: "Anyone (open sign-up)" }, { value: "invited", label: "Only people who were invited" }], { default: param("identity.accounts", "signUp") === false ? "invited" : "open" })) === "open");
|
|
275
|
+
}
|
|
276
|
+
else {
|
|
277
|
+
const sender = await io.text("Sender address for account e-mail (verification, password reset, sign-in links); empty for none", { default: param("identity.accounts", "emailFrom") || undefined, validate: (v) => (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) ? null : "An e-mail address, like auth@example.com.") });
|
|
278
|
+
setParam("identity.accounts", "emailFrom", sender || null);
|
|
279
|
+
setParam("identity.accounts", "magicLink", sender ? await io.confirm("E-mailed sign-in links (with a code) besides passwords?", param("identity.accounts", "magicLink") ?? false) : false);
|
|
280
|
+
setParam("identity.accounts", "signUp", true);
|
|
281
|
+
io.say(c.dim(" Sign-up is open: without invitations, nothing else would create an account (an operator cannot create one today)."));
|
|
282
|
+
setParam("identity.accounts", "baseRole", await io.text("What is a signed-in person called? The role every account holds (person, user, member…)", { default: param("identity.accounts", "baseRole") ?? "person", required: true, validate: (v) => (IDENT.test(v) ? null : "A single lower-case word.") }));
|
|
283
|
+
const base = param("identity.accounts", "baseRole");
|
|
284
|
+
const rolesText = await io.text(`Application roles beyond ${base}, highest first, comma-separated (e.g. admin); empty for none. They are held by accounts; granting one has no Studio or CLI action yet (the runtime's accounts.setRoles).`, { default: (a.roles.length ? a.roles : suggestedAppRoles(a.participants)).join(", ") || undefined, validate: (v) => (v.split(",").map((r) => r.trim()).filter(Boolean).every((r) => IDENT.test(r) && r !== base) ? null : `Lower-case words other than ${base}, comma-separated.`) });
|
|
285
|
+
a.roles = [...new Set(rolesText.split(",").map((r) => r.trim()).filter(Boolean))];
|
|
286
|
+
a.managers = a.roles.length ? await io.multi("Which of these may change anyone's shared records (and write shared records nobody owns)?", a.roles.map((r) => ({ value: r, label: r })), { default: (a.managers.length ? a.managers : [a.roles[0]]).filter((r) => a.roles.includes(r)) }) : [];
|
|
287
|
+
io.say(c.dim(` Personal entities are each person's own, whatever their role; shared entities are read by every ${base}${a.managers.length ? ` and changed by ${a.managers.join(", ")}` : ""}; you choose per entity in a moment.`));
|
|
288
|
+
}
|
|
289
|
+
// Workspaces (required by the collaborative-workspace profile): noun, roles, managers, creation.
|
|
290
|
+
if (a.tenancy === "workspaces") {
|
|
291
|
+
const nounDefault = param("workspace.tenancy", "noun") ?? (a.kind === "business" || a.kind === "operations" ? "organization" : a.kind === "portal" ? "account" : a.kind === "marketplace" ? "store" : "workspace");
|
|
292
|
+
setParam("workspace.tenancy", "noun", await io.text("What is a workspace called in your application? (workspace, organization, team, account, store…)", { default: nounDefault, required: true, validate: (v) => (IDENT.test(v) ? null : "A single lower-case word.") }));
|
|
293
|
+
const roleDefault = param("workspace.tenancy", "roles") ?? suggestedRoles(a.participants);
|
|
294
|
+
const rolesText = await io.text("Member roles, highest first (comma-separated). The first holds every workspace permission.", { default: roleDefault.join(", "), required: true, validate: (v) => (v.split(",").map((r) => r.trim()).every((r) => IDENT.test(r)) ? null : "Lower-case words, comma-separated.") });
|
|
295
|
+
const roles = [...new Set(rolesText.split(",").map((r) => r.trim()).filter(Boolean))];
|
|
296
|
+
setParam("workspace.tenancy", "roles", roles);
|
|
297
|
+
const managerDefault = (param("workspace.tenancy", "managers") ?? roles.filter((r) => r === "admin")).filter((r) => roles.includes(r) && r !== roles[0]);
|
|
298
|
+
const managers = roles.length > 1 ? await io.multi(`Which roles manage members (invite, change roles, remove) without being the ${roles[0]}?`, roles.slice(1).map((r) => ({ value: r, label: r })), { default: managerDefault }) : [];
|
|
299
|
+
setParam("workspace.tenancy", "managers", managers);
|
|
300
|
+
setParam("workspace.tenancy", "create", (await io.choose(`Who may create a ${param("workspace.tenancy", "noun")}?`, [{ value: "anyone", label: "Anyone signed in" }, { value: "none", label: "Nobody through the application (you create them another way)" }], { default: param("workspace.tenancy", "create") ?? "anyone" })));
|
|
301
|
+
const existingClaims = param("workspace.tenancy", "claims") ?? {};
|
|
302
|
+
const claimsText = await io.text(`Typed claims each membership carries beside its role: name:type, comma-separated (string, number, integer, boolean, enum(a|b); =value sets a default); empty for none`, { default: Object.entries(existingClaims).map(([n, s]) => `${n}:${s.type === "enum" ? `enum(${s.values.join("|")})` : s.type}${s.default !== undefined ? `=${String(s.default)}` : ""}`).join(", ") || undefined, validate: (v) => { try {
|
|
303
|
+
parseClaims(v);
|
|
304
|
+
return null;
|
|
305
|
+
}
|
|
306
|
+
catch (e) {
|
|
307
|
+
return `${e.message} ${e.hint}`;
|
|
308
|
+
} } });
|
|
309
|
+
const claims = parseClaims(claimsText);
|
|
310
|
+
if (Object.keys(claims).length) {
|
|
311
|
+
setParam("workspace.tenancy", "claims", claims);
|
|
312
|
+
io.say(c.dim(` Claims are set per member through the server (an invitation, or POST /api/tenants/current/members/claims by a member manager), validated on write and checked on every call; a request never supplies one. Entities may require one in a moment.`));
|
|
313
|
+
}
|
|
314
|
+
else if (a.params["workspace.tenancy"])
|
|
315
|
+
delete a.params["workspace.tenancy"].claims;
|
|
316
|
+
io.say(c.dim(` Data isolation: collections you mark { tenant: true } are scoped to the current ${param("workspace.tenancy", "noun")}; you choose per entity in a moment.`));
|
|
317
|
+
}
|
|
318
|
+
// Optional capabilities' parameters.
|
|
319
|
+
if (a.include.includes("services.files")) {
|
|
320
|
+
const max = await io.text("Largest file, in MiB (empty keeps FeltKit's default of 1)", { default: param("services.files", "maxBytes") ? String(Number(param("services.files", "maxBytes")) / 1048576) : undefined, validate: (v) => (Number(v) > 0 ? null : "A positive number of MiB.") });
|
|
321
|
+
if (max)
|
|
322
|
+
setParam("services.files", "maxBytes", Math.round(Number(max) * 1048576));
|
|
323
|
+
io.say(c.dim(" Who may read which files, and what they attach to, is yours (permissions files.read / files.write on your roles)."));
|
|
324
|
+
}
|
|
325
|
+
if (a.include.includes("services.notifications")) {
|
|
326
|
+
const types = await io.text("Notification types, comma-separated (empty for untyped)", { default: (param("services.notifications", "types") ?? []).join(", ") || undefined });
|
|
327
|
+
setParam("services.notifications", "types", types.split(",").map((t) => t.trim()).filter(Boolean));
|
|
328
|
+
}
|
|
329
|
+
if (a.include.includes("services.jobs"))
|
|
330
|
+
io.say(c.dim(" Background jobs: handlers are your functions (\"<module>:<function>\"); declare them in feltkit/app.ts under services.jobs.handlers when you write them. Jobs are durable: queued in a transaction, retried, inspectable in Studio."));
|
|
331
|
+
if (a.include.includes("services.schedules"))
|
|
332
|
+
io.say(c.dim(" Scheduled work runs jobs on a schedule; the schedules are yours to declare."));
|
|
333
|
+
if (a.include.includes("agents.membership")) {
|
|
334
|
+
setParam("agents.membership", "role", await io.text("Name of the agent role", { default: param("agents.membership", "role") ?? "agent", required: true, validate: (v) => (IDENT.test(v) ? null : "A lower-case word.") }));
|
|
335
|
+
const perms = await io.text("What may agents do? Permissions, comma-separated (e.g. notes.read, notes.create); empty for nothing yet", { default: a.agentPermissions.join(", ") || undefined, validate: (v) => (v.split(",").map((p) => p.trim()).filter(Boolean).every((p) => PERMISSION.test(p)) ? null : "Permissions like entity.action or entity.*") });
|
|
336
|
+
a.agentPermissions = perms.split(",").map((p) => p.trim()).filter(Boolean);
|
|
337
|
+
}
|
|
338
|
+
if (a.include.includes("ops.operator"))
|
|
339
|
+
setParam("ops.operator", "role", await io.text("Name of the operator role", { default: param("ops.operator", "role") ?? "operator", required: true, validate: (v) => (IDENT.test(v) ? null : "A lower-case word.") }));
|
|
340
|
+
}
|
|
341
|
+
if (sections.includes("data")) {
|
|
342
|
+
const noun = param("workspace.tenancy", "noun") ?? "workspace";
|
|
343
|
+
const base = param("identity.accounts", "baseRole") ?? "person";
|
|
344
|
+
const names = await io.text("What business information does it manage? Entity names, comma-separated (e.g. notes, projects, invoices); empty for none yet", { default: a.entities.map((e) => e.name).join(", ") || undefined, validate: (v) => (v.split(",").map((e) => e.trim()).filter(Boolean).every((e) => IDENT.test(e)) ? null : "Lower-case names like notes, projects.") });
|
|
345
|
+
const entityNames = [...new Set(names.split(",").map((e) => e.trim()).filter(Boolean))];
|
|
346
|
+
const entities = [];
|
|
347
|
+
for (const name of entityNames) {
|
|
348
|
+
const previous = a.entities.find((e) => e.name === name);
|
|
349
|
+
io.say(c.bold(` ${name}`));
|
|
350
|
+
const description = await io.text(` What is a ${name.replace(/s$/, "")}? (one line, optional)`, { default: previous?.description || undefined });
|
|
351
|
+
const scopes = a.tenancy === "workspaces"
|
|
352
|
+
? [{ value: "workspace", label: `Members of the ${noun} it belongs to`, hint: `{ tenant: true }: scoped on every read and write` }, { value: "shared", label: `Everyone signed in, across ${noun}s`, hint: "a shared collection" }]
|
|
353
|
+
: [{ value: "personal", label: "Only the person who created it", hint: "each person's own records; nobody else sees them" }, { value: "shared", label: `Every ${base} signed in`, hint: `a shared collection${a.managers.length ? `; ${a.managers.join(", ")} may change any record` : ""}` }];
|
|
354
|
+
const scope = (await io.choose(` Who can see ${name}?`, scopes, { default: previous?.scope && scopes.some((x) => x.value === previous.scope) ? previous.scope : scopes[0].value }));
|
|
355
|
+
const fields = parseFields(await io.text(` Fields of ${name}: name:type, comma-separated (string, number, boolean, enum(a|b); ? = optional)`, { default: previous ? previous.fields.map((f) => `${f.name}:${f.type === "enum" ? `enum(${f.values.join("|")})` : f.type}${f.required ? "" : "?"}`).join(", ") : "title:string", required: true, validate: (v) => { try {
|
|
356
|
+
parseFields(v);
|
|
357
|
+
return null;
|
|
358
|
+
}
|
|
359
|
+
catch (e) {
|
|
360
|
+
return `${e.message} ${e.hint}`;
|
|
361
|
+
} } }));
|
|
362
|
+
const others = entityNames.filter((n) => n !== name);
|
|
363
|
+
const relations = others.length
|
|
364
|
+
? parseRelations(await io.text(` Relationships of ${name}: field -> entity, comma-separated (one of ${others.join(", ")}; ? = optional); empty for none`, { default: previous?.relations.map((r) => `${r.field.replace(/Id$/, "")} -> ${r.target}${r.required ? "" : "?"}`).join(", ") || undefined, validate: (v) => { try {
|
|
365
|
+
for (const r of parseRelations(v))
|
|
366
|
+
if (!others.includes(r.target))
|
|
367
|
+
return `"${r.target}" is not one of ${others.join(", ")}.`;
|
|
368
|
+
return null;
|
|
369
|
+
}
|
|
370
|
+
catch (e) {
|
|
371
|
+
return `${e.message} ${e.hint}`;
|
|
372
|
+
} } }))
|
|
373
|
+
: [];
|
|
374
|
+
const owned = scope === "personal" ? true : await io.confirm(` Is a ${name.replace(/s$/, "")} owned by whoever creates it (only the creator${scope === "workspace" || a.managers.length ? " or a managing role" : ""} may change or remove it)?`, previous?.owned ?? true);
|
|
375
|
+
const isPublic = scope === "shared" ? await io.confirm(` May anyone read ${name} without signing in (list and get public; writes still need their permission)?`, previous?.public ?? false) : false;
|
|
376
|
+
const attachments = await io.confirm(` Do ${name} carry file attachments (seen by whoever sees the record; attached and removed by whoever may change it)?`, previous?.attachments ?? false);
|
|
377
|
+
if (attachments && !a.include.includes("services.files")) {
|
|
378
|
+
io.say(` ${symbols.ok} Files and documents is included because ${name} carry attachments.`);
|
|
379
|
+
a.include.push("services.files");
|
|
380
|
+
}
|
|
381
|
+
const declaredClaims = param("workspace.tenancy", "claims") ?? {};
|
|
382
|
+
let requires;
|
|
383
|
+
if (scope === "workspace" && Object.keys(declaredClaims).length) {
|
|
384
|
+
const text = await io.text(` Require a membership claim to use ${name} at all? claim=value (| for several; one of ${Object.keys(declaredClaims).join(", ")}); empty for none`, { default: previous?.requires ? `${previous.requires.claim}=${previous.requires.values.map(String).join("|")}` : undefined, validate: (v) => { if (!v.trim())
|
|
385
|
+
return null; try {
|
|
386
|
+
parseRequire(v, declaredClaims);
|
|
387
|
+
return null;
|
|
388
|
+
}
|
|
389
|
+
catch (e) {
|
|
390
|
+
return `${e.message} ${e.hint}`;
|
|
391
|
+
} } });
|
|
392
|
+
if (text.trim())
|
|
393
|
+
requires = parseRequire(text, declaredClaims);
|
|
394
|
+
}
|
|
395
|
+
const unique = parseUnique(await io.text(` Unique fields of ${name}, comma-separated (several constraints with ;); empty for none`, { default: previous?.unique.map((g) => g.join(",")).join("; ") || undefined, validate: (v) => { const known = [...fields.map((f) => f.name), ...relations.map((r) => r.field)]; const bad = parseUnique(v).flat().find((f) => !known.includes(f)); return bad ? `"${bad}" is not a field of ${name} (${known.join(", ")}).` : null; } }));
|
|
396
|
+
entities.push({ name, ...(description ? { description } : {}), scope, owned, ...(isPublic ? { public: true } : {}), ...(attachments ? { attachments: true } : {}), ...(requires ? { requires } : {}), fields, relations, unique });
|
|
397
|
+
}
|
|
398
|
+
try {
|
|
399
|
+
validateEntities(entities, a.tenancy, param("workspace.tenancy", "claims") ?? {});
|
|
400
|
+
}
|
|
401
|
+
catch (e) {
|
|
402
|
+
io.say(`${symbols.fail} ${e.message} ${c.dim(e.hint)}`);
|
|
403
|
+
return interview(io, { ...a, entities }, ["data"]);
|
|
404
|
+
}
|
|
405
|
+
a.entities = entities;
|
|
406
|
+
const workflows = await io.text("Important workflows it should support, comma-separated (recorded as application work; empty for none)", { default: a.workflows.join(", ") || undefined });
|
|
407
|
+
a.workflows = workflows.split(",").map((w) => w.trim()).filter(Boolean);
|
|
408
|
+
}
|
|
409
|
+
return a;
|
|
410
|
+
}
|
|
411
|
+
/** Application roles for a foundation without workspaces: administrators and staff, when present, manage shared data. */
|
|
412
|
+
function suggestedAppRoles(participants) {
|
|
413
|
+
const roles = [];
|
|
414
|
+
if (participants.includes("administrators"))
|
|
415
|
+
roles.push("admin");
|
|
416
|
+
if (participants.includes("staff"))
|
|
417
|
+
roles.push("staff");
|
|
418
|
+
return roles;
|
|
419
|
+
}
|
|
420
|
+
function suggestedRoles(participants) {
|
|
421
|
+
const roles = ["owner"];
|
|
422
|
+
if (participants.includes("administrators"))
|
|
423
|
+
roles.push("admin");
|
|
424
|
+
if (participants.includes("staff") || participants.includes("collaborators") || !participants.length)
|
|
425
|
+
roles.push("member");
|
|
426
|
+
if (participants.includes("customers"))
|
|
427
|
+
roles.push("customer");
|
|
428
|
+
if (participants.includes("partners"))
|
|
429
|
+
roles.push("partner");
|
|
430
|
+
if (participants.includes("collaborators") || participants.includes("staff"))
|
|
431
|
+
roles.push("guest");
|
|
432
|
+
return [...new Set(roles)];
|
|
433
|
+
}
|
|
434
|
+
// ── The composition, from the answers ────────────────────────────────────────
|
|
435
|
+
/** The composition request the answers translate to: the inputs `feltkit compose` records. */
|
|
436
|
+
export function compositionInputs(a) {
|
|
437
|
+
const PROFILE = profileFor(a);
|
|
438
|
+
const params = {};
|
|
439
|
+
for (const [cap, ps] of Object.entries(a.params)) {
|
|
440
|
+
// Parameters of capabilities that are not part of the composition are not recorded.
|
|
441
|
+
if (!PROFILE.required.includes(cap) && !a.include.includes(cap))
|
|
442
|
+
continue;
|
|
443
|
+
const own = {};
|
|
444
|
+
for (const [k, v] of Object.entries(ps)) {
|
|
445
|
+
const spec = CATALOG.get(cap)?.parameters[k];
|
|
446
|
+
// Only values that differ from the capability's own default (and the profile's) are recorded.
|
|
447
|
+
const profileDefault = PROFILE.defaults[cap]?.[k];
|
|
448
|
+
const effectiveDefault = profileDefault !== undefined ? profileDefault : spec?.default;
|
|
449
|
+
if (spec && canonical(v) === canonical(effectiveDefault === undefined ? null : effectiveDefault))
|
|
450
|
+
continue;
|
|
451
|
+
own[k] = v;
|
|
452
|
+
}
|
|
453
|
+
if (Object.keys(own).length)
|
|
454
|
+
params[cap] = own;
|
|
455
|
+
}
|
|
456
|
+
return { profile: PROFILE.id, include: [...new Set(a.include)].sort(), params };
|
|
457
|
+
}
|
|
458
|
+
/** What the composition would be: the resolver's own output, plus what the application adds and what stays its own. */
|
|
459
|
+
export function preview(a) {
|
|
460
|
+
const PROFILE = profileFor(a);
|
|
461
|
+
const inputs = compositionInputs(a);
|
|
462
|
+
const result = generateFoundation(inputs);
|
|
463
|
+
const explicit = a.include.filter((id) => !CATALOG.get(id).requires.some((dep) => a.include.includes(dep) && !PROFILE.required.includes(dep)) || true);
|
|
464
|
+
const implied = PROFILE.required.map((id) => ({ id, because: `required by the ${PROFILE.id} profile` }));
|
|
465
|
+
for (const id of a.include)
|
|
466
|
+
for (const dep of CATALOG.get(id).requires)
|
|
467
|
+
if (!PROFILE.required.includes(dep) && a.include.includes(dep) && !explicit.includes(dep))
|
|
468
|
+
implied.push({ id: dep, because: `required by ${id}` });
|
|
469
|
+
const attached = a.entities.filter((e) => e.attachments).map((e) => e.name);
|
|
470
|
+
if (attached.length && a.include.includes("services.files"))
|
|
471
|
+
implied.push({ id: "services.files", because: `${attached.join(", ")} carry file attachments` });
|
|
472
|
+
return {
|
|
473
|
+
profile: PROFILE,
|
|
474
|
+
inputs,
|
|
475
|
+
result,
|
|
476
|
+
explicit,
|
|
477
|
+
implied,
|
|
478
|
+
entities: a.entities,
|
|
479
|
+
roles: result.ok ? applicationRoles(a, result) : {},
|
|
480
|
+
notComposable: a.notComposable.map((id) => NOT_COMPOSABLE.find((n) => n.id === id)).filter(Boolean).map((n) => ({ label: n.label, status: n.status })),
|
|
481
|
+
applicationOwned: [
|
|
482
|
+
...a.entities.map((e) => `${e.name}: the screens that use it, and any rule beyond create/list/get/update/remove with ${e.scope === "personal" ? "personal scope (the creator's alone)" : e.owned ? "creator ownership" : "no ownership rule"}${e.public ? ", public reads" : ""} (generated in feltkit/${e.name}.ts, yours to change)`),
|
|
483
|
+
...(a.tenancy === "individuals" && a.roles.length ? [`granting ${a.roles.join(", ")} to accounts: the runtime's accounts.setRoles; no Studio or CLI action exists yet (limitation roles.assignment)`] : []),
|
|
484
|
+
...a.workflows.map((w) => `workflow: ${w}`),
|
|
485
|
+
...(a.include.includes("services.jobs") ? ["job handlers, and queuing them from your functions"] : []),
|
|
486
|
+
...(a.include.includes("services.notifications") ? ["sending notifications from your functions"] : []),
|
|
487
|
+
...(a.entities.some((e) => e.attachments) ? [`uploading files from the browser (PUT the bytes to the url attachLink returns) and showing them; the Files service is application-wide, so the per-record binding is the generated functions' (feltkit/<entity>.ts files, download, attach, attachLink, detach)`] : []),
|
|
488
|
+
...(a.include.includes("services.files") && !a.entities.some((e) => e.attachments) ? ["files: the service is enabled but no entity carries attachments, so nothing uses it yet; your roles hold no files.* until you grant it"] : []),
|
|
489
|
+
...(Object.keys(a.params["workspace.tenancy"]?.claims ?? {}).length ? ["setting members' claims: an invitation's claims, or POST /api/tenants/current/members/claims by a member manager; no Studio screen edits claims yet"] : []),
|
|
490
|
+
...(a.include.includes("agents.membership") ? ["the agent itself (app.agent)"] : []),
|
|
491
|
+
...a.notComposable.map((id) => NOT_COMPOSABLE.find((n) => n.id === id)?.label ?? id),
|
|
492
|
+
...PROFILE.limitations.map((l) => `${l.id}: ${l.requirement} (upheld by your tests; the foundation cannot enforce it)`),
|
|
493
|
+
],
|
|
494
|
+
};
|
|
495
|
+
}
|
|
496
|
+
/** The application's roles: the foundation's permissions, plus permissions on the application's own entities. */
|
|
497
|
+
/**
|
|
498
|
+
* File permissions follow entity permissions, for the entities that carry attachments: a role that reads such an entity
|
|
499
|
+
* holds files.read; one that changes it holds files.write and files.delete (attach, detach and the record's removal need
|
|
500
|
+
* them). Derived, never granted for an entity without attachments; shown in the review.
|
|
501
|
+
*/
|
|
502
|
+
function withFileGrants(a, roles) {
|
|
503
|
+
const attached = a.entities.filter((e) => e.attachments);
|
|
504
|
+
if (!attached.length)
|
|
505
|
+
return roles;
|
|
506
|
+
const out = {};
|
|
507
|
+
for (const [role, perms] of Object.entries(roles)) {
|
|
508
|
+
const files = [];
|
|
509
|
+
if (attached.some((e) => grants(perms, `${e.name}.read`)))
|
|
510
|
+
files.push("files.read");
|
|
511
|
+
if (attached.some((e) => grants(perms, `${e.name}.update`) || grants(perms, `${e.name}.delete`)))
|
|
512
|
+
files.push("files.write", "files.delete");
|
|
513
|
+
// Before the foundation's own permissions (the application's part comes first in app.ts), after the entity permissions.
|
|
514
|
+
const foundationIndex = perms.findIndex((x) => !a.entities.some((e) => x.startsWith(`${e.name}.`)) && !a.agentPermissions.includes(x));
|
|
515
|
+
const own = foundationIndex < 0 ? perms : perms.slice(0, foundationIndex);
|
|
516
|
+
const rest = foundationIndex < 0 ? [] : perms.slice(foundationIndex);
|
|
517
|
+
out[role] = [...own, ...files.filter((f) => !perms.includes(f)), ...rest];
|
|
518
|
+
}
|
|
519
|
+
return out;
|
|
520
|
+
}
|
|
521
|
+
function applicationRoles(a, result) {
|
|
522
|
+
return withFileGrants(a, baseApplicationRoles(a, result));
|
|
523
|
+
}
|
|
524
|
+
function baseApplicationRoles(a, result) {
|
|
525
|
+
const foundationRoles = result.resolved.options.roles ?? {};
|
|
526
|
+
if (a.tenancy === "individuals") {
|
|
527
|
+
// The base role (every account) and the application's roles. A starting point, stated in the review: everyone works
|
|
528
|
+
// with personal entities (ownership keeps them personal) and reads shared ones; owned shared records may be created by
|
|
529
|
+
// anyone (changed by the creator or a manager); managers do everything with shared entities.
|
|
530
|
+
const roles = {};
|
|
531
|
+
// Without any manager, a shared record nobody owns must still be writable by someone: the base role.
|
|
532
|
+
const entityPermissions = (manager) => a.entities.flatMap((e) => (e.scope === "personal" || manager || (!e.owned && !a.managers.length) ? [`${e.name}.*`] : e.owned ? [`${e.name}.read`, `${e.name}.create`, `${e.name}.update`, `${e.name}.delete`] : [`${e.name}.read`]));
|
|
533
|
+
const base = result.resolved.capabilities.find((x) => x.id === "identity.accounts")?.params.baseRole ?? "person";
|
|
534
|
+
for (const [role, perms] of Object.entries(foundationRoles))
|
|
535
|
+
roles[role] = [...(role === base ? entityPermissions(false) : []), ...perms];
|
|
536
|
+
for (const role of a.roles)
|
|
537
|
+
roles[role] = entityPermissions(a.managers.includes(role));
|
|
538
|
+
return roles;
|
|
539
|
+
}
|
|
540
|
+
const workspaceRoles = a.params["workspace.tenancy"]?.roles ?? ["owner", "admin", "member", "guest"];
|
|
541
|
+
const agentRole = a.include.includes("agents.membership") ? (a.params["agents.membership"]?.role ?? "agent") : null;
|
|
542
|
+
const roles = {};
|
|
543
|
+
for (const [role, perms] of Object.entries(foundationRoles)) {
|
|
544
|
+
const own = [];
|
|
545
|
+
if (workspaceRoles.includes(role) && a.entities.length) {
|
|
546
|
+
// A starting point, stated in the review: every workspace role but the last may manage the application's entities; the last may read them.
|
|
547
|
+
const last = workspaceRoles.length > 1 && role === workspaceRoles[workspaceRoles.length - 1];
|
|
548
|
+
for (const e of a.entities)
|
|
549
|
+
own.push(last ? `${e.name}.read` : `${e.name}.*`);
|
|
550
|
+
}
|
|
551
|
+
if (agentRole && role === agentRole)
|
|
552
|
+
own.push(...a.agentPermissions);
|
|
553
|
+
roles[role] = [...own, ...perms];
|
|
554
|
+
}
|
|
555
|
+
return roles;
|
|
556
|
+
}
|
|
557
|
+
// ── Rendering the review ─────────────────────────────────────────────────────
|
|
558
|
+
const grants = (held, permission) => held.some((g) => g === "*" || g === permission || (g.endsWith(".*") && permission.startsWith(g.slice(0, -1))));
|
|
559
|
+
/**
|
|
560
|
+
* Who may do what with an entity, operation by operation, from the resolved roles (what the application's roles will
|
|
561
|
+
* really grant) and the generated functions' rules: the roles holding each permission, "anyone" for a public read, and
|
|
562
|
+
* the ownership or scope rule the function applies after the permission. A description of generated behavior, proven by
|
|
563
|
+
* the generated tests; the permission check itself is the runtime's.
|
|
564
|
+
*/
|
|
565
|
+
export function authorizationLines(a, p, e) {
|
|
566
|
+
const roles = Object.entries(p.roles);
|
|
567
|
+
const holders = (permission) => roles.filter(([, held]) => grants(held, permission)).map(([role]) => role);
|
|
568
|
+
const tenancyParams = p.result.ok ? p.result.resolved.capabilities.find((x) => x.id === "workspace.tenancy")?.params : undefined;
|
|
569
|
+
// The same derivation the modules and tests use, so the preview cannot describe a rule the generator will not write.
|
|
570
|
+
const managers = a.tenancy === "workspaces" ? managingRoles(tenancyParams?.roles ?? [], tenancyParams?.managers ?? []) : managingRoles(a.roles, a.managers, "individuals");
|
|
571
|
+
const managed = e.owned && managers.length > 0 && (a.tenancy === "workspaces" ? e.scope === "workspace" : e.scope === "shared");
|
|
572
|
+
const then = e.scope === "workspace" ? `, in the caller's ${a.params["workspace.tenancy"]?.noun ?? "workspace"} only` : e.scope === "personal" ? ", the caller's own records only" : "";
|
|
573
|
+
const change = e.scope === "personal" ? ", the caller's own records only" : e.owned ? `, the creator${managed ? ` or ${managers.join("/")}` : ""} only` : "";
|
|
574
|
+
const who = (permission) => (holders(permission).length ? holders(permission).join(", ") : "nobody yet");
|
|
575
|
+
return [
|
|
576
|
+
...(e.requires ? [`every operation: only a membership whose claim ${e.requires.claim} is ${e.requires.values.map((v) => JSON.stringify(v)).join(" or ")} (set through the server; a permission alone is refused)`] : []),
|
|
577
|
+
`list, get: ${e.public ? "anyone, signed in or not (public)" : who(`${e.name}.read`)}${then}`,
|
|
578
|
+
`create: ${who(`${e.name}.create`)}`,
|
|
579
|
+
`update, remove: ${who(`${e.name}.update`)}${holders(`${e.name}.update`).join() !== holders(`${e.name}.delete`).join() ? ` / ${who(`${e.name}.delete`)}` : ""}${change}`,
|
|
580
|
+
...(e.scope === "personal" ? ["another person's record does not exist for the caller (NOT_FOUND), whatever their role"] : []),
|
|
581
|
+
...(e.attachments
|
|
582
|
+
? [
|
|
583
|
+
`files, download: ${who(`${e.name}.read`)}${then} (files.read granted to these roles${e.public ? "; public reads do not extend to files: the Files service needs a signed-in caller" : ""})`,
|
|
584
|
+
`attach, attachLink, detach: ${who(`${e.name}.update`)}${change} (files.write and files.delete granted to these roles)`,
|
|
585
|
+
"a file is bound to its record by metadata fixed at upload and checked on every read; a file of another record does not exist here",
|
|
586
|
+
]
|
|
587
|
+
: []),
|
|
588
|
+
];
|
|
589
|
+
}
|
|
590
|
+
export function renderPreview(a, p) {
|
|
591
|
+
const out = [];
|
|
592
|
+
const noun = a.params["workspace.tenancy"]?.noun ?? "workspace";
|
|
593
|
+
out.push(`${c.bold(a.name)}${a.description ? ` — ${a.description}` : ""} ${c.dim(`(${APP_KINDS.find((k) => k.value === a.kind)?.label}; ${a.participants.map((x) => PARTICIPANTS.find((q) => q.value === x)?.label ?? x).join(", ")})`)}`);
|
|
594
|
+
const PROFILE = p.profile;
|
|
595
|
+
out.push(`Foundation: ${PROFILE.id} v${PROFILE.version} — ${PROFILE.purpose}`);
|
|
596
|
+
out.push(c.dim(` Chosen because ${a.tenancy === "workspaces" ? "the data belongs to organizations people join" : "each person has their own account and their own records"}. Workspaces and invitations: ${a.tenancy === "workspaces" ? "included (required by this foundation)" : "not included (nothing in this foundation needs them)"}.`));
|
|
597
|
+
if (!p.result.ok) {
|
|
598
|
+
out.push(`${symbols.fail} The selection does not resolve:`);
|
|
599
|
+
for (const e of p.result.errors)
|
|
600
|
+
out.push(` ${e.code}${e.capability ? ` ${e.capability}${e.parameter ? `.${e.parameter}` : ""}` : ""}: ${e.message} ${c.dim(e.hint)}`);
|
|
601
|
+
return out;
|
|
602
|
+
}
|
|
603
|
+
const r = p.result.resolved;
|
|
604
|
+
out.push("Capabilities (the resolver's result):");
|
|
605
|
+
for (const cap of r.capabilities) {
|
|
606
|
+
const why = p.implied.find((i) => i.id === cap.id)?.because;
|
|
607
|
+
const g = guideFor(cap.id);
|
|
608
|
+
out.push(` ${symbols.ok} ${g?.label ?? cap.id} ${c.dim(`(${cap.id}@${cap.version}; ${why ?? "selected"})`)}`);
|
|
609
|
+
const shown = Object.entries(cap.params).filter(([, v]) => !(v && typeof v === "object" && !Array.isArray(v) && !Object.keys(v).length));
|
|
610
|
+
if (shown.length)
|
|
611
|
+
out.push(c.dim(` ${shown.map(([k, v]) => `${k} = ${JSON.stringify(v)}`).join(", ")}`));
|
|
612
|
+
if (g)
|
|
613
|
+
out.push(c.dim(` constraints: ${g.constraints}. yours: ${g.applicationOwned}.`));
|
|
614
|
+
}
|
|
615
|
+
if (a.tenancy === "workspaces")
|
|
616
|
+
out.push(`Identity and authority: accounts${r.options.auth?.accounts?.magicLink ? " with sign-in links" : ""}${r.options.auth?.accounts?.signUp === false ? ", invitation-only sign-up" : ", open sign-up"}; a ${noun} per group with roles ${(r.options.auth?.tenant?.roles ?? []).join(" > ")}${r.options.auth?.tenant?.create === "none" ? `; ${noun}s are not created through the application` : ""}.`);
|
|
617
|
+
const declaredClaims = (a.tenancy === "workspaces" ? r.options.auth?.tenant?.claims : undefined) ?? {};
|
|
618
|
+
if (Object.keys(declaredClaims).length) {
|
|
619
|
+
out.push(`Membership claims (typed, set through the server, checked at the boundary on every call; never a request field): ${Object.entries(declaredClaims).map(([n, s]) => `${n}: ${s.type === "enum" ? s.values.join(" | ") : s.type}${s.default !== undefined ? ` (default ${JSON.stringify(s.default)})` : ""}`).join("; ")}.`);
|
|
620
|
+
out.push(c.dim(` Set by an invitation's claims or POST /api/tenants/current/members/claims (tenant.members.manage); a value the declaration no longer accepts is withheld until set again. No Studio screen edits claims yet.`));
|
|
621
|
+
}
|
|
622
|
+
else
|
|
623
|
+
out.push(`Identity and authority: accounts${r.options.auth?.accounts?.magicLink ? " with sign-in links" : ""}, open sign-up${r.options.auth?.accounts?.email ? "" : ", no account e-mail (no verification or reset mail)"}; every account holds ${(r.options.auth?.accounts?.roles ?? []).join(", ")}${a.roles.length ? `; application roles ${a.roles.join(" > ")} held by accounts${a.managers.length ? ` (${a.managers.join(", ")} manage shared data)` : ""}` : ""}; no workspaces, memberships or invitations.`);
|
|
624
|
+
out.push("Roles (foundation permissions, plus yours on your entities):");
|
|
625
|
+
for (const [role, perms] of Object.entries(p.roles))
|
|
626
|
+
out.push(` ${role}: ${perms.length ? perms.join(", ") : c.dim("(nothing yet)")}`);
|
|
627
|
+
if (p.entities.length) {
|
|
628
|
+
out.push("Data (collections in feltkit/app.ts; list, get, create, update, remove in feltkit/<entity>.ts; proven by tests/domain.test.ts):");
|
|
629
|
+
for (const e of p.entities) {
|
|
630
|
+
out.push(` ${e.name}${e.description ? ` — ${e.description}` : ""}: ${e.scope === "workspace" ? `scoped to its ${noun} ({ tenant: true })` : e.scope === "personal" ? "personal (the creator's alone; nobody else lists, reads or changes it)" : a.tenancy === "workspaces" ? `shared across ${noun}s` : "shared by every signed-in person"}${e.owned && e.scope !== "personal" ? "; owned by the creator" : ""}${e.public ? "; readable by anyone (public list and get)" : ""}${e.attachments ? "; carries file attachments" : ""}${e.requires ? `; requires claim ${e.requires.claim} = ${e.requires.values.map((v) => JSON.stringify(v)).join(" | ")}` : ""}`);
|
|
631
|
+
out.push(c.dim(` fields: ${[...e.fields.map((f) => `${f.name}: ${f.type === "enum" ? f.values.join(" | ") : f.type}${f.required ? "" : "?"}`), ...(e.owned ? ["createdBy"] : []), "createdAt", "updatedAt"].join(", ")}`));
|
|
632
|
+
if (e.relations.length)
|
|
633
|
+
out.push(c.dim(` refers to: ${e.relations.map((r) => `${r.field} → ${r.target}${r.required ? "" : "?"} (FeltDB enforces the reference)`).join(", ")}`));
|
|
634
|
+
if (e.unique.length)
|
|
635
|
+
out.push(c.dim(` unique: ${e.unique.map((g) => g.join("+")).join("; ")}`));
|
|
636
|
+
out.push(c.dim(` permissions: ${PERMISSIONS.map((x) => `${e.name}.${x}`).join(", ")}`));
|
|
637
|
+
for (const l of authorizationLines(a, p, e))
|
|
638
|
+
out.push(c.dim(` ${l}`));
|
|
639
|
+
}
|
|
640
|
+
}
|
|
641
|
+
out.push(`Generated: ${GENERATED_PATHS.join(", ")} (generator-owned) · feltkit/app.ts, feltkit/<entity>.ts, tests, the screens (yours, written once).`);
|
|
642
|
+
out.push(c.dim(`Enforced by FeltKit for every application: ${r.enforced.join(", ")} (every function names its access; a caller gets nothing by being signed in).`));
|
|
643
|
+
if (PROFILE.limitations.length)
|
|
644
|
+
out.push(c.dim(`Limitations of this foundation (upheld by your code and tests, not by the declaration): ${PROFILE.limitations.map((l) => l.id).join(", ")}.`));
|
|
645
|
+
if (p.notComposable.length) {
|
|
646
|
+
out.push("Not composable yet (recorded as your work):");
|
|
647
|
+
for (const n of p.notComposable)
|
|
648
|
+
out.push(` ${n.label}: ${n.status}`);
|
|
649
|
+
}
|
|
650
|
+
out.push("Still yours to build:");
|
|
651
|
+
for (const w of p.applicationOwned)
|
|
652
|
+
out.push(` - ${w}`);
|
|
653
|
+
return out;
|
|
654
|
+
}
|
|
655
|
+
/** feltkit/app.ts for the answers: application-owned, written once, never touched by composition again. */
|
|
656
|
+
export function renderAppModule(a, p) {
|
|
657
|
+
const noun = a.params["workspace.tenancy"]?.noun ?? "workspace";
|
|
658
|
+
const lines = [];
|
|
659
|
+
lines.push("/**");
|
|
660
|
+
lines.push(` * ${a.name}${a.description ? `: ${a.description}` : ""}`);
|
|
661
|
+
lines.push(" *");
|
|
662
|
+
if (a.tenancy === "workspaces")
|
|
663
|
+
lines.push(" * Composed with `feltkit create`. The foundation (accounts, " + `${noun}s` + ", roles' " + `${noun}` + " permissions, invitations" + (a.include.length ? `, ${a.include.map((id) => guideFor(id)?.label.split(" (")[0].toLowerCase() ?? id).join(", ")}` : "") + ")");
|
|
664
|
+
else
|
|
665
|
+
lines.push(" * Composed with `feltkit create`. The foundation (accounts; no workspaces, memberships or invitations" + (a.include.length ? `; ${a.include.map((id) => guideFor(id)?.label.split(" (")[0].toLowerCase() ?? id).join(", ")}` : "") + ")");
|
|
666
|
+
lines.push(" * is generated into ./_foundation/declaration.ts from feltkit.composition.json; never edit it. Everything in this");
|
|
667
|
+
lines.push(" * file is yours: change it freely. `feltkit compose reconcile` tells you how the two relate.");
|
|
668
|
+
if (a.workflows.length || a.notComposable.length) {
|
|
669
|
+
lines.push(" *");
|
|
670
|
+
lines.push(" * Application work recorded at creation (not provided by the foundation):");
|
|
671
|
+
for (const w of a.workflows)
|
|
672
|
+
lines.push(` * - workflow: ${w}`);
|
|
673
|
+
for (const id of a.notComposable) {
|
|
674
|
+
const n = NOT_COMPOSABLE.find((x) => x.id === id);
|
|
675
|
+
if (n)
|
|
676
|
+
lines.push(` * - ${n.label}: ${n.status}`);
|
|
677
|
+
}
|
|
678
|
+
}
|
|
679
|
+
lines.push(" */");
|
|
680
|
+
lines.push('import { feltkit, s } from "@feltdb/feltkit";');
|
|
681
|
+
lines.push('import { foundation } from "./_foundation/declaration.js";');
|
|
682
|
+
lines.push("");
|
|
683
|
+
lines.push("export const app = feltkit({");
|
|
684
|
+
lines.push(` name: ${JSON.stringify(a.name)},`);
|
|
685
|
+
if (a.description)
|
|
686
|
+
lines.push(` description: ${JSON.stringify(a.description)},`);
|
|
687
|
+
lines.push(" // The whole foundation: a new capability's paths reach the declaration without an edit here.");
|
|
688
|
+
lines.push(" ...foundation,");
|
|
689
|
+
if (a.tenancy === "workspaces")
|
|
690
|
+
lines.push(` // Roles: the foundation's ${noun} permissions, plus what each role may do with your data. A starting point.`);
|
|
691
|
+
else
|
|
692
|
+
lines.push(" // Roles: the base role every account holds (from the foundation), plus the application's own roles, held by accounts (accounts.setRoles). A starting point.");
|
|
693
|
+
lines.push(" roles: {");
|
|
694
|
+
lines.push(" ...foundation.roles,");
|
|
695
|
+
const foundationRoles = p.result.ok ? (p.result.resolved.options.roles ?? {}) : {};
|
|
696
|
+
for (const [role, perms] of Object.entries(p.roles)) {
|
|
697
|
+
if (!(role in foundationRoles)) {
|
|
698
|
+
lines.push(` ${role}: [${perms.map((x) => JSON.stringify(x)).join(", ")}],`);
|
|
699
|
+
continue;
|
|
700
|
+
}
|
|
701
|
+
const own = perms.slice(0, perms.length - (foundationRoles[role]?.length ?? 0));
|
|
702
|
+
if (own.length)
|
|
703
|
+
lines.push(` ${role}: [${own.map((x) => JSON.stringify(x)).join(", ")}, ...foundation.roles.${role}],`);
|
|
704
|
+
}
|
|
705
|
+
lines.push(" },");
|
|
706
|
+
lines.push("});");
|
|
707
|
+
for (const e of a.entities) {
|
|
708
|
+
lines.push("");
|
|
709
|
+
lines.push(...renderCollection(e, noun, a.tenancy));
|
|
710
|
+
}
|
|
711
|
+
lines.push("");
|
|
712
|
+
return lines.join("\n");
|
|
713
|
+
}
|
|
714
|
+
/** Every file under dir, relative, sorted (node_modules and state excluded). */
|
|
715
|
+
function listFiles(dir) {
|
|
716
|
+
const out = [];
|
|
717
|
+
const walk = (at) => {
|
|
718
|
+
for (const name of readdirSync(at).sort()) {
|
|
719
|
+
if (name === "node_modules" || name === ".feltkit")
|
|
720
|
+
continue;
|
|
721
|
+
const path = join(at, name);
|
|
722
|
+
if (statSync(path).isDirectory())
|
|
723
|
+
walk(path);
|
|
724
|
+
else
|
|
725
|
+
out.push(relative(dir, path).split("\\").join("/"));
|
|
726
|
+
}
|
|
727
|
+
};
|
|
728
|
+
walk(dir);
|
|
729
|
+
return out;
|
|
730
|
+
}
|
|
731
|
+
/** Scaffold the shell, write the application-owned app.ts, compose the foundation with `feltkit compose`, verify. */
|
|
732
|
+
export async function createApplication(a, p) {
|
|
733
|
+
if (!p.result.ok)
|
|
734
|
+
throw new FeltKitError("INVALID_ARGUMENT", "The selection does not resolve; nothing was created.", { hint: p.result.errors.map((e) => `${e.code}: ${e.message}`).join("; ") });
|
|
735
|
+
const dir = resolve(a.dir);
|
|
736
|
+
try {
|
|
737
|
+
scaffold({ target: dir, name: a.name, template: "foundation" });
|
|
738
|
+
}
|
|
739
|
+
catch (error) {
|
|
740
|
+
if (error instanceof ScaffoldError)
|
|
741
|
+
throw new FeltKitError("CONFIGURATION", error.message, error.hint ? { hint: error.hint } : {});
|
|
742
|
+
throw error;
|
|
743
|
+
}
|
|
744
|
+
// Application-owned, written once at creation: the declaration, one module per entity, the API index, the domain tests.
|
|
745
|
+
writeFileSync(join(dir, "feltkit/app.ts"), renderAppModule(a, p));
|
|
746
|
+
const accounts = p.result.resolved.capabilities.find((x) => x.id === "identity.accounts")?.params ?? {};
|
|
747
|
+
writeFileSync(join(dir, "feltkit/_generated/api.ts"), renderApi(creationOrder(a.entities).map((e) => e.name)));
|
|
748
|
+
if (a.tenancy === "workspaces") {
|
|
749
|
+
// The workspace's noun, roles and managers as the resolver settled them (defaults included): the one source for the modules and tests.
|
|
750
|
+
const tenancy = p.result.resolved.capabilities.find((x) => x.id === "workspace.tenancy")?.params ?? {};
|
|
751
|
+
const noun = tenancy.noun ?? "workspace";
|
|
752
|
+
const workspaceRoles = tenancy.roles ?? ["owner", "admin", "member", "guest"];
|
|
753
|
+
const managerRoles = tenancy.managers ?? [];
|
|
754
|
+
const declaredClaims = tenancy.claims ?? {};
|
|
755
|
+
// One derivation of who manages owned records, for the modules and for the tests that check them.
|
|
756
|
+
const managing = managingRoles(workspaceRoles, managerRoles);
|
|
757
|
+
for (const e of a.entities)
|
|
758
|
+
writeFileSync(join(dir, `feltkit/${e.name}.ts`), renderEntityModule(e, noun, managing));
|
|
759
|
+
const create = tenancy.create === "none" ? "none" : "anyone";
|
|
760
|
+
if (a.entities.length)
|
|
761
|
+
writeFileSync(join(dir, "tests/domain.test.ts"), renderDomainTests(a.entities, { roles: workspaceRoles, managers: managing, noun, claims: declaredClaims, create }));
|
|
762
|
+
if (a.entities.some((e) => e.attachments))
|
|
763
|
+
writeFileSync(join(dir, "tests/files.test.ts"), renderFilesTests(a.entities, { roles: workspaceRoles, managers: managing, noun, claims: declaredClaims, create }));
|
|
764
|
+
// The declared tenant roles include every capability's contribution (an agent role, for one): the foundation test checks the declaration.
|
|
765
|
+
const declaredRoles = [...(p.result.resolved.options.auth?.tenant?.roles ?? workspaceRoles)];
|
|
766
|
+
writeFileSync(join(dir, "tests/foundation.test.ts"), renderFoundationTests({ noun, roles: declaredRoles, signUp: accounts.signUp !== false, magicLink: accounts.magicLink === true, create: tenancy.create === "none" ? "none" : "anyone" }));
|
|
767
|
+
}
|
|
768
|
+
else {
|
|
769
|
+
// No workspace: the base role as the resolver settled it; the application's roles and managers from the answers (declared in app.ts, not in the foundation).
|
|
770
|
+
const baseRole = accounts.baseRole ?? "person";
|
|
771
|
+
const managing = managingRoles(a.roles, a.managers, "individuals");
|
|
772
|
+
for (const e of a.entities)
|
|
773
|
+
writeFileSync(join(dir, `feltkit/${e.name}.ts`), renderEntityModule(e, "", managing, "individuals"));
|
|
774
|
+
if (a.entities.length)
|
|
775
|
+
writeFileSync(join(dir, "tests/domain.test.ts"), renderDomainTests(a.entities, { roles: a.roles, managers: managing, noun: "", tenancy: "individuals", baseRole }));
|
|
776
|
+
if (a.entities.some((e) => e.attachments))
|
|
777
|
+
writeFileSync(join(dir, "tests/files.test.ts"), renderFilesTests(a.entities, { roles: a.roles, managers: managing, noun: "", tenancy: "individuals", baseRole }));
|
|
778
|
+
writeFileSync(join(dir, "tests/foundation.test.ts"), renderFoundationTests({ noun: "", roles: a.roles, signUp: true, magicLink: accounts.magicLink === true, create: "anyone", tenancy: "individuals", baseRole }));
|
|
779
|
+
// The shell without workspaces, and a README that does not promise them.
|
|
780
|
+
writeFileSync(join(dir, "src/App.tsx"), INDIVIDUAL_APP_SHELL);
|
|
781
|
+
const readme = join(dir, "README.md");
|
|
782
|
+
if (existsSync(readme))
|
|
783
|
+
writeFileSync(readme, readFileSync(readme, "utf8").replace("Its foundation (accounts, workspaces, roles,\ninvitations, and the capabilities you selected)", "Its foundation (accounts, the base role, and the capabilities you selected;\nno workspaces or invitations)"));
|
|
784
|
+
}
|
|
785
|
+
for (const file of ["src/App.tsx", "index.html", "README.md"]) {
|
|
786
|
+
const path = join(dir, file);
|
|
787
|
+
if (existsSync(path))
|
|
788
|
+
writeFileSync(path, readFileSync(path, "utf8").replaceAll('const BRAND = "foundation";', `const BRAND = ${JSON.stringify(a.name)};`).replaceAll("foundation · FeltKit", `${a.name} · FeltKit`).replace(/^# foundation$/m, `# ${a.name}`));
|
|
789
|
+
}
|
|
790
|
+
// The foundation, through the one generator (`feltkit compose`), with its own output captured.
|
|
791
|
+
const flags = Object.entries(p.inputs.params).flatMap(([cap, ps]) => Object.entries(ps).map(([k, v]) => `${cap}.${k}=${typeof v === "string" ? v : JSON.stringify(v)}`));
|
|
792
|
+
parseParams(flags); // the same parsing the CLI does; throws on a malformed flag
|
|
793
|
+
let captured = "";
|
|
794
|
+
const restore = setOutput((t) => void (captured += t));
|
|
795
|
+
let code;
|
|
796
|
+
try {
|
|
797
|
+
code = compose(dir, { check: false, profile: p.inputs.profile, include: p.inputs.include, params: flags, json: true });
|
|
798
|
+
}
|
|
799
|
+
finally {
|
|
800
|
+
restore();
|
|
801
|
+
}
|
|
802
|
+
if (code !== 0)
|
|
803
|
+
throw new FeltKitError("CONFIGURATION", `feltkit compose refused: ${captured.trim()}`);
|
|
804
|
+
const written = JSON.parse(captured);
|
|
805
|
+
const integrity = checkFoundation(readGeneratedState(dir)).ok;
|
|
806
|
+
let reconciliation = null;
|
|
807
|
+
try {
|
|
808
|
+
reconciliation = (await reconcile(dir)).state;
|
|
809
|
+
}
|
|
810
|
+
catch {
|
|
811
|
+
// The application cannot be loaded here (its dependencies are not installed yet): reconcile after `npm install`.
|
|
812
|
+
reconciliation = null;
|
|
813
|
+
}
|
|
814
|
+
const next = [`cd ${relative(process.cwd(), dir) || "."}`, "npm install", "npm test", "npm run dev", ...(reconciliation === null ? ["npx feltkit compose reconcile # after install: must be CURRENT"] : [])];
|
|
815
|
+
return { dir, files: listFiles(dir), composition: written.composition, integrity, reconciliation, next };
|
|
816
|
+
}
|
|
817
|
+
/** Answers from flags alone (the machine-usable form); what is missing is named. */
|
|
818
|
+
export function answersFromOptions(o) {
|
|
819
|
+
if (!o.dir)
|
|
820
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Tell me where to create the app: feltkit create <dir> …");
|
|
821
|
+
const a = defaultAnswers(o.dir, o.name ?? toAppName(basename(resolve(o.dir))));
|
|
822
|
+
if (o.description)
|
|
823
|
+
a.description = o.description;
|
|
824
|
+
if (o.kind) {
|
|
825
|
+
if (!APP_KINDS.some((k) => k.value === o.kind))
|
|
826
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--kind ${o.kind} is not one of ${APP_KINDS.map((k) => k.value).join(", ")}.`);
|
|
827
|
+
a.kind = o.kind;
|
|
828
|
+
}
|
|
829
|
+
if (o.tenancy !== undefined) {
|
|
830
|
+
if (!TENANCIES.some((t) => t.value === o.tenancy))
|
|
831
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--data-belongs-to ${o.tenancy} is not one of ${TENANCIES.map((t) => t.value).join(", ")}.`, { hint: "workspaces: data belongs to organizations people join; individuals: each person has their own account and records." });
|
|
832
|
+
a.tenancy = o.tenancy;
|
|
833
|
+
}
|
|
834
|
+
else {
|
|
835
|
+
a.tenancy = APP_KINDS.find((k) => k.value === a.kind).tenancy;
|
|
836
|
+
}
|
|
837
|
+
const PROFILE = profileFor(a);
|
|
838
|
+
if (o.participants.length) {
|
|
839
|
+
for (const x of o.participants) {
|
|
840
|
+
const q = PARTICIPANTS.find((q) => q.value === x);
|
|
841
|
+
if (!q)
|
|
842
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--participant ${x} is not one of ${PARTICIPANTS.map((q) => q.value).join(", ")}.`);
|
|
843
|
+
if (q.needs && q.needs !== a.tenancy)
|
|
844
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--participant ${x} needs workspaces (${q.hint}), and this application's data belongs to individuals.`, { hint: "Say --data-belongs-to workspaces, or leave the participant out." });
|
|
845
|
+
}
|
|
846
|
+
a.participants = o.participants;
|
|
847
|
+
}
|
|
848
|
+
else if (a.tenancy === "individuals") {
|
|
849
|
+
a.participants = a.kind === "personal" ? ["customers"] : a.participants.filter((p) => !PARTICIPANTS.find((q) => q.value === p)?.needs);
|
|
850
|
+
}
|
|
851
|
+
for (const id of o.include) {
|
|
852
|
+
if (!isCapability(id))
|
|
853
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--include ${id} is not a capability in the catalog (${[...CATALOG.keys()].join(", ")}).`);
|
|
854
|
+
if (PROFILE.required.includes(id))
|
|
855
|
+
continue;
|
|
856
|
+
a.include.push(id);
|
|
857
|
+
}
|
|
858
|
+
for (const id of [...a.include])
|
|
859
|
+
for (const dep of CATALOG.get(id).requires)
|
|
860
|
+
if (!PROFILE.required.includes(dep) && !a.include.includes(dep))
|
|
861
|
+
a.include.push(dep);
|
|
862
|
+
a.params = parseParams(o.params);
|
|
863
|
+
// A parameter for a capability that is not part of this composition is refused, never dropped: with flags there is no review loop to notice.
|
|
864
|
+
for (const cap of Object.keys(a.params)) {
|
|
865
|
+
if (!isCapability(cap))
|
|
866
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--param ${cap}.…: "${cap}" is not a capability in the catalog (${[...CATALOG.keys()].join(", ")}).`);
|
|
867
|
+
if (!PROFILE.required.includes(cap) && !a.include.includes(cap)) {
|
|
868
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--param ${cap}.…: ${cap} is not part of this composition.`, { hint: PROFILE.optional.includes(cap) ? `Include it: --include ${cap}.` : `${cap} is not part of the ${PROFILE.id} foundation${a.tenancy === "individuals" ? " (no workspaces: say --data-belongs-to workspaces if the data belongs to organizations)" : ""}.` });
|
|
869
|
+
}
|
|
870
|
+
}
|
|
871
|
+
const optRoles = o.roles ?? [];
|
|
872
|
+
const optManagers = o.managers ?? [];
|
|
873
|
+
if (a.tenancy === "individuals") {
|
|
874
|
+
const base = a.params["identity.accounts"]?.baseRole ?? "person";
|
|
875
|
+
for (const r of optRoles)
|
|
876
|
+
if (!IDENT.test(r) || r === base)
|
|
877
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--role ${r} must be a lower-case word other than the base role ${base}.`);
|
|
878
|
+
a.roles = [...new Set(optRoles)];
|
|
879
|
+
for (const m of optManagers)
|
|
880
|
+
if (!a.roles.includes(m))
|
|
881
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--manager ${m} is not one of the roles (${a.roles.join(", ") || "none given"}).`, { hint: "Declare it first with --role <role>." });
|
|
882
|
+
a.managers = [...new Set(optManagers)];
|
|
883
|
+
if (a.params["identity.accounts"]?.signUp === false)
|
|
884
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Without workspaces there are no invitations, so sign-up cannot be closed: nothing else would create an account.", { hint: "Drop identity.accounts.signUp=false, or choose --data-belongs-to workspaces (people are then invited)." });
|
|
885
|
+
}
|
|
886
|
+
else if (optRoles.length || optManagers.length) {
|
|
887
|
+
throw new FeltKitError("INVALID_ARGUMENT", "--role and --manager describe application roles of a foundation without workspaces; with workspaces, roles are the workspace's (--param workspace.tenancy.roles=[…], workspace.tenancy.managers=[…]).");
|
|
888
|
+
}
|
|
889
|
+
const entities = [];
|
|
890
|
+
const defaultScope = a.tenancy === "workspaces" ? "workspace" : "personal";
|
|
891
|
+
for (const spec of o.entities) {
|
|
892
|
+
const [name, scope = defaultScope, ...rest] = spec.split(":");
|
|
893
|
+
if (!name || !IDENT.test(name) || (scope !== "workspace" && scope !== "shared" && scope !== "personal"))
|
|
894
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--entity ${spec} is not <name>[:workspace|shared|personal][:description].`);
|
|
895
|
+
entities.push({ name, scope, ...(rest.length ? { description: rest.join(":") } : {}), owned: scope === "personal", fields: [], relations: [], unique: [] });
|
|
896
|
+
}
|
|
897
|
+
const entityOf = (ref, flag) => {
|
|
898
|
+
const dot = ref.indexOf(".");
|
|
899
|
+
const e = dot > 0 ? entities.find((x) => x.name === ref.slice(0, dot)) : undefined;
|
|
900
|
+
if (!e)
|
|
901
|
+
throw new FeltKitError("INVALID_ARGUMENT", `${flag} ${ref}: "${dot > 0 ? ref.slice(0, dot) : ref}" is not one of the entities (${entities.map((x) => x.name).join(", ") || "none given"}).`, { hint: "Declare it first with --entity <name>." });
|
|
902
|
+
return { e, rest: ref.slice(dot + 1) };
|
|
903
|
+
};
|
|
904
|
+
const claims = {};
|
|
905
|
+
try {
|
|
906
|
+
if (o.claims?.length) {
|
|
907
|
+
if (a.tenancy === "individuals")
|
|
908
|
+
throw new FeltKitError("INVALID_ARGUMENT", "--claim declares membership claims, but this application has no workspaces (its data belongs to individuals).", { hint: "Claims belong to workspace memberships. Use --data-belongs-to workspaces, or drop --claim: with individuals, authority is the account's roles." });
|
|
909
|
+
Object.assign(claims, parseClaims(o.claims.join(", ")));
|
|
910
|
+
a.params["workspace.tenancy"] = { ...a.params["workspace.tenancy"], claims };
|
|
911
|
+
}
|
|
912
|
+
// Each --field / --ref is parsed on its own; a name repeated across flags is refused here, as it is within one.
|
|
913
|
+
const declared = (e, name, flag) => {
|
|
914
|
+
if (e.fields.some((x) => x.name === name) || e.relations.some((x) => x.field === name))
|
|
915
|
+
throw new DomainError(`${flag} ${e.name}.${name}: "${name}" is declared twice.`, "Each field or relationship once.");
|
|
916
|
+
};
|
|
917
|
+
for (const f of o.fields) {
|
|
918
|
+
const { e, rest } = entityOf(f, "--field");
|
|
919
|
+
const parsed = parseFields(rest);
|
|
920
|
+
for (const x of parsed)
|
|
921
|
+
declared(e, x.name, "--field");
|
|
922
|
+
e.fields = [...e.fields, ...parsed];
|
|
923
|
+
}
|
|
924
|
+
for (const r of o.refs) {
|
|
925
|
+
const { e, rest } = entityOf(r, "--ref");
|
|
926
|
+
const parsed = parseRelations(rest);
|
|
927
|
+
for (const x of parsed)
|
|
928
|
+
declared(e, x.field, "--ref");
|
|
929
|
+
e.relations = [...e.relations, ...parsed];
|
|
930
|
+
}
|
|
931
|
+
for (const name of o.owned) {
|
|
932
|
+
const e = entities.find((x) => x.name === name);
|
|
933
|
+
if (!e)
|
|
934
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--owned ${name} is not one of the entities.`);
|
|
935
|
+
e.owned = true;
|
|
936
|
+
}
|
|
937
|
+
for (const name of o.public ?? []) {
|
|
938
|
+
const e = entities.find((x) => x.name === name);
|
|
939
|
+
if (!e)
|
|
940
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--public ${name} is not one of the entities.`);
|
|
941
|
+
e.public = true;
|
|
942
|
+
}
|
|
943
|
+
for (const name of o.attach ?? []) {
|
|
944
|
+
const e = entities.find((x) => x.name === name);
|
|
945
|
+
if (!e)
|
|
946
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--attach ${name} is not one of the entities.`, { hint: "Declare it first with --entity <name>." });
|
|
947
|
+
e.attachments = true;
|
|
948
|
+
}
|
|
949
|
+
for (const spec of o.require ?? []) {
|
|
950
|
+
const colon = spec.indexOf(":");
|
|
951
|
+
const e = colon > 0 ? entities.find((x) => x.name === spec.slice(0, colon)) : undefined;
|
|
952
|
+
if (!e)
|
|
953
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--require ${spec} is not <entity>:<claim>=<value>[|<value>] naming one of the entities (${entities.map((x) => x.name).join(", ") || "none given"}).`, { hint: "Declare the entity first with --entity <name>, and the claim with --claim <name>:<type>." });
|
|
954
|
+
if (e.requires)
|
|
955
|
+
throw new FeltKitError("INVALID_ARGUMENT", `--require ${spec}: ${e.name} already requires ${e.requires.claim}.`, { hint: "One claim requirement per entity." });
|
|
956
|
+
e.requires = parseRequire(spec.slice(colon + 1), claims);
|
|
957
|
+
}
|
|
958
|
+
// Attachments need the Files service: included here, with the reason shown in the review, never silently.
|
|
959
|
+
if (entities.some((e) => e.attachments) && !a.include.includes("services.files"))
|
|
960
|
+
a.include.push("services.files");
|
|
961
|
+
for (const u of o.unique) {
|
|
962
|
+
const { e, rest } = entityOf(u, "--unique");
|
|
963
|
+
e.unique = [...e.unique, ...parseUnique(rest)];
|
|
964
|
+
}
|
|
965
|
+
for (const e of entities)
|
|
966
|
+
if (!e.fields.length && !e.relations.length)
|
|
967
|
+
e.fields = [{ name: "title", type: "string", required: true }];
|
|
968
|
+
validateEntities(entities, a.tenancy, claims);
|
|
969
|
+
}
|
|
970
|
+
catch (error) {
|
|
971
|
+
if (error instanceof DomainError)
|
|
972
|
+
throw new FeltKitError("INVALID_ARGUMENT", error.message, { hint: error.hint });
|
|
973
|
+
throw error;
|
|
974
|
+
}
|
|
975
|
+
a.entities = entities;
|
|
976
|
+
a.workflows = o.workflows;
|
|
977
|
+
if (!NAME.test(a.name))
|
|
978
|
+
throw new FeltKitError("INVALID_ARGUMENT", `Application name ${JSON.stringify(a.name)} must be lower-case letters, digits and dashes.`, { hint: "Pass --name <name>." });
|
|
979
|
+
if (a.tenancy === "workspaces" && typeof a.params["identity.accounts"]?.emailFrom !== "string")
|
|
980
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Account e-mail needs a sender: --param identity.accounts.emailFrom=<address>.", { hint: "Verification, sign-in links and invitations are e-mailed; the collaborative-workspace profile requires the sender." });
|
|
981
|
+
return a;
|
|
982
|
+
}
|
|
983
|
+
/** An existing application: never written here. Reconcile, plan what the developer wants, hand over the apply command. */
|
|
984
|
+
async function existingApplication(dir, o, io) {
|
|
985
|
+
const report = await reconcile(dir);
|
|
986
|
+
line(`${report.ok ? symbols.ok : symbols.fail} ${dir} is already a FeltKit application (feltkit/app.ts); \`feltkit create\` does not write into one.`);
|
|
987
|
+
line(` Composition: ${report.recorded.profile ? `${report.recorded.profile.id} v${report.recorded.profile.version}; ${report.recorded.capabilities.map((x) => x.id).join(", ")}` : "none recorded"}; reconciliation ${report.state}.`);
|
|
988
|
+
if (report.state === "NOT_COMPOSED") {
|
|
989
|
+
line(c.dim(" This application was not composed with `feltkit compose`. To start composing it: `feltkit compose --profile <collaborative-workspace|individual-accounts> [--param identity.accounts.emailFrom=<sender>]`, then import { foundation } from \"./_foundation/declaration.js\" in feltkit/app.ts."));
|
|
990
|
+
return 1;
|
|
991
|
+
}
|
|
992
|
+
if (!report.ok) {
|
|
993
|
+
line(` Resolve this first: ${report.findings.map((f) => `${f.code}${f.paths.length ? ` ${f.paths.join(", ")}` : ""}`).join("; ")}.`);
|
|
994
|
+
line(c.dim(" `feltkit compose reconcile` explains each finding; `feltkit compose recover --inspect` if an execution was interrupted."));
|
|
995
|
+
return 1;
|
|
996
|
+
}
|
|
997
|
+
const current = report.recorded.capabilities.map((x) => x.id);
|
|
998
|
+
const recordedProfile = [COLLABORATIVE_WORKSPACE, INDIVIDUAL_ACCOUNTS].find((x) => x.id === report.recorded.profile?.id);
|
|
999
|
+
// Only what the recorded foundation can take: a workspace capability is never offered to an application without workspaces.
|
|
1000
|
+
const addable = CAPABILITY_GUIDE.filter((g) => !current.includes(g.id) && (!recordedProfile || recordedProfile.optional.includes(g.id)));
|
|
1001
|
+
let include = o.include;
|
|
1002
|
+
let params = o.params;
|
|
1003
|
+
if (io && !include.length && !params.length) {
|
|
1004
|
+
include = await io.multi("Add capabilities to this application?", addable.map((g) => ({ value: g.id, label: g.label, hint: g.provides })));
|
|
1005
|
+
if (!include.length) {
|
|
1006
|
+
line(c.dim(" Nothing to change."));
|
|
1007
|
+
return 0;
|
|
1008
|
+
}
|
|
1009
|
+
if (include.includes("services.files")) {
|
|
1010
|
+
const max = await io.text("Largest file, in MiB (empty keeps FeltKit's default of 1)", { validate: (v) => (Number(v) > 0 ? null : "A positive number of MiB.") });
|
|
1011
|
+
if (max)
|
|
1012
|
+
params = [...params, `services.files.maxBytes=${Math.round(Number(max) * 1048576)}`];
|
|
1013
|
+
}
|
|
1014
|
+
if (include.includes("agents.membership"))
|
|
1015
|
+
params = [...params, `agents.membership.role=${await io.text("Name of the agent role", { default: "agent", required: true })}`];
|
|
1016
|
+
if (include.includes("ops.operator"))
|
|
1017
|
+
params = [...params, `ops.operator.role=${await io.text("Name of the operator role", { default: "operator", required: true })}`];
|
|
1018
|
+
}
|
|
1019
|
+
if (!include.length && !params.length) {
|
|
1020
|
+
line(c.dim(" To change the composition: `feltkit compose plan --include <capability> …`, then `feltkit compose apply … --approve <plan id>`."));
|
|
1021
|
+
return 0;
|
|
1022
|
+
}
|
|
1023
|
+
const plan = await planComposition(dir, { include, params: parseParams(params) });
|
|
1024
|
+
line(` Plan ${plan.id} (${plan.status}): ${plan.operations.filter((op) => op.classification !== "DETERMINISTIC").length} decision(s) or blocker(s), ${plan.affected.paths.length} declaration path(s).`);
|
|
1025
|
+
for (const d of plan.decisions)
|
|
1026
|
+
line(` decide ${d.operation}: ${d.decision}`);
|
|
1027
|
+
for (const b of plan.blockers)
|
|
1028
|
+
line(` blocked ${b.operation}: ${b.reason}`);
|
|
1029
|
+
for (const u of plan.unsupported)
|
|
1030
|
+
line(` unsupported ${u.operation}: ${u.reason}`);
|
|
1031
|
+
const flags = [...include.flatMap((i) => ["--include", i]), ...params.flatMap((pp) => ["--param", pp])].join(" ");
|
|
1032
|
+
line(` Review it: feltkit compose plan ${flags}`);
|
|
1033
|
+
if (plan.status === "READY")
|
|
1034
|
+
line(` Apply exactly it: feltkit compose apply ${flags} --approve ${plan.id}`);
|
|
1035
|
+
else
|
|
1036
|
+
line(c.dim(" It cannot be applied as is: decide or resolve what is listed, then plan again."));
|
|
1037
|
+
line(c.dim(" Nothing was written."));
|
|
1038
|
+
return plan.status === "READY" || plan.status === "NO_CHANGE" ? 0 : 1;
|
|
1039
|
+
}
|
|
1040
|
+
export async function createCommand(o) {
|
|
1041
|
+
const interactive = o.interactive || ((o.stdinIsTTY ?? Boolean(process.stdin.isTTY)) && Boolean(process.stdout.isTTY) && !o.yes);
|
|
1042
|
+
const target = o.dir ? resolve(o.dir) : null;
|
|
1043
|
+
const existing = target && existsSync(join(target, "feltkit/app.ts")) ? target : !o.dir && existsSync(join(process.cwd(), "feltkit/app.ts")) ? process.cwd() : null;
|
|
1044
|
+
const io = interactive ? o.prompter ?? terminalPrompter() : null;
|
|
1045
|
+
try {
|
|
1046
|
+
if (existing)
|
|
1047
|
+
return await existingApplication(existing, o, io);
|
|
1048
|
+
if (target && existsSync(target) && readdirSync(target).filter((f) => f !== ".git" && f !== ".DS_Store").length) {
|
|
1049
|
+
throw new FeltKitError("CONFIGURATION", `${target} exists and is not empty, and it is not a FeltKit application. Nothing was written.`, { hint: "Choose a new directory." });
|
|
1050
|
+
}
|
|
1051
|
+
let answers;
|
|
1052
|
+
if (!io) {
|
|
1053
|
+
if (!o.yes)
|
|
1054
|
+
throw new FeltKitError("INVALID_ARGUMENT", "Not a terminal: `feltkit create` needs its selections as flags, with --yes.", { hint: "feltkit create <dir> --yes [--data-belongs-to workspaces|individuals] [--param identity.accounts.emailFrom=<sender>] [--name …] [--kind …] [--participant …]… [--include …]… [--param …]… [--role …]… [--manager …]… [--entity name[:workspace|shared|personal][:description]]… [--field entity.name:type[?]]… [--ref entity.field->target[?]]… [--owned entity]… [--public entity]… [--attach entity]… [--unique entity.f1,f2]… [--workflow …]…; or --interactive to answer questions over a pipe." });
|
|
1055
|
+
answers = answersFromOptions(o);
|
|
1056
|
+
}
|
|
1057
|
+
else {
|
|
1058
|
+
io.say(`${c.bold("feltkit create")} composes an application from what you select. Answer q at any time to cancel; nothing is written before you confirm.`);
|
|
1059
|
+
const start = defaultAnswers(o.dir ?? "", o.name ?? (o.dir ? toAppName(basename(resolve(o.dir))) : "my-app"));
|
|
1060
|
+
if (o.kind && APP_KINDS.some((k) => k.value === o.kind)) {
|
|
1061
|
+
start.kind = o.kind;
|
|
1062
|
+
start.tenancy = APP_KINDS.find((k) => k.value === o.kind).tenancy;
|
|
1063
|
+
}
|
|
1064
|
+
if (o.tenancy && TENANCIES.some((t) => t.value === o.tenancy))
|
|
1065
|
+
start.tenancy = o.tenancy;
|
|
1066
|
+
if (o.entities.length)
|
|
1067
|
+
start.entities = answersFromOptions({ ...o, yes: true, dir: o.dir ?? "x", tenancy: start.tenancy, params: o.params.length ? o.params : ["identity.accounts.emailFrom=placeholder@example.com"] }).entities;
|
|
1068
|
+
if (!o.dir)
|
|
1069
|
+
start.dir = await io.text("Directory to create", { default: start.name, required: true });
|
|
1070
|
+
answers = await interview(io, start);
|
|
1071
|
+
answers.dir = start.dir;
|
|
1072
|
+
}
|
|
1073
|
+
// Review, change, confirm.
|
|
1074
|
+
for (;;) {
|
|
1075
|
+
const p = preview(answers);
|
|
1076
|
+
if (!o.json)
|
|
1077
|
+
for (const l of renderPreview(answers, p))
|
|
1078
|
+
line(l);
|
|
1079
|
+
if (o.dryRun) {
|
|
1080
|
+
if (o.json)
|
|
1081
|
+
line(JSON.stringify({ inputs: p.inputs, ok: p.result.ok, capabilities: p.result.ok ? p.result.record.capabilities : [], errors: p.result.ok ? [] : p.result.errors, roles: p.roles, entities: p.entities, applicationOwned: p.applicationOwned }, null, 2));
|
|
1082
|
+
if (!o.json)
|
|
1083
|
+
line(c.dim("Dry run: nothing was written."));
|
|
1084
|
+
return p.result.ok ? 0 : 1;
|
|
1085
|
+
}
|
|
1086
|
+
if (!io) {
|
|
1087
|
+
if (!p.result.ok)
|
|
1088
|
+
return 1;
|
|
1089
|
+
break;
|
|
1090
|
+
}
|
|
1091
|
+
const action = await io.choose("Create it?", [
|
|
1092
|
+
{ value: "create", label: "Create the application", hint: p.result.ok ? "writes the files listed above" : "not possible: the selection does not resolve" },
|
|
1093
|
+
{ value: "basics", label: "Change the name or description" },
|
|
1094
|
+
{ value: "kind", label: "Change the application type" },
|
|
1095
|
+
{ value: "participants", label: "Change who uses it" },
|
|
1096
|
+
{ value: "capabilities", label: "Change the capabilities" },
|
|
1097
|
+
{ value: "details", label: "Change accounts, roles, workspaces or capability details" },
|
|
1098
|
+
{ value: "data", label: "Change the data and workflows" },
|
|
1099
|
+
{ value: "cancel", label: "Cancel (nothing is written)" },
|
|
1100
|
+
], { default: p.result.ok ? "create" : "capabilities" });
|
|
1101
|
+
if (action === "cancel")
|
|
1102
|
+
throw new Cancelled();
|
|
1103
|
+
if (action === "create") {
|
|
1104
|
+
if (!p.result.ok) {
|
|
1105
|
+
io.say(`${symbols.fail} The selection does not resolve; change it first.`);
|
|
1106
|
+
continue;
|
|
1107
|
+
}
|
|
1108
|
+
break;
|
|
1109
|
+
}
|
|
1110
|
+
answers = await interview(io, answers, [action]);
|
|
1111
|
+
}
|
|
1112
|
+
const created = await createApplication(answers, preview(answers));
|
|
1113
|
+
if (o.json) {
|
|
1114
|
+
line(JSON.stringify(created, null, 2));
|
|
1115
|
+
return created.integrity ? 0 : 1;
|
|
1116
|
+
}
|
|
1117
|
+
line(`${symbols.ok} Created ${c.bold(answers.name)} in ${created.dir}`);
|
|
1118
|
+
line(` Composition ${created.composition?.slice(0, 19)}… · integrity ${created.integrity ? "verified" : "FAILED"}${created.reconciliation ? ` · reconciliation ${created.reconciliation}` : " · reconcile after `npm install`"}`);
|
|
1119
|
+
line(" Files:");
|
|
1120
|
+
for (const f of created.files)
|
|
1121
|
+
line(` ${GENERATED_PATHS.includes(f) ? c.dim("generated ") : f === "feltkit/app.ts" ? "yours " : " "}${f}`);
|
|
1122
|
+
line(" Next:");
|
|
1123
|
+
for (const n of created.next)
|
|
1124
|
+
line(` ${n}`);
|
|
1125
|
+
return created.integrity ? 0 : 1;
|
|
1126
|
+
}
|
|
1127
|
+
catch (error) {
|
|
1128
|
+
if (error instanceof Cancelled) {
|
|
1129
|
+
line(`${symbols.fail} Cancelled. Nothing was written.`);
|
|
1130
|
+
return 1;
|
|
1131
|
+
}
|
|
1132
|
+
throw error;
|
|
1133
|
+
}
|
|
1134
|
+
finally {
|
|
1135
|
+
io?.close?.();
|
|
1136
|
+
}
|
|
1137
|
+
}
|
|
1138
|
+
export { DECLARATION_PATH, LOCK_PATH, RECORD_PATH };
|
|
1139
|
+
//# sourceMappingURL=create.js.map
|