create-foliwake 0.0.0-stage → 0.4.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 (68) hide show
  1. package/CHANGELOG.md +85 -0
  2. package/LICENSE +202 -0
  3. package/README.md +64 -2
  4. package/dist/bin.d.ts +2 -0
  5. package/dist/bin.js +16 -0
  6. package/dist/cli.d.ts +8 -0
  7. package/dist/cli.js +88 -0
  8. package/dist/create.d.ts +50 -0
  9. package/dist/create.js +250 -0
  10. package/dist/destination.d.ts +47 -0
  11. package/dist/destination.js +243 -0
  12. package/dist/editor-files.d.ts +6 -0
  13. package/dist/editor-files.js +39 -0
  14. package/dist/files.d.ts +26 -0
  15. package/dist/files.js +94 -0
  16. package/dist/git.d.ts +22 -0
  17. package/dist/git.js +64 -0
  18. package/dist/index.d.ts +5 -0
  19. package/dist/index.js +7 -0
  20. package/dist/install.d.ts +12 -0
  21. package/dist/install.js +18 -0
  22. package/dist/options.d.ts +48 -0
  23. package/dist/options.js +54 -0
  24. package/dist/prompts.d.ts +16 -0
  25. package/dist/prompts.js +67 -0
  26. package/dist/starters.d.ts +20 -0
  27. package/dist/starters.js +61 -0
  28. package/dist/validate.d.ts +3 -0
  29. package/dist/validate.js +12 -0
  30. package/package.json +64 -3
  31. package/starters/examples/components/quiz/quiz.css +33 -0
  32. package/starters/examples/components/quiz/quiz.example.md +29 -0
  33. package/starters/examples/components/quiz/quiz.js +36 -0
  34. package/starters/examples/components/quiz/quiz.json +14 -0
  35. package/starters/examples/components/steps/steps.css +38 -0
  36. package/starters/examples/components/steps/steps.example.md +25 -0
  37. package/starters/examples/components/steps/steps.json +8 -0
  38. package/starters/examples/content/blocks.md +49 -0
  39. package/starters/examples/content/index.md +44 -0
  40. package/starters/minimal/components/note/note.css +15 -0
  41. package/starters/minimal/components/note/note.example.md +23 -0
  42. package/starters/minimal/components/note/note.json +8 -0
  43. package/starters/minimal/content/images/foliwake-logo.png +0 -0
  44. package/starters/minimal/content/index.md +32 -0
  45. package/starters/react/components/poll/poll.css +32 -0
  46. package/starters/react/components/poll/poll.example.md +26 -0
  47. package/starters/react/components/poll/poll.js +35 -0
  48. package/starters/react/components/poll/poll.json +13 -0
  49. package/starters/react/scripts/react-view.js +22 -0
  50. package/starters/shared/README.md +104 -0
  51. package/starters/shared/_github/actions/foliwake-request/action.yml +45 -0
  52. package/starters/shared/_github/scripts/foliwake-report.py +68 -0
  53. package/starters/shared/_github/workflows/branch-preview.yml +104 -0
  54. package/starters/shared/_github/workflows/frontend-checks.yml +28 -0
  55. package/starters/shared/_github/workflows/production.yml +134 -0
  56. package/starters/shared/_gitignore +8 -0
  57. package/starters/shared/jsconfig.json +15 -0
  58. package/starters/shared/scripts/components.js +284 -0
  59. package/starters/shared/site.yaml +2 -0
  60. package/starters/shared/styles/styles.css +106 -0
  61. package/starters/shared/tests/site.test.mjs +21 -0
  62. package/starters/shared/tests/workflows.test.mjs +84 -0
  63. package/starters/storybook/_storybook/main.js +49 -0
  64. package/starters/storybook/_storybook/preview.js +7 -0
  65. package/starters/storybook/_storybook/run.mjs +25 -0
  66. package/starters/storybook/pnpm-workspace.yaml +8 -0
  67. package/vendor/react.LICENSE.txt +21 -0
  68. package/vendor/react.js +32 -0
package/dist/create.js ADDED
@@ -0,0 +1,250 @@
1
+ // create-foliwake: a new site frontend: blocks, styles, local sample pages, checks and workflows.
2
+ //
3
+ // Order, so that nothing is written unless everything before it held:
4
+ // 1. flag values checked;
5
+ // 2. answers: flags first; in a terminal, questions for what is missing; otherwise defaults (Ctrl+C in a
6
+ // question: "cancelled", exit 130);
7
+ // 3. the destination checked (destination.ts: never Git metadata, never through a link, never over another
8
+ // repository) and the files planned in memory from the starters;
9
+ // 4. @foliwake/site-check over the planned files (validate.ts);
10
+ // 5. the files written as one transaction: on any failure nothing of this run stays, and with --overwrite the
11
+ // original files are put back; then the files for editors (git-ignored: the JSON Schema of block
12
+ // definitions, the types of `@foliwake/block-kit`);
13
+ // 6. the npm packages installed, when the project has some (Storybook) and that was asked;
14
+ // 7. `git init` and the first commit (when asked; never inside another repository, and not when that cannot
15
+ // be determined).
16
+ // Exit status: 0 created; 1 failure (also a failed or skipped-for-doubt Git step: the project stays);
17
+ // 2 refused input; 130 cancelled.
18
+ import { existsSync } from 'node:fs';
19
+ import path from 'node:path';
20
+ import { cancel } from '@clack/prompts';
21
+ import { nestedRepositories, pathProblems, resolveDestination, writeProject } from './destination.js';
22
+ import { projectFiles } from './files.js';
23
+ import { INITIAL_BRANCH, enclosingRepository, initAndCommit } from './git.js';
24
+ import { installPackages, packageManagerOf } from './install.js';
25
+ import { CreateCancelled, CreateUsageError, DEFAULT_FOLDER, DEFAULT_TEMPLATE, folderProblem, siteIdProblem, templateProblem, } from './options.js';
26
+ import { askExisting, askFolder, askGit, askInstall, askReact, askStorybook, askTemplate, welcome, } from './prompts.js';
27
+ import { writeKitTypes, writeLocalSchema } from './editor-files.js';
28
+ import { packageVersion, siteCheckVersion } from './starters.js';
29
+ import { projectProblems } from './validate.js';
30
+ export const EXIT_CANCELLED = 130;
31
+ /** The nearest existing folder at or above `target` (where Git discovery starts before the folder exists). */
32
+ function nearestExisting(target) {
33
+ for (let at = target;; at = path.dirname(at)) {
34
+ if (existsSync(at) || path.dirname(at) === at)
35
+ return at;
36
+ }
37
+ }
38
+ function checkRequest(request) {
39
+ const problem = (request.folder !== undefined ? folderProblem(request.folder) : null) ??
40
+ (request.template !== undefined ? templateProblem(request.template) : null) ??
41
+ (request.site ? siteIdProblem(request.site) : null);
42
+ if (problem)
43
+ throw new CreateUsageError(problem);
44
+ }
45
+ /** A path as a shell word (quoted only when needed). */
46
+ export function shellWord(value) {
47
+ return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
48
+ }
49
+ const listed = (items, max) => `${items.slice(0, max).join(', ')}${items.length > max ? ', …' : ''}`;
50
+ function notEmptyProblem(folder, entries) {
51
+ const choices = 'pass --overwrite to remove its files (.git is kept) or --keep-existing to add the project next to them';
52
+ return new CreateUsageError(`${folder} is not empty (${listed(entries, 4)}). Choose a new folder, or ${choices}.`);
53
+ }
54
+ async function answer(request, io, interactive) {
55
+ const prompts = io.prompts ?? { input: io.stdin, output: io.stdout };
56
+ const ask = (given, question, fallback) => given !== undefined ? given : interactive ? question() : fallback;
57
+ if (interactive)
58
+ welcome(prompts);
59
+ const folder = await ask(request.folder, () => askFolder(prompts), DEFAULT_FOLDER);
60
+ const { target, state } = await resolveDestination(io.cwd, folder);
61
+ let existing = null;
62
+ if (state.kind === 'files') {
63
+ existing = await ask(request.existing, () => askExisting(prompts, folder, state.entries), null);
64
+ if (existing === null)
65
+ throw notEmptyProblem(folder, state.entries);
66
+ }
67
+ const template = await ask(request.template, () => askTemplate(prompts), DEFAULT_TEMPLATE);
68
+ const siteId = request.site ? request.site : null;
69
+ const react = await ask(request.react, () => askReact(prompts), false);
70
+ const storybook = await ask(request.storybook, () => askStorybook(prompts), false);
71
+ const manager = packageManagerOf(io.env);
72
+ const install = storybook ? await ask(request.install, () => askInstall(prompts, manager), false) : false;
73
+ const git = await ask(request.git, () => askGit(prompts), true);
74
+ return { folder, target, template, siteId, git, react, storybook, install, existing };
75
+ }
76
+ async function placementProblems(answers, files) {
77
+ const { folder, target, existing } = answers;
78
+ if (existing === 'keep') {
79
+ const { taken, unsafe } = await pathProblems(target, files.map((file) => file.path));
80
+ if (unsafe.length) {
81
+ throw new CreateUsageError(`${folder} has ${listed(unsafe, 6)} where the project needs a real folder (a symbolic link or a file); ` +
82
+ 'nothing is written through links. Nothing was written.');
83
+ }
84
+ if (taken.length) {
85
+ throw new CreateUsageError(`${folder} already has ${listed(taken, 6)}; kept files are never replaced. Nothing was written. ` +
86
+ 'Use --overwrite to remove the existing files, or another folder.');
87
+ }
88
+ }
89
+ if (existing === 'clear') {
90
+ const repositories = await nestedRepositories(target);
91
+ if (repositories.length) {
92
+ throw new CreateUsageError(`${folder} contains Git repositories (${listed(repositories, 6)}); --overwrite never removes a repository. ` +
93
+ 'Move them out or choose another folder. Nothing was changed.');
94
+ }
95
+ }
96
+ }
97
+ function shownFolder(io, folder, target) {
98
+ const relative = path.relative(io.cwd, path.resolve(io.cwd, folder));
99
+ return relative === '' ? '.' : relative.startsWith('..') ? target : relative;
100
+ }
101
+ function firstCommitHelp(others, files) {
102
+ const stage = others ? `git add -- ${files.map(shellWord).join(' ')}` : 'git add -A';
103
+ const only = others ? " (only the project's files; the other files in the folder stay out)" : '';
104
+ const commit = '`git commit -m "Create the site"`';
105
+ return `run \`git init -b ${INITIAL_BRANCH}\`, \`${stage}\`${only} and ${commit} in the folder.`;
106
+ }
107
+ async function gitStep(answers, files, others, io, version) {
108
+ const { folder, target, template } = answers;
109
+ const skipped = (line) => ({ line, help: null, failed: false, committed: false });
110
+ if (!answers.git)
111
+ return skipped('Git: skipped. The platform takes code from commits: run `git init` and commit when you are ready.');
112
+ const repository = await enclosingRepository(nearestExisting(target), io.env);
113
+ if (repository.kind === 'inside') {
114
+ return skipped(`Git: ${folder} is inside the repository ${repository.top}; no repository was created and nothing was ` +
115
+ 'committed. Review and commit the new files there.');
116
+ }
117
+ if (repository.kind === 'unknown') {
118
+ const check = `Check with \`git -C ${shellWord(folder)} rev-parse --show-toplevel\`.`;
119
+ return {
120
+ line: `Git: skipped: could not tell whether ${folder} is inside another repository (${repository.reason}), ` +
121
+ 'so no repository was created and nothing was committed.',
122
+ help: `${check} Inside a repository: commit the new files there. Otherwise ${firstCommitHelp(others, files)}`,
123
+ failed: true,
124
+ committed: false,
125
+ };
126
+ }
127
+ const message = `Create the site with create-foliwake ${version} (template ${template})`;
128
+ const commit = await initAndCommit(target, files, message, io.env);
129
+ if (commit.ok) {
130
+ const line = `Git: new repository (branch ${INITIAL_BRANCH}), first commit ${commit.sha.slice(0, 7)}.`;
131
+ return { line, help: null, failed: false, committed: true };
132
+ }
133
+ const identity = "The project's files are staged (nothing else). Fix the problem above (for a missing identity: " +
134
+ '`git config --global user.name …` and `user.email …`), then run `git commit -m "Create the site"` in the folder.';
135
+ const help = commit.step === 'commit' ? identity : `Fix the problem above, then ${firstCommitHelp(others, files)}`;
136
+ return { line: `Git: FAILED at \`git ${commit.step}\`: ${commit.reason}`, help, failed: true, committed: false };
137
+ }
138
+ async function installStep(target, manager, io) {
139
+ const result = await installPackages(target, manager, io.env);
140
+ if (result.ok)
141
+ return `Installed the npm packages with ${manager}.`;
142
+ return `Install FAILED (${result.reason}); run \`${manager} install\` in the folder.`;
143
+ }
144
+ const nothingCreated = (status, report) => ({
145
+ status,
146
+ created: false,
147
+ answers: null,
148
+ shown: '',
149
+ files: [],
150
+ committed: false,
151
+ report,
152
+ help: null,
153
+ });
154
+ /**
155
+ * Creates the project; resolves to what it did (create-foliwake prints it with printResult, a wrapper may add
156
+ * its own steps first). Throws CreateUsageError for refused input (nothing was written).
157
+ */
158
+ export async function createProject(request, io) {
159
+ checkRequest(request);
160
+ const interactive = request.interactive ?? (io.stdin.isTTY === true && io.stdout.isTTY === true);
161
+ let answers;
162
+ try {
163
+ answers = await answer(request, io, interactive);
164
+ }
165
+ catch (error) {
166
+ if (!(error instanceof CreateCancelled))
167
+ throw error;
168
+ if (interactive)
169
+ cancel(error.message, io.prompts ?? { input: io.stdin, output: io.stdout });
170
+ return nothingCreated(EXIT_CANCELLED, interactive ? [] : [error.message]);
171
+ }
172
+ const version = await packageVersion();
173
+ const files = await projectFiles({ ...answers });
174
+ await placementProblems(answers, files);
175
+ const problems = await projectProblems(files);
176
+ if (problems.length) {
177
+ const template = `The ${answers.template} template of create-foliwake ${version}`;
178
+ const head = `${template} fails its own checks, so nothing was written. Please report this:`;
179
+ return nothingCreated(1, [head, ...problems.map((problem) => ` ${problem}`)]);
180
+ }
181
+ const written = await writeProject(answers.target, files, answers.existing);
182
+ const notes = [];
183
+ let status = 0;
184
+ await writeLocalSchema(answers.target).catch((error) => {
185
+ notes.push(`The JSON Schema for editors was not written (${error.message}); \`foliwake dev\` writes it.`);
186
+ });
187
+ await writeKitTypes(answers.target).catch((error) => {
188
+ notes.push(`The types of \`foliwake\` for editors were not written (${error.message}); \`foliwake dev\` writes them.`);
189
+ });
190
+ if (written.leftover) {
191
+ status = 1;
192
+ notes.push(`Cleanup incomplete: the project was created, but some of the replaced files could not be deleted ` +
193
+ `(${written.leftover.reason}); they are in ${written.leftover.folder}. ` +
194
+ 'Delete that folder yourself; it is not committed.');
195
+ }
196
+ if (answers.install)
197
+ notes.push(await installStep(answers.target, packageManagerOf(io.env), io));
198
+ const paths = files.map((file) => file.path);
199
+ const others = answers.existing === 'keep' || written.leftover !== null;
200
+ const git = await gitStep(answers, paths, others, io, version);
201
+ if (git.failed)
202
+ status = 1;
203
+ const shown = shownFolder(io, answers.folder, answers.target);
204
+ const extras = [answers.react ? ', React' : '', answers.storybook ? ', Storybook' : ''].join('');
205
+ const options = `template ${answers.template}${extras}`;
206
+ const site = answers.siteId ? `, site id ${answers.siteId}` : '';
207
+ const report = [
208
+ `Checked with @foliwake/site-check ${await siteCheckVersion()}: no problems.`,
209
+ `Created ${shown} (${options}, create-foliwake ${version}${site}).`,
210
+ git.line,
211
+ ...notes,
212
+ ];
213
+ return { status, created: true, answers, shown, files: paths, committed: git.committed, report, help: git.help };
214
+ }
215
+ /** The «Next» steps after a project is created. */
216
+ export function nextSteps(result) {
217
+ const steps = ['Next:'];
218
+ if (result.shown !== '.')
219
+ steps.push(` cd ${shellWord(result.shown)}`);
220
+ steps.push(' npx @foliwake/site-check re-check after every change; the platform runs the same checks', ' Push the repository to GitHub and connect it to your site in the Foliwake admin ' +
221
+ '(README.md, "Connect to Foliwake"):', " every branch gets a preview with the site's content; " +
222
+ "a merge to main goes to the site's preview, then Release in the admin.", ' Local preview and page checks need the Foliwake CLI (Docker image or Foliwake Cloud): foliwake dev --watch');
223
+ if (result.answers?.storybook && !result.answers.install)
224
+ steps.push(' npm install (Storybook; `npm run stories` needs the Foliwake CLI)');
225
+ return steps;
226
+ }
227
+ /** Prints the report (and the Next steps of a created project). */
228
+ export function printResult(result, io) {
229
+ const out = (text = '') => io.stdout.write(`${text}\n`);
230
+ const err = (text = '') => io.stderr.write(`${text}\n`);
231
+ if (!result.created) {
232
+ for (const line of result.report)
233
+ err(line);
234
+ return;
235
+ }
236
+ out();
237
+ for (const line of result.report)
238
+ out(line);
239
+ if (result.help)
240
+ err(`The project files are complete and checked. ${result.help}`);
241
+ out();
242
+ for (const line of nextSteps(result))
243
+ out(line);
244
+ }
245
+ /** Runs create-foliwake; resolves to the exit status. Throws CreateUsageError for refused input. */
246
+ export async function runCreate(request, io) {
247
+ const result = await createProject(request, io);
248
+ printResult(result, io);
249
+ return result.status;
250
+ }
@@ -0,0 +1,47 @@
1
+ import { type FileHandle } from 'node:fs/promises';
2
+ import { type ExistingFiles } from './options.js';
3
+ export type FolderState = {
4
+ kind: 'missing';
5
+ } | {
6
+ kind: 'empty';
7
+ } | {
8
+ kind: 'files';
9
+ entries: string[];
10
+ };
11
+ export interface Destination {
12
+ /** Real absolute path (links above it resolved; the target itself is not a link). */
13
+ target: string;
14
+ state: FolderState;
15
+ }
16
+ /** Resolves and checks the target folder; refuses Git metadata, a link or a file there. */
17
+ export declare function resolveDestination(cwd: string, folder: string): Promise<Destination>;
18
+ /** Repositories below the target (other than its own .git) that clearing would destroy; never follows links. */
19
+ export declare function nestedRepositories(target: string): Promise<string[]>;
20
+ /**
21
+ * Problems of the generated paths in a folder that keeps its files: an existing
22
+ * file to be replaced, or an existing part of a path that is a link or a file.
23
+ */
24
+ export declare function pathProblems(target: string, files: readonly string[]): Promise<{
25
+ taken: string[];
26
+ unsafe: string[];
27
+ }>;
28
+ /** How a file's bytes are written and the replaced entries removed (tests inject failures here). */
29
+ export interface WriteHooks {
30
+ writeBytes?: (handle: FileHandle, bytes: Buffer, file: string) => Promise<void>;
31
+ removeBackup?: (backup: string) => Promise<void>;
32
+ }
33
+ /** The project is written. With --overwrite, `leftover` is set when the replaced entries could not all be deleted. */
34
+ export interface WriteResult {
35
+ leftover: {
36
+ folder: string;
37
+ reason: string;
38
+ } | null;
39
+ }
40
+ /**
41
+ * Writes the project as one transaction. `existing: 'clear'` moves the current
42
+ * entries (never .git) aside first and deletes them only after every file is written.
43
+ */
44
+ export declare function writeProject(target: string, files: ReadonlyArray<{
45
+ path: string;
46
+ bytes: Buffer;
47
+ }>, existing: ExistingFiles | null, hooks?: WriteHooks): Promise<WriteResult>;
@@ -0,0 +1,243 @@
1
+ // create-foliwake: the target folder, and writing into it as one transaction.
2
+ //
3
+ // Guarantees:
4
+ // - Git metadata is never a destination and never touched: a path with a `.git`
5
+ // component, a real path (after resolving links above the target) running
6
+ // through one, or a folder shaped like a repository's metadata (HEAD, objects/,
7
+ // refs/: a bare repository) is refused; the target's own `.git` is never moved
8
+ // or read; clearing refuses a folder holding other repositories (`.git` at
9
+ // any depth, or a bare one), since that would destroy their history.
10
+ // - Nothing is written through a symbolic link inside the destination: the
11
+ // target itself must not be a link, every existing folder on the way to a
12
+ // generated file must be a real folder (checked before and while writing),
13
+ // and files are created exclusively (O_EXCL never follows a link).
14
+ // Links ABOVE the target (macOS /tmp → /private/tmp, a linked home) are
15
+ // resolved once; the work then happens on the real path.
16
+ // - All or nothing: a file is owned as soon as its exclusive create succeeds,
17
+ // so a failure removes every file and folder this run made; `--overwrite`
18
+ // first moves the existing entries into a hidden folder inside the target,
19
+ // deletes them only after every file is written, and moves them back on failure.
20
+ import { randomBytes } from 'node:crypto';
21
+ import { lstat, mkdir, open, readdir, realpath, rename, rm, rmdir, unlink } from 'node:fs/promises';
22
+ import path from 'node:path';
23
+ import { CreateUsageError } from './options.js';
24
+ const isGitName = (name) => name.toLowerCase() === '.git';
25
+ const BACKUP_PREFIX = '.foliwake-create-old-';
26
+ async function lstatOrNull(file) {
27
+ try {
28
+ return await lstat(file);
29
+ }
30
+ catch (error) {
31
+ const code = error.code;
32
+ if (code === 'ENOENT')
33
+ return null;
34
+ if (code === 'ENOTDIR')
35
+ throw new CreateUsageError(`${file}: a part of this path is a file, not a folder.`);
36
+ throw error;
37
+ }
38
+ }
39
+ /** True for a folder holding a repository's metadata (HEAD, objects/, refs/), as a bare repository does. */
40
+ async function looksLikeGitDir(dir) {
41
+ const [head, objects, refs] = await Promise.all(['HEAD', 'objects', 'refs'].map((name) => lstat(path.join(dir, name)).catch(() => null)));
42
+ return Boolean(head?.isFile() && objects?.isDirectory() && refs?.isDirectory());
43
+ }
44
+ function gitMetadataProblem(shown) {
45
+ return new CreateUsageError(`${shown} is inside Git metadata (a .git folder or a bare repository); choose a folder outside it.`);
46
+ }
47
+ /** Resolves and checks the target folder; refuses Git metadata, a link or a file there. */
48
+ export async function resolveDestination(cwd, folder) {
49
+ const absolute = path.resolve(cwd, folder);
50
+ if (absolute.split(path.sep).some(isGitName))
51
+ throw gitMetadataProblem(folder);
52
+ // The nearest existing folder at or above the target, and what is still missing below it.
53
+ let base = absolute;
54
+ const missing = [];
55
+ for (;;) {
56
+ const stats = await lstatOrNull(base);
57
+ if (stats) {
58
+ if (base === absolute && stats.isSymbolicLink())
59
+ throw new CreateUsageError(`${folder} is a symbolic link; choose a real folder.`);
60
+ if (base === absolute && !stats.isDirectory())
61
+ throw new CreateUsageError(`${folder} exists and is not a folder; choose another name.`);
62
+ break;
63
+ }
64
+ const parent = path.dirname(base);
65
+ if (parent === base)
66
+ break;
67
+ missing.unshift(path.basename(base));
68
+ base = parent;
69
+ }
70
+ const realBase = await realpath(base);
71
+ if (!(await lstat(realBase)).isDirectory())
72
+ throw new CreateUsageError(`${folder}: ${base} is not a folder.`);
73
+ const target = path.join(realBase, ...missing);
74
+ if (target.split(path.sep).some(isGitName))
75
+ throw gitMetadataProblem(folder);
76
+ for (let at = realBase;; at = path.dirname(at)) {
77
+ if (await looksLikeGitDir(at))
78
+ throw gitMetadataProblem(folder);
79
+ if (path.dirname(at) === at)
80
+ break;
81
+ }
82
+ if (missing.length)
83
+ return { target, state: { kind: 'missing' } };
84
+ const entries = (await readdir(target)).filter((name) => !isGitName(name)).sort();
85
+ return { target, state: entries.length === 0 ? { kind: 'empty' } : { kind: 'files', entries } };
86
+ }
87
+ /** Repositories below the target (other than its own .git) that clearing would destroy; never follows links. */
88
+ export async function nestedRepositories(target) {
89
+ const found = [];
90
+ const walk = async (dir, depth) => {
91
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
92
+ const full = path.join(dir, entry.name);
93
+ const relative = path.relative(target, full);
94
+ if (isGitName(entry.name)) {
95
+ if (depth > 0)
96
+ found.push(relative);
97
+ continue; // the target's own .git: kept, never read
98
+ }
99
+ if (entry.isDirectory()) {
100
+ if (await looksLikeGitDir(full))
101
+ found.push(relative);
102
+ else
103
+ await walk(full, depth + 1);
104
+ }
105
+ }
106
+ };
107
+ await walk(target, 0);
108
+ return found.sort();
109
+ }
110
+ /**
111
+ * Problems of the generated paths in a folder that keeps its files: an existing
112
+ * file to be replaced, or an existing part of a path that is a link or a file.
113
+ */
114
+ export async function pathProblems(target, files) {
115
+ const taken = [];
116
+ const unsafe = new Set();
117
+ for (const file of files) {
118
+ const parts = file.split('/');
119
+ for (let i = 1; i <= parts.length; i++) {
120
+ const relative = parts.slice(0, i).join('/');
121
+ const stats = await lstatOrNull(path.join(target, ...parts.slice(0, i)));
122
+ if (!stats)
123
+ break;
124
+ if (i === parts.length)
125
+ taken.push(file);
126
+ else if (stats.isSymbolicLink() || !stats.isDirectory()) {
127
+ unsafe.add(relative);
128
+ break;
129
+ }
130
+ }
131
+ }
132
+ return { taken, unsafe: [...unsafe].sort() };
133
+ }
134
+ const defaultWrite = (handle, bytes) => handle.writeFile(bytes);
135
+ const defaultRemove = (backup) => rm(backup, { recursive: true, force: true });
136
+ /** What this run made, so exactly that can be undone. */
137
+ class Owned {
138
+ dirs = [];
139
+ files = [];
140
+ moved = null;
141
+ /** Removes our files and folders, then puts moved entries back. Returns paths it could not restore or remove. */
142
+ async undo() {
143
+ const left = [];
144
+ for (const file of [...this.files].reverse())
145
+ await unlink(file).catch((e) => e.code !== 'ENOENT' && left.push(file));
146
+ for (const dir of [...this.dirs].reverse())
147
+ await rmdir(dir).catch((e) => e.code !== 'ENOENT' && left.push(dir));
148
+ if (this.moved) {
149
+ const { backup, names } = this.moved;
150
+ for (const name of names)
151
+ await rename(path.join(backup, name), path.join(path.dirname(backup), name)).catch(() => left.push(path.join(backup, name)));
152
+ await rmdir(backup).catch(() => left.push(backup));
153
+ }
154
+ return left;
155
+ }
156
+ }
157
+ /** Creates one folder (not recursively) or accepts an existing real one; never a link. */
158
+ async function enterFolder(dir, owned) {
159
+ try {
160
+ await mkdir(dir);
161
+ owned.dirs.push(dir);
162
+ }
163
+ catch (error) {
164
+ if (error.code !== 'EEXIST')
165
+ throw error;
166
+ const stats = await lstat(dir);
167
+ if (stats.isSymbolicLink() || !stats.isDirectory())
168
+ throw new CreateUsageError(`${dir} is a symbolic link or a file; nothing is written through it.`);
169
+ }
170
+ }
171
+ /**
172
+ * Writes the project as one transaction. `existing: 'clear'` moves the current
173
+ * entries (never .git) aside first and deletes them only after every file is written.
174
+ */
175
+ export async function writeProject(target, files, existing, hooks = {}) {
176
+ const writeBytes = hooks.writeBytes ?? defaultWrite;
177
+ const owned = new Owned();
178
+ try {
179
+ // The target and its missing parents, one level at a time.
180
+ const chain = [];
181
+ for (let at = target; !(await lstatOrNull(at)); at = path.dirname(at))
182
+ chain.unshift(at);
183
+ for (const dir of chain)
184
+ await enterFolder(dir, owned);
185
+ await enterFolder(target, owned);
186
+ if (existing === 'clear') {
187
+ const backup = path.join(target, `${BACKUP_PREFIX}${randomBytes(6).toString('hex')}`);
188
+ await mkdir(backup);
189
+ owned.moved = { backup, names: [] };
190
+ for (const name of await readdir(target)) {
191
+ if (isGitName(name) || path.join(target, name) === backup)
192
+ continue;
193
+ await rename(path.join(target, name), path.join(backup, name));
194
+ owned.moved.names.push(name);
195
+ }
196
+ }
197
+ for (const file of files) {
198
+ const parts = file.path.split('/');
199
+ let dir = target;
200
+ for (const part of parts.slice(0, -1))
201
+ await enterFolder((dir = path.join(dir, part)), owned);
202
+ const absolute = path.join(dir, parts.at(-1));
203
+ const handle = await open(absolute, 'wx');
204
+ owned.files.push(absolute); // ours from here on, even if writing fails
205
+ try {
206
+ await writeBytes(handle, file.bytes, file.path);
207
+ }
208
+ finally {
209
+ await handle.close();
210
+ }
211
+ }
212
+ }
213
+ catch (error) {
214
+ const left = await owned.undo();
215
+ const note = left.length ? ` Could not undo: ${left.join(', ')}.` : '';
216
+ const restored = owned.moved ? ' The existing files were put back.' : '';
217
+ if (error instanceof CreateUsageError)
218
+ throw new CreateUsageError(`${error.message} Nothing was written.${restored}${note}`);
219
+ if (error.code === 'EEXIST') {
220
+ const file = error.path ?? 'A file';
221
+ const what = `${file} appeared while the project was being written; nothing was replaced or kept.`;
222
+ throw new CreateUsageError(`${what}${restored}${note}`);
223
+ }
224
+ error.message = `${error.message} — nothing was kept.${restored}${note}`;
225
+ throw error;
226
+ }
227
+ // Every file is written: only now are the replaced entries deleted. The project is complete
228
+ // either way; a failure here is reported (what is left, and where), never undone.
229
+ if (!owned.moved)
230
+ return { leftover: null };
231
+ try {
232
+ await (hooks.removeBackup ?? defaultRemove)(owned.moved.backup);
233
+ return { leftover: null };
234
+ }
235
+ catch (error) {
236
+ return {
237
+ leftover: {
238
+ folder: owned.moved.backup,
239
+ reason: error.code ?? error.message,
240
+ },
241
+ };
242
+ }
243
+ }
@@ -0,0 +1,6 @@
1
+ export declare const LOCAL_SCHEMA_PATH = ".foliwake/schemas/block-1.schema.json";
2
+ export declare const KIT_TYPES_PATH = ".foliwake/types/foliwake.d.ts";
3
+ /** Writes (or refreshes) the JSON Schema of block definitions. */
4
+ export declare function writeLocalSchema(projectRoot: string): Promise<string>;
5
+ /** Writes (or refreshes) the types of the module `@foliwake/block-kit`. */
6
+ export declare function writeKitTypes(projectRoot: string): Promise<string>;
@@ -0,0 +1,39 @@
1
+ // Files for editors in a new project, git-ignored and never committed (`foliwake dev` refreshes them):
2
+ // - `.foliwake/schemas/block-1.schema.json`, named by the `$schema` of each `components/<name>/<name>.json`,
3
+ // written from @foliwake/site-check, so it is the checker's own rule set;
4
+ // - `.foliwake/types/foliwake.d.ts`, the types of the module `@foliwake/block-kit` (jsconfig.json maps the
5
+ // specifier there), from @foliwake/block-kit. The types of each block (`.foliwake/types/blocks/`) come from the CLI.
6
+ // Nothing is written through a symbolic link.
7
+ import { lstat, mkdir, readFile, writeFile } from 'node:fs/promises';
8
+ import path from 'node:path';
9
+ import { BLOCK_SCHEMA_FILE, blockSchemaText } from '@foliwake/site-check/blocks/schema';
10
+ export const LOCAL_SCHEMA_PATH = `.foliwake/schemas/${BLOCK_SCHEMA_FILE}`;
11
+ export const KIT_TYPES_PATH = '.foliwake/types/foliwake.d.ts';
12
+ async function refuseLinks(projectRoot, relative) {
13
+ const parts = relative.split('/');
14
+ for (let depth = 1; depth <= parts.length; depth++) {
15
+ const info = await lstat(path.join(projectRoot, ...parts.slice(0, depth))).catch(() => null);
16
+ if (!info?.isSymbolicLink())
17
+ continue;
18
+ throw new Error(`${parts.slice(0, depth).join('/')} is a symbolic link; nothing is written through links`);
19
+ }
20
+ }
21
+ /** Writes `text` at `relative` unless it is there already; returns `relative`. */
22
+ async function writeEditorFile(projectRoot, relative, text) {
23
+ await refuseLinks(projectRoot, relative);
24
+ const target = path.join(projectRoot, ...relative.split('/'));
25
+ if ((await readFile(target, 'utf8').catch(() => null)) === text)
26
+ return relative;
27
+ await mkdir(path.dirname(target), { recursive: true });
28
+ await writeFile(target, text);
29
+ return relative;
30
+ }
31
+ /** Writes (or refreshes) the JSON Schema of block definitions. */
32
+ export function writeLocalSchema(projectRoot) {
33
+ return writeEditorFile(projectRoot, LOCAL_SCHEMA_PATH, blockSchemaText());
34
+ }
35
+ /** Writes (or refreshes) the types of the module `@foliwake/block-kit`. */
36
+ export async function writeKitTypes(projectRoot) {
37
+ const declaration = new URL(import.meta.resolve('@foliwake/block-kit/foliwake.d.ts'));
38
+ return writeEditorFile(projectRoot, KIT_TYPES_PATH, await readFile(declaration, 'utf8'));
39
+ }
@@ -0,0 +1,26 @@
1
+ import { type TemplateName } from './options.js';
2
+ /** Storybook's packages: exact versions, at least two weeks old when chosen. */
3
+ export declare const STORYBOOK_PACKAGES: Readonly<{
4
+ '@storybook/html-vite': "10.6.3";
5
+ storybook: "10.6.3";
6
+ vite: "8.3.5";
7
+ }>;
8
+ /** The local configuration of the Foliwake CLI (`foliwake dev`); harmless without it. */
9
+ export declare const CONFIG_FILE_NAME = "foliwake.config.json";
10
+ export interface ProjectFile {
11
+ /** Project-relative, with "/" */
12
+ path: string;
13
+ bytes: Buffer;
14
+ }
15
+ export interface ProjectInput {
16
+ template: TemplateName;
17
+ /** Absolute target folder (its base name names the package). */
18
+ target: string;
19
+ siteId: string | null;
20
+ /** add starters/storybook/ and its npm packages */
21
+ storybook?: boolean;
22
+ /** add starters/react/ (a React block) and the vendored React in scripts/vendor/ */
23
+ react?: boolean;
24
+ }
25
+ /** Every file of the new project, sorted by path. */
26
+ export declare function projectFiles(input: ProjectInput): Promise<ProjectFile[]>;