@foliwake/cli 0.0.0-stage → 0.7.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 (256) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/LICENSE +202 -0
  3. package/README.md +654 -2
  4. package/dist/bin.d.ts +2 -0
  5. package/dist/bin.js +9 -0
  6. package/dist/command-words.d.ts +13 -0
  7. package/dist/command-words.js +53 -0
  8. package/dist/commands/account/keys/create.d.ts +12 -0
  9. package/dist/commands/account/keys/create.js +36 -0
  10. package/dist/commands/account/keys/list.d.ts +9 -0
  11. package/dist/commands/account/keys/list.js +23 -0
  12. package/dist/commands/account/keys/revoke.d.ts +12 -0
  13. package/dist/commands/account/keys/revoke.js +15 -0
  14. package/dist/commands/branch/bootstrap.d.ts +11 -0
  15. package/dist/commands/branch/bootstrap.js +23 -0
  16. package/dist/commands/branch/delete.d.ts +17 -0
  17. package/dist/commands/branch/delete.js +38 -0
  18. package/dist/commands/branch/history.d.ts +14 -0
  19. package/dist/commands/branch/history.js +24 -0
  20. package/dist/commands/branch/list.d.ts +11 -0
  21. package/dist/commands/branch/list.js +15 -0
  22. package/dist/commands/branch/update.d.ts +19 -0
  23. package/dist/commands/branch/update.js +49 -0
  24. package/dist/commands/code/deploy.d.ts +15 -0
  25. package/dist/commands/code/deploy.js +78 -0
  26. package/dist/commands/code/prepare.d.ts +13 -0
  27. package/dist/commands/code/prepare.js +54 -0
  28. package/dist/commands/code/release.d.ts +19 -0
  29. package/dist/commands/code/release.js +51 -0
  30. package/dist/commands/code/rollback.d.ts +17 -0
  31. package/dist/commands/code/rollback.js +38 -0
  32. package/dist/commands/connect.d.ts +19 -0
  33. package/dist/commands/connect.js +100 -0
  34. package/dist/commands/create.d.ts +32 -0
  35. package/dist/commands/create.js +171 -0
  36. package/dist/commands/credential/list.d.ts +10 -0
  37. package/dist/commands/credential/list.js +21 -0
  38. package/dist/commands/credential/rm.d.ts +12 -0
  39. package/dist/commands/credential/rm.js +18 -0
  40. package/dist/commands/credential/set.d.ts +15 -0
  41. package/dist/commands/credential/set.js +58 -0
  42. package/dist/commands/dev.d.ts +30 -0
  43. package/dist/commands/dev.js +144 -0
  44. package/dist/commands/login.d.ts +20 -0
  45. package/dist/commands/login.js +94 -0
  46. package/dist/commands/logout.d.ts +14 -0
  47. package/dist/commands/logout.js +61 -0
  48. package/dist/commands/migration/commit.d.ts +13 -0
  49. package/dist/commands/migration/commit.js +42 -0
  50. package/dist/commands/migration/prepare.d.ts +18 -0
  51. package/dist/commands/migration/prepare.js +53 -0
  52. package/dist/commands/operation/cancel.d.ts +14 -0
  53. package/dist/commands/operation/cancel.js +21 -0
  54. package/dist/commands/operation/get.d.ts +14 -0
  55. package/dist/commands/operation/get.js +26 -0
  56. package/dist/commands/operation/list.d.ts +12 -0
  57. package/dist/commands/operation/list.js +25 -0
  58. package/dist/commands/operation/recover.d.ts +20 -0
  59. package/dist/commands/operation/recover.js +61 -0
  60. package/dist/commands/page/changes.d.ts +13 -0
  61. package/dist/commands/page/changes.js +26 -0
  62. package/dist/commands/page/check.d.ts +12 -0
  63. package/dist/commands/page/check.js +25 -0
  64. package/dist/commands/page/replace.d.ts +13 -0
  65. package/dist/commands/page/replace.js +59 -0
  66. package/dist/commands/page/unpreview.d.ts +17 -0
  67. package/dist/commands/page/unpreview.js +54 -0
  68. package/dist/commands/page/unpublish.d.ts +18 -0
  69. package/dist/commands/page/unpublish.js +36 -0
  70. package/dist/commands/project/preview.d.ts +8 -0
  71. package/dist/commands/project/preview.js +20 -0
  72. package/dist/commands/project/publish.d.ts +16 -0
  73. package/dist/commands/project/publish.js +40 -0
  74. package/dist/commands/project/unpublish.d.ts +16 -0
  75. package/dist/commands/project/unpublish.js +33 -0
  76. package/dist/commands/release/rollback.d.ts +17 -0
  77. package/dist/commands/release/rollback.js +38 -0
  78. package/dist/commands/servers/index.d.ts +20 -0
  79. package/dist/commands/servers/index.js +36 -0
  80. package/dist/commands/servers/use.d.ts +11 -0
  81. package/dist/commands/servers/use.js +30 -0
  82. package/dist/commands/site/adopt.d.ts +11 -0
  83. package/dist/commands/site/adopt.js +21 -0
  84. package/dist/commands/site/create.d.ts +18 -0
  85. package/dist/commands/site/create.js +61 -0
  86. package/dist/commands/site/edit.d.ts +11 -0
  87. package/dist/commands/site/edit.js +56 -0
  88. package/dist/commands/site/history.d.ts +11 -0
  89. package/dist/commands/site/history.js +25 -0
  90. package/dist/commands/site/link.d.ts +15 -0
  91. package/dist/commands/site/link.js +35 -0
  92. package/dist/commands/site/list.d.ts +9 -0
  93. package/dist/commands/site/list.js +29 -0
  94. package/dist/commands/site/reset-storage.d.ts +15 -0
  95. package/dist/commands/site/reset-storage.js +61 -0
  96. package/dist/commands/site/set.d.ts +16 -0
  97. package/dist/commands/site/set.js +45 -0
  98. package/dist/commands/site/show.d.ts +10 -0
  99. package/dist/commands/site/show.js +19 -0
  100. package/dist/commands/site/status.d.ts +11 -0
  101. package/dist/commands/site/status.js +15 -0
  102. package/dist/commands/site/unlink.d.ts +11 -0
  103. package/dist/commands/site/unlink.js +28 -0
  104. package/dist/commands/source/add.d.ts +32 -0
  105. package/dist/commands/source/add.js +103 -0
  106. package/dist/commands/source/adopt-pages.d.ts +14 -0
  107. package/dist/commands/source/adopt-pages.js +30 -0
  108. package/dist/commands/source/check.d.ts +17 -0
  109. package/dist/commands/source/check.js +52 -0
  110. package/dist/commands/source/list.d.ts +11 -0
  111. package/dist/commands/source/list.js +15 -0
  112. package/dist/commands/source/mappings/check.d.ts +13 -0
  113. package/dist/commands/source/mappings/check.js +69 -0
  114. package/dist/commands/source/pending.d.ts +12 -0
  115. package/dist/commands/source/pending.js +25 -0
  116. package/dist/commands/source/plugins.d.ts +6 -0
  117. package/dist/commands/source/plugins.js +17 -0
  118. package/dist/commands/source/sync.d.ts +16 -0
  119. package/dist/commands/source/sync.js +58 -0
  120. package/dist/commands/whoami.d.ts +6 -0
  121. package/dist/commands/whoami.js +22 -0
  122. package/dist/connect-prompts.d.ts +16 -0
  123. package/dist/connect-prompts.js +24 -0
  124. package/dist/connect.d.ts +133 -0
  125. package/dist/connect.js +416 -0
  126. package/dist/core-command.d.ts +99 -0
  127. package/dist/core-command.js +332 -0
  128. package/dist/core-types.d.ts +21 -0
  129. package/dist/core-types.js +1 -0
  130. package/dist/create-connect.d.ts +26 -0
  131. package/dist/create-connect.js +93 -0
  132. package/dist/dev/code-watcher.d.ts +66 -0
  133. package/dist/dev/code-watcher.js +254 -0
  134. package/dist/dev/dev-checks.d.ts +14 -0
  135. package/dist/dev/dev-checks.js +138 -0
  136. package/dist/dev/dev-reload.d.ts +51 -0
  137. package/dist/dev/dev-reload.js +345 -0
  138. package/dist/dev/flags.d.ts +19 -0
  139. package/dist/dev/flags.js +54 -0
  140. package/dist/dev/html.d.ts +30 -0
  141. package/dist/dev/html.js +106 -0
  142. package/dist/dev/kit-files.d.ts +7 -0
  143. package/dist/dev/kit-files.js +33 -0
  144. package/dist/dev/local-code.d.ts +22 -0
  145. package/dist/dev/local-code.js +101 -0
  146. package/dist/dev/remote-config.d.ts +57 -0
  147. package/dist/dev/remote-config.js +100 -0
  148. package/dist/dev/remote-dev.d.ts +41 -0
  149. package/dist/dev/remote-dev.js +527 -0
  150. package/dist/dev/remote-fetch.d.ts +5 -0
  151. package/dist/dev/remote-fetch.js +36 -0
  152. package/dist/dev/remote-html.d.ts +10 -0
  153. package/dist/dev/remote-html.js +60 -0
  154. package/dist/dev/remote-page.d.ts +34 -0
  155. package/dist/dev/remote-page.js +183 -0
  156. package/dist/dev/remote-routes.d.ts +63 -0
  157. package/dist/dev/remote-routes.js +114 -0
  158. package/dist/dev/signal-stop.d.ts +17 -0
  159. package/dist/dev/signal-stop.js +46 -0
  160. package/dist/dev/start.d.ts +18 -0
  161. package/dist/dev/start.js +80 -0
  162. package/dist/index.d.ts +6 -0
  163. package/dist/index.js +8 -0
  164. package/dist/lib/diagnostics.d.ts +15 -0
  165. package/dist/lib/diagnostics.js +12 -0
  166. package/dist/lib/front-matter.d.ts +6 -0
  167. package/dist/lib/front-matter.js +59 -0
  168. package/dist/lib/operation-result.d.ts +3 -0
  169. package/dist/lib/operation-result.js +16 -0
  170. package/dist/lib/problem-groups.d.ts +27 -0
  171. package/dist/lib/problem-groups.js +49 -0
  172. package/dist/lib/problems.d.ts +50 -0
  173. package/dist/lib/problems.js +94 -0
  174. package/dist/lib/prompts.d.ts +38 -0
  175. package/dist/lib/prompts.js +77 -0
  176. package/dist/lib/result-types.d.ts +198 -0
  177. package/dist/lib/result-types.js +3 -0
  178. package/dist/lib/rules.d.ts +15 -0
  179. package/dist/lib/rules.js +26 -0
  180. package/dist/lib/summaries.d.ts +19 -0
  181. package/dist/lib/summaries.js +22 -0
  182. package/dist/lib/sync-problems.d.ts +21 -0
  183. package/dist/lib/sync-problems.js +19 -0
  184. package/dist/local-runtime.d.ts +78 -0
  185. package/dist/local-runtime.js +11 -0
  186. package/dist/local-target.d.ts +6 -0
  187. package/dist/local-target.js +23 -0
  188. package/dist/main.d.ts +2 -0
  189. package/dist/main.js +40 -0
  190. package/dist/project-preview.d.ts +35 -0
  191. package/dist/project-preview.js +156 -0
  192. package/dist/project-publish.d.ts +28 -0
  193. package/dist/project-publish.js +173 -0
  194. package/dist/remote/connection.d.ts +8 -0
  195. package/dist/remote/connection.js +19 -0
  196. package/dist/remote/core-failure.d.ts +8 -0
  197. package/dist/remote/core-failure.js +15 -0
  198. package/dist/remote/credentials.d.ts +15 -0
  199. package/dist/remote/credentials.js +112 -0
  200. package/dist/remote/device-login.d.ts +33 -0
  201. package/dist/remote/device-login.js +161 -0
  202. package/dist/remote/remote-caller.d.ts +14 -0
  203. package/dist/remote/remote-caller.js +52 -0
  204. package/dist/remote/rpc-wire.d.ts +18 -0
  205. package/dist/remote/rpc-wire.js +57 -0
  206. package/dist/remote/servers.d.ts +80 -0
  207. package/dist/remote/servers.js +162 -0
  208. package/dist/remote/session.d.ts +53 -0
  209. package/dist/remote/session.js +132 -0
  210. package/dist/remote/sign-in-here.d.ts +5 -0
  211. package/dist/remote/sign-in-here.js +33 -0
  212. package/dist/remote/sign-in.d.ts +25 -0
  213. package/dist/remote/sign-in.js +55 -0
  214. package/dist/remote/wait-slices.d.ts +16 -0
  215. package/dist/remote/wait-slices.js +21 -0
  216. package/dist/render/add.d.ts +3 -0
  217. package/dist/render/add.js +9 -0
  218. package/dist/render/branch-write.d.ts +9 -0
  219. package/dist/render/branch-write.js +28 -0
  220. package/dist/render/branches.d.ts +5 -0
  221. package/dist/render/branches.js +28 -0
  222. package/dist/render/credentials.d.ts +5 -0
  223. package/dist/render/credentials.js +39 -0
  224. package/dist/render/operation-result.d.ts +16 -0
  225. package/dist/render/operation-result.js +65 -0
  226. package/dist/render/operation.d.ts +7 -0
  227. package/dist/render/operation.js +15 -0
  228. package/dist/render/page-changes.d.ts +3 -0
  229. package/dist/render/page-changes.js +36 -0
  230. package/dist/render/pending.d.ts +3 -0
  231. package/dist/render/pending.js +46 -0
  232. package/dist/render/plugin-list.d.ts +3 -0
  233. package/dist/render/plugin-list.js +30 -0
  234. package/dist/render/probe.d.ts +3 -0
  235. package/dist/render/probe.js +61 -0
  236. package/dist/render/problems.d.ts +35 -0
  237. package/dist/render/problems.js +64 -0
  238. package/dist/render/recovery.d.ts +2 -0
  239. package/dist/render/recovery.js +36 -0
  240. package/dist/render/reset-storage.d.ts +4 -0
  241. package/dist/render/reset-storage.js +70 -0
  242. package/dist/render/site-status.d.ts +2 -0
  243. package/dist/render/site-status.js +81 -0
  244. package/dist/render/source-list.d.ts +2 -0
  245. package/dist/render/source-list.js +37 -0
  246. package/dist/render/sync.d.ts +5 -0
  247. package/dist/render/sync.js +66 -0
  248. package/dist/settings.d.ts +10 -0
  249. package/dist/settings.js +45 -0
  250. package/dist/site-entry-edit.d.ts +5 -0
  251. package/dist/site-entry-edit.js +44 -0
  252. package/dist/source-entry.d.ts +32 -0
  253. package/dist/source-entry.js +89 -0
  254. package/dist/version.d.ts +3 -0
  255. package/dist/version.js +10 -0
  256. package/package.json +112 -3
@@ -0,0 +1,19 @@
1
+ /** A source input of a release: the snapshot it read and the upstream revision, if any. */
2
+ export type SourceInputs = Record<string, {
3
+ snapshot: string;
4
+ revision?: string | null;
5
+ }>;
6
+ /** One entry per pinned source: `docs=ss_… (r2)`. */
7
+ export declare function describeInputs(inputs: SourceInputs | null): string;
8
+ /** What one rule catches in a dry run of a source's path mapping rules. */
9
+ export interface RuleCoverage {
10
+ rule: number;
11
+ match: string;
12
+ documents: number;
13
+ shadowed: number;
14
+ shadowedBy: number[];
15
+ example: string | null;
16
+ ignoreNotChecked?: boolean;
17
+ }
18
+ /** The summary of the rules: `rule 1: 72, rule 3: 0 (2 shadowed by rule 1: …/questions.md)`. */
19
+ export declare function coverageSummary(rows: readonly RuleCoverage[]): string;
@@ -0,0 +1,22 @@
1
+ // One-line summaries the commands print: the source inputs a release was built from, and what each path
2
+ // mapping rule of a source catches.
3
+ /** One entry per pinned source: `docs=ss_… (r2)`. */
4
+ export function describeInputs(inputs) {
5
+ if (!inputs || Object.keys(inputs).length === 0)
6
+ return 'working folders only';
7
+ return Object.entries(inputs)
8
+ .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
9
+ .map(([source, input]) => `${source}=${input.snapshot}${input.revision ? ` (${input.revision})` : ''}`)
10
+ .join(', ');
11
+ }
12
+ function coverageText(row) {
13
+ if (row.ignoreNotChecked && row.shadowed === 0)
14
+ return `rule ${row.rule}: ignore, not checked against the snapshot`;
15
+ const by = row.shadowedBy.join(', ');
16
+ const hidden = row.shadowed > 0 ? ` (${row.shadowed} shadowed by rule ${by}: ${row.example})` : '';
17
+ return `rule ${row.rule}: ${row.documents}${hidden}`;
18
+ }
19
+ /** The summary of the rules: `rule 1: 72, rule 3: 0 (2 shadowed by rule 1: …/questions.md)`. */
20
+ export function coverageSummary(rows) {
21
+ return rows.map(coverageText).join('; ');
22
+ }
@@ -0,0 +1,21 @@
1
+ import { type Problem } from './problems.js';
2
+ /** A diagnostic of a content source, as a sync result holds it. */
3
+ export interface SourceDiagnostic {
4
+ code: string;
5
+ severity: 'error' | 'warning';
6
+ source: string;
7
+ message: string;
8
+ fix?: string | null;
9
+ origin?: {
10
+ kind: 'file';
11
+ file: string;
12
+ line: number;
13
+ } | {
14
+ kind: 'element';
15
+ document: string;
16
+ } | {
17
+ kind: string;
18
+ };
19
+ }
20
+ /** The problems of a sync attempt's diagnostics, in their order. */
21
+ export declare function syncProblems(diagnostics: readonly SourceDiagnostic[]): Problem[];
@@ -0,0 +1,19 @@
1
+ // The problems of a sync result stored before results carried `problems`: made from its diagnostics, without
2
+ // page facts (the source's path mapping rules are on the server).
3
+ import { problemOf } from './problems.js';
4
+ function fileOf(d) {
5
+ const origin = d.origin;
6
+ if (origin?.kind === 'file' && origin.file)
7
+ return { file: origin.file, line: (origin.line ?? 0) > 0 ? origin.line : null };
8
+ if (origin?.kind === 'element' && origin.document)
9
+ return { file: origin.document, line: null };
10
+ return { file: null, line: null };
11
+ }
12
+ /** The problems of a sync attempt's diagnostics, in their order. */
13
+ export function syncProblems(diagnostics) {
14
+ return diagnostics.map((d) => {
15
+ const { file, line } = fileOf(d);
16
+ const input = { code: d.code, severity: d.severity, source: d.source, file, line, message: d.message };
17
+ return problemOf({ ...input, fix: d.fix, page: null }, d.code === 'SOURCE_PATH_UNMAPPED' ? { expectedFiles: [] } : {});
18
+ });
19
+ }
@@ -0,0 +1,78 @@
1
+ import type { CoreCaller, CoreError } from '@foliwake/core-contract';
2
+ /** What a command opens the local runtime with. */
3
+ export interface LocalCoreOptions {
4
+ /** `--config`, else undefined: the engine's default ($FOLIWAKE_CONFIG, then ./foliwake.config.json). */
5
+ config: string | undefined;
6
+ /** `--content`: this folder instead of the site's content sources (absolute). */
7
+ content: string | undefined;
8
+ debug: boolean;
9
+ }
10
+ /** The engine's core on this computer, open for one command. */
11
+ export interface LocalCore {
12
+ core: CoreCaller;
13
+ /** The configured sites (the default `--site` is the only one). */
14
+ sites(): Promise<readonly {
15
+ id: string;
16
+ }[]>;
17
+ /** The site's settle delay, which default waits start from. */
18
+ settleDelayMs(site: string): Promise<number>;
19
+ /** Removes a state lock left by a process that is gone; the line to print. */
20
+ breakLock(site: string): Promise<string>;
21
+ /** Takes no new work and waits for what runs. */
22
+ close(): Promise<void>;
23
+ }
24
+ /** `foliwake dev --remote`, served by the engine. */
25
+ export interface LocalDevRemote {
26
+ target: 'preview' | 'live';
27
+ url: string | undefined;
28
+ config: string | undefined;
29
+ authEnv: string | undefined;
30
+ authUser: string | undefined;
31
+ }
32
+ /** `foliwake dev`: local content, or with `remote` the deployed site's. */
33
+ export interface LocalDevOptions {
34
+ port: number | undefined;
35
+ watch: boolean | undefined;
36
+ polling: boolean | undefined;
37
+ content: string | undefined;
38
+ config: string | undefined;
39
+ site: string | undefined;
40
+ remote: LocalDevRemote | undefined;
41
+ }
42
+ export interface LocalDevIo {
43
+ log(line: string): void;
44
+ warn(line: string): void;
45
+ }
46
+ export interface TimedOptions {
47
+ requested: boolean;
48
+ json: boolean;
49
+ }
50
+ /** What the engine gives this CLI. */
51
+ export interface LocalRuntime {
52
+ /** True when this folder has a local configuration (./foliwake.config.json). */
53
+ folderConfig(cwd: string): boolean;
54
+ open(options: LocalCoreOptions): LocalCore;
55
+ /** Anything a command threw, as core's error and its cause (the engine knows its own failures). */
56
+ failure(error: unknown): Promise<{
57
+ coreError: CoreError;
58
+ cause: unknown;
59
+ }>;
60
+ /** Phase timings of a command (`--timings`, FOLIWAKE_TIMINGS); also for calls to a server. */
61
+ timed<T>(name: string, options: TimedOptions, fn: () => Promise<T>): Promise<T>;
62
+ /** The command as the entry of its trace (OTEL_EXPORTER_OTLP_ENDPOINT). */
63
+ traced<T>(name: string, fn: () => Promise<T>): Promise<T>;
64
+ /**
65
+ * Serves `dev` until Ctrl+C or SIGTERM stops it (the engine stops it, as its other servers); prints its own
66
+ * errors. Resolves to the exit code: 0, 1 (failed), 2 (a refused command line).
67
+ */
68
+ dev(options: LocalDevOptions, io: LocalDevIo): Promise<number>;
69
+ /**
70
+ * `create` made a project in `folder`: the engine trusts the configuration it wrote, so `dev` and local
71
+ * commands run there at once. Resolves to a line to print when that failed, else null.
72
+ */
73
+ created(folder: string): Promise<string | null>;
74
+ }
75
+ /** Called by the engine before oclif loads the commands. */
76
+ export declare function registerLocalRuntime(runtime: LocalRuntime): void;
77
+ /** The engine's runtime, or null in the CLI alone. */
78
+ export declare function localRuntime(): LocalRuntime | null;
@@ -0,0 +1,11 @@
1
+ // One registration per process, also when two copies of this module are loaded (a symlinked plugin).
2
+ const KEY = Symbol.for('@foliwake/cli/local-runtime');
3
+ const slot = globalThis;
4
+ /** Called by the engine before oclif loads the commands. */
5
+ export function registerLocalRuntime(runtime) {
6
+ slot[KEY] = runtime;
7
+ }
8
+ /** The engine's runtime, or null in the CLI alone. */
9
+ export function localRuntime() {
10
+ return slot[KEY] ?? null;
11
+ }
@@ -0,0 +1,6 @@
1
+ import { type Target } from './remote/servers.js';
2
+ export interface TargetFlags {
3
+ server: string | undefined;
4
+ config: string | undefined;
5
+ }
6
+ export declare function chooseTarget({ server, config }: TargetFlags, env?: NodeJS.ProcessEnv, cwd?: string): Target | 'local' | null;
@@ -0,0 +1,23 @@
1
+ // Where a core command's calls go: a server, or with the engine's runtime registered, this computer.
2
+ // --server, then --config or $FOLIWAKE_CONFIG (local), then the folder's .foliwake/connection.json, then
3
+ // $FOLIWAKE_SERVER, then ./foliwake.config.json in this folder (local), then the last `login`, else local.
4
+ // Without the engine nothing is local: null when nothing names a server.
5
+ import { localRuntime } from './local-runtime.js';
6
+ import { ServerAddressError, resolveTarget } from './remote/servers.js';
7
+ import { setting } from './settings.js';
8
+ export function chooseTarget({ server, config }, env = process.env, cwd = process.cwd()) {
9
+ const engine = localRuntime();
10
+ if (!engine)
11
+ return resolveTarget({ server }, env, cwd);
12
+ if (server !== undefined && config !== undefined) {
13
+ throw new ServerAddressError('Use either --server or --config, not both.');
14
+ }
15
+ if (server === undefined && (config !== undefined || setting('CONFIG', env)))
16
+ return 'local';
17
+ const target = resolveTarget({ server }, env, cwd);
18
+ if (target && target.from !== 'login')
19
+ return target;
20
+ if (engine.folderConfig(cwd))
21
+ return 'local';
22
+ return target ?? 'local';
23
+ }
package/dist/main.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ /** Runs one command line; resolves to its exit code. */
2
+ export declare function main(argv: string[]): Promise<number>;
package/dist/main.js ADDED
@@ -0,0 +1,40 @@
1
+ // The `foliwake` command of @foliwake/cli: oclif over the commands in dist/commands. People also write flags
2
+ // before the command words (`foliwake --server x whoami`); those are moved behind the words first.
3
+ // `preview` and `publish` are the linked folder's (`project preview|publish`).
4
+ import { Config, flush, handle, run, settings } from '@oclif/core';
5
+ import { commandWordsFirst, engineOnlyProject, projectCommand } from './command-words.js';
6
+ import { NEEDS_ENGINE } from './core-command.js';
7
+ /** The command line for oclif: as given, or with the command words moved before the flags given first. */
8
+ async function forOclif(argv) {
9
+ const project = projectCommand(argv);
10
+ if (project)
11
+ return project;
12
+ if (!argv.slice(0, 2).some((arg) => arg.startsWith('-')))
13
+ return argv;
14
+ const config = await Config.load(import.meta.url);
15
+ const optionFlags = config.commands.flatMap((command) => Object.entries(command.flags)
16
+ .filter(([, flag]) => flag.type === 'option')
17
+ .map(([name]) => name));
18
+ const valueFlags = new Set(optionFlags);
19
+ const ids = new Set(config.commands.map((command) => command.id));
20
+ return commandWordsFirst(argv, (name) => valueFlags.has(name), ids) ?? argv;
21
+ }
22
+ /** Runs one command line; resolves to its exit code. */
23
+ export async function main(argv) {
24
+ // The package runs from dist/; oclif must not look for TypeScript sources beside it.
25
+ settings.enableAutoTranspile = false;
26
+ const engineFlag = engineOnlyProject(argv);
27
+ if (engineFlag) {
28
+ process.stderr.write(`${argv[0]} ${engineFlag} ${NEEDS_ENGINE}\n`);
29
+ return 2;
30
+ }
31
+ try {
32
+ await run(await forOclif(argv), import.meta.url);
33
+ await flush();
34
+ return Number(process.exitCode ?? 0);
35
+ }
36
+ catch (error) {
37
+ await handle(error instanceof Error ? error : new Error(String(error)));
38
+ return 1;
39
+ }
40
+ }
@@ -0,0 +1,35 @@
1
+ import { type ConnectIO } from './connect.js';
2
+ export interface Connection {
3
+ server: string;
4
+ site: string;
5
+ org: string;
6
+ }
7
+ export interface LastPreview {
8
+ server: string;
9
+ site: string;
10
+ siteRelease: string;
11
+ commit: string | null;
12
+ at: string;
13
+ }
14
+ export declare const connectionFile: (cwd: string) => string;
15
+ export declare const lastPreviewFile: (cwd: string) => string;
16
+ export declare function readConnection(cwd: string): Promise<Connection | null>;
17
+ /** Pushes the pages and code, previews them, prints the address. Exit 0 previewed, 1 refused or failed. */
18
+ export declare function previewProject({ cwd, env }: {
19
+ cwd: string;
20
+ env: NodeJS.ProcessEnv;
21
+ }, io: ConnectIO): Promise<{
22
+ exit: number;
23
+ siteRelease: string | null;
24
+ previewUrl: string | null;
25
+ }>;
26
+ /**
27
+ * Calls `fn` again while the server answers a retryable `busy` refusal (PUSH_BUSY, PREVIEW_BUSY), with a
28
+ * growing pause, up to `limitMs`; then the last refusal stands ("try again").
29
+ */
30
+ export declare function whileBusy<T>(fn: () => Promise<T>, { limitMs, firstDelayMs, onWait, sleep, }?: {
31
+ limitMs?: number;
32
+ firstDelayMs?: number;
33
+ onWait?: () => void;
34
+ sleep?: (ms: number) => Promise<unknown>;
35
+ }): Promise<T>;
@@ -0,0 +1,156 @@
1
+ // `foliwake preview` in a project folder linked to a site (`.foliwake/connection.json`,
2
+ // written by `site create` / `site link`): sends the folder's pages and its last commit's
3
+ // code to the server and rebuilds the site's preview there.
4
+ // Pages may be uncommitted (they are content); code must be committed.
5
+ import { lstat, mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
6
+ import path from 'node:path';
7
+ import { COMMAND } from './settings.js';
8
+ import { ConnectRefused, projectCommit, signedInTo } from './connect.js';
9
+ const C = COMMAND;
10
+ const CONTENT = 'content';
11
+ const PUSHED_FILE = /\.(md|png|jpe?g|gif|webp|avif)$/i;
12
+ const SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,99}$/;
13
+ const MAX_PUSH_BYTES = 500_000;
14
+ const WAIT_MS = 10 * 60 * 1000;
15
+ export const connectionFile = (cwd) => path.join(cwd, '.foliwake', 'connection.json');
16
+ export const lastPreviewFile = (cwd) => path.join(cwd, '.foliwake', 'last-preview.json');
17
+ export async function readConnection(cwd) {
18
+ try {
19
+ const raw = JSON.parse(await readFile(connectionFile(cwd), 'utf8'));
20
+ return typeof raw.server === 'string' && typeof raw.site === 'string' && typeof raw.org === 'string'
21
+ ? { server: raw.server, site: raw.site, org: raw.org }
22
+ : null;
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ /** The pages and images of content/: real files only, no hidden names, no links. */
29
+ async function contentFiles(cwd) {
30
+ const root = path.join(cwd, CONTENT);
31
+ const out = [];
32
+ let total = 0;
33
+ async function walk(dir, rel) {
34
+ for (const entry of (await readdir(dir)).sort()) {
35
+ if (!SEGMENT.test(entry))
36
+ continue;
37
+ const file = path.join(dir, entry);
38
+ const info = await lstat(file);
39
+ if (info.isSymbolicLink())
40
+ continue;
41
+ if (info.isDirectory())
42
+ await walk(file, [...rel, entry]);
43
+ else if (info.isFile() && PUSHED_FILE.test(entry)) {
44
+ const bytes = await readFile(file);
45
+ total += bytes.length;
46
+ if (total > MAX_PUSH_BYTES)
47
+ throw new ConnectRefused(`The pages and images of ${CONTENT}/ are larger than ${MAX_PUSH_BYTES / 1000} KB, more than one push ` +
48
+ `takes in this version.`);
49
+ out.push({ path: [...rel, entry].join('/'), data: bytes.toString('base64') });
50
+ }
51
+ }
52
+ }
53
+ await walk(root, []).catch((error) => {
54
+ if (error.code === 'ENOENT')
55
+ throw new ConnectRefused(`This folder has no ${CONTENT}/ folder of pages.`);
56
+ throw error;
57
+ });
58
+ if (!out.some((file) => file.path.endsWith('.md')))
59
+ throw new ConnectRefused(`${CONTENT}/ holds no page (.md).`);
60
+ return out;
61
+ }
62
+ async function waitFor(core, operation) {
63
+ const { waitInSlices } = await import('./remote/wait-slices.js');
64
+ return waitInSlices((sliceMs) => core.operations.wait({ site: operation.site, id: operation.id, until: 'commit', timeoutMs: sliceMs }), { until: 'commit', timeoutMs: WAIT_MS });
65
+ }
66
+ const failure = (what, operation) => new ConnectRefused(`${what} did not succeed ` +
67
+ `(${operation.state}${operation.error ? `: ${operation.error.code}: ${operation.error.message}` : ''}).`);
68
+ /** Pushes the pages and code, previews them, prints the address. Exit 0 previewed, 1 refused or failed. */
69
+ export async function previewProject({ cwd, env }, io) {
70
+ try {
71
+ const connection = await readConnection(cwd);
72
+ if (!connection)
73
+ throw new ConnectRefused(`This folder is not linked to a site: run \`${C} site create <id>\` or \`${C} site link <id>\` first.`);
74
+ const { core, server } = await signedInTo({ server: connection.server, env }, io);
75
+ const commit = await projectCommit(cwd, env, { codeOnly: true });
76
+ if ('none' in commit)
77
+ throw new ConnectRefused(`The code is not sent: ${commit.none}.`);
78
+ if (commit.dirty)
79
+ throw new ConnectRefused('The code has uncommitted changes (components/, scripts/, styles/ or other files outside content/): commit ' +
80
+ 'them, then preview again. Pages in content/ may stay uncommitted.');
81
+ const files = await contentFiles(cwd);
82
+ const source = (await core.sources.list({ site: connection.site })).sources.find((candidate) => candidate.plugin === 'cli-push');
83
+ if (!source)
84
+ throw new ConnectRefused(`Site ${connection.site} on ${server} takes no pages from a project folder (no cli-push source).`);
85
+ io.out(`Sending ${files.length} file(s) of ${CONTENT}/ to ${connection.site} on ${server}…`);
86
+ const pushed = await whileBusy(() => core.sources.push({
87
+ site: connection.site,
88
+ source: source.id,
89
+ files,
90
+ expect: { selected: source.selected?.snapshot ?? null },
91
+ }), {
92
+ onWait: () => io.out('The previous push is still being read on the server; trying again…'),
93
+ });
94
+ const synced = await waitFor(core, pushed);
95
+ if (synced.state !== 'succeeded')
96
+ throw failure('Reading the pages', synced);
97
+ const status = await core.sites.status({ site: connection.site });
98
+ io.out(`Building the preview with code ${commit.commit.slice(0, 7)}…`);
99
+ const previewed = await waitFor(core, await core.channels.preview({
100
+ site: connection.site,
101
+ pages: null,
102
+ expect: { preview: status.preview?.site_release ?? null },
103
+ code: { bundle: commit.bundle, commit: commit.commit },
104
+ }));
105
+ const result = previewed.result;
106
+ for (const diagnostic of result?.diagnostics ?? [])
107
+ io.err(` ${diagnostic.file}:${diagnostic.line}: ${diagnostic.message}`);
108
+ if (previewed.state !== 'succeeded' || !result?.siteRelease)
109
+ throw failure('The preview', previewed);
110
+ const previewUrl = (await core.sites.list()).sites.find((candidate) => candidate.id === connection.site)?.previewUrl ?? null;
111
+ const last = {
112
+ server: connection.server,
113
+ site: connection.site,
114
+ siteRelease: result.siteRelease,
115
+ commit: commit.commit,
116
+ at: new Date().toISOString(),
117
+ };
118
+ await mkdir(path.dirname(lastPreviewFile(cwd)), { recursive: true });
119
+ await writeFile(lastPreviewFile(cwd), `${JSON.stringify(last, null, 2)}\n`);
120
+ io.out(`Preview ${result.siteRelease} is ready${previewUrl && previewUrl !== '-' ? `: ${previewUrl}` : ''}.`);
121
+ io.out(`Publish it with \`${C} publish --expect ${result.siteRelease} <page-id>…\` on the server, or in the admin.`);
122
+ return { exit: 0, siteRelease: result.siteRelease, previewUrl: previewUrl === '-' ? null : previewUrl };
123
+ }
124
+ catch (error) {
125
+ if (error instanceof ConnectRefused) {
126
+ io.err(error.message);
127
+ return { exit: 1, siteRelease: null, previewUrl: null };
128
+ }
129
+ const coreError = error.coreError;
130
+ if (!coreError)
131
+ throw error;
132
+ io.err(`${coreError.code}: ${coreError.message}`);
133
+ return { exit: 1, siteRelease: null, previewUrl: null };
134
+ }
135
+ }
136
+ /**
137
+ * Calls `fn` again while the server answers a retryable `busy` refusal (PUSH_BUSY, PREVIEW_BUSY), with a
138
+ * growing pause, up to `limitMs`; then the last refusal stands ("try again").
139
+ */
140
+ export async function whileBusy(fn, { limitMs = 120_000, firstDelayMs = 1_000, onWait = () => { }, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)), } = {}) {
141
+ const deadline = Date.now() + limitMs;
142
+ for (let delay = firstDelayMs, told = false;; delay = Math.min(delay * 2, 10_000)) {
143
+ try {
144
+ return await fn();
145
+ }
146
+ catch (error) {
147
+ const coreError = error.coreError;
148
+ if (!coreError || coreError.category !== 'busy' || !coreError.retryable || Date.now() + delay > deadline)
149
+ throw error;
150
+ if (!told)
151
+ onWait();
152
+ told = true;
153
+ await sleep(delay);
154
+ }
155
+ }
156
+ }
@@ -0,0 +1,28 @@
1
+ import type { Readable, Writable } from 'node:stream';
2
+ import type { Operation } from './core-types.js';
3
+ import { type ConnectIO } from './connect.js';
4
+ export interface PublishRequest {
5
+ cwd: string;
6
+ env: NodeJS.ProcessEnv;
7
+ paths: string[];
8
+ expect?: string | undefined;
9
+ yes: boolean;
10
+ /** Asks the question in a terminal; null: no terminal. */
11
+ confirm: ((question: string) => Promise<boolean>) | null;
12
+ }
13
+ export declare function publishProject(request: PublishRequest, io: ConnectIO): Promise<{
14
+ exit: number;
15
+ pages: string[];
16
+ operation: Operation | null;
17
+ }>;
18
+ export declare function unpublishProject(request: PublishRequest, io: ConnectIO): Promise<{
19
+ exit: number;
20
+ pages: string[];
21
+ operation: Operation | null;
22
+ }>;
23
+ /** A yes/no question in a terminal (null when stdin or stdout is not one). */
24
+ export declare function terminalConfirm(stdin: Readable & {
25
+ isTTY?: boolean;
26
+ }, stdout: Writable & {
27
+ isTTY?: boolean;
28
+ }): PublishRequest['confirm'];
@@ -0,0 +1,173 @@
1
+ // `foliwake publish` and `foliwake project unpublish` in a folder linked to a site.
2
+ // Publish: with no paths, the pages the last
3
+ // `foliwake preview` of this folder changed, with `expect` filled from it; paths of
4
+ // files or folders under content/ choose pages by their front matter id. The API
5
+ // always requires expect; this only fills it in. A terminal asks before anything
6
+ // goes live; scripts pass --yes.
7
+ import { lstat, readFile, readdir, realpath } from 'node:fs/promises';
8
+ import path from 'node:path';
9
+ import { COMMAND } from './settings.js';
10
+ import { frontMatterId } from './lib/front-matter.js';
11
+ import { ConnectRefused, signedInTo } from './connect.js';
12
+ import { lastPreviewFile, readConnection } from './project-preview.js';
13
+ const C = COMMAND;
14
+ const WAIT_MS = 10 * 60 * 1000;
15
+ /**
16
+ * Page ids of the .md files under the given paths, read as the server's reader reads them (the
17
+ * front-matter `id`, lib/front-matter.ts). The same rules as `preview`'s push: real
18
+ * files and folders inside content/ only, no symbolic link anywhere (so no cycle either), no hidden name.
19
+ */
20
+ async function pagesOf(cwd, paths) {
21
+ const content = await realpath(path.join(cwd, 'content')).catch(() => {
22
+ throw new ConnectRefused('This folder has no content/ folder of pages.');
23
+ });
24
+ const found = [];
25
+ async function visit(target) {
26
+ const info = await lstat(target).catch(() => null);
27
+ if (!info)
28
+ throw new ConnectRefused(`${path.relative(cwd, target)} does not exist.`);
29
+ if (info.isSymbolicLink())
30
+ throw new ConnectRefused(`${path.relative(cwd, target)} is a symbolic link; pages are real files under content/.`);
31
+ if (info.isDirectory()) {
32
+ for (const entry of (await readdir(target)).sort())
33
+ if (!entry.startsWith('.'))
34
+ await visit(path.join(target, entry));
35
+ return;
36
+ }
37
+ if (!info.isFile() || !target.endsWith('.md'))
38
+ return;
39
+ const id = frontMatterId(await readFile(target));
40
+ if (!id)
41
+ throw new ConnectRefused(`${path.relative(cwd, target)} has no id in its front matter.`);
42
+ found.push({ file: path.relative(cwd, target), id });
43
+ }
44
+ for (const given of paths) {
45
+ const lexical = path.resolve(cwd, given);
46
+ // Every folder on the way is checked by its real path: a linked folder above the file leaves content/.
47
+ const real = await realpath(path.dirname(lexical)).then((dir) => path.join(dir, path.basename(lexical)), () => lexical);
48
+ if (real !== content && !real.startsWith(`${content}${path.sep}`))
49
+ throw new ConnectRefused(`${given} is not inside content/.`);
50
+ await visit(real);
51
+ }
52
+ return found;
53
+ }
54
+ async function waitFor(core, operation) {
55
+ const { waitInSlices } = await import('./remote/wait-slices.js');
56
+ return waitInSlices((sliceMs) => core.operations.wait({ site: operation.site, id: operation.id, until: 'commit', timeoutMs: sliceMs }), { until: 'commit', timeoutMs: WAIT_MS });
57
+ }
58
+ async function confirmed(request, question) {
59
+ if (request.yes)
60
+ return true;
61
+ if (!request.confirm)
62
+ throw new ConnectRefused(`Not a terminal: pass --yes to ${question.toLowerCase().replace(/\?$/, '')} without being asked.`);
63
+ return request.confirm(question);
64
+ }
65
+ async function finish(operation, io, verb) {
66
+ const result = operation.result;
67
+ if (operation.state !== 'succeeded') {
68
+ io.err(`${verb} did not succeed ` +
69
+ `(${operation.state}${operation.error ? `: ${operation.error.code}: ${operation.error.message}` : ''}).`);
70
+ if (operation.error?.code === 'PUBLISH_PREVIEW_CHANGED')
71
+ io.err(`The preview changed since your last \`${C} preview\`; run it again.`);
72
+ return 1;
73
+ }
74
+ io.out(`${verb}: live is release ${result?.generation ?? '?'} (${result?.siteRelease ?? '?'}).`);
75
+ if (operation.delivery?.state === 'pending')
76
+ io.out(`The cache refresh is still running; \`${C} operation recover\` on the server finishes it.`);
77
+ return 0;
78
+ }
79
+ export async function publishProject(request, io) {
80
+ try {
81
+ const connection = await readConnection(request.cwd);
82
+ if (!connection)
83
+ throw new ConnectRefused(`This folder is not linked to a site: run \`${C} site create <id>\` or \`${C} site link <id>\` first.`);
84
+ let expect = request.expect ?? null;
85
+ if (!expect) {
86
+ const last = await readFile(lastPreviewFile(request.cwd), 'utf8').then((text) => JSON.parse(text), () => null);
87
+ if (!last || last.site !== connection.site || last.server !== connection.server)
88
+ throw new ConnectRefused(`There is no preview of this folder to publish: run \`${C} preview\` first (or name one with --expect sr_…).`);
89
+ expect = last.siteRelease;
90
+ }
91
+ const { core } = await signedInTo({ server: connection.server, env: request.env }, io);
92
+ const changes = await core.channels.changes({ site: connection.site, preview: expect }).catch((error) => {
93
+ if (error.coreError?.code === 'PREVIEW_CHANGED')
94
+ throw new ConnectRefused(`The preview changed since your last \`${C} preview\`; run it again, review it, then publish.`);
95
+ throw error;
96
+ });
97
+ const changed = new Map(changes.pages.map((page) => [page.id, page]));
98
+ let pages;
99
+ if (request.paths.length === 0)
100
+ pages = [...changed.keys()];
101
+ else {
102
+ pages = [];
103
+ for (const { file, id } of await pagesOf(request.cwd, request.paths)) {
104
+ if (changed.has(id))
105
+ pages.push(id);
106
+ else
107
+ io.err(`${file}: nothing to publish (not in this preview, or live has it as it is).`);
108
+ }
109
+ }
110
+ pages = [...new Set(pages)];
111
+ if (pages.length === 0) {
112
+ io.out('Nothing to publish: the preview changes no page on live.');
113
+ return { exit: 0, pages, operation: null };
114
+ }
115
+ io.out(`From preview ${expect}:`);
116
+ for (const id of pages)
117
+ io.out(` ${changed.get(id)?.change === 'new' ? 'new ' : 'changed'} ${id} (${changed.get(id)?.path ?? ''})`);
118
+ if (!(await confirmed(request, `Publish these ${pages.length} page(s) to live?`))) {
119
+ io.out('Nothing was published.');
120
+ return { exit: 0, pages: [], operation: null };
121
+ }
122
+ const operation = await waitFor(core, await core.channels.publish({ site: connection.site, pages, expect: { preview: expect } }));
123
+ return { exit: await finish(operation, io, `Published ${pages.length} page(s)`), pages, operation };
124
+ }
125
+ catch (error) {
126
+ return { exit: failure(error, io), pages: [], operation: null };
127
+ }
128
+ }
129
+ export async function unpublishProject(request, io) {
130
+ try {
131
+ const connection = await readConnection(request.cwd);
132
+ if (!connection)
133
+ throw new ConnectRefused(`This folder is not linked to a site: run \`${C} site create <id>\` or \`${C} site link <id>\` first.`);
134
+ if (request.paths.length === 0)
135
+ throw new ConnectRefused('Name the pages to take off live: files or folders under content/.');
136
+ const pages = [...new Set((await pagesOf(request.cwd, request.paths)).map((page) => page.id))];
137
+ const { core } = await signedInTo({ server: connection.server, env: request.env }, io);
138
+ const live = request.expect ?? (await core.sites.status({ site: connection.site })).live?.site_release;
139
+ if (!live)
140
+ throw new ConnectRefused('This site has nothing live.');
141
+ io.out(`From live ${live}: ${pages.join(', ')}`);
142
+ if (!(await confirmed(request, `Take these ${pages.length} page(s) off live?`))) {
143
+ io.out('Nothing was changed.');
144
+ return { exit: 0, pages: [], operation: null };
145
+ }
146
+ const operation = await waitFor(core, await core.channels.unpublish({ site: connection.site, pages, expect: { live } }));
147
+ return { exit: await finish(operation, io, `Took ${pages.length} page(s) off live`), pages, operation };
148
+ }
149
+ catch (error) {
150
+ return { exit: failure(error, io), pages: [], operation: null };
151
+ }
152
+ }
153
+ function failure(error, io) {
154
+ if (error instanceof ConnectRefused) {
155
+ io.err(error.message);
156
+ return 1;
157
+ }
158
+ const coreError = error.coreError;
159
+ if (!coreError)
160
+ throw error;
161
+ io.err(`${coreError.code}: ${coreError.message}`);
162
+ return 1;
163
+ }
164
+ /** A yes/no question in a terminal (null when stdin or stdout is not one). */
165
+ export function terminalConfirm(stdin, stdout) {
166
+ if (!stdin.isTTY || !stdout.isTTY)
167
+ return null;
168
+ return async (message) => {
169
+ const { confirm, isCancel } = await import('@clack/prompts');
170
+ const answer = await confirm({ input: stdin, output: stdout, message, initialValue: false });
171
+ return !isCancel(answer) && answer === true;
172
+ };
173
+ }
@@ -0,0 +1,8 @@
1
+ export interface Connection {
2
+ server: string;
3
+ site: string;
4
+ org: string;
5
+ }
6
+ export declare const connectionFile: (cwd: string) => string;
7
+ /** The folder's link, or null when it has none or the file is not a complete link. */
8
+ export declare function readConnection(cwd: string): Connection | null;