@fedify/cli 1.8.11 → 2.0.0-dev.1757

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 (130) hide show
  1. package/deno.json +72 -0
  2. package/dist/cache.js +17 -0
  3. package/dist/deno.js +72 -0
  4. package/dist/docloader.js +52 -0
  5. package/dist/globals.js +49 -0
  6. package/dist/imagerenderer.js +105 -0
  7. package/dist/inbox/rendercode.js +57 -0
  8. package/dist/inbox/view.js +508 -0
  9. package/dist/inbox.js +315 -0
  10. package/dist/init/action/configs.js +81 -0
  11. package/dist/init/action/deps.js +52 -0
  12. package/dist/init/action/dir.js +16 -0
  13. package/dist/init/action/env.js +13 -0
  14. package/dist/init/action/install.js +22 -0
  15. package/dist/init/action/mod.js +39 -0
  16. package/dist/init/action/notice.js +62 -0
  17. package/dist/init/action/patch.js +141 -0
  18. package/dist/init/action/precommand.js +23 -0
  19. package/dist/init/action/recommend.js +24 -0
  20. package/dist/init/action/set.js +31 -0
  21. package/dist/init/action/templates.js +57 -0
  22. package/dist/init/action/utils.js +50 -0
  23. package/dist/init/ask/dir.js +82 -0
  24. package/dist/init/ask/kv.js +33 -0
  25. package/dist/init/ask/mod.js +16 -0
  26. package/dist/init/ask/mq.js +33 -0
  27. package/dist/init/ask/pm.js +49 -0
  28. package/dist/init/ask/wf.js +29 -0
  29. package/dist/init/command.js +25 -0
  30. package/dist/init/const.js +31 -0
  31. package/dist/init/json/biome.js +24 -0
  32. package/dist/init/json/kv.js +53 -0
  33. package/dist/init/json/mq.js +72 -0
  34. package/dist/init/json/pm.js +44 -0
  35. package/dist/init/json/rt.js +39 -0
  36. package/dist/init/json/vscode-settings-for-deno.js +53 -0
  37. package/dist/init/json/vscode-settings.js +49 -0
  38. package/dist/init/lib.js +129 -0
  39. package/dist/init/mod.js +5 -0
  40. package/dist/init/webframeworks.js +133 -0
  41. package/dist/kv.bun.js +17 -0
  42. package/dist/kv.node.js +17 -0
  43. package/dist/log.js +52 -0
  44. package/dist/lookup.js +287 -0
  45. package/dist/mod.js +34 -0
  46. package/dist/nodeinfo.js +261 -0
  47. package/dist/table.js +24 -0
  48. package/dist/tempserver.js +71 -0
  49. package/dist/tunnel.js +21 -0
  50. package/dist/utils.js +67 -0
  51. package/dist/webfinger/action.js +44 -0
  52. package/dist/webfinger/command.js +20 -0
  53. package/dist/webfinger/error.js +47 -0
  54. package/dist/webfinger/lib.js +45 -0
  55. package/dist/webfinger/mod.js +5 -0
  56. package/package.json +64 -24
  57. package/scripts/pack.ts +64 -0
  58. package/src/cache.ts +17 -0
  59. package/src/docloader.ts +67 -0
  60. package/src/globals.ts +43 -0
  61. package/src/imagerenderer.ts +149 -0
  62. package/src/inbox/entry.ts +10 -0
  63. package/src/inbox/rendercode.ts +68 -0
  64. package/src/inbox/view.tsx +598 -0
  65. package/src/inbox.tsx +535 -0
  66. package/src/init/action/configs.ts +88 -0
  67. package/src/init/action/deps.ts +93 -0
  68. package/src/init/action/dir.ts +11 -0
  69. package/src/init/action/env.ts +14 -0
  70. package/src/init/action/install.ts +59 -0
  71. package/src/init/action/mod.ts +66 -0
  72. package/src/init/action/notice.ts +101 -0
  73. package/src/init/action/patch.ts +212 -0
  74. package/src/init/action/precommand.ts +22 -0
  75. package/src/init/action/recommend.ts +38 -0
  76. package/src/init/action/set.ts +78 -0
  77. package/src/init/action/templates.ts +95 -0
  78. package/src/init/action/utils.ts +64 -0
  79. package/src/init/ask/dir.ts +98 -0
  80. package/src/init/ask/kv.ts +39 -0
  81. package/src/init/ask/mod.ts +23 -0
  82. package/src/init/ask/mq.ts +37 -0
  83. package/src/init/ask/pm.ts +58 -0
  84. package/src/init/ask/wf.ts +27 -0
  85. package/src/init/command.ts +64 -0
  86. package/src/init/const.ts +4 -0
  87. package/src/init/json/biome.json +17 -0
  88. package/src/init/json/kv.json +39 -0
  89. package/src/init/json/mq.json +95 -0
  90. package/src/init/json/pm.json +47 -0
  91. package/src/init/json/rt.json +42 -0
  92. package/src/init/json/vscode-settings-for-deno.json +43 -0
  93. package/src/init/json/vscode-settings.json +41 -0
  94. package/src/init/lib.ts +220 -0
  95. package/src/init/mod.ts +2 -0
  96. package/src/init/templates/defaults/federation.ts.tpl +23 -0
  97. package/src/init/templates/defaults/logging.ts.tpl +23 -0
  98. package/src/init/templates/express/app.ts.tpl +16 -0
  99. package/src/init/templates/express/index.ts.tpl +6 -0
  100. package/src/init/templates/hono/app.tsx.tpl +14 -0
  101. package/src/init/templates/hono/index/bun.ts.tpl +10 -0
  102. package/src/init/templates/hono/index/deno.ts.tpl +13 -0
  103. package/src/init/templates/hono/index/node.ts.tpl +14 -0
  104. package/src/init/templates/next/middleware.ts.tpl +45 -0
  105. package/src/init/templates/nitro/nitro.config.ts.tpl +5 -0
  106. package/src/init/templates/nitro/server/error.ts.tpl +3 -0
  107. package/src/init/templates/nitro/server/middleware/federation.ts.tpl +8 -0
  108. package/src/init/types.ts +88 -0
  109. package/src/init/webframeworks.ts +151 -0
  110. package/src/kv.bun.ts +12 -0
  111. package/src/kv.node.ts +11 -0
  112. package/src/log.ts +64 -0
  113. package/src/lookup.test.ts +182 -0
  114. package/src/lookup.ts +558 -0
  115. package/src/mod.ts +45 -0
  116. package/src/nodeinfo.test.ts +229 -0
  117. package/src/nodeinfo.ts +447 -0
  118. package/src/table.ts +17 -0
  119. package/src/tempserver.ts +87 -0
  120. package/src/tunnel.ts +32 -0
  121. package/src/utils.ts +136 -0
  122. package/src/webfinger/action.ts +50 -0
  123. package/src/webfinger/command.ts +59 -0
  124. package/src/webfinger/error.ts +47 -0
  125. package/src/webfinger/lib.ts +37 -0
  126. package/src/webfinger/mod.test.ts +79 -0
  127. package/src/webfinger/mod.ts +2 -0
  128. package/tsdown.config.ts +24 -0
  129. package/src/install.mjs +0 -189
  130. package/src/run.mjs +0 -22
@@ -0,0 +1,11 @@
1
+ import { mkdir } from "node:fs/promises";
2
+ import type { InitCommandData } from "../types.ts";
3
+
4
+ /**
5
+ * Creates the target directory if it does not exist.
6
+ *
7
+ * @param data - The directory
8
+ * @returns A promise that resolves when the directory is created
9
+ */
10
+ export const makeDirIfHyd = ({ dir }: InitCommandData): //
11
+ Promise<string | undefined> => mkdir(dir, { recursive: true });
@@ -0,0 +1,14 @@
1
+ import { entries, forEach, pipeLazy, tap, toArray, when } from "@fxts/core";
2
+ import { notEmpty } from "../../utils.ts";
3
+ import type { InitCommandIo } from "../types.ts";
4
+ import { noticeConfigEnv, noticeEnvKeyValue } from "./notice.ts";
5
+
6
+ const recommendConfigEnv: InitCommandIo = pipeLazy(
7
+ (data) => data.env,
8
+ entries,
9
+ toArray<Iterable<[string, string]>>,
10
+ when(notEmpty, tap<[string, string][], void>(noticeConfigEnv)),
11
+ forEach(noticeEnvKeyValue),
12
+ );
13
+
14
+ export default recommendConfigEnv;
@@ -0,0 +1,59 @@
1
+ import { always, concat, pipe, tap, toArray, unless, when } from "@fxts/core";
2
+ import { notEmpty, runSubCommand, set } from "../../utils.ts";
3
+ import type { InitCommandData } from "../types.ts";
4
+ import {
5
+ getAddDepsArgs,
6
+ getDependencies,
7
+ getDevDependencies,
8
+ joinDepsVer,
9
+ } from "./deps.ts";
10
+ import { noticeErrorWhileAddDeps } from "./notice.ts";
11
+ import { isDeno } from "./utils.ts";
12
+
13
+ const installDependencies = (data: InitCommandData) =>
14
+ pipe(
15
+ data,
16
+ tap(installDeps),
17
+ unless(isDeno, tap(installDevDeps)),
18
+ );
19
+
20
+ export default installDependencies;
21
+
22
+ type Deps = Record<string, string>;
23
+
24
+ const installDeps = (data: InitCommandData) =>
25
+ pipe(
26
+ data,
27
+ set("dependencies", getDependencies),
28
+ getAddDepsCommand,
29
+ when(notEmpty, runAddDeps(data)),
30
+ );
31
+
32
+ const installDevDeps = (data: InitCommandData) =>
33
+ pipe(
34
+ data,
35
+ set("dependencies", getDevDependencies),
36
+ set("dev", always(true)),
37
+ getAddDepsCommand,
38
+ when(notEmpty, runAddDeps(data)),
39
+ );
40
+
41
+ const getAddDepsCommand = <
42
+ T extends InitCommandData & {
43
+ dependencies: Deps;
44
+ dev?: boolean;
45
+ },
46
+ >(data: T) =>
47
+ pipe(
48
+ data,
49
+ joinDepsVer,
50
+ when(notEmpty<string[]>, concat(getAddDepsArgs(data))),
51
+ toArray,
52
+ );
53
+
54
+ const runAddDeps =
55
+ <T extends { dir: string }>({ dir }: T) => (command: string[]) =>
56
+ runSubCommand(command, {
57
+ cwd: dir,
58
+ stdio: "inherit",
59
+ }).catch(noticeErrorWhileAddDeps(command));
@@ -0,0 +1,66 @@
1
+ import { pipe, tap, unless, when } from "@fxts/core";
2
+ import askOptions from "../ask/mod.ts";
3
+ import type { InitCommand } from "../command.ts";
4
+ import type { InitCommandData } from "../types.ts";
5
+ import { makeDirIfHyd } from "./dir.ts";
6
+ import recommendConfigEnv from "./env.ts";
7
+ import installDependencies from "./install.ts";
8
+ import {
9
+ drawDinosaur,
10
+ noticeHowToRun,
11
+ noticeOptions,
12
+ noticePrecommand,
13
+ } from "./notice.ts";
14
+ import { patchFiles, recommendPatchFiles } from "./patch.ts";
15
+ import runPrecommand from "./precommand.ts";
16
+ import recommendDependencies from "./recommend.ts";
17
+ import setData from "./set.ts";
18
+ import { hasCommand, isDry } from "./utils.ts";
19
+
20
+ /**
21
+ * options: InitCommand
22
+ * ├ drawDinosaur
23
+ * ┌─────┴──────┐
24
+ * │ askOptions │ InitCommand -> InitCommandOptions
25
+ * └─────┬──────┘
26
+ * ├ noticeOptions
27
+ * ┌────┴────┐
28
+ * │ setData │ InitCommandOptions -> InitCommandData
29
+ * └────┬────┘
30
+ * ┌─┴─┐ isDry
31
+ * handleDryRun ┤ ├ handleHydRun
32
+ * └─┬─┘
33
+ * ├ recommendConfigEnv
34
+ * ├ noticeHowToRun
35
+ */
36
+ const runInit = (options: InitCommand) =>
37
+ pipe(
38
+ options,
39
+ tap(drawDinosaur),
40
+ askOptions,
41
+ tap(noticeOptions),
42
+ setData,
43
+ when(isDry, handleDryRun),
44
+ unless(isDry, handleHydRun),
45
+ tap(recommendConfigEnv),
46
+ tap(noticeHowToRun),
47
+ );
48
+
49
+ export default runInit;
50
+
51
+ const handleDryRun = (data: InitCommandData) =>
52
+ pipe(
53
+ data,
54
+ tap(when(hasCommand, noticePrecommand)),
55
+ tap(recommendPatchFiles),
56
+ tap(recommendDependencies),
57
+ );
58
+
59
+ const handleHydRun = (data: InitCommandData) =>
60
+ pipe(
61
+ data,
62
+ tap(makeDirIfHyd),
63
+ tap(when(hasCommand, runPrecommand)),
64
+ tap(patchFiles),
65
+ tap(installDependencies),
66
+ );
@@ -0,0 +1,101 @@
1
+ import { message } from "@optique/core";
2
+ import { print, printError } from "@optique/run";
3
+ import { flow } from "es-toolkit";
4
+ import { colors, type RequiredNotNull } from "../../utils.ts";
5
+ import type { InitCommand } from "../command.ts";
6
+ import type { InitCommandData } from "../types.ts";
7
+
8
+ type PrintMessage = (...args: Parameters<typeof message>) => void;
9
+ const printMessage: PrintMessage = flow(message, print);
10
+ const printErrorMessage: PrintMessage = flow(message, printError);
11
+
12
+ export function drawDinosaur() {
13
+ const d = flow(colors.bgBlue, colors.black);
14
+ const f = colors.blue;
15
+ console.error(`\
16
+ ${d(" ___ ")} ${f(" _____ _ _ __")}
17
+ ${d(" /'_') ")} ${f("| ___|__ __| (_)/ _|_ _")}
18
+ ${d(" .-^^^-/ / ")} ${f("| |_ / _ \\/ _` | | |_| | | |")}
19
+ ${d(" __/ / ")} ${f("| _| __/ (_| | | _| |_| |")}
20
+ ${d(" <__.|_|-|_| ")} ${f("|_| \\___|\\__,_|_|_| \\__, |")}
21
+ ${d(" ")} ${f(" |___/")}
22
+ `);
23
+ }
24
+
25
+ export const noticeOptions: (options: RequiredNotNull<InitCommand>) => void = (
26
+ {
27
+ packageManager,
28
+ webFramework,
29
+ kvStore,
30
+ messageQueue,
31
+ },
32
+ ) =>
33
+ printMessage`
34
+ Package manager: ${packageManager};
35
+ Web framework: ${webFramework};
36
+ Key–value store: ${kvStore};
37
+ Message queue: ${messageQueue};
38
+ `;
39
+
40
+ export const noticeDry = () =>
41
+ printMessage`🔍 DRY RUN MODE - No files will be created\n`;
42
+
43
+ export function noticePrecommand({
44
+ initializer: { command },
45
+ dir,
46
+ }: InitCommandData) {
47
+ printMessage`📦 Would run command:`;
48
+ printMessage` cd ${dir}`;
49
+ printMessage` ${command!.join(" ")}\n`;
50
+ }
51
+
52
+ export const noticeFilesToCreate = () =>
53
+ //
54
+ printMessage`📄 Would create files:\n`;
55
+
56
+ export const noticeFilesToInsert = () =>
57
+ printMessage`Would create/update JSON files:\n`;
58
+
59
+ export const noticeDepsIfExist = () =>
60
+ printMessage`📦 Would install dependencies:`;
61
+
62
+ export const noticeDevDepsIfExist = () =>
63
+ printMessage`📦 Would install dev dependencies:`;
64
+
65
+ export const noticeDeps = ([name, version]: [string, string]) =>
66
+ printMessage`${name}@${version}`;
67
+
68
+ export function displayFile(
69
+ path: string,
70
+ content: string,
71
+ emoji: string = "📄",
72
+ ) {
73
+ printMessage`${emoji} ${path}`;
74
+ printMessage`${"─".repeat(60)}`;
75
+ printMessage`${content}`;
76
+ printMessage`${"─".repeat(60)}\n`;
77
+ }
78
+
79
+ export const noticeConfigEnv = () =>
80
+ printMessage`Note that you probably want to edit the ${".env"} file.
81
+ It currently contains the following values:\n`;
82
+
83
+ export const noticeEnvKeyValue = ([key, value]: [string, string]) =>
84
+ printMessage` ${key}=${value}`;
85
+
86
+ export function noticeHowToRun(
87
+ { initializer: { instruction, federationFile } }: InitCommandData,
88
+ ) {
89
+ printMessage`${instruction}`;
90
+ printMessage`Start by editing the ${federationFile} file to define your federation!
91
+ `;
92
+ }
93
+
94
+ export function noticeErrorWhileAddDeps(command: string[]) {
95
+ return (error: unknown) => {
96
+ printErrorMessage`The command ${command.join(" ")} failed with the error: ${
97
+ String(error)
98
+ }`;
99
+ throw new Error("Failed to add dependencies.");
100
+ };
101
+ }
@@ -0,0 +1,212 @@
1
+ import { apply, entries, forEach, pipe, pipeLazy, tap } from "@fxts/core";
2
+ import { toMerged } from "es-toolkit";
3
+ import { readFile } from "node:fs/promises";
4
+ import { formatJson, merge, set } from "../../utils.ts";
5
+ import { createFile, throwUnlessNotExists } from "../lib.ts";
6
+ import type { InitCommandData } from "../types.ts";
7
+ import {
8
+ devToolConfigs,
9
+ loadDenoConfig,
10
+ loadPackageJson,
11
+ loadTsConfig,
12
+ } from "./configs.ts";
13
+ import {
14
+ displayFile,
15
+ noticeFilesToCreate,
16
+ noticeFilesToInsert,
17
+ } from "./notice.ts";
18
+ import { getImports, loadFederation, loadLogging } from "./templates.ts";
19
+ import { joinDir, stringifyEnvs } from "./utils.ts";
20
+
21
+ /**
22
+ * Main function that initializes the project by creating necessary files and configurations.
23
+ * Handles both dry-run mode (recommending files) and actual file creation.
24
+ * Orchestrates the entire file generation and writing process.
25
+ *
26
+ * @param data - The initialization command data containing project configuration
27
+ * @returns A processed data object with files and JSONs ready for creation
28
+ */
29
+ export const patchFiles = (data: InitCommandData) =>
30
+ pipe(
31
+ data,
32
+ set("files", getFiles),
33
+ set("jsons", getJsons),
34
+ createFiles,
35
+ );
36
+
37
+ export const recommendPatchFiles = (data: InitCommandData) =>
38
+ pipe(
39
+ data,
40
+ set("files", getFiles),
41
+ set("jsons", getJsons),
42
+ recommendFiles,
43
+ );
44
+
45
+ /**
46
+ * Generates text-based files (TypeScript, environment files) for the project.
47
+ * Creates federation configuration, logging setup, environment variables, and framework-specific files
48
+ * by processing templates and combining them with project-specific data.
49
+ *
50
+ * @param data - The initialization command data
51
+ * @returns A record of file paths to their string content
52
+ */
53
+ const getFiles = <
54
+ T extends InitCommandData,
55
+ >(data: T) => ({
56
+ [data.initializer.federationFile]: loadFederation({
57
+ imports: getImports(data),
58
+ ...data,
59
+ }),
60
+ [data.initializer.loggingFile]: loadLogging(data),
61
+ ".env": stringifyEnvs(data.env),
62
+ ...data.initializer.files,
63
+ });
64
+
65
+ /**
66
+ * Generates JSON configuration files based on the package manager type.
67
+ * Creates different sets of configuration files for Deno vs Node.js/Bun environments,
68
+ * including compiler configs, package manifests, and development tool configurations.
69
+ *
70
+ * @param data - The initialization command data
71
+ * @returns A record of file paths to their JSON object content
72
+ */
73
+ const getJsons = <
74
+ T extends InitCommandData,
75
+ >(data: T): Record<string, object> =>
76
+ data.packageManager === "deno"
77
+ ? {
78
+ "deno.json": loadDenoConfig(data).data,
79
+ [devToolConfigs["vscSetDeno"].path]: devToolConfigs["vscSetDeno"].data,
80
+ [devToolConfigs["vscExtDeno"].path]: devToolConfigs["vscExtDeno"].data,
81
+ }
82
+ : {
83
+ "tsconfig.json": loadTsConfig(data).data,
84
+ "package.json": loadPackageJson(data).data,
85
+ [devToolConfigs["biome"].path]: devToolConfigs["biome"].data,
86
+ [devToolConfigs["vscSet"].path]: devToolConfigs["vscSet"].data,
87
+ [devToolConfigs["vscExt"].path]: devToolConfigs["vscExt"].data,
88
+ };
89
+
90
+ /**
91
+ * Handles dry-run mode by recommending files to be created without actually creating them.
92
+ * Displays what files would be created and shows their content for user review.
93
+ * This allows users to preview the initialization process before committing to it.
94
+ *
95
+ * @param data - The initialization command data with files and JSONs prepared
96
+ * @returns The processed data with recommendations displayed
97
+ */
98
+ const recommendFiles = (data: InitCommandWithFiles) =>
99
+ pipe(
100
+ data,
101
+ tap(noticeFilesToCreate),
102
+ tap(processAllFiles(displayFile)),
103
+ tap(noticeFilesToInsert),
104
+ set("files", ({ jsons }) => jsons),
105
+ tap(processAllFiles(displayFile)),
106
+ );
107
+
108
+ /**
109
+ * Actually creates files on the filesystem during normal (non-dry-run) execution.
110
+ * Merges text files and JSON files together and writes them to disk.
111
+ * This performs the actual file system operations to initialize the project.
112
+ *
113
+ * @param data - The initialization command data with files and JSONs prepared
114
+ * @returns The processed data after files have been created
115
+ */
116
+ const createFiles = (data: InitCommandWithFiles) =>
117
+ pipe(
118
+ data,
119
+ set("files", ({ jsons, files }) => toMerged(files, jsons)),
120
+ tap(processAllFiles(createFile)),
121
+ );
122
+
123
+ interface InitCommandWithFiles extends InitCommandData {
124
+ files: Record<string, string>;
125
+ jsons: Record<string, object>;
126
+ }
127
+
128
+ /**
129
+ * Higher-order function that processes all files with a given processing function.
130
+ * Takes a processing function (either display or create) and applies it to all files
131
+ * in the target directory, handling path resolution and content patching.
132
+ *
133
+ * @param process - Function to process each file (either display or create)
134
+ * @returns A function that processes all files in the given directory with the provided processor
135
+ */
136
+ const processAllFiles = (
137
+ process: (path: string, content: string) => void | Promise<void>,
138
+ ) =>
139
+ ({ dir, files }: InitCommandWithFiles) =>
140
+ pipe(
141
+ files,
142
+ entries,
143
+ forEach(
144
+ pipeLazy(
145
+ joinDir(dir),
146
+ apply(patchContent),
147
+ apply(process),
148
+ ),
149
+ ),
150
+ );
151
+
152
+ /**
153
+ * Patches file content by either merging JSON objects or appending text content.
154
+ * Handles existing files by reading their current content and intelligently combining
155
+ * it with new content based on the content type (JSON vs text).
156
+ *
157
+ * @param path - The file path to patch
158
+ * @param content - The new content (either string or object)
159
+ * @returns A tuple containing the file path and the final content string
160
+ */
161
+ async function patchContent(
162
+ path: string,
163
+ content: string | object,
164
+ ): Promise<[string, string]> {
165
+ const prev = await readFileIfExists(path);
166
+ const data = typeof content === "object"
167
+ ? mergeJson(prev, content)
168
+ : appendText(prev, content);
169
+ return [path, data];
170
+ }
171
+
172
+ /**
173
+ * Merges new JSON data with existing JSON content and formats the result.
174
+ * Parses existing JSON content (if any) and deep merges it with new data,
175
+ * then formats the result for consistent output.
176
+ *
177
+ * @param prev - The previous JSON content as string
178
+ * @param data - The new data object to merge
179
+ * @returns Formatted JSON string with merged content
180
+ */
181
+ const mergeJson = (prev: string, data: object): string =>
182
+ pipe(prev ? JSON.parse(prev) : {}, merge(data), formatJson);
183
+
184
+ /**
185
+ * Appends new text content to existing text content line by line.
186
+ * Concatenates new content lines with existing content lines,
187
+ * preserving line structure and formatting.
188
+ *
189
+ * @param prev - The previous text content
190
+ * @param data - The new text content to append
191
+ * @returns Combined text content as a single string
192
+ */
193
+ const appendText = (prev: string, data: string) =>
194
+ prev ? `${prev}\n${data}` : data;
195
+
196
+ /**
197
+ * Safely reads a file if it exists, returns empty string if it doesn't exist.
198
+ * Provides error handling to distinguish between "file not found" and other
199
+ * file system errors, throwing only for unexpected errors.
200
+ *
201
+ * @param path - The file path to read
202
+ * @returns The file content as string, or empty string if file doesn't exist
203
+ * @throws Error if file access fails for reasons other than file not existing
204
+ */
205
+ async function readFileIfExists(path: string): Promise<string> {
206
+ try {
207
+ return await readFile(path, "utf8");
208
+ } catch (e) {
209
+ throwUnlessNotExists(e);
210
+ return "";
211
+ }
212
+ }
@@ -0,0 +1,22 @@
1
+ import { exit, runSubCommand } from "../../utils.ts";
2
+ import type { InitCommandData } from "../types.ts";
3
+
4
+ /**
5
+ * Runs the precommand specified in the initializer to set up the project.
6
+ *
7
+ * @param data - The initialization command data containing the initializer command and directory
8
+ * @returns A promise that resolves when the precommand has been executed
9
+ */
10
+ const runPrecommand = ({
11
+ initializer: { command },
12
+ dir,
13
+ }: InitCommandData) =>
14
+ runSubCommand(command!, {
15
+ cwd: dir,
16
+ stdio: "inherit",
17
+ }).catch((e) => {
18
+ console.error("Failed to run the precommand:", e);
19
+ exit(1);
20
+ });
21
+
22
+ export default runPrecommand;
@@ -0,0 +1,38 @@
1
+ import { map, peek, pipeLazy, tap, unless, when } from "@fxts/core";
2
+ import { notEmpty } from "../../utils.ts";
3
+ import type { InitCommandIo } from "../types.ts";
4
+ import { getDependencies, getDevDependencies } from "./deps.ts";
5
+ import {
6
+ noticeDeps,
7
+ noticeDepsIfExist,
8
+ noticeDevDepsIfExist,
9
+ } from "./notice.ts";
10
+ import { isDeno } from "./utils.ts";
11
+
12
+ const recommendDeps: InitCommandIo = pipeLazy(
13
+ getDependencies,
14
+ Object.entries<string>,
15
+ when(notEmpty<[string, string][]>, tap(noticeDepsIfExist)),
16
+ peek(noticeDeps),
17
+ );
18
+
19
+ const recommendDevDeps: InitCommandIo = pipeLazy(
20
+ getDevDependencies,
21
+ Object.entries<string>,
22
+ when(notEmpty<[string, string][]>, tap(noticeDevDepsIfExist)),
23
+ map(noticeDeps),
24
+ );
25
+
26
+ /**
27
+ * Recommends dependencies and devDependencies to be added to package.json.
28
+ * Skips devDependencies recommendation if the package manager is Deno.
29
+ *
30
+ * @param data - The initialization command data
31
+ * @returns An InitCommandIo function that performs the recommendation
32
+ */
33
+ const recommendDependencies: InitCommandIo = pipeLazy(
34
+ tap(recommendDeps),
35
+ unless(isDeno, tap(recommendDevDeps)),
36
+ );
37
+
38
+ export default recommendDependencies;
@@ -0,0 +1,78 @@
1
+ import { pipe } from "@fxts/core";
2
+ import { existsSync } from "node:fs";
3
+ import { realpath } from "node:fs/promises";
4
+ import { basename, normalize } from "node:path";
5
+ import { merge, set } from "../../utils.ts";
6
+ import { kvStores, messageQueues } from "../lib.ts";
7
+ import type {
8
+ InitCommandData,
9
+ InitCommandOptions,
10
+ KvStore,
11
+ KvStoreDescription,
12
+ MessageQueue,
13
+ MessageQueueDescription,
14
+ PackageManager,
15
+ } from "../types.ts";
16
+ import webFrameworks from "../webframeworks.ts";
17
+
18
+ /**
19
+ * Set all necessary data for initializing the project.
20
+ * This function orchestrates the setting of project name, initializer,
21
+ * key-value store, message queue, and environment variables by calling
22
+ * individual setter functions for each piece of data.
23
+ *
24
+ * @param data - The initial command options provided by the user
25
+ * @returns A promise resolving to a complete InitCommandData object
26
+ */
27
+ const setData = (data: InitCommandOptions): Promise<InitCommandData> =>
28
+ pipe(
29
+ data,
30
+ setProjectName,
31
+ setInitializer,
32
+ setKv,
33
+ setMq,
34
+ setEnv,
35
+ );
36
+
37
+ export default setData;
38
+
39
+ const setProjectName = set(
40
+ "projectName",
41
+ async <
42
+ T extends { dir: string },
43
+ >({ dir }: T) =>
44
+ basename(existsSync(dir) ? await realpath(dir) : normalize(dir)),
45
+ );
46
+
47
+ const setInitializer = set("initializer", <
48
+ T extends {
49
+ webFramework: keyof typeof webFrameworks;
50
+ projectName: string;
51
+ packageManager: PackageManager;
52
+ },
53
+ >({
54
+ webFramework,
55
+ projectName,
56
+ packageManager,
57
+ }: T) =>
58
+ webFrameworks[webFramework].init(
59
+ projectName,
60
+ packageManager,
61
+ ));
62
+
63
+ const setKv = set("kv", <
64
+ T extends { kvStore: KvStore },
65
+ >({ kvStore }: T) => kvStores[kvStore]);
66
+
67
+ const setMq = set(
68
+ "mq",
69
+ <
70
+ T extends { messageQueue: MessageQueue },
71
+ >({ messageQueue }: T) => messageQueues[messageQueue],
72
+ );
73
+ const setEnv = set(
74
+ "env",
75
+ <
76
+ T extends { kv: KvStoreDescription; mq: MessageQueueDescription },
77
+ >({ kv, mq }: T) => merge(kv.env)(mq.env),
78
+ );