create-mana 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +28 -2
  3. package/bin/create-mana.mjs +5 -0
  4. package/kits/auth/files/src/api/auth.ts +100 -0
  5. package/kits/auth/files/src/api/profile.ts +48 -0
  6. package/kits/auth/files/src/api/types.ts +28 -0
  7. package/kits/auth/files/src/components/AppLayout.mana +31 -0
  8. package/kits/auth/files/src/components/VerifyBanner.mana +47 -0
  9. package/kits/auth/files/src/router/routes.ts +31 -0
  10. package/kits/auth/files/src/shared/events.ts +11 -0
  11. package/kits/auth/files/src/stores/session.ts +99 -0
  12. package/kits/auth/files/src/views/ForgotPassword.mana +83 -0
  13. package/kits/auth/files/src/views/Home.mana +15 -0
  14. package/kits/auth/files/src/views/Profile.mana +172 -0
  15. package/kits/auth/files/src/views/Register.mana +86 -0
  16. package/kits/auth/files/src/views/ResetPassword.mana +90 -0
  17. package/kits/auth/files/src/views/SignIn.mana +84 -0
  18. package/kits/auth/files/src/views/VerifyEmail.mana +78 -0
  19. package/kits/auth/files/tests/auth.test.mjs +93 -0
  20. package/kits/auth/files/tests/home.test.mjs +38 -0
  21. package/kits/auth/files/tests/profile.test.mjs +68 -0
  22. package/kits/auth/files/tests/support/users.mjs +2 -0
  23. package/kits/auth/kit.json +80 -0
  24. package/kits/base/files/README.md +39 -0
  25. package/kits/base/kit.json +7 -0
  26. package/kits/organisations/files/src/api/auth.ts +124 -0
  27. package/kits/organisations/files/src/api/members.ts +243 -0
  28. package/kits/organisations/files/src/api/notifications.ts +63 -0
  29. package/kits/organisations/files/src/api/organisations.ts +41 -0
  30. package/kits/organisations/files/src/api/scope.ts +98 -0
  31. package/kits/organisations/files/src/api/types.ts +72 -0
  32. package/kits/organisations/files/src/assets/styles/organisations.css +46 -0
  33. package/kits/organisations/files/src/components/AppLayout.mana +90 -0
  34. package/kits/organisations/files/src/components/NotificationBell.mana +35 -0
  35. package/kits/organisations/files/src/components/NotificationList.mana +112 -0
  36. package/kits/organisations/files/src/components/OrganisationSwitcher.mana +171 -0
  37. package/kits/organisations/files/src/composables/notifications.ts +28 -0
  38. package/kits/organisations/files/src/router/routes.ts +43 -0
  39. package/kits/organisations/files/src/shared/roles.ts +10 -0
  40. package/kits/organisations/files/src/stores/notifications.ts +41 -0
  41. package/kits/organisations/files/src/stores/session.ts +158 -0
  42. package/kits/organisations/files/src/utilities/format.ts +15 -0
  43. package/kits/organisations/files/src/views/Forbidden.mana +28 -0
  44. package/kits/organisations/files/src/views/Home.mana +15 -0
  45. package/kits/organisations/files/src/views/Invite.mana +156 -0
  46. package/kits/organisations/files/src/views/InviteMember.mana +99 -0
  47. package/kits/organisations/files/src/views/Members.mana +218 -0
  48. package/kits/organisations/files/src/views/NoOrganisation.mana +184 -0
  49. package/kits/organisations/files/src/views/Notifications.mana +30 -0
  50. package/kits/organisations/files/src/views/OrganisationForm.mana +76 -0
  51. package/kits/organisations/files/src/views/OrganisationSettings.mana +62 -0
  52. package/kits/organisations/files/src/views/Profile.mana +213 -0
  53. package/kits/organisations/files/src/views/Register.mana +113 -0
  54. package/kits/organisations/files/tests/auth.test.mjs +82 -0
  55. package/kits/organisations/files/tests/home.test.mjs +43 -0
  56. package/kits/organisations/files/tests/members.test.mjs +89 -0
  57. package/kits/organisations/files/tests/notifications.test.mjs +49 -0
  58. package/kits/organisations/files/tests/organisations.test.mjs +70 -0
  59. package/kits/organisations/files/tests/profile.test.mjs +79 -0
  60. package/kits/organisations/files/tests/support/users.mjs +3 -0
  61. package/kits/organisations/kit.json +51 -0
  62. package/lib/compose.mjs +209 -0
  63. package/lib/new.mjs +161 -0
  64. package/lib/prompts.mjs +182 -0
  65. package/package.json +36 -4
  66. package/template/.nvmrc +1 -0
  67. package/template/README.md +23 -0
  68. package/template/_gitignore +25 -0
  69. package/template/index.html +17 -0
  70. package/template/package.json +22 -0
  71. package/template/public/favicon.svg +1 -0
  72. package/template/public/icons.svg +24 -0
  73. package/template/src/App.mana +15 -0
  74. package/template/src/api/ApiError.ts +17 -0
  75. package/template/src/api/client.ts +116 -0
  76. package/template/src/assets/styles/main.css +158 -0
  77. package/template/src/components/AppLogo.mana +20 -0
  78. package/template/src/components/Button.mana +25 -0
  79. package/template/src/components/ConfirmHost.mana +43 -0
  80. package/template/src/components/TextField.mana +60 -0
  81. package/template/src/components/ToastHost.mana +40 -0
  82. package/template/src/composables/media.ts +19 -0
  83. package/template/src/composables/unsaved.ts +29 -0
  84. package/template/src/main.ts +25 -0
  85. package/template/src/router/index.ts +14 -0
  86. package/template/src/router/routes.ts +11 -0
  87. package/template/src/stores/confirm.ts +45 -0
  88. package/template/src/stores/toasts.ts +64 -0
  89. package/template/src/utilities/query.ts +40 -0
  90. package/template/src/utilities/timers.ts +12 -0
  91. package/template/src/views/Home.mana +12 -0
  92. package/template/src/views/NotFound.mana +13 -0
  93. package/template/tests/home.test.mjs +29 -0
  94. package/template/tests/support/api.mjs +44 -0
  95. package/template/tests/support/check.mjs +15 -0
  96. package/template/tests/support/dom.mjs +45 -0
  97. package/template/tests/support/paths.mjs +54 -0
  98. package/template/tests/support/settle.mjs +15 -0
  99. package/template/tsconfig.json +35 -0
  100. package/template/vite.config.ts +29 -0
  101. package/versions.json +3 -0
@@ -0,0 +1,70 @@
1
+ // Organisations: the switcher in the frame lists yours with your role in each and switches; New organisation starts one, which you own and work in from then; and the page for someone in none
2
+ // lists the invitations waiting for their email, to accept or decline, and starts one of their own.
3
+ import { check } from "./support/check.mjs";
4
+ import { settle } from "./support/settle.mjs";
5
+ import { useDom } from "./support/dom.mjs";
6
+ import { useFakeApi } from "./support/api.mjs";
7
+ import { acme, apiUser } from "./support/users.mjs";
8
+
9
+ const w = useDom('<main id="app"></main>', { url: "http://app.test/" });
10
+ const api = useFakeApi();
11
+ const bakery = { id: 2, name: "Bakery", role: "member" };
12
+ let user = apiUser({ organisations: [acme, bakery] });
13
+ let invitations = [];
14
+
15
+ api.get("/api/user", () => ({ json: user }));
16
+ api.get("/api/user/notifications", () => ({ json: { notifications: [], total: 0, unread: 0, page: 1, page_size: 25 } }));
17
+ api.put("/api/user/organisation", body => (user = apiUser({ organisations: user.organisations, current_organisation_id: body.organisation }), { json: user }));
18
+ api.post("/api/organisations", body => (user = apiUser({ organisations: [...user.organisations, { id: 9, name: body.name, role: "owner" }], current_organisation_id: 9 }), { status: 201, json: user }));
19
+ api.get("/api/user/invitations", () => ({ json: invitations }));
20
+ api.post("/api/user/invitations/5/accept", () => (user = apiUser({ organisations: [{ id: 2, name: "Bakery", role: "member" }], current_organisation_id: 2 }), { json: user }));
21
+ api.post("/api/user/invitations/5/decline", () => (invitations = [], { status: 204 }));
22
+
23
+ const { createApp, createEvents, createStores } = await import("@mana-js/mana");
24
+ const { default: App } = await import("@/App.mana");
25
+ const { default: router } = await import("@/router");
26
+ const { useSession } = await import("@/stores/session");
27
+ let session;
28
+ const Probe = { setup() { session = useSession(); return {}; }, template: `<i></i>` };
29
+
30
+ createApp({ components: { App, Probe }, template: `<div><App /><Probe /></div>` }).use(createStores()).use(createEvents()).use(router).mount("#app");
31
+ await session.load();
32
+ await router.isReady();
33
+ await router.push("/");
34
+ await settle();
35
+
36
+ const root = document.getElementById("app");
37
+ const $ = s => root.querySelector(s);
38
+ const text = s => $(s)?.textContent.replace(/\s+/g, " ").trim() ?? null;
39
+ const type = (id, value) => { const input = $(id); input.value = value; input.dispatchEvent(new w.Event("input")); };
40
+ const click = el => el.dispatchEvent(new w.MouseEvent("click", { bubbles: true, cancelable: true }));
41
+ const button = label => [...root.querySelectorAll("button")].find(b => b.textContent.trim() == label);
42
+ const wait = async () => { await new Promise(resolve => setTimeout(resolve, 30)); await settle(); };
43
+
44
+ const open = async () => { click($(".switcher-button")); await new Promise(resolve => setTimeout(resolve, 20)); };
45
+
46
+ check("the switcher names the organisation they work in", text(".switcher-button") == "Acme ▾");
47
+ await open();
48
+ check("opened: each organisation with the role in it, then New organisation", [...root.querySelectorAll(".switcher-menu [role=menuitemradio]")].map(item => item.textContent.replace(/\s+/g, " ").trim()).join() == "Acme Owner,Bakery Member" && button("New organisation"));
49
+ click([...root.querySelectorAll(".switcher-menu [role=menuitemradio]")][1]); await wait();
50
+ check("choosing another asks the API and works in it from then: the frame and the home page follow", api.calls.some(call => call.method == "PUT" && call.path == "/api/user/organisation" && call.body.organisation == 2) && text(".switcher-button") == "Bakery ▾" && /working in Bakery as member/.test(text("main") ?? ""));
51
+
52
+ await open();
53
+ click(button("New organisation")); await wait();
54
+ check("New organisation: its page", w.location.pathname == "/organisations/new" && text("h1") == "New organisation" || /organisation/i.test(text("h1") ?? ""));
55
+ type("#organisation-name", " ");
56
+ click([...root.querySelectorAll("button[type=submit]")][0]); await settle();
57
+ check("a blank name is refused before it's sent", /name/i.test(text("#organisation-name-error") ?? "") || document.body.textContent.includes("Enter the organisation's name"));
58
+ type("#organisation-name", "Kofi's Farm");
59
+ click([...root.querySelectorAll("button[type=submit]")][0]); await wait();
60
+ check("a name: made, owned and worked in from now on, on its home page", api.calls.some(call => call.method == "POST" && call.path == "/api/organisations" && call.body.name == "Kofi's Farm") && w.location.pathname == "/" && /working in Kofi's Farm as owner/.test(text("main") ?? ""));
61
+
62
+ // Someone in none.
63
+ invitations = [{ id: 5, organisation: "Bakery", role: "member", invited_by: "Esi", sent_at: "2026-11-01T10:00:00Z", expires_at: "2026-11-08T10:00:00Z", expired: false }];
64
+ user = apiUser({ current_organisation_id: null, organisations: [] });
65
+ await session.load();
66
+ await router.push("/profile");
67
+ await wait();
68
+ check("in none: sent to the page that says so, listing the invitation waiting for their email", w.location.pathname == "/no-organisation" && /not in an organisation/.test(text("h1") ?? "") && /Bakery/.test(text("#none-invitations-title + p, .invitations") ?? "") && /from Esi/.test(text(".invitations") ?? ""));
69
+ click(button("Accept")); await wait();
70
+ check("Accept joins it, and they work in it: the home page", api.calls.some(call => call.path == "/api/user/invitations/5/accept") && w.location.pathname == "/" && /working in Bakery as member/.test(text("main") ?? ""));
@@ -0,0 +1,79 @@
1
+ // The profile page: the details and the password, through the real page against a faked API — a new name applies at once; a new email waits for its link, with Resend and Cancel; the API's words about a
2
+ // field show on it; a password is checked before it's sent, and the API has the last word.
3
+ import { check } from "./support/check.mjs";
4
+ import { settle } from "./support/settle.mjs";
5
+ import { useDom } from "./support/dom.mjs";
6
+ import { useFakeApi } from "./support/api.mjs";
7
+ import { apiUser, acme } from "./support/users.mjs";
8
+
9
+ const w = useDom('<main id="app"></main>', { url: "http://app.test/profile" });
10
+ const api = useFakeApi();
11
+ let user = apiUser({ organisations: [acme, { id: 2, name: "Bakery", role: "member" }] });
12
+
13
+ api.get("/api/user", () => ({ json: user }));
14
+ api.get("/api/user/notifications", () => ({ json: { notifications: [], total: 0, unread: 0, page: 1, page_size: 25 } }));
15
+ api.delete("/api/organisations/2/membership", () => (user = apiUser({ ...user, organisations: [user.organisations[0]] }), { json: user }));
16
+ api.patch("/api/user", body => body.email == "taken@example.test"
17
+ ? { status: 422, json: { message: "Another account uses this email.", errors: { email: ["Another account uses this email."] } } }
18
+ : (user = apiUser({ name: body.name, pending_email: body.email == user.email ? null : body.email }), { json: user }));
19
+ api.post("/api/user/email/resend", () => ({ status: 204 }));
20
+ api.delete("/api/user/email/pending", () => (user = apiUser({ ...user, pending_email: null }), { json: user }));
21
+ api.put("/api/user/password", body => body.current_password == "password" ? { status: 204 } : { status: 422, json: { message: "That isn't your current password.", errors: { current_password: ["That isn't your current password."] } } });
22
+
23
+ const { createApp, createEvents, createStores } = await import("@mana-js/mana");
24
+ const { default: App } = await import("@/App.mana");
25
+ const { default: router } = await import("@/router");
26
+ const { useSession } = await import("@/stores/session");
27
+ let session;
28
+ const Probe = { setup() { session = useSession(); return {}; }, template: `<i></i>` };
29
+
30
+ createApp({ components: { App, Probe }, template: `<div><App /><Probe /></div>` }).use(createStores()).use(createEvents()).use(router).mount("#app");
31
+ await session.load();
32
+ await router.isReady();
33
+ await router.push("/profile");
34
+ await settle();
35
+
36
+ const root = document.getElementById("app");
37
+ const $ = s => root.querySelector(s);
38
+ const text = s => $(s)?.textContent.replace(/\s+/g, " ").trim() ?? null;
39
+ const type = (id, value) => { const input = $(id); input.value = value; input.dispatchEvent(new w.Event("input")); };
40
+ const click = el => el.dispatchEvent(new w.MouseEvent("click", { bubbles: true, cancelable: true }));
41
+ const button = label => [...root.querySelectorAll("button")].find(b => b.textContent.trim() == label);
42
+ const wait = async () => { await new Promise(resolve => setTimeout(resolve, 30)); await settle(); };
43
+
44
+ check("the profile: their name and email in the form, Save changes off until something changes", $("#profile-name").value == "Ama Owusu" && $("#profile-email").value == "ama@example.test" && button("Save changes").disabled);
45
+
46
+ type("#profile-name", "Ama Owusu-Boateng");
47
+ click(button("Save changes")); await wait();
48
+ check("a new name applies at once: the API's asked, the top bar follows, Saved.", api.calls.some(call => call.method == "PATCH" && call.body.name == "Ama Owusu-Boateng" && call.body.email == "ama@example.test") && /Ama Owusu-Boateng/.test(text(".topbar") ?? "") && /Saved\./.test(text(".saved") ?? ""));
49
+
50
+ type("#profile-email", "NEW@example.test");
51
+ click(button("Save changes")); await wait();
52
+ check("a new email waits for its link: said so, with Resend and Cancel; the old one still signs in", /We sent a link to new@example\.test/.test(text(".pending") ?? "") && button("Resend the link") && button("Cancel the change") && session.user.email == "ama@example.test");
53
+ click(button("Resend the link")); await wait();
54
+ check("Resend asks the API", api.calls.some(call => call.path == "/api/user/email/resend"));
55
+ click(button("Cancel the change")); await wait();
56
+ check("Cancel gives it up: nothing's waiting", !$(".pending") && api.calls.some(call => call.method == "DELETE" && call.path == "/api/user/email/pending"));
57
+
58
+ type("#profile-email", "taken@example.test");
59
+ click(button("Save changes")); await wait();
60
+ check("an email another account has: the API's words, on the email", text("#profile-email-error") == "Another account uses this email.");
61
+
62
+ type("#profile-current", "wrong"); type("#profile-password", "short"); type("#profile-confirm", "other");
63
+ click(button("Change password")); await settle();
64
+ check("a password is checked first: too short and unconfirmed, nothing sent", /at least 8/.test(text("#profile-password-error") ?? "") && /don't match/.test(text("#profile-confirm-error") ?? "") && api.calls.every(call => call.method != "PUT"));
65
+ type("#profile-password", "a long new password"); type("#profile-confirm", "a long new password");
66
+ click(button("Change password")); await wait();
67
+ check("the API has the last word: a wrong current password is said on its field", text("#profile-current-error") == "That isn't your current password.");
68
+ type("#profile-current", "password");
69
+ click(button("Change password")); await wait();
70
+ check("the right one: Password changed., the fields empty", /Password changed\./.test(document.body.textContent) && $("#profile-current").value == "");
71
+
72
+ // The organisations they belong to, and leaving one.
73
+ user = apiUser({ organisations: [acme, { id: 2, name: "Bakery", role: "member" }] });
74
+ await session.load();
75
+ await settle();
76
+ check("their organisations: each with their role, the one they work in marked, Leave for the ones they don't own", /Acme/.test(text("[aria-labelledby=organisations-title]") ?? "") && /Current/.test(text("[aria-labelledby=organisations-title]") ?? "") && /You own it/.test(text("[aria-labelledby=organisations-title]") ?? "") && button("Leave"));
77
+ click(button("Leave")); await settle();
78
+ click([...document.querySelectorAll("dialog button")].find(b => b.textContent.trim() == "Leave")); await wait();
79
+ check("Leave asks first, then the API; the organisation's gone from the list", api.calls.some(call => call.method == "DELETE" && call.path == "/api/organisations/2/membership") && !/Bakery/.test(text("[aria-labelledby=organisations-title]") ?? ""));
@@ -0,0 +1,3 @@
1
+ // A user as the API answers with them — working in Acme, as its owner unless said — for the suites of the pages that need someone signed in.
2
+ export const acme = { id: 1, name: "Acme", role: "owner" };
3
+ export const apiUser = (more = {}) => ({ id: 1, name: "Ama Owusu", email: "ama@example.test", verified: true, pending_email: null, current_organisation_id: 1, organisations: [acme], ...more });
@@ -0,0 +1,51 @@
1
+ {
2
+ "id": "organisations",
3
+ "type": "kit",
4
+ "title": "Organisations",
5
+ "requires": [
6
+ "auth"
7
+ ],
8
+ "description": "Workspaces — teams, companies, schools: a switcher, creating one, members and their roles, inviting by email (and joining by the link), settings, a bell for what the app tells you — the pages for the Coven starter's Organisations kit.",
9
+ "patches": [
10
+ {
11
+ "file": "src/main.ts",
12
+ "marker": "imports",
13
+ "insert": [
14
+ "import \"@/assets/styles/organisations.css\";"
15
+ ]
16
+ },
17
+ {
18
+ "file": "src/router/index.ts",
19
+ "marker": "middleware",
20
+ "insert": [
21
+ "// Pages inside an organisation: someone in none (removed from their only one) is taken to the page that says so and offers a way in, and comes back once they're in one.",
22
+ "router.middleware(\"organisation\", () => {",
23
+ " const sessionStore = useSession();",
24
+ "",
25
+ " if(sessionStore.signedIn && !sessionStore.organisation)",
26
+ " return { name: \"organisations.none\" };",
27
+ "});",
28
+ "",
29
+ "// The page for someone in no organisation: anyone who is in one has no use for it.",
30
+ "router.middleware(\"without-organisation\", () => {",
31
+ " const sessionStore = useSession();",
32
+ "",
33
+ " if(sessionStore.organisation)",
34
+ " return { name: \"dashboard\" };",
35
+ "});",
36
+ "",
37
+ "// Pages for some roles in the organisation only: `role:owner,admin`. Anyone else is told they don't have access (the API refuses them too).",
38
+ "router.middleware(\"role\", (_to, _from, ...roles) => {",
39
+ " const sessionStore = useSession();",
40
+ "",
41
+ " if(!sessionStore.role || !roles.includes(sessionStore.role))",
42
+ " return { name: \"forbidden\" };",
43
+ "});",
44
+ ""
45
+ ]
46
+ }
47
+ ],
48
+ "notes": [
49
+ "An organisation is a workspace: what belongs to one is asked of the API for it (src/api/scope.ts's `call()` puts its id in the path); add your pages in src/router/routes.ts where it says."
50
+ ]
51
+ }
@@ -0,0 +1,209 @@
1
+ // Composes a project: a copy of the starter skeleton, with the chosen starter kit and options laid over it. Used by `create-mana`, and by the tests that make every combination.
2
+ //
3
+ // A kit (or an option) is a folder in kits/: `kit.json` and `files/`. Its `files/` are copied over the project as they are (a file the skeleton or an earlier kit has is replaced), and its
4
+ // `patches` (each with an optional `if`: the id of another kit or option it needs) add lines to what's already there at a marker — a comment `@mana:<name>` in the file, which the lines go in front of, so the marker is there for the next to use. Its `env`
5
+ // entries are added to `.env.example`. A text file's `{{#if x}}…{{/if}}` and `{{#unless x}}…{{/unless}}` lines (x: a kit's or an option's id) keep or drop what's between them; `Mana Starter`,
6
+ // `mana_starter` and `MANA_STARTER` in any text file (and any file's name) become the app's name and its slug, as it is and in capitals (what its database, its cookie and its units are named after).
7
+ import { chmodSync, copyFileSync, existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
8
+ import { dirname, join, relative } from "node:path";
9
+
10
+ // What the skeleton has that a new project doesn't: the installer and the kits themselves, the repository's own, and what's made as it runs.
11
+ const LEFT_OUT = new Set(["installer", "kits", ".git", ".github", "node_modules", "graphify-out", "dist", "package-lock.json", ".env", ".DS_Store", ".graphifyrc"]);
12
+
13
+ // The order they're laid over the project in: starter kits first (each after the kit it needs), then the options.
14
+ export const KITS = ["none", "auth", "organisations"];
15
+ export const OPTIONS = [];
16
+
17
+ const TEXT = /\.(ts|mjs|js|json|md|mana|html|css|sh|txt|yml|yaml)$|(^|\/)(\.gitignore|\.nvmrc|\.env\.[a-z]+)$/;
18
+ const isText = path => TEXT.test(path) || /(^|\/)\.env/.test(path);
19
+
20
+ function walk(folder) {
21
+ return readdirSync(folder).flatMap(name => statSync(join(folder, name)).isDirectory() ? walk(join(folder, name)) : [join(folder, name)]);
22
+ }
23
+
24
+ // The kits and options a choice means, in the order they're applied: `organisations` is `auth` then `organisations`.
25
+ export function chosen({ kit, options = [] }) {
26
+ if(!KITS.includes(kit))
27
+ throw new Error(`The starter kit must be one of ${KITS.join(", ")}; "${kit}" isn't.`);
28
+
29
+ const unknown = options.filter(option => !OPTIONS.includes(option));
30
+
31
+ if(unknown.length)
32
+ throw new Error(`Unknown option${unknown.length == 1 ? "" : "s"}: ${unknown.join(", ")}. The options are ${OPTIONS.join(", ")}.`);
33
+
34
+ const kits = kit == "none" ? [] : KITS.slice(1, KITS.indexOf(kit) + 1);
35
+
36
+ return [...kits, ...OPTIONS.filter(option => options.includes(option))];
37
+ }
38
+
39
+ // Whether a choice can be made, before anything is: the kit and options exist, and each option has the kits it needs. Throws what to say.
40
+ export function check(answers, kits) {
41
+ const applied = chosen(answers);
42
+ const on = new Set([...(answers.kit == "none" ? [] : [answers.kit, ...(answers.kit == "organisations" ? ["auth"] : [])]), ...applied]);
43
+
44
+ for(const id of applied) {
45
+ const manifest = JSON.parse(readFileSync(join(kits, id, "kit.json"), "utf8"));
46
+
47
+ for(const needed of manifest.requires ?? [])
48
+ if(!on.has(needed))
49
+ throw new Error(`${manifest.title ?? id} needs ${needed}, which isn't chosen.`);
50
+ }
51
+ }
52
+
53
+ // Keeps or drops the lines between `{{#if x}}` and `{{/if}}` (or `{{#unless x}}` … `{{/unless}}`), nested or not; the tag lines go either way, whether bare or after `//`, `#` or `<!--`. Both
54
+ // tags on one line keep or drop the words between them.
55
+ export function conditionals(text, on) {
56
+ // Within one line first: `three{{#if realtime}} and /ws{{/if}}`.
57
+ text = text.replace(/\{\{#(if|unless) ([\w-]+)\}\}(.*?)\{\{\/\1\}\}/g, (_, kind, name, inner) => (kind == "if") == on.has(name) ? inner : "");
58
+
59
+ const tag = /^\s*(?:\/\/|#|<!--)?\s*\{\{(#if|#unless|\/if|\/unless)(?: ([\w-]+))?\}\}\s*(?:-->)?\s*$/;
60
+ const stack = [];
61
+ const out = [];
62
+
63
+ for(const line of text.split("\n")) {
64
+ const found = tag.exec(line);
65
+
66
+ if(found) {
67
+ const [, kind, name] = found;
68
+
69
+ if(kind == "#if" || kind == "#unless")
70
+ stack.push(kind == "#if" ? on.has(name) : !on.has(name));
71
+ else if(stack.pop() === undefined)
72
+ throw new Error(`A {{${kind}}} has nothing to close.`);
73
+
74
+ continue;
75
+ }
76
+
77
+ if(stack.every(Boolean))
78
+ out.push(line);
79
+ }
80
+
81
+ if(stack.length)
82
+ throw new Error("A {{#if}} or {{#unless}} was never closed.");
83
+
84
+ return out.join("\n");
85
+ }
86
+
87
+ // Adds lines in front of the marker `@mana:<marker>` in a file's text; the marker must be there once.
88
+ export function patched(text, file, marker, lines) {
89
+ const rows = text.split("\n");
90
+ const found = new RegExp(`@mana:${marker.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w-])`);
91
+ const at = rows.flatMap((row, index) => found.test(row) ? [index] : []);
92
+
93
+ if(at.length != 1)
94
+ throw new Error(`${file}: expected the marker @mana:${marker} once, found it ${at.length} times.`);
95
+
96
+ rows.splice(at[0], 0, ...lines);
97
+
98
+ return rows.join("\n");
99
+ }
100
+
101
+ // Writes a project to `target`. `answers`: { name, slug, kit, options }; `skeleton` and `kits` are the folders to read; `frameworkRange` is how package.json asks for Mana (`^0.1.0`).
102
+ export function compose({ skeleton, kits, target, answers, frameworkRange, onFile = () => {} }) {
103
+ const { name, slug } = answers;
104
+ const applied = chosen(answers);
105
+ const on = new Set([...(answers.kit == "none" ? [] : [answers.kit, ...(answers.kit == "organisations" ? ["auth"] : [])]), ...applied]);
106
+ const names = text => text.replaceAll("Mana Starter", name).replaceAll("mana_starter", slug).replaceAll("MANA_STARTER", slug.toUpperCase());
107
+ const written = new Map();
108
+ const modes = new Map();
109
+ const notes = [];
110
+
111
+ const put = (source, from) => {
112
+ // A file's name may carry the slug too (`mana_starter.config.ts`), and `_gitignore` is `.gitignore`: npm leaves a `.gitignore` out of what it packs.
113
+ const path = names(source).replace(/(^|\/)_gitignore$/, "$1.gitignore");
114
+ const to = join(target, path);
115
+
116
+ mkdirSync(dirname(to), { recursive: true });
117
+
118
+ // A script stays executable.
119
+ modes.set(path, statSync(from).mode & 0o777);
120
+
121
+ if(isText(path))
122
+ written.set(path, names(readFileSync(from, "utf8")));
123
+ else {
124
+ copyFileSync(from, to);
125
+ written.delete(path);
126
+ }
127
+
128
+ onFile(path);
129
+ };
130
+ const read = path => written.get(path) ?? (existsSync(join(target, path)) ? readFileSync(join(target, path), "utf8") : null);
131
+
132
+ // The skeleton.
133
+ for(const file of walk(skeleton)) {
134
+ const path = relative(skeleton, file);
135
+
136
+ if(!LEFT_OUT.has(path.split("/")[0]) && !path.endsWith(".DS_Store"))
137
+ put(path, file);
138
+ }
139
+
140
+ // What every project has (its README, which says what was chosen), then the kits and options, in order.
141
+ for(const id of [...(existsSync(join(kits, "base")) ? ["base"] : []), ...applied]) {
142
+ const folder = join(kits, id);
143
+ const manifest = JSON.parse(readFileSync(join(folder, "kit.json"), "utf8"));
144
+
145
+ for(const needed of manifest.requires ?? [])
146
+ if(!on.has(needed))
147
+ throw new Error(`${manifest.title ?? id} needs ${needed}, which isn't chosen.`);
148
+
149
+ if(existsSync(join(folder, "files")))
150
+ for(const file of walk(join(folder, "files")))
151
+ put(relative(join(folder, "files"), file), file);
152
+
153
+ // `files-if/<id>/…` are copied only when the kit or option <id> is chosen too (a test that needs another kit).
154
+ for(const other of on)
155
+ if(existsSync(join(folder, "files-if", other)))
156
+ for(const file of walk(join(folder, "files-if", other)))
157
+ put(relative(join(folder, "files-if", other), file), file);
158
+
159
+ for(const patch of (manifest.patches ?? []).filter(each => !each.if || on.has(each.if))) {
160
+ const text = read(patch.file);
161
+
162
+ if(text === null)
163
+ throw new Error(`${id}: ${patch.file} isn't there to patch.`);
164
+
165
+ written.set(patch.file, patched(text, patch.file, patch.marker, patch.insert.map(names)));
166
+ }
167
+
168
+ for(const entry of (manifest.env ?? []).filter(each => !each.if || on.has(each.if))) {
169
+ const text = read(".env.example") ?? "";
170
+ const line = `${entry.key}=${entry.value}`;
171
+ const own = new RegExp(`^${entry.key}=.*$`, "m");
172
+
173
+ written.set(".env.example", own.test(text) ? text.replace(own, line) : `${text.replace(/\n*$/, "\n")}${entry.comment ? `\n${entry.comment.split("\n").map(row => `# ${row}`).join("\n")}\n` : "\n"}${line}\n`);
174
+ }
175
+
176
+ // What the tests' own environment (`.env.testing`) needs too.
177
+ for(const entry of manifest.envTesting ?? []) {
178
+ const text = read(".env.testing") ?? "";
179
+ const own = new RegExp(`^${entry.key}=.*$`, "m");
180
+
181
+ written.set(".env.testing", own.test(text) ? text.replace(own, `${entry.key}=${entry.value}`) : `${text.replace(/\n*$/, "\n")}${entry.key}=${entry.value}\n`);
182
+ }
183
+
184
+ notes.push(...(manifest.notes ?? []));
185
+ }
186
+
187
+ // package.json asks for Mana by version, not by the path it's developed beside.
188
+ const manifest = JSON.parse(read("package.json"));
189
+
190
+ manifest.name = slug;
191
+ manifest.description = `${name}, on Mana`;
192
+
193
+ for(const section of ["dependencies", "devDependencies"])
194
+ for(const [dependency, range] of Object.entries(manifest[section] ?? {}))
195
+ if(dependency.startsWith("@mana-js/") && String(range).startsWith("file:"))
196
+ manifest[section][dependency] = frameworkRange;
197
+
198
+ written.set("package.json", `${JSON.stringify(manifest, null, 2)}\n`);
199
+
200
+ // Conditionals, then to disk.
201
+ for(const [path, text] of written) {
202
+ writeFileSync(join(target, path), text.includes("{{#") ? conditionals(text, on) : text);
203
+
204
+ if(modes.has(path))
205
+ chmodSync(join(target, path), modes.get(path));
206
+ }
207
+
208
+ return { applied, notes, files: [...new Set([...written.keys()])] };
209
+ }
package/lib/new.mjs ADDED
@@ -0,0 +1,161 @@
1
+ // `create-mana <folder>`: asks what the application is to have, makes the folder from the starter and the kit chosen, and — if asked — installs what it needs. Everything it asks can be said on the
2
+ // command line (`--kit`, `--name`, `--no-install`, `--yes`), so it runs with no one there.
3
+ import { spawnSync } from "node:child_process";
4
+ import { existsSync, mkdirSync, readdirSync, readFileSync } from "node:fs";
5
+ import { basename, dirname, join, resolve } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { check, compose, KITS } from "./compose.mjs";
8
+ import { confirm, select, text } from "./prompts.mjs";
9
+
10
+ const here = resolve(dirname(fileURLToPath(import.meta.url)), "..");
11
+ // Published, the starter and the kits are beside this file's folder (`template/`, `kits/`, made by `npm pack`); in the repository they're the repository itself.
12
+ const packed = existsSync(join(here, "template"));
13
+ const skeleton = packed ? join(here, "template") : resolve(here, "..");
14
+ const kitsFolder = packed ? join(here, "kits") : resolve(here, "..", "kits");
15
+
16
+ const TITLES = { none: "None", auth: "Auth", organisations: "Organisations" };
17
+ const dim = text => `\x1b[2m${text}\x1b[22m`;
18
+ const bold = text => `\x1b[1m${text}\x1b[22m`;
19
+
20
+ // The kits' own words, from their kit.json.
21
+ const about = id => JSON.parse(readFileSync(join(kitsFolder, id, "kit.json"), "utf8"));
22
+
23
+ // "my-school" is "my_school" to a package name: lower case, letters and digits, and not starting with a digit.
24
+ export function slugOf(text) {
25
+ const slug = text.toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "") || "app";
26
+
27
+ return /^[0-9]/.test(slug) ? `app_${slug}` : slug;
28
+ }
29
+
30
+ // "my-school" as people read it: "My School".
31
+ export function titleOf(text) {
32
+ return slugOf(text).split("_").map(word => word[0].toUpperCase() + word.slice(1)).join(" ");
33
+ }
34
+
35
+ function parse(argv) {
36
+ const flags = {};
37
+ const words = [];
38
+
39
+ for(const arg of argv) {
40
+ if(arg.startsWith("--")) {
41
+ const [key, ...rest] = arg.slice(2).split("=");
42
+
43
+ flags[key] = rest.length ? rest.join("=") : true;
44
+ } else if(arg == "-y")
45
+ flags.yes = true;
46
+ else
47
+ words.push(arg);
48
+ }
49
+
50
+ return { flags, words };
51
+ }
52
+
53
+ export const USAGE = `Usage: npm create mana@latest <folder> -- [options] (or: npx create-mana <folder> [options])
54
+
55
+ <folder> where to make the application; its name makes the app's
56
+ --name="My School" the app's name as people see it, if the folder's isn't it
57
+ --kit=<kit> none, auth or organisations
58
+ --no-install don't run npm install
59
+ --yes, -y ask nothing: take what's said, and the defaults for the rest (the Auth kit)
60
+ --force make it in a folder that has things in it, writing over files of the same name
61
+
62
+ The kits: none (Vite, the router, a home page), auth (+ sign in, register, password reset, email confirmation, a profile), organisations (+ workspaces: create, switch, members, roles, invitations). The
63
+ pages are for the API the Coven starter makes (\`coven new\`), which they reach at /api.`;
64
+
65
+ // Runs `create-mana`. `io` is { input, output } for the prompts (a test types into them); the answer is the exit code.
66
+ export async function run(argv, io = {}) {
67
+ const input = io.input ?? process.stdin;
68
+ const output = io.output ?? process.stdout;
69
+ const say = line => output.write(`${line}\n`);
70
+ const { flags, words } = parse(argv);
71
+
72
+ if(flags.help || flags.h) {
73
+ say(USAGE);
74
+
75
+ return 0;
76
+ }
77
+
78
+ if(Number(process.versions.node.split(".")[0]) < 22) {
79
+ say(`Mana's tooling needs Node 22 or later (24 is current); this is ${process.versions.node}.`);
80
+
81
+ return 1;
82
+ }
83
+
84
+ const interactive = Boolean(input.isTTY && output.isTTY) && !flags.yes;
85
+ const options = { input, output };
86
+ let target = words[0];
87
+
88
+ if(!target) {
89
+ if(!interactive) {
90
+ say(USAGE);
91
+
92
+ return 1;
93
+ }
94
+
95
+ say(`\n ${bold("Mana")} ${dim("— a new application")}\n`);
96
+ target = await text("What is the application's folder called?", { ...options, initial: "my-app", check: answer => /^[\w.-]+$/.test(answer) ? null : "Letters, digits, dots, dashes and underscores." });
97
+ } else if(interactive)
98
+ say(`\n ${bold("Mana")} ${dim("— a new application")}\n`);
99
+
100
+ const folder = resolve(target);
101
+
102
+ if(!flags.force && existsSync(folder) && readdirSync(folder).length) {
103
+ say(`${folder} isn't empty: choose a folder that doesn't exist, an empty one, or say --force.`);
104
+
105
+ return 1;
106
+ }
107
+
108
+ const slug = slugOf(basename(folder));
109
+ const name = typeof flags.name == "string" ? flags.name : titleOf(basename(folder));
110
+ let kit = typeof flags.kit == "string" ? flags.kit : null;
111
+
112
+ if(kit !== null && !KITS.includes(kit)) {
113
+ say(`The starter kit must be one of ${KITS.join(", ")}; "${kit}" isn't.`);
114
+
115
+ return 1;
116
+ }
117
+
118
+ if(kit === null)
119
+ kit = interactive ? await select("Which starter kit would you like?", KITS.map(id => ({ value: id, label: TITLES[id], hint: id == "none" ? "Vite, the router and a home page: nothing about users." : about(id).description })), { ...options, initial: 1 }) : "auth";
120
+
121
+ try {
122
+ check({ kit, options: [] }, kitsFolder);
123
+ } catch(error) {
124
+ say(error.message);
125
+
126
+ return 1;
127
+ }
128
+
129
+ const install = flags["no-install"] ? false : interactive ? await confirm("Install the dependencies now (npm install)?", options) : Boolean(flags.install ?? flags.yes ?? false);
130
+
131
+ mkdirSync(folder, { recursive: true });
132
+
133
+ const versions = packed ? JSON.parse(readFileSync(join(here, "versions.json"), "utf8")) : { mana: JSON.parse(readFileSync(resolve(here, "..", "..", "mana-framework", "packages", "mana", "package.json"), "utf8")).version };
134
+ const { applied, notes } = compose({ skeleton, kits: kitsFolder, target: folder, answers: { name, slug, kit, options: [] }, frameworkRange: `^${versions.mana}` });
135
+
136
+ say(`\n ${bold(name)} is in ${folder}${applied.length ? ` ${dim(`(${applied.map(id => about(id).title).join(", ")})`)}` : ""}\n`);
137
+
138
+ let installed = false;
139
+
140
+ if(install) {
141
+ say(dim(" Installing what it needs (npm install)…\n"));
142
+
143
+ const done = spawnSync("npm", ["install", "--no-audit", "--no-fund"], { cwd: folder, stdio: ["ignore", "inherit", "inherit"], shell: process.platform == "win32" });
144
+
145
+ installed = done.status === 0;
146
+
147
+ if(!installed)
148
+ say("\n npm install failed; fix what it said, then run it again in the folder.");
149
+ }
150
+
151
+ const relative = target.startsWith("/") ? folder : target;
152
+
153
+ say(` Next:\n\n cd ${relative}${installed ? "" : "\n npm install"}\n npm run dev ${dim("# http://localhost:5173 — it passes /api on to the API on port 3000 (`coven new` makes one)")}\n npm test\n`);
154
+
155
+ for(const note of notes)
156
+ say(` ${dim("•")} ${note}`);
157
+
158
+ say(`\n The README says what's where.\n`);
159
+
160
+ return 0;
161
+ }