@astryxdesign/cli 0.7.16 → 0.7.17-canary.gb36275e

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 (239) hide show
  1. package/README.md +13 -23
  2. package/api/build/_adapter.d.mts +5 -0
  3. package/api/build/_adapter.mjs +49 -34
  4. package/api/build/blocks/blocks.d.mts +7 -5
  5. package/api/build/blocks/blocks.mjs +113 -26
  6. package/api/build/build.doc.mjs +2 -1
  7. package/api/build/kit/rank.mjs +59 -12
  8. package/api/build/kit/weights.d.mts +16 -3
  9. package/api/build/kit/weights.json +1 -1
  10. package/api/build/kit/weights.mjs +238 -31
  11. package/api/build/kit/word-model.d.mts +23 -0
  12. package/api/build/kit/word-model.mjs +46 -0
  13. package/api/build/kit/words.d.mts +42 -0
  14. package/api/build/kit/words.mjs +82 -1
  15. package/api/component/__fixtures__/resolutions/modules.txt +4 -5
  16. package/api/component/list/list.d.mts +1 -1
  17. package/api/component/list/list.mjs +46 -5
  18. package/api/discover/_adapter.d.mts +1 -1
  19. package/api/docs/_adapter.d.mts +26 -2
  20. package/api/docs/_adapter.mjs +217 -5
  21. package/api/docs/docs.d.mts +3 -0
  22. package/api/docs/docs.doc.mjs +7 -1
  23. package/api/docs/docs.mjs +12 -0
  24. package/api/docs/docs.type.d.mts +5 -0
  25. package/api/docs/docs.type.mjs +2 -0
  26. package/api/docs/node/node.mjs +1 -1
  27. package/api/doctor/_adapter.d.mts +27 -5
  28. package/api/doctor/_adapter.mjs +77 -6
  29. package/api/doctor/built-checks.mjs +38 -13
  30. package/api/doctor/doctor.d.mts +4 -3
  31. package/api/doctor/doctor.mjs +14 -7
  32. package/api/doctor/theme-checks.mjs +121 -17
  33. package/api/render/_adapter.mjs +531 -192
  34. package/api/render/render.doc.mjs +11 -3
  35. package/api/render/render.type.d.mts +30 -0
  36. package/api/render/render.type.mjs +19 -0
  37. package/api/search/ORDERING.md +1 -1
  38. package/api/search/_candidate-score.mjs +51 -32
  39. package/api/search/_fit-order.mjs +3 -3
  40. package/api/search/_result.d.mts +5 -5
  41. package/api/search/_score.d.mts +6 -1
  42. package/api/search/_score.mjs +15 -3
  43. package/api/search/search.d.mts +1 -1
  44. package/api/theme/_adapter.mjs +10 -0
  45. package/api/theme/build/build.d.mts +47 -0
  46. package/api/theme/build/build.mjs +147 -25
  47. package/api/theme/theme.type.d.mts +10 -0
  48. package/api/theme/theme.type.mjs +7 -1
  49. package/api/theme-edit/_adapter.d.mts +48 -0
  50. package/api/theme-edit/_adapter.mjs +675 -42
  51. package/api/theme-edit/_check.d.mts +28 -22
  52. package/api/theme-edit/_check.mjs +1481 -252
  53. package/api/theme-edit/_color.d.mts +9 -0
  54. package/api/theme-edit/_color.mjs +41 -1
  55. package/api/theme-edit/_compiler.mjs +9 -0
  56. package/api/theme-edit/_context.mjs +60 -3
  57. package/api/theme-edit/_css.mjs +21 -1
  58. package/api/theme-edit/_edit.d.mts +22 -0
  59. package/api/theme-edit/_edit.mjs +1196 -88
  60. package/api/theme-edit/_how-commands.d.mts +57 -0
  61. package/api/theme-edit/_how-commands.mjs +536 -1
  62. package/api/theme-edit/_how-question.d.mts +65 -0
  63. package/api/theme-edit/_how-question.mjs +4401 -225
  64. package/api/theme-edit/_how.mjs +104 -4
  65. package/api/theme-edit/_marks.d.mts +31 -5
  66. package/api/theme-edit/_marks.mjs +57 -5
  67. package/api/theme-edit/_normal.d.mts +153 -0
  68. package/api/theme-edit/_normal.mjs +661 -0
  69. package/api/theme-edit/_palette.mjs +10 -4
  70. package/api/theme-edit/_parts.d.mts +8 -0
  71. package/api/theme-edit/_parts.mjs +103 -2
  72. package/api/theme-edit/_preview-app.d.mts +7 -1
  73. package/api/theme-edit/_preview-app.mjs +205 -17
  74. package/api/theme-edit/_preview.d.mts +64 -8
  75. package/api/theme-edit/_preview.mjs +447 -89
  76. package/api/theme-edit/_settings.d.mts +176 -5
  77. package/api/theme-edit/_settings.mjs +1936 -128
  78. package/api/theme-edit/_tables.d.mts +6 -0
  79. package/api/theme-edit/_tables.mjs +32 -1
  80. package/api/theme-edit/theme-edit.type.d.mts +10 -1
  81. package/api/theme-edit/theme-edit.type.mjs +4 -1
  82. package/api/theme-edit/themeEditPreviewApp.doc.mjs +3 -3
  83. package/assets/codemods/run-codemod.mjs +73 -6
  84. package/assets/codemods/transforms/next/index.mjs +11 -1
  85. package/assets/codemods/transforms/next/migrate-item-swipe-actions-to-swipe.mjs +394 -0
  86. package/assets/docs/author-a-theme.doc.mjs +1 -0
  87. package/assets/docs/theme.doc.dense.mjs +2 -2
  88. package/assets/docs/theme.doc.mjs +1 -1
  89. package/assets/docs/tree/check-your-docs.doc.mjs +1 -1
  90. package/assets/docs/tree/cli-command.doc.mjs +2 -3
  91. package/assets/docs/tree/render-pages.doc.mjs +43 -2
  92. package/assets/docs/tree/template-doc-overview.doc.mjs +1 -1
  93. package/assets/docs/tree/test-in-an-app.doc.mjs +1 -1
  94. package/assets/docs/use-a-theme.doc.mjs +1 -1
  95. package/assets/docs.generated.json +2 -2
  96. package/assets/self-audit.generated.json +1 -1
  97. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.doc.mjs +14 -0
  98. package/assets/templates/blocks/components/ChatComposerInput/useChatDictationHookUsage.tsx +38 -0
  99. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.doc.mjs +14 -0
  100. package/assets/templates/blocks/components/SyntaxTheme/useSyntaxThemeHookUsage.tsx +36 -0
  101. package/assets/templates/components.generated.json +1 -1
  102. package/assets/templates/pages/ai-chat/template.doc.mjs +5 -4
  103. package/assets/templates/pages/ai-chat-landing/template.doc.mjs +2 -1
  104. package/assets/templates/pages/blank/template.doc.mjs +1 -1
  105. package/assets/templates/pages/canvas-editor/template.doc.mjs +4 -2
  106. package/assets/templates/pages/centered-hero/template.doc.mjs +9 -1
  107. package/assets/templates/pages/classic-gallery/template.doc.mjs +1 -1
  108. package/assets/templates/pages/contact-form/template.doc.mjs +2 -1
  109. package/assets/templates/pages/dashboard/template.doc.mjs +3 -2
  110. package/assets/templates/pages/dashboard-alert-rail/template.doc.mjs +2 -1
  111. package/assets/templates/pages/dashboard-cohort-funnel/template.doc.mjs +2 -1
  112. package/assets/templates/pages/dashboard-composition/template.doc.mjs +2 -1
  113. package/assets/templates/pages/dashboard-progress/template.doc.mjs +6 -3
  114. package/assets/templates/pages/detail-page/template.doc.mjs +10 -3
  115. package/assets/templates/pages/documentation/template.doc.mjs +4 -1
  116. package/assets/templates/pages/documentation-design/template.doc.mjs +7 -1
  117. package/assets/templates/pages/documentation-technical/template.doc.mjs +7 -1
  118. package/assets/templates/pages/editor/template.doc.mjs +2 -8
  119. package/assets/templates/pages/file-explorer/template.doc.mjs +1 -1
  120. package/assets/templates/pages/form-two-column/template.doc.mjs +4 -3
  121. package/assets/templates/pages/form-wizard/template.doc.mjs +5 -3
  122. package/assets/templates/pages/gallery-hero/template.doc.mjs +4 -2
  123. package/assets/templates/pages/ide/page.tsx +24 -2
  124. package/assets/templates/pages/kanban-board/template.doc.mjs +1 -9
  125. package/assets/templates/pages/library/template.doc.mjs +4 -1
  126. package/assets/templates/pages/login/template.doc.mjs +2 -1
  127. package/assets/templates/pages/login-card/template.doc.mjs +2 -1
  128. package/assets/templates/pages/login-split/template.doc.mjs +2 -1
  129. package/assets/templates/pages/login-sso/template.doc.mjs +4 -2
  130. package/assets/templates/pages/mixed-gallery/template.doc.mjs +2 -1
  131. package/assets/templates/pages/product-detail/template.doc.mjs +4 -2
  132. package/assets/templates/pages/product-gallery/template.doc.mjs +2 -1
  133. package/assets/templates/pages/settings-dialog/template.doc.mjs +2 -1
  134. package/assets/templates/pages/settings-sidebar/template.doc.mjs +2 -1
  135. package/assets/templates/pages/shell-nav/template.doc.mjs +4 -2
  136. package/assets/templates/pages/shell-side-nav/template.doc.mjs +5 -3
  137. package/assets/templates/pages/shell-top-nav/template.doc.mjs +2 -1
  138. package/assets/templates/pages/side-gallery/template.doc.mjs +9 -1
  139. package/assets/templates/pages/table-filter/template.doc.mjs +9 -8
  140. package/assets/templates/pages/table-grouped/template.doc.mjs +4 -2
  141. package/assets/templates/pages/table-page/template.doc.mjs +5 -4
  142. package/assets/templates/pages/table-tree/template.doc.mjs +6 -3
  143. package/assets/templates/pages/theme-showcase/template.doc.mjs +2 -9
  144. package/assets/templates/pages/work-item-detail/template.doc.mjs +1 -0
  145. package/authoring/debug/parse.d.mts +3 -3
  146. package/authoring/doctypes/_schema.d.mts +3 -3
  147. package/authoring/doctypes/command/command.doc.mjs +1 -1
  148. package/authoring/doctypes/template/template.doc.mjs +1 -1
  149. package/authoring/doctypes/template/type.ts +9 -0
  150. package/clients/cli/bin/astryx.mjs +6 -9
  151. package/clients/cli/build-id.generated.json +1 -1
  152. package/clients/cli/commands/component.doc.mjs +1 -1
  153. package/clients/cli/commands/component.mjs +20 -2
  154. package/clients/cli/commands/docs.doc.mjs +7 -1
  155. package/clients/cli/commands/docs.mjs +3 -1
  156. package/clients/cli/commands/doctor.mjs +22 -14
  157. package/clients/cli/commands/experimental/render.mjs +32 -1
  158. package/clients/cli/commands/experimental/theme.mjs +65 -14
  159. package/clients/cli/commands/experimental-render.doc.mjs +2 -2
  160. package/clients/cli/commands/experimental-theme-compile.doc.mjs +3 -3
  161. package/clients/cli/commands/experimental-theme-editor-show.doc.mjs +1 -1
  162. package/clients/cli/commands/experimental-theme-editor-undo.doc.mjs +1 -1
  163. package/clients/cli/commands/experimental-theme-editor.doc.mjs +1 -1
  164. package/clients/cli/commands/experimental-theme-preview-app.doc.mjs +1 -1
  165. package/clients/cli/commands/search.doc.mjs +2 -1
  166. package/clients/cli/commands/search.mjs +6 -1
  167. package/clients/cli/commands/template.mjs +4 -2
  168. package/clients/cli/commands/theme-build.doc.mjs +5 -1
  169. package/clients/cli/commands/theme.doc.mjs +1 -1
  170. package/clients/cli/commands/theme.mjs +153 -5
  171. package/clients/cli/commands/upgrade.mjs +42 -7
  172. package/clients/cli/index.mjs +1 -1
  173. package/clients/cli/lib/component-format.mjs +205 -98
  174. package/clients/cli/lib/hook-format.mjs +9 -19
  175. package/clients/cli/manifest.generated.json +1 -1
  176. package/foundation/agent-docs/agent-docs.mjs +1 -1
  177. package/foundation/config/theme-state.d.mts +13 -1
  178. package/foundation/config/theme-state.mjs +47 -7
  179. package/foundation/discovery/component-discovery.d.mts +11 -0
  180. package/foundation/discovery/component-discovery.mjs +27 -2
  181. package/foundation/discovery/component-replacement.mjs +130 -1
  182. package/foundation/discovery/entry-name-files.d.mts +43 -0
  183. package/foundation/discovery/entry-name-files.mjs +264 -0
  184. package/foundation/discovery/hook-discovery.d.mts +8 -2
  185. package/foundation/discovery/hook-discovery.mjs +20 -7
  186. package/foundation/discovery/package-exports.d.mts +10 -0
  187. package/foundation/discovery/package-exports.mjs +56 -3
  188. package/foundation/discovery/runner-allowlist.d.mts +1 -0
  189. package/foundation/discovery/runner-allowlist.mjs +2 -0
  190. package/foundation/discovery/template-adapter.d.mts +52 -0
  191. package/foundation/discovery/template-adapter.mjs +173 -10
  192. package/foundation/discovery/theme-imports.d.mts +14 -0
  193. package/foundation/discovery/theme-imports.mjs +43 -1
  194. package/foundation/doc-compiler/import.mjs +7 -1
  195. package/foundation/doc-compiler/parse-readable.mjs +4 -1
  196. package/foundation/doc-compiler/stored-docs.d.mts +22 -0
  197. package/foundation/doc-compiler/stored-docs.mjs +49 -0
  198. package/foundation/fs/cache-eviction.d.mts +21 -0
  199. package/foundation/fs/cache-eviction.mjs +73 -0
  200. package/foundation/fs/gather-cache.d.mts +25 -4
  201. package/foundation/fs/gather-cache.mjs +163 -53
  202. package/foundation/fs/jiti-cache.d.mts +19 -1
  203. package/foundation/fs/jiti-cache.mjs +130 -6
  204. package/foundation/fs/kept-tree.d.mts +60 -0
  205. package/foundation/fs/kept-tree.mjs +154 -0
  206. package/foundation/fs/module-loader.d.mts +18 -2
  207. package/foundation/fs/module-loader.mjs +92 -20
  208. package/foundation/identity/provider-identity.d.mts +6 -0
  209. package/foundation/identity/provider-identity.mjs +10 -1
  210. package/foundation/render/embedded-imports.d.mts +5 -4
  211. package/foundation/render/embedded-imports.mjs +7 -16
  212. package/foundation/render/file-header.d.mts +66 -0
  213. package/foundation/render/file-header.mjs +118 -0
  214. package/foundation/render/host-answer.d.mts +18 -0
  215. package/foundation/render/host-answer.mjs +46 -0
  216. package/foundation/render/host-exit.d.mts +1 -0
  217. package/foundation/render/host-exit.mjs +6 -1
  218. package/foundation/render/html-reader.d.mts +55 -2
  219. package/foundation/render/html-reader.mjs +145 -26
  220. package/foundation/render/markup-edits.d.mts +57 -0
  221. package/foundation/render/markup-edits.mjs +182 -0
  222. package/foundation/render/page-host.mjs +29 -12
  223. package/foundation/render/page-worker.mjs +83 -13
  224. package/foundation/render/render-page.d.mts +34 -2
  225. package/foundation/render/render-page.mjs +210 -29
  226. package/foundation/render/source-block.d.mts +73 -6
  227. package/foundation/render/source-block.mjs +170 -19
  228. package/foundation/render/ts-paths.d.mts +53 -6
  229. package/foundation/render/ts-paths.mjs +286 -41
  230. package/foundation/response/error-codes.d.mts +3 -1
  231. package/foundation/response/error-codes.d.ts +1 -0
  232. package/foundation/response/error-codes.doc.mjs +12 -1
  233. package/foundation/response/error-codes.mjs +10 -0
  234. package/foundation/text/string-utils.d.mts +3 -2
  235. package/foundation/text/string-utils.mjs +16 -3
  236. package/foundation/text/suggest-order.d.mts +9 -0
  237. package/foundation/text/suggest-order.mjs +13 -0
  238. package/host/index.mjs +8 -6
  239. package/package.json +6 -6
@@ -8,7 +8,9 @@
8
8
  */
9
9
 
10
10
  import * as fs from 'node:fs';
11
+ import * as os from 'node:os';
11
12
  import * as path from 'node:path';
13
+ import {randomUUID} from 'node:crypto';
12
14
  import {createRequire} from 'node:module';
13
15
  import {AstryxError} from '../error.mjs';
14
16
  import {ERROR_CODES} from '../../foundation/response/error-codes.mjs';
@@ -17,10 +19,25 @@ import {
17
19
  RenderError,
18
20
  renderPage,
19
21
  } from '../../foundation/render/render-page.mjs';
20
- import {readSourceBlock} from '../../foundation/render/source-block.mjs';
22
+ import {
23
+ RENDER_FORMAT,
24
+ asParsed,
25
+ readSourceBlock,
26
+ recordedText,
27
+ renderedHeadOf,
28
+ renderedMarkupOf,
29
+ sha256,
30
+ } from '../../foundation/render/source-block.mjs';
31
+ import {decode} from '../../foundation/render/html-reader.mjs';
32
+ import {clip, locate, textEdits, textRuns} from '../../foundation/render/markup-edits.mjs';
33
+ import {isPackageName} from '../../foundation/identity/provider-identity.mjs';
34
+ import {cliCommand} from '../../foundation/render/file-header.mjs';
35
+ import {shellArg} from '../../foundation/text/shell-arg.mjs';
36
+ import {isValidSemver} from '../../foundation/env/semver.mjs';
21
37
  import {embeddedPathProblem, runnerPicksUp} from '../../foundation/render/embedded-files.mjs';
22
38
  import {isAssetBytes, isAssetPath} from '../../foundation/render/assets.mjs';
23
39
  import {createFileProtectionResolver} from '../../foundation/fs/file-protection.mjs';
40
+ import {publishNewFile} from '../../foundation/fs/publish-file.mjs';
24
41
  import {reachableFiles, receivingAliases} from '../../foundation/render/embedded-imports.mjs';
25
42
  import {isAstryxMarkup} from '../../foundation/render/html-reader.mjs';
26
43
  import {rebuildPage} from '../../foundation/render/rebuild.mjs';
@@ -28,6 +45,7 @@ import {cliVersion} from '../../foundation/integrations/cli-peer-version.mjs';
28
45
  import {assertWithin, PathSafetyError} from '../../foundation/fs/path-safety.mjs';
29
46
  import {requireCoreDir} from '../../foundation/fs/paths.mjs';
30
47
  import {runChoice} from '../../foundation/release/run-context.mjs';
48
+ import {isAlive, pidSpace} from '../../foundation/release/cache.mjs';
31
49
  import {isServedPackage} from '../../foundation/render/served-packages.mjs';
32
50
  import {hostedRun, recordResolved} from '../../foundation/runtime/package-root.mjs';
33
51
 
@@ -41,23 +59,57 @@ const shown = (cwd, file) => {
41
59
  : file;
42
60
  };
43
61
 
62
+ /** Why a file cannot be read, in a few words, by its errno. */
63
+ const READ_FAILURES = {EACCES: 'no permission', EPERM: 'no permission', EISDIR: 'it is a folder'};
64
+
44
65
  /**
45
- * Read a file the caller named, or throw ERR_FILE_NOT_FOUND.
66
+ * The error for an input the file system would not give: ERR_FILE_NOT_FOUND
67
+ * when nothing is there, ERR_READ_FAILED with the errno and its reason
68
+ * otherwise.
69
+ * @param {string} file absolute
70
+ * @param {string} cwd
71
+ * @param {unknown} e what the file system threw
72
+ */
73
+ function inputFailure(file, cwd, e) {
74
+ const errno = /** @type {NodeJS.ErrnoException} */ (e).code;
75
+ if (errno === 'ENOENT' || errno === 'ENOTDIR') {
76
+ return new AstryxError(`${shown(cwd, file)} does not exist`, [], ERROR_CODES.ERR_FILE_NOT_FOUND);
77
+ }
78
+ const why = READ_FAILURES[/** @type {keyof typeof READ_FAILURES} */ (errno)];
79
+ return new AstryxError(
80
+ `${shown(cwd, file)} cannot be read${errno ? ` (${errno}${why ? `: ${why}` : ''})` : ''}; nothing was written.`,
81
+ [],
82
+ ERROR_CODES.ERR_READ_FAILED,
83
+ );
84
+ }
85
+
86
+ /**
87
+ * Read a file the caller named. A folder, a pipe or any other entry that is
88
+ * not a regular file is refused before it is opened, so nothing waits on it.
46
89
  * @param {string} file absolute
47
90
  * @param {string} cwd
48
91
  * @returns {Buffer}
49
92
  */
50
93
  function readInput(file, cwd) {
94
+ /** @type {fs.Stats} */
95
+ let stat;
51
96
  try {
52
- if (!fs.statSync(file).isFile()) throw new Error('not a file');
53
- return fs.readFileSync(file);
54
- } catch {
97
+ stat = fs.statSync(file);
98
+ } catch (e) {
99
+ throw inputFailure(file, cwd, e);
100
+ }
101
+ if (!stat.isFile()) {
55
102
  throw new AstryxError(
56
- `${shown(cwd, file)} does not exist`,
103
+ `${shown(cwd, file)} cannot be read (${stat.isDirectory() ? 'it is a folder' : 'it is not a regular file'}); nothing was written.`,
57
104
  [],
58
- ERROR_CODES.ERR_FILE_NOT_FOUND,
105
+ ERROR_CODES.ERR_READ_FAILED,
59
106
  );
60
107
  }
108
+ try {
109
+ return fs.readFileSync(file);
110
+ } catch (e) {
111
+ throw inputFailure(file, cwd, e);
112
+ }
61
113
  }
62
114
 
63
115
  /**
@@ -99,15 +151,29 @@ function confined(file, cwd, what) {
99
151
  }
100
152
  }
101
153
 
154
+ /**
155
+ * Whether a file is inside a folder (not the folder itself).
156
+ * @param {string} file absolute
157
+ * @param {string | null} folder absolute
158
+ */
159
+ const isInside = (file, folder) => {
160
+ if (!folder) return false;
161
+ const rel = path.relative(folder, file);
162
+ return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
163
+ };
164
+
102
165
  /**
103
166
  * Refuse, before anything is written, a write that reaches through a
104
167
  * symbolic link, and the replacement of an existing file the project
105
168
  * protects (generated, vendored, ignored, a dependency or version-control
106
- * metadata; spec:AST-040 FR2), even with --overwrite.
169
+ * metadata; spec:AST-040 FR2), even with --overwrite. A file inside the new
170
+ * folder a restore creates replaces nothing: that folder takes its name in
171
+ * one step, after every check.
107
172
  * @param {string[]} files absolute
108
173
  * @param {string} cwd
174
+ * @param {string | null} [newFolder] the new folder a restore creates, if any
109
175
  */
110
- function refuseProtected(files, cwd) {
176
+ function refuseProtected(files, cwd, newFolder = null) {
111
177
  for (const file of files) {
112
178
  let current = cwd;
113
179
  for (const part of path.relative(cwd, file).split(path.sep)) {
@@ -127,7 +193,7 @@ function refuseProtected(files, cwd) {
127
193
  }
128
194
  }
129
195
  }
130
- const existing = files.filter(file => fs.existsSync(file));
196
+ const existing = files.filter(file => !isInside(file, newFolder) && fs.existsSync(file));
131
197
  if (existing.length === 0) return;
132
198
  /** @type {ReturnType<typeof createFileProtectionResolver>} */
133
199
  let resolver;
@@ -154,76 +220,204 @@ function refuseProtected(files, cwd) {
154
220
  }
155
221
 
156
222
  /**
157
- * Write several files all or nothing: each goes to a temporary file beside
158
- * its target first, and only when every one is written are they moved into
159
- * place. On a failure, the temporary files and the folders this made are
160
- * removed, so nothing is left behind.
161
- * @param {{file: string, bytes: Buffer}[]} writes absolute targets
223
+ * The process space runs here share: this computer's name and its process-ID
224
+ * namespace (a container or sandbox on one computer has its own), in which a
225
+ * process id names one process.
226
+ */
227
+ const PROCESS_SPACE = `${os.hostname()}-${/\[(\d+)\]/.exec(pidSpace() ?? '')?.[1] ?? 'x'}`;
228
+
229
+ /**
230
+ * The start of the hidden temporary names a run in this process space gives
231
+ * a file or folder beside its target, before the run's process id.
232
+ * @param {string} target absolute
233
+ */
234
+ const temporaryPrefix = target => `.${path.basename(target)}.tmp-${PROCESS_SPACE}-`;
235
+
236
+ /**
237
+ * A hidden temporary name beside a file or folder, as the CLI's other writers
238
+ * name theirs, with this process space and this process's id, so a later run
239
+ * can tell when the run that made it is gone.
240
+ * @param {string} target absolute
241
+ */
242
+ const temporaryBeside = target => path.join(path.dirname(target), `${temporaryPrefix(target)}${process.pid}-${randomUUID()}`);
243
+
244
+ /**
245
+ * Remove the temporaries that runs in this process space left beside a
246
+ * target when they stopped between their write and their rename: those whose
247
+ * process no longer runs. A temporary of a run that still runs, or of a run
248
+ * in another process space (another computer, container or sandbox, whose
249
+ * processes cannot be seen from here), stays.
250
+ * @param {string} target absolute
251
+ */
252
+ function removeStaleTemporaries(target) {
253
+ const prefix = temporaryPrefix(target);
254
+ let names;
255
+ try {
256
+ names = fs.readdirSync(path.dirname(target));
257
+ } catch {
258
+ return;
259
+ }
260
+ for (const name of names) {
261
+ if (!name.startsWith(prefix)) continue;
262
+ const pid = /^(\d+)-[0-9a-f-]{36}$/.exec(name.slice(prefix.length))?.[1];
263
+ if (pid === undefined || isAlive(Number(pid))) continue;
264
+ fs.rmSync(path.join(path.dirname(target), name), {recursive: true, force: true});
265
+ }
266
+ }
267
+
268
+ /**
269
+ * The topmost folder on the way to `file` that does not exist yet, or null
270
+ * when the file's own folder exists.
271
+ * @param {string} file absolute
272
+ * @returns {string | null}
273
+ */
274
+ function newFolderOf(file) {
275
+ /** @type {string | null} */
276
+ let top = null;
277
+ for (let d = path.dirname(file); !fs.existsSync(d) && path.dirname(d) !== d; d = path.dirname(d)) top = d;
278
+ return top;
279
+ }
280
+
281
+ /**
282
+ * Why a write failed, in terms of the target, never the hidden temporary
283
+ * file or folder beside it: the folder that would not take the temporary,
284
+ * or the error a file inside the temporary folder met.
285
+ * @param {unknown} e
286
+ * @param {string | null} temporary the temporary file or folder
287
+ * @param {string} folder the folder that holds the target
288
+ * @param {string} cwd
289
+ */
290
+ function writeFailure(e, temporary, folder, cwd) {
291
+ const err = /** @type {NodeJS.ErrnoException} */ (e);
292
+ if (temporary && err?.path === temporary && (err.syscall === 'open' || err.syscall === 'mkdir')) {
293
+ return `${shown(cwd, folder)} does not take a new file (${err.code ?? err.message})`;
294
+ }
295
+ if (temporary && err?.path?.startsWith(temporary + path.sep)) return err.code ?? err.message;
296
+ return String(err?.message ?? e);
297
+ }
298
+
299
+ /**
300
+ * Write one file in one step: its bytes go to a temporary file beside it,
301
+ * which then takes its name. A reader, or another run at the same time, sees
302
+ * the old whole file or the new one, never part of one, and a run stopped
303
+ * part-way leaves the old file as it was; the next write to the file removes
304
+ * the temporary that run left.
305
+ * @param {string} file absolute
306
+ * @param {string | Buffer} content
162
307
  * @param {string} cwd
308
+ * @param {{replace: boolean, mode?: number}} options `replace`: an existing
309
+ * file may be replaced; without it, a file that appeared since the checks
310
+ * stays. `mode`: the permission bits the file gets
163
311
  */
164
- function writeAll(writes, cwd) {
165
- /** @type {string[]} */
166
- const madeDirs = [];
167
- /** @type {{temp: string, file: string}[]} */
168
- const staged = [];
169
- const undo = () => {
170
- for (const {temp} of staged) fs.rmSync(temp, {force: true});
171
- for (const dir of madeDirs.reverse()) {
172
- try {
173
- fs.rmdirSync(dir);
174
- } catch {
175
- // Not empty or already gone: leave it.
176
- }
177
- }
178
- };
179
- let current = '';
312
+ function writeOutput(file, content, cwd, {replace, mode}) {
313
+ /** @type {string | null} */
314
+ let temporary = null;
180
315
  try {
181
- for (const w of writes) {
182
- current = w.file;
183
- /** @type {string[]} */
184
- const missing = [];
185
- for (let d = path.dirname(w.file); !fs.existsSync(d); d = path.dirname(d)) missing.unshift(d);
186
- for (const d of missing) {
187
- fs.mkdirSync(d);
188
- madeDirs.push(d);
189
- }
190
- const temp = `${w.file}.astryx-${process.pid}.tmp`;
191
- fs.writeFileSync(temp, w.bytes, {flag: 'wx'});
192
- staged.push({temp, file: w.file});
316
+ fs.mkdirSync(path.dirname(file), {recursive: true});
317
+ /** @type {fs.Stats | null} */
318
+ let existing = null;
319
+ try {
320
+ existing = fs.statSync(file);
321
+ } catch {
322
+ // No file there yet.
193
323
  }
194
- for (const {temp, file} of staged) {
195
- current = file;
196
- fs.renameSync(temp, file);
324
+ if (existing?.isDirectory()) {
325
+ throw Object.assign(new Error(`EISDIR: illegal operation on a directory, open '${file}'`), {code: 'EISDIR'});
197
326
  }
327
+ removeStaleTemporaries(file);
328
+ temporary = temporaryBeside(file);
329
+ fs.writeFileSync(temporary, content, {flag: 'wx'});
330
+ if (mode !== undefined) fs.chmodSync(temporary, mode);
331
+ if (replace) fs.renameSync(temporary, file);
332
+ else publishNewFile(temporary, file);
198
333
  } catch (e) {
199
- undo();
334
+ if (!replace && /** @type {any} */ (e)?.code === 'EEXIST') {
335
+ throw new AstryxError(
336
+ `${shown(cwd, file)} appeared while this ran; nothing was written. Pass --overwrite to replace it.`,
337
+ [],
338
+ ERROR_CODES.ERR_FILE_EXISTS,
339
+ );
340
+ }
200
341
  throw new AstryxError(
201
- `Could not write ${shown(cwd, current)}: ${/** @type {Error} */ (e).message}; nothing was written.`,
342
+ `Could not write ${shown(cwd, file)}: ${writeFailure(e, temporary, path.dirname(file), cwd)}; nothing was written.`,
202
343
  [],
203
344
  ERROR_CODES.ERR_WRITE_FAILED,
204
345
  );
346
+ } finally {
347
+ if (temporary) fs.rmSync(temporary, {force: true});
205
348
  }
206
349
  }
207
350
 
208
351
  /**
209
- * Write one file, creating its folder.
210
- * @param {string} file absolute
211
- * @param {string | Buffer} content
352
+ * Write a new folder and every file in it, all or nothing, in one step: the
353
+ * files go into a temporary folder beside it, which then takes the folder's
354
+ * name. A run stopped part-way leaves no folder behind, so running it again
355
+ * works (and removes the temporary folder that run left), and of two runs
356
+ * that pick the same name, one gets it and the other learns that it is
357
+ * taken.
358
+ * @param {string} folder absolute; does not exist yet
359
+ * @param {{file: string, bytes: Buffer}[]} writes absolute targets inside `folder`
212
360
  * @param {string} cwd
361
+ * @returns {boolean} false when the folder appeared before this run could take its name
213
362
  */
214
- function writeOutput(file, content, cwd) {
363
+ function writeFolder(folder, writes, cwd) {
364
+ removeStaleTemporaries(folder);
365
+ const staging = temporaryBeside(folder);
366
+ let current = folder;
215
367
  try {
216
- fs.mkdirSync(path.dirname(file), {recursive: true});
217
- fs.writeFileSync(file, content);
368
+ for (const w of writes) {
369
+ current = w.file;
370
+ const staged = path.join(staging, path.relative(folder, w.file));
371
+ fs.mkdirSync(path.dirname(staged), {recursive: true});
372
+ fs.writeFileSync(staged, w.bytes, {flag: 'wx'});
373
+ }
374
+ current = folder;
375
+ try {
376
+ fs.renameSync(staging, folder);
377
+ } catch (e) {
378
+ if (fs.existsSync(folder)) return false;
379
+ throw e;
380
+ }
381
+ return true;
218
382
  } catch (e) {
219
383
  throw new AstryxError(
220
- `Could not write ${shown(cwd, file)}: ${/** @type {Error} */ (e).message}`,
384
+ `Could not write ${shown(cwd, current)}: ${writeFailure(e, staging, path.dirname(folder), cwd)}; nothing was written.`,
221
385
  [],
222
386
  ERROR_CODES.ERR_WRITE_FAILED,
223
387
  );
388
+ } finally {
389
+ fs.rmSync(staging, {recursive: true, force: true});
224
390
  }
225
391
  }
226
392
 
393
+ /**
394
+ * Write a restore's files: into the new folder that holds them all, in one
395
+ * step, or, when the page goes into a folder that exists (the only file a
396
+ * restore writes there), the page alone.
397
+ * @param {{file: string, bytes: Buffer}[]} writes absolute targets, the page first
398
+ * @param {string | null} folder the new folder that holds every file, or null
399
+ * @param {string} cwd
400
+ * @param {boolean} overwrite whether an existing page may be replaced
401
+ * @returns {boolean} false when the new folder appeared before this run could take its name
402
+ */
403
+ function writeRestore(writes, folder, cwd, overwrite) {
404
+ if (folder) return writeFolder(folder, writes, cwd);
405
+ writeOutput(writes[0].file, writes[0].bytes, cwd, {replace: overwrite});
406
+ return true;
407
+ }
408
+
409
+ /**
410
+ * The refusal for a restore whose new folder another run created first.
411
+ * @param {string} folder
412
+ * @param {string} cwd
413
+ */
414
+ const folderTaken = (folder, cwd) =>
415
+ new AstryxError(
416
+ `${shown(cwd, folder)} appeared while this restore ran; nothing was written. Restore into another folder with --out.`,
417
+ [],
418
+ ERROR_CODES.ERR_FILE_EXISTS,
419
+ );
420
+
227
421
  /** @param {unknown} e */
228
422
  function asAstryxError(e) {
229
423
  if (e instanceof RenderError) {
@@ -278,7 +472,7 @@ export async function renderToFile({cwd, input, output, title}) {
278
472
  try {
279
473
  const set = servedSet(input);
280
474
  try {
281
- page = await renderPage(input, {title, version: cliVersion(), served: set && 'dir' in set ? set : null});
475
+ page = await renderPage(input, {title, version: cliVersion(), served: set && 'dir' in set ? set : null, output, cwd});
282
476
  } catch (e) {
283
477
  // A page that needs the Core the CLI could not obtain says why.
284
478
  const missing = /** @type {any} */ (e)?.code === 'ERR_RENDER_MISSING_DEPENDENCY' ? /** @type {any} */ (e).detail?.package : null;
@@ -312,7 +506,21 @@ export async function renderToFile({cwd, input, output, title}) {
312
506
  ERROR_CODES.ERR_FILE_EXISTS,
313
507
  );
314
508
  }
315
- writeOutput(output, page.html, cwd);
509
+ // A render never replaces an HTML file this user cannot write, and the file
510
+ // it replaces keeps its permission bits.
511
+ const existingMode = fs.statSync(output, {throwIfNoEntry: false})?.mode;
512
+ if (existingMode !== undefined) {
513
+ try {
514
+ fs.accessSync(output, fs.constants.W_OK);
515
+ } catch (e) {
516
+ throw new AstryxError(
517
+ `Could not write ${shown(cwd, output)}: ${/** @type {Error} */ (e).message}; nothing was written.`,
518
+ [],
519
+ ERROR_CODES.ERR_WRITE_FAILED,
520
+ );
521
+ }
522
+ }
523
+ writeOutput(output, page.html, cwd, {replace: true, ...(existingMode === undefined ? {} : {mode: existingMode & 0o7777})});
316
524
  return {
317
525
  input: shown(cwd, input),
318
526
  output: shown(cwd, output),
@@ -364,16 +572,89 @@ function refuseRunnable(files, cwd, input) {
364
572
  /**
365
573
  * The new folder a restore without --out writes into: beside the HTML file,
366
574
  * named after it (`report.html` gives `report-restored/`, then
367
- * `report-restored-2/` when that exists).
575
+ * `report-restored-2/` when that exists). A name already taken is never
576
+ * written again, so a temporary folder a stopped run left for it goes.
368
577
  * @param {string} input absolute
369
578
  */
370
579
  function restoreFolder(input) {
371
580
  const stem = path.basename(input).replace(/\.[^.]+$/, '');
372
581
  let folder = path.join(path.dirname(input), `${stem}-restored`);
373
- for (let n = 2; fs.existsSync(folder); n++) folder = path.join(path.dirname(input), `${stem}-restored-${n}`);
582
+ for (let n = 2; fs.existsSync(folder); n++) {
583
+ removeStaleTemporaries(folder);
584
+ folder = path.join(path.dirname(input), `${stem}-restored-${n}`);
585
+ }
374
586
  return folder;
375
587
  }
376
588
 
589
+ /**
590
+ * The version of the CLI that rendered a file: the one its embedded source
591
+ * records, else the one its generator meta names.
592
+ * @param {import('../../foundation/render/source-block.mjs').EmbeddedSource} source
593
+ * @param {string} html
594
+ * @returns {string | null}
595
+ */
596
+ function renderedByOf(source, html) {
597
+ const named = source.cli ?? /<meta name="generator" content="Astryx ([^"<>]+)">/.exec(html.slice(0, 4096))?.[1];
598
+ return isValidSemver(named) ? /** @type {string} */ (named) : null;
599
+ }
600
+
601
+ /**
602
+ * The packages a file says its page rendered with, as `name@version`, when
603
+ * it records them.
604
+ * @param {import('../../foundation/render/source-block.mjs').EmbeddedSource} source
605
+ * @returns {string[] | null}
606
+ */
607
+ function packagesOf(source) {
608
+ const recorded = source.packages;
609
+ if (!recorded || typeof recorded !== 'object' || Array.isArray(recorded)) return null;
610
+ return Object.entries(recorded)
611
+ .filter(([name, version]) => isPackageName(name) && isValidSemver(version))
612
+ .map(([name, version]) => `${name}@${version}`);
613
+ }
614
+
615
+ /**
616
+ * Whether someone changed the page after the render, for a file that records
617
+ * the page as rendered: each run of text that changed (the title first), and
618
+ * whether the styles changed. The restored source never takes these changes:
619
+ * it is the page as rendered.
620
+ * @param {import('../../foundation/render/source-block.mjs').EmbeddedSource} source
621
+ * @param {string} html
622
+ * @param {{file: string, text: string}[]} modules the restored modules, as shown to the caller
623
+ * @returns {{edited?: boolean, stylesEdited?: boolean, edits?: import('./render.type.mjs').RenderEdit[], moreEdits?: number}}
624
+ */
625
+ function pageChanges(source, html, modules) {
626
+ const recorded = source.markup;
627
+ if (!recorded || typeof recorded.sha256 !== 'string') return {};
628
+ // The page as a browser reads it, so a copy whose line ends changed on the
629
+ // way is no edit.
630
+ const markupNow = renderedMarkupOf(html);
631
+ const now = markupNow === null ? null : asParsed(markupNow);
632
+ const head = renderedHeadOf(html);
633
+ const text = recordedText(recorded);
634
+ const titleNow = head.title === null ? null : asParsed(decode(head.title));
635
+ const titleEdited = typeof text?.title === 'string' && titleNow !== asParsed(text.title);
636
+ const stylesEdited = typeof recorded.style === 'string' ? head.style === null || sha256(asParsed(head.style)) !== recorded.style : undefined;
637
+ const markupEdited = now === null || sha256(now) !== recorded.sha256;
638
+ const styles = stylesEdited === undefined ? {} : {stylesEdited};
639
+ if (!markupEdited && !titleEdited && !stylesEdited) return {edited: false, ...styles};
640
+ const {edits, more} = markupEdited ? textEdits(text?.runs ?? [], textRuns(now ?? '')) : {edits: [], more: 0};
641
+ // A title that changed with the heading it comes from is one change, not two.
642
+ const titleEdit = {was: /** @type {string} */ (text?.title), now: titleNow};
643
+ const titleAgain = edits.some(edit => edit.was === titleEdit.was && edit.now === titleEdit.now);
644
+ const all = [...(titleEdited && !titleAgain ? [titleEdit] : []), ...edits];
645
+ return {
646
+ edited: true,
647
+ ...styles,
648
+ // Each change is found in the source by its whole text, then cut to show.
649
+ edits: all.map(edit => ({
650
+ was: edit.was === null ? null : clip(edit.was),
651
+ now: edit.now === null ? null : clip(edit.now),
652
+ ...((edit.was && locate(edit.was, modules)) || {}),
653
+ })),
654
+ ...(more > 0 ? {moreEdits: more} : {}),
655
+ };
656
+ }
657
+
377
658
  /**
378
659
  * Turn a rendered HTML file back into a page module.
379
660
  * @param {{cwd: string, input: string, output: string | undefined, overwrite: boolean}} args absolute paths
@@ -382,6 +663,17 @@ function restoreFolder(input) {
382
663
  export function reverseToFile({cwd, input, output, overwrite}) {
383
664
  const html = readInput(input, cwd).toString('utf8');
384
665
  const block = readSourceBlock(html);
666
+ const rendered = /<meta name="generator" content="Astryx[ "]/.test(html);
667
+ // A merge that left conflict markers in an Astryx page holds two versions
668
+ // of it at once, the embedded source too: choosing one would choose for
669
+ // the user.
670
+ if ((block.found || rendered || isAstryxMarkup(html)) && /^<{7}(?: |$)/m.test(html) && /^>{7}(?: |$)/m.test(html)) {
671
+ throw new AstryxError(
672
+ `${shown(cwd, input)} holds unresolved merge conflict markers (<<<<<<< and >>>>>>>), so it holds two versions at once; nothing was written. Keep the whole file from one side, or render the merged page again, then run this again.`,
673
+ [],
674
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
675
+ );
676
+ }
385
677
  /** @param {string[]} files */
386
678
  const refuseExisting = files => {
387
679
  if (overwrite) return;
@@ -410,6 +702,15 @@ export function reverseToFile({cwd, input, output, overwrite}) {
410
702
  );
411
703
  }
412
704
  };
705
+ if (block.found && 'newer' in block) {
706
+ const {format, cli} = block.newer;
707
+ const command = `${cliCommand(cli ?? 'latest')} experimental render --reverse ${shellArg(shown(cwd, input))}`;
708
+ throw new AstryxError(
709
+ `${shown(cwd, input)} is in render format ${format}${cli ? `, written by @astryxdesign/cli ${cli}` : ''}, which is newer than this CLI reads (render format ${RENDER_FORMAT}, @astryxdesign/cli ${cliVersion()}); nothing was written. Give it back with ${cli ? 'the CLI that wrote it' : 'the latest CLI'}: ${command}`,
710
+ [{name: command, reason: cli ? 'give it back with the CLI version that wrote the file' : 'give it back with the latest CLI'}],
711
+ ERROR_CODES.ERR_RENDER_NEWER_FORMAT,
712
+ );
713
+ }
413
714
  if (block.found && 'damaged' in block) {
414
715
  throw new AstryxError(
415
716
  `${shown(cwd, input)} carries an Astryx page source, but ${block.damaged}, so it cannot be given back exactly.`,
@@ -431,126 +732,156 @@ export function reverseToFile({cwd, input, output, overwrite}) {
431
732
  );
432
733
  }
433
734
  });
434
- // Without --out, the page and the files it imports come back into a new
435
- // folder beside the HTML file, named after it (`report.html` gives
436
- // `report-restored/`), with the layout they were rendered in. Nothing in
437
- // the received file decides where in your project anything goes.
438
- const requested = output ?? path.join(restoreFolder(input), ...source.files[0].path.split('/'));
439
- refuseConfigTarget(requested);
440
- const seen = new Set();
441
- for (const f of source.files) {
442
- const key = f.path.toLowerCase();
443
- if (seen.has(key)) {
735
+ // A restore without --out picks the first folder name no folder has.
736
+ // When another run takes that name first, this one takes the next: each
737
+ // name it loses exists from then on, so every pass picks a new one.
738
+ for (;;) {
739
+ // Without --out, the page and the files it imports come back into a new
740
+ // folder beside the HTML file, named after it (`report.html` gives
741
+ // `report-restored/`), with the layout they were rendered in. Nothing in
742
+ // the received file decides where in your project anything goes.
743
+ const folder = output ? null : restoreFolder(input);
744
+ const requested = output ?? path.join(/** @type {string} */ (folder), ...source.files[0].path.split('/'));
745
+ refuseConfigTarget(requested);
746
+ const seen = new Set();
747
+ for (const f of source.files) {
748
+ const key = f.path.toLowerCase();
749
+ if (seen.has(key)) {
750
+ throw new AstryxError(
751
+ `${shown(cwd, input)} lists ${f.path} more than once, which a render never does; nothing was written.`,
752
+ [],
753
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
754
+ );
755
+ }
756
+ seen.add(key);
757
+ }
758
+ // Modules, stylesheets and JSON are written only when the page reaches
759
+ // them through its own imports: one it never imports is not part of it,
760
+ // whatever its name.
761
+ const {reached, missing} = reachableFiles(source.files, {aliases: receivingAliases(requested)});
762
+ // A carried image, font or media file needs no import to be part of the
763
+ // page (it may be named in markup, a stylesheet, JSON or a computed
764
+ // path): the render's own list is the authority, so it is kept when its
765
+ // bytes are a known image, font or media format (any, whatever the
766
+ // extension), and goes where the layout puts it.
767
+ for (const f of source.files) {
768
+ if (reached.has(f.path) || !isAssetPath(f.path)) continue;
769
+ if (isAssetBytes(Buffer.from(f.base64, 'base64'))) reached.set(f.path, {relative: true, aliased: new Set()});
770
+ }
771
+ const stray = source.files.filter(f => !reached.has(f.path)).map(f => f.path);
772
+ if (stray.length > 0) {
444
773
  throw new AstryxError(
445
- `${shown(cwd, input)} lists ${f.path} more than once, which a render never does; nothing was written.`,
774
+ `${shown(cwd, input)} carries ${stray.length === 1 ? 'a file' : 'files'} the page does not import, or that is not the image, font or media file its name says (${stray.join(', ')}), which a render never embeds; nothing was written. A file reached through a path alias needs the same alias in this project's tsconfig.json or jsconfig.json.`,
446
775
  [],
447
776
  ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
448
777
  );
449
778
  }
450
- seen.add(key);
451
- }
452
- // Modules, stylesheets and JSON are written only when the page reaches
453
- // them through its own imports: one it never imports is not part of it,
454
- // whatever its name.
455
- const {reached, missing} = reachableFiles(source.files, {aliases: receivingAliases(path.dirname(requested))});
456
- // A carried image, font or media file needs no import to be part of the
457
- // page (it may be named in markup, a stylesheet, JSON or a computed
458
- // path): the render's own list is the authority, so it is kept when its
459
- // bytes are a known image, font or media format (any, whatever the
460
- // extension), and goes where the layout puts it.
461
- for (const f of source.files) {
462
- if (reached.has(f.path) || !isAssetPath(f.path)) continue;
463
- if (isAssetBytes(Buffer.from(f.base64, 'base64'))) reached.set(f.path, {relative: true, aliased: new Set()});
464
- }
465
- const stray = source.files.filter(f => !reached.has(f.path)).map(f => f.path);
466
- if (stray.length > 0) {
467
- throw new AstryxError(
468
- `${shown(cwd, input)} carries ${stray.length === 1 ? 'a file' : 'files'} the page does not import, or that is not the image, font or media file its name says (${stray.join(', ')}), which a render never embeds; nothing was written. A file reached through a path alias needs the same alias in this project's tsconfig.json or jsconfig.json.`,
469
- [],
470
- ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
471
- );
472
- }
473
- // Each file the page reaches by a relative import goes where that import
474
- // finds it from the page's new folder, so every relative import still
475
- // resolves wherever the page lands; a file reached through an alias goes
476
- // where this project's alias points. Every file but the page must land
477
- // in a folder this restore creates: a received file never adds a file to
478
- // a folder that already exists (a server hook at the project root, a
479
- // middleware module), so a page with neighbours comes back into a new
480
- // folder.
481
- const entryDir = path.posix.dirname(source.files[0].path);
482
- const anchor = path.dirname(requested);
483
- /** @param {string} p */
484
- const placeFrom = p => path.resolve(anchor, path.posix.relative(entryDir, p));
485
- // A file beside the page or elsewhere goes only into a folder this
486
- // restore creates: never into a folder that already exists.
487
- // The one folder every file but the page must land in: the topmost
488
- // folder on the page's path that this restore creates. When the page's
489
- // folder already exists there is none, so a page with neighbours comes
490
- // back only into a new folder.
491
- /** @type {string | null} */
492
- let home = null;
493
- for (let d = anchor; !fs.existsSync(d) && path.dirname(d) !== d; d = path.dirname(d)) home = d;
494
- const within = (/** @type {string} */ file) => {
495
- if (!home) return false;
496
- const rel = path.relative(home, file);
497
- return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
498
- };
499
- const target = path.join(anchor, path.basename(requested));
500
- /** @type {{file: string, bytes: Buffer}[]} */
501
- const writes = [];
502
- const placed = new Set();
503
- /** @type {string[]} */
504
- const outside = [];
505
- /** @type {string[]} */
506
- const aliasedOutside = [];
507
- source.files.forEach((f, i) => {
508
- const reach = /** @type {import('../../foundation/render/embedded-imports.mjs').Reach} */ (reached.get(f.path));
509
- const relative = i === 0 ? [target] : reach.relative ? [placeFrom(f.path)] : [];
510
- for (const [file, aliased] of [...relative.map(x => /** @type {[string, boolean]} */ ([x, false])), ...[...reach.aliased].map(x => /** @type {[string, boolean]} */ ([x, true]))]) {
511
- if (placed.has(file)) continue;
512
- placed.add(file);
513
- if (i > 0 && !within(file)) (aliased ? aliasedOutside : outside).push(file);
514
- writes.push({file, bytes: Buffer.from(f.base64, 'base64')});
779
+ // Each file the page reaches by a relative import goes where that import
780
+ // finds it from the page's new folder, so every relative import still
781
+ // resolves wherever the page lands; a file reached through an alias goes
782
+ // where this project's alias points. Every file but the page must land
783
+ // in a folder this restore creates: a received file never adds a file to
784
+ // a folder that already exists (a server hook at the project root, a
785
+ // middleware module), so a page with neighbours comes back into a new
786
+ // folder.
787
+ const entryDir = path.posix.dirname(source.files[0].path);
788
+ const anchor = path.dirname(requested);
789
+ /** @param {string} p */
790
+ const placeFrom = p => path.resolve(anchor, path.posix.relative(entryDir, p));
791
+ // A file beside the page or elsewhere goes only into a folder this
792
+ // restore creates: never into a folder that already exists.
793
+ // The one folder every file but the page must land in: the topmost
794
+ // folder on the page's path that this restore creates. When the page's
795
+ // folder already exists there is none, so a page with neighbours comes
796
+ // back only into a new folder.
797
+ // Without --out, that is the folder this restore picked because no
798
+ // folder had its name: another run that takes the name first makes this
799
+ // one take the next.
800
+ const home = folder ?? newFolderOf(requested);
801
+ const within = (/** @type {string} */ file) => isInside(file, home);
802
+ const target = path.join(anchor, path.basename(requested));
803
+ /** @type {{file: string, bytes: Buffer}[]} */
804
+ const writes = [];
805
+ const placed = new Set();
806
+ /** @type {string[]} */
807
+ const outside = [];
808
+ /** @type {string[]} */
809
+ const aliasedOutside = [];
810
+ source.files.forEach((f, i) => {
811
+ const reach = /** @type {import('../../foundation/render/embedded-imports.mjs').Reach} */ (reached.get(f.path));
812
+ const relative = i === 0 ? [target] : reach.relative ? [placeFrom(f.path)] : [];
813
+ for (const [file, aliased] of [...relative.map(x => /** @type {[string, boolean]} */ ([x, false])), ...[...reach.aliased].map(x => /** @type {[string, boolean]} */ ([x, true]))]) {
814
+ if (placed.has(file)) continue;
815
+ placed.add(file);
816
+ // Every copy but the page at its target, the page's own copy that an
817
+ // alias places included, lands in the one new folder.
818
+ if (file !== target && !within(file)) (aliased ? aliasedOutside : outside).push(file);
819
+ writes.push({file, bytes: Buffer.from(f.base64, 'base64')});
820
+ }
821
+ });
822
+ if (aliasedOutside.length > 0) {
823
+ throw new AstryxError(
824
+ `${shown(cwd, input)} imports ${aliasedOutside.map(file => shown(cwd, file)).join(', ')} through a path alias that points outside the folder the restore creates; nothing was written. A received page never adds files to your existing folders: change those imports to relative ones before rendering, or restore it in a project whose alias points somewhere new.`,
825
+ [],
826
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
827
+ );
515
828
  }
516
- });
517
- if (aliasedOutside.length > 0) {
518
- throw new AstryxError(
519
- `${shown(cwd, input)} imports ${aliasedOutside.map(file => shown(cwd, file)).join(', ')} through a path alias that points outside the folder the restore creates; nothing was written. A received page never adds files to your existing folders: change those imports to relative ones before rendering, or restore it in a project whose alias points somewhere new.`,
520
- [],
521
- ERROR_CODES.ERR_PATH_TRAVERSAL,
522
- );
523
- }
524
- if (outside.length > 0) {
525
- const top = entryDir === '.' ? '' : `${entryDir}/`;
526
- let fresh = 'restored';
527
- for (let n = 2; fs.existsSync(path.join(cwd, fresh)); n++) fresh = `restored-${n}`;
528
- const suggestion = `--out ${fresh}/${top}${path.basename(requested)}`;
529
- throw new AstryxError(
530
- `${shown(cwd, input)} would add ${outside.map(file => shown(cwd, file)).join(', ')} outside the folder the restore creates; nothing was written. A received page writes the files it imports only inside one new folder: restore it into one, such as ${suggestion}.`,
531
- [{name: suggestion, reason: 'restore the page and the files it imports into a new folder, keeping their layout'}],
532
- ERROR_CODES.ERR_PATH_TRAVERSAL,
533
- );
829
+ if (outside.length > 0) {
830
+ const top = entryDir === '.' ? '' : `${entryDir}/`;
831
+ let fresh = 'restored';
832
+ for (let n = 2; fs.existsSync(path.join(cwd, fresh)); n++) fresh = `restored-${n}`;
833
+ const suggestion = `--out ${shellArg(`${fresh}/${top}${path.basename(requested)}`)}`;
834
+ throw new AstryxError(
835
+ `${shown(cwd, input)} would add ${outside.map(file => shown(cwd, file)).join(', ')} outside the folder the restore creates; nothing was written. A received page writes the files it imports only inside one new folder: restore it into one, such as ${suggestion}.`,
836
+ [{name: suggestion, reason: 'restore the page and the files it imports into a new folder, keeping their layout'}],
837
+ ERROR_CODES.ERR_PATH_TRAVERSAL,
838
+ );
839
+ }
840
+ writes.forEach((w, i) => confined(w.file, cwd, i === 0 ? 'The page' : 'The embedded file'));
841
+ refuseRunnable(writes.map(w => w.file), cwd, input);
842
+ refuseExisting(writes.filter(w => !isInside(w.file, home)).map(w => w.file));
843
+ refuseProtected(writes.map(w => w.file), cwd, home);
844
+ if (!writeRestore(writes, home, cwd, overwrite)) {
845
+ // Another run took the folder's name first: a restore without --out
846
+ // takes the next one.
847
+ if (output) throw folderTaken(/** @type {string} */ (home), cwd);
848
+ continue;
849
+ }
850
+ const renderedBy = renderedByOf(source, html);
851
+ const packages = packagesOf(source);
852
+ const modules = writes
853
+ .filter(w => PAGE_EXTENSIONS.includes(path.extname(w.file).toLowerCase()))
854
+ .map(w => ({file: shown(cwd, w.file), text: w.bytes.toString('utf8')}));
855
+ return {
856
+ input: shown(cwd, input),
857
+ mode: 'embedded',
858
+ output: shown(cwd, target),
859
+ files: writes.map(w => shown(cwd, w.file)),
860
+ // The page is byte for byte the one rendered; an import it makes that
861
+ // the file does not carry (a file a render never embeds) is named.
862
+ exact: missing.length === 0,
863
+ ...(missing.length > 0 ? {missing} : {}),
864
+ format: source.version,
865
+ ...(renderedBy ? {renderedBy} : {}),
866
+ ...(packages ? {packages} : {}),
867
+ ...(typeof source.title === 'string' ? {title: source.title} : {}),
868
+ ...pageChanges(source, html, modules),
869
+ };
534
870
  }
535
- writes.forEach((w, i) => confined(w.file, cwd, i === 0 ? 'The page' : 'The embedded file'));
536
- refuseRunnable(writes.map(w => w.file), cwd, input);
537
- refuseExisting(writes.map(w => w.file));
538
- refuseProtected(writes.map(w => w.file), cwd);
539
- writeAll(writes, cwd);
540
- return {
541
- input: shown(cwd, input),
542
- mode: 'embedded',
543
- output: shown(cwd, target),
544
- files: writes.map(w => shown(cwd, w.file)),
545
- // The page is byte for byte the one rendered; an import it makes that
546
- // the file does not carry (a file a render never embeds) is named.
547
- exact: missing.length === 0,
548
- ...(missing.length > 0 ? {missing} : {}),
549
- };
871
+ }
872
+ // A render always ends its file with `</html>`. A file a render wrote that
873
+ // has none lost its end on the way, the embedded source with it: the
874
+ // markup left is only part of the page.
875
+ if (rendered && !/<\/html>/i.test(html)) {
876
+ throw new AstryxError(
877
+ `${shown(cwd, input)} is cut short: it ends before its embedded source, so the page cannot be given back; nothing was written. Get the whole file again.`,
878
+ [],
879
+ ERROR_CODES.ERR_RENDER_SOURCE_DAMAGED,
880
+ );
550
881
  }
551
882
  // A file a render wrote, whose source block was taken out on the way
552
883
  // (sanitizers and editors strip <script> elements), says so.
553
- if (!isAstryxMarkup(html) && /<meta name="generator" content="Astryx[ "]/.test(html)) {
884
+ if (!isAstryxMarkup(html) && rendered) {
554
885
  throw new AstryxError(
555
886
  `${shown(cwd, input)} was rendered by Astryx, but its embedded source was removed (a sanitizer or an editor strips <script> blocks) and it has no Astryx components to rebuild from; nothing was written. Render the page again from its source and send the new file as is.`,
556
887
  [],
@@ -569,27 +900,35 @@ export function reverseToFile({cwd, input, output, overwrite}) {
569
900
  ERROR_CODES.ERR_RENDER_NOT_ASTRYX,
570
901
  );
571
902
  }
572
- const target = output ?? path.join(restoreFolder(input), 'page.tsx');
573
- refuseConfigTarget(target);
574
- confined(target, cwd, 'The page');
575
- refuseRunnable([target], cwd, input);
576
- refuseExisting([target]);
577
- // Components resolve from where the page will live, then from the HTML
578
- // file's folder, then from the current folder.
579
- const from =
580
- [path.dirname(target), path.dirname(input), cwd].find(d => resolvesCore(d)) ?? cwd;
581
- const rebuilt = rebuildPage(html, from);
582
- refuseProtected([target], cwd);
583
- writeOutput(target, rebuilt.source, cwd);
584
- return {
585
- input: shown(cwd, input),
586
- mode: 'rebuilt',
587
- output: shown(cwd, target),
588
- files: [shown(cwd, target)],
589
- exact: false,
590
- components: rebuilt.components,
591
- elements: rebuilt.elements,
592
- unknown: rebuilt.unknown,
593
- omitted: rebuilt.omitted,
594
- };
903
+ // As above: a name another run takes first exists from then on.
904
+ for (;;) {
905
+ const folder = output ? null : restoreFolder(input);
906
+ const target = output ?? path.join(/** @type {string} */ (folder), 'page.tsx');
907
+ const home = folder ?? newFolderOf(target);
908
+ refuseConfigTarget(target);
909
+ confined(target, cwd, 'The page');
910
+ refuseRunnable([target], cwd, input);
911
+ refuseExisting(isInside(target, home) ? [] : [target]);
912
+ // Components resolve from where the page will live, then from the HTML
913
+ // file's folder, then from the current folder.
914
+ const from =
915
+ [path.dirname(target), path.dirname(input), cwd].find(d => resolvesCore(d)) ?? cwd;
916
+ const rebuilt = rebuildPage(html, from);
917
+ refuseProtected([target], cwd, home);
918
+ if (!writeRestore([{file: target, bytes: Buffer.from(rebuilt.source)}], home, cwd, overwrite)) {
919
+ if (output) throw folderTaken(/** @type {string} */ (home), cwd);
920
+ continue;
921
+ }
922
+ return {
923
+ input: shown(cwd, input),
924
+ mode: 'rebuilt',
925
+ output: shown(cwd, target),
926
+ files: [shown(cwd, target)],
927
+ exact: false,
928
+ components: rebuilt.components,
929
+ elements: rebuilt.elements,
930
+ unknown: rebuilt.unknown,
931
+ omitted: rebuilt.omitted,
932
+ };
933
+ }
595
934
  }