@homepages/concrete 1.0.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 (327) hide show
  1. package/CHANGELOG.md +59 -0
  2. package/README.md +174 -0
  3. package/codemods/manifest.json +9 -0
  4. package/dist/artifact/playground/client/assets/index-BSA1yutg.css +1 -0
  5. package/dist/artifact/playground/client/assets/index-JloQyj8h.js +1101 -0
  6. package/dist/artifact/playground/client/index.html +13 -0
  7. package/dist/artifact/playground/client/island-canvas-host.mjs +1 -0
  8. package/dist/artifact/playground/host.mjs +127 -0
  9. package/dist/asset-modules.d.ts +99 -0
  10. package/dist/base.css +220 -0
  11. package/dist/browser/site-config.d.ts +18 -0
  12. package/dist/browser/site-config.js +56 -0
  13. package/dist/browser/submit-lead.d.ts +98 -0
  14. package/dist/browser/submit-lead.js +188 -0
  15. package/dist/browser.d.ts +3 -0
  16. package/dist/browser.js +4 -0
  17. package/dist/cli/build/artifact.js +225 -0
  18. package/dist/cli/build/captures.js +67 -0
  19. package/dist/cli/build/esbuild.js +127 -0
  20. package/dist/cli/build/fixtures.js +96 -0
  21. package/dist/cli/build/icons.js +76 -0
  22. package/dist/cli/build/index.js +38 -0
  23. package/dist/cli/build/playground.js +31 -0
  24. package/dist/cli/build/sections.js +236 -0
  25. package/dist/cli/build/source.js +62 -0
  26. package/dist/cli/build/static.js +156 -0
  27. package/dist/cli/capture/bundle.js +37 -0
  28. package/dist/cli/capture/capture-browser.js +51 -0
  29. package/dist/cli/capture/capture.js +121 -0
  30. package/dist/cli/check/analyze.js +95 -0
  31. package/dist/cli/check/index.js +19 -0
  32. package/dist/cli/check/load-workspace.js +119 -0
  33. package/dist/cli/check/messages.js +16 -0
  34. package/dist/cli/check/render/class-conflicts.js +39 -0
  35. package/dist/cli/check/render/html.js +86 -0
  36. package/dist/cli/check/render/inputs.js +53 -0
  37. package/dist/cli/check/render/invariants.js +58 -0
  38. package/dist/cli/check/render/island-frames.js +72 -0
  39. package/dist/cli/check/render/marker-coverage.js +102 -0
  40. package/dist/cli/check/render/nav.js +64 -0
  41. package/dist/cli/check/report.js +73 -0
  42. package/dist/cli/check/stages/bundles.js +129 -0
  43. package/dist/cli/check/stages/composition.js +67 -0
  44. package/dist/cli/check/stages/contracts.js +22 -0
  45. package/dist/cli/check/stages/dependencies.js +261 -0
  46. package/dist/cli/check/stages/fixtures.js +74 -0
  47. package/dist/cli/check/stages/lint.js +41 -0
  48. package/dist/cli/check/stages/logic.js +63 -0
  49. package/dist/cli/check/stages/render.js +144 -0
  50. package/dist/cli/check/stages/sections.js +83 -0
  51. package/dist/cli/check/stages/stylesheet.js +31 -0
  52. package/dist/cli/check/stages/typecheck.js +68 -0
  53. package/dist/cli/check/stages/workspace.js +26 -0
  54. package/dist/cli/commands.js +342 -0
  55. package/dist/cli/currency/cache.js +89 -0
  56. package/dist/cli/currency/decide.js +65 -0
  57. package/dist/cli/currency/opt-out.js +16 -0
  58. package/dist/cli/currency/preamble.js +183 -0
  59. package/dist/cli/currency/prompt.js +28 -0
  60. package/dist/cli/currency/refresh.js +44 -0
  61. package/dist/cli/currency/resolve-latest.js +185 -0
  62. package/dist/cli/currency/version-order.js +38 -0
  63. package/dist/cli/dev/crop.js +22 -0
  64. package/dist/cli/dev/hmr.js +26 -0
  65. package/dist/cli/dev/http.js +129 -0
  66. package/dist/cli/dev/index.js +70 -0
  67. package/dist/cli/dev/islands.js +390 -0
  68. package/dist/cli/dev/load-template.js +46 -0
  69. package/dist/cli/dev/request-error.js +22 -0
  70. package/dist/cli/dev/server.js +307 -0
  71. package/dist/cli/dev/tsconfig-paths.js +95 -0
  72. package/dist/cli/dev/vite.js +85 -0
  73. package/dist/cli/dev/workspace-reader.js +274 -0
  74. package/dist/cli/io.d.ts +14 -0
  75. package/dist/cli/media/cache.js +125 -0
  76. package/dist/cli/media/derive.js +252 -0
  77. package/dist/cli/media/deriver-plugin.js +71 -0
  78. package/dist/cli/property/index.js +180 -0
  79. package/dist/cli/property/library.js +137 -0
  80. package/dist/cli/publish/client.js +119 -0
  81. package/dist/cli/publish/freshness.js +66 -0
  82. package/dist/cli/publish/git.js +43 -0
  83. package/dist/cli/publish/index.js +207 -0
  84. package/dist/cli/publish/pack.js +78 -0
  85. package/dist/cli/publish/report.js +98 -0
  86. package/dist/cli/publish/target.js +87 -0
  87. package/dist/cli/publish/wire.js +29 -0
  88. package/dist/cli/tar.js +87 -0
  89. package/dist/cli/upgrade/codemod.js +56 -0
  90. package/dist/cli/upgrade/index.js +263 -0
  91. package/dist/cli/upgrade/manifest.js +72 -0
  92. package/dist/cli/upgrade/plan.js +68 -0
  93. package/dist/cli/upgrade/stage.js +71 -0
  94. package/dist/cli/version.d.ts +12 -0
  95. package/dist/cli/version.js +15 -0
  96. package/dist/cli/workspace.js +108 -0
  97. package/dist/cli.d.ts +6 -0
  98. package/dist/cli.js +94 -0
  99. package/dist/css/compile.js +77 -0
  100. package/dist/css/graph.js +109 -0
  101. package/dist/css/inline.js +132 -0
  102. package/dist/css/rules.js +65 -0
  103. package/dist/design-system/format-variants.js +127 -0
  104. package/dist/eslint/authoring.js +46 -0
  105. package/dist/eslint/correctness.js +42 -0
  106. package/dist/eslint/rules/editor-declaration.js +103 -0
  107. package/dist/eslint/rules/editor-reason.js +135 -0
  108. package/dist/eslint/rules/island-imports.js +20 -0
  109. package/dist/eslint/rules/jsx-visitor.js +20 -0
  110. package/dist/eslint/rules/no-client-runtime.js +88 -0
  111. package/dist/eslint/rules/no-editor-globals.js +60 -0
  112. package/dist/eslint/rules/no-hard-coded-color.js +183 -0
  113. package/dist/eslint/rules/no-inline-style.js +24 -0
  114. package/dist/eslint/rules/no-marker-literal.js +37 -0
  115. package/dist/eslint/rules/no-nondeterminism.js +44 -0
  116. package/dist/eslint/rules/no-px-breakpoint.js +44 -0
  117. package/dist/eslint/rules/no-raw-values.js +45 -0
  118. package/dist/eslint/rules/serializable-props.js +95 -0
  119. package/dist/eslint.d.ts +6 -0
  120. package/dist/eslint.js +26 -0
  121. package/dist/fixtures/brand.d.ts +4 -0
  122. package/dist/fixtures/brand.js +9 -0
  123. package/dist/fixtures/bundle-rule.js +67 -0
  124. package/dist/fixtures/canonical.d.ts +149 -0
  125. package/dist/fixtures/image-dimensions.js +59 -0
  126. package/dist/fixtures/load.js +154 -0
  127. package/dist/fixtures/media-plugin.js +141 -0
  128. package/dist/fixtures/media.js +165 -0
  129. package/dist/fixtures/property.js +210 -0
  130. package/dist/fixtures/resolve.js +202 -0
  131. package/dist/fixtures/rows.js +108 -0
  132. package/dist/fixtures/synthesize-empties.js +42 -0
  133. package/dist/fixtures.d.ts +213 -0
  134. package/dist/fixtures.js +37 -0
  135. package/dist/index.d.ts +53 -0
  136. package/dist/index.js +37 -0
  137. package/dist/islands/client-module.js +97 -0
  138. package/dist/islands/marker.d.ts +43 -0
  139. package/dist/islands/marker.js +44 -0
  140. package/dist/node_modules/.pnpm/fflate@0.8.3/node_modules/fflate/esm/browser.js +687 -0
  141. package/dist/packages/external/concrete/package.js +5 -0
  142. package/dist/packages/internal/fact-interpolation/dist/index.js +22 -0
  143. package/dist/packages/internal/fill-bake/dist/bake-property-ref.js +111 -0
  144. package/dist/packages/internal/fill-bake/dist/display.js +9 -0
  145. package/dist/packages/internal/fill-bake/dist/index.js +6 -0
  146. package/dist/packages/internal/fill-bake/dist/reconcile-cross-section.js +170 -0
  147. package/dist/packages/internal/fill-vocabulary/dist/facts.d.ts +32 -0
  148. package/dist/packages/internal/fill-vocabulary/dist/facts.js +131 -0
  149. package/dist/packages/internal/fill-vocabulary/dist/row-planners.js +73 -0
  150. package/dist/packages/internal/format-geometry/dist/capture.js +404 -0
  151. package/dist/packages/internal/format-geometry/dist/format.d.ts +41 -0
  152. package/dist/packages/internal/format-geometry/dist/geometry.js +58 -0
  153. package/dist/packages/internal/format-geometry/dist/index.js +4 -0
  154. package/dist/packages/internal/image-descriptor/dist/index.d.ts +35 -0
  155. package/dist/packages/internal/image-ladder/dist/crop.js +82 -0
  156. package/dist/packages/internal/image-ladder/dist/encode.js +23 -0
  157. package/dist/packages/internal/image-ladder/dist/index.js +4 -0
  158. package/dist/packages/internal/image-ladder/dist/policy.js +102 -0
  159. package/dist/packages/internal/island-runtime/dist/capture-holds.d.ts +13 -0
  160. package/dist/packages/internal/island-runtime/dist/capture-holds.js +45 -0
  161. package/dist/packages/internal/island-runtime/dist/contract.d.ts +176 -0
  162. package/dist/packages/internal/island-runtime/dist/contract.js +94 -0
  163. package/dist/packages/internal/island-runtime/dist/editor-instance-context.js +15 -0
  164. package/dist/packages/internal/island-runtime/dist/index.d.ts +103 -0
  165. package/dist/packages/internal/island-runtime/dist/index.js +163 -0
  166. package/dist/packages/internal/island-runtime/dist/use-capture-ready.d.ts +19 -0
  167. package/dist/packages/internal/island-runtime/dist/use-capture-ready.js +39 -0
  168. package/dist/packages/internal/island-runtime/dist/use-editor.d.ts +22 -0
  169. package/dist/packages/internal/island-runtime/dist/use-editor.js +54 -0
  170. package/dist/packages/internal/island-runtime/dist/viewport-schedule.js +105 -0
  171. package/dist/packages/internal/property-facts/dist/derive-facts-view.js +25 -0
  172. package/dist/packages/internal/property-facts/dist/index.js +3 -0
  173. package/dist/packages/internal/property-facts/dist/property-facts-CSdkSuD7.js +181 -0
  174. package/dist/packages/internal/section-contracts/dist/cap-contract.js +59 -0
  175. package/dist/packages/internal/section-contracts/dist/catalog.js +102 -0
  176. package/dist/packages/internal/section-contracts/dist/choose-select-contract.js +24 -0
  177. package/dist/packages/internal/section-contracts/dist/count-bounds-contract.js +48 -0
  178. package/dist/packages/internal/section-contracts/dist/display-contract.js +30 -0
  179. package/dist/packages/internal/section-contracts/dist/display-evidence-contract.js +17 -0
  180. package/dist/packages/internal/section-contracts/dist/group-contract.js +21 -0
  181. package/dist/packages/internal/section-contracts/dist/index.js +26 -0
  182. package/dist/packages/internal/section-contracts/dist/interpolation-contract.js +48 -0
  183. package/dist/packages/internal/section-contracts/dist/list-fill-contract.js +53 -0
  184. package/dist/packages/internal/section-contracts/dist/list-scalar-contract.js +70 -0
  185. package/dist/packages/internal/section-contracts/dist/name-title-contract.js +27 -0
  186. package/dist/packages/internal/section-contracts/dist/nested-slot-contract.js +12 -0
  187. package/dist/packages/internal/section-contracts/dist/option-source-contract.js +22 -0
  188. package/dist/packages/internal/section-contracts/dist/poi-curation-contract.js +18 -0
  189. package/dist/packages/internal/section-contracts/dist/pooling-field-contract.js +30 -0
  190. package/dist/packages/internal/section-contracts/dist/record-collection-contract.js +24 -0
  191. package/dist/packages/internal/section-contracts/dist/row-contract.js +37 -0
  192. package/dist/packages/internal/section-contracts/dist/row-fill-contract.js +38 -0
  193. package/dist/packages/internal/section-contracts/dist/runners.js +181 -0
  194. package/dist/packages/internal/section-contracts/dist/select-contract.js +28 -0
  195. package/dist/packages/internal/section-contracts/dist/source-contract.js +48 -0
  196. package/dist/packages/internal/section-contracts/dist/source-filter-contract.js +15 -0
  197. package/dist/packages/internal/section-contracts/dist/sources-contract.js +28 -0
  198. package/dist/packages/internal/section-contracts/dist/url-contract.js +20 -0
  199. package/dist/packages/internal/source-resolution/dist/index.js +222 -0
  200. package/dist/packages/internal/template-artifact/dist/hash.js +50 -0
  201. package/dist/packages/internal/template-artifact/dist/index.js +7 -0
  202. package/dist/packages/internal/template-artifact/dist/layout.js +165 -0
  203. package/dist/packages/internal/template-artifact/dist/manifest.js +73 -0
  204. package/dist/packages/internal/template-artifact/dist/sha256.js +138 -0
  205. package/dist/packages/internal/template-artifact/dist/verify.js +275 -0
  206. package/dist/packages/internal/template-contracts/dist/collection-editing.js +38 -0
  207. package/dist/packages/internal/template-contracts/dist/content-categories.d.ts +10 -0
  208. package/dist/packages/internal/template-contracts/dist/content-categories.js +17 -0
  209. package/dist/packages/internal/template-contracts/dist/document-value.d.ts +33 -0
  210. package/dist/packages/internal/template-contracts/dist/facts-view.d.ts +81 -0
  211. package/dist/packages/internal/template-contracts/dist/facts-view.js +136 -0
  212. package/dist/packages/internal/template-contracts/dist/layout.js +17 -0
  213. package/dist/packages/internal/template-contracts/dist/markers.d.ts +40 -0
  214. package/dist/packages/internal/template-contracts/dist/markers.js +41 -0
  215. package/dist/packages/internal/template-contracts/dist/poi-row.d.ts +63 -0
  216. package/dist/packages/internal/template-contracts/dist/select-key.js +13 -0
  217. package/dist/packages/internal/template-contracts/dist/slot-catalog.d.ts +1112 -0
  218. package/dist/packages/internal/template-contracts/dist/slot-catalog.js +1109 -0
  219. package/dist/packages/internal/template-contracts/dist/slot-overrides.js +11 -0
  220. package/dist/packages/internal/template-contracts/dist/tour-value.d.ts +45 -0
  221. package/dist/packages/internal/template-contracts/dist/video-value.d.ts +63 -0
  222. package/dist/playground/host/page-state.js +12 -0
  223. package/dist/playground/host/paths.js +9 -0
  224. package/dist/playground/layout.js +24 -0
  225. package/dist/playground/wire.js +36 -0
  226. package/dist/playground-island-runtime.d.ts +3 -0
  227. package/dist/playground-island-runtime.js +4 -0
  228. package/dist/primitives/FrameShell.d.ts +29 -0
  229. package/dist/primitives/FrameShell.js +34 -0
  230. package/dist/primitives/Image.d.ts +119 -0
  231. package/dist/primitives/Image.js +173 -0
  232. package/dist/primitives/Section.d.ts +22 -0
  233. package/dist/primitives/Section.js +26 -0
  234. package/dist/primitives/Tour.d.ts +43 -0
  235. package/dist/primitives/Tour.js +72 -0
  236. package/dist/primitives/Video.d.ts +57 -0
  237. package/dist/primitives/Video.js +116 -0
  238. package/dist/primitives/embed-playback.js +50 -0
  239. package/dist/primitives/index.d.ts +11 -0
  240. package/dist/primitives/marker-attrs.js +44 -0
  241. package/dist/primitives/object-fit.js +11 -0
  242. package/dist/primitives/picture-sources.d.ts +24 -0
  243. package/dist/primitives/picture-sources.js +52 -0
  244. package/dist/primitives/probe-context.js +24 -0
  245. package/dist/primitives/slot-bindings.d.ts +96 -0
  246. package/dist/primitives/slot-bindings.js +226 -0
  247. package/dist/primitives/slot-document.d.ts +35 -0
  248. package/dist/primitives/slot-document.js +37 -0
  249. package/dist/primitives/slot-group.d.ts +40 -0
  250. package/dist/primitives/slot-group.js +45 -0
  251. package/dist/primitives/slot-list.d.ts +21 -0
  252. package/dist/primitives/slot-list.js +23 -0
  253. package/dist/primitives/slot-media.d.ts +71 -0
  254. package/dist/primitives/slot-media.js +98 -0
  255. package/dist/primitives/slot-scalar.d.ts +53 -0
  256. package/dist/primitives/slot-scalar.js +98 -0
  257. package/dist/primitives/slot.d.ts +26 -0
  258. package/dist/primitives/slot.js +28 -0
  259. package/dist/rules/registry.js +479 -0
  260. package/dist/schema/compute.d.ts +22 -0
  261. package/dist/schema/compute.js +30 -0
  262. package/dist/schema/define-schema.d.ts +27 -0
  263. package/dist/schema/define-schema.js +73 -0
  264. package/dist/schema/extract-fill-spec.js +246 -0
  265. package/dist/schema/extract-used-facts.js +176 -0
  266. package/dist/schema/fact.d.ts +65 -0
  267. package/dist/schema/fact.js +33 -0
  268. package/dist/schema/fill-builders.d.ts +387 -0
  269. package/dist/schema/fill-builders.js +263 -0
  270. package/dist/schema/fill-declaration.d.ts +76 -0
  271. package/dist/schema/fill-declaration.js +43 -0
  272. package/dist/schema/fill-spec.d.ts +18 -0
  273. package/dist/schema/fill-spec.js +170 -0
  274. package/dist/schema/format-presets.d.ts +27 -0
  275. package/dist/schema/format-presets.js +76 -0
  276. package/dist/schema/format.d.ts +22 -0
  277. package/dist/schema/format.js +40 -0
  278. package/dist/schema/formats.d.ts +6 -0
  279. package/dist/schema/formats.js +7 -0
  280. package/dist/schema/layout.d.ts +32 -0
  281. package/dist/schema/layout.js +30 -0
  282. package/dist/schema/manifest.js +300 -0
  283. package/dist/schema/property-facts.d.ts +83 -0
  284. package/dist/schema/runtime-values.d.ts +88 -0
  285. package/dist/schema/section-nav.d.ts +38 -0
  286. package/dist/schema/section-nav.js +29 -0
  287. package/dist/schema/section-props.d.ts +98 -0
  288. package/dist/schema/section-schema.d.ts +53 -0
  289. package/dist/schema/section-schema.js +54 -0
  290. package/dist/schema/slot-builders.d.ts +497 -0
  291. package/dist/schema/slot-builders.js +331 -0
  292. package/dist/schema/slot-types.d.ts +110 -0
  293. package/dist/schema/slot-types.js +187 -0
  294. package/dist/section/declare.d.ts +44 -0
  295. package/dist/section/declare.js +27 -0
  296. package/dist/section/discovery.js +76 -0
  297. package/dist/section/groups.js +74 -0
  298. package/dist/section/materialize.js +28 -0
  299. package/dist/section/placements.js +28 -0
  300. package/dist/section/section.d.ts +69 -0
  301. package/dist/section/section.js +101 -0
  302. package/dist/site-analytics.d.ts +1 -0
  303. package/dist/site-analytics.js +15 -0
  304. package/dist/site-runtime/analytics.js +97 -0
  305. package/dist/site-runtime/site-integrations.js +97 -0
  306. package/dist/styles.css +60 -0
  307. package/dist/template/define-template.d.ts +139 -0
  308. package/dist/template/define-template.js +98 -0
  309. package/dist/template/logic-build.js +191 -0
  310. package/dist/template/logic-shim.d.ts +43 -0
  311. package/dist/template/logic-shim.js +52 -0
  312. package/dist/template/logic-transform.js +92 -0
  313. package/dist/template/materialize.js +107 -0
  314. package/dist/template/reconcile.d.ts +67 -0
  315. package/dist/template/reconcile.js +25 -0
  316. package/dist/template/running-copy.js +58 -0
  317. package/guide/reference/cli/INDEX.md +79 -0
  318. package/guide/reference/cli/build.md +48 -0
  319. package/guide/reference/cli/check.md +49 -0
  320. package/guide/reference/cli/dev.md +46 -0
  321. package/guide/reference/cli/property-add.md +53 -0
  322. package/guide/reference/cli/property-list.md +46 -0
  323. package/guide/reference/cli/publish.md +54 -0
  324. package/guide/reference/cli/upgrade.md +48 -0
  325. package/guide/reference/rules/INDEX.md +190 -0
  326. package/package.json +137 -0
  327. package/tsconfig.base.json +16 -0
@@ -0,0 +1,207 @@
1
+ import { DEFAULT_BUILD_DIR, booleanFlag, parseSpec } from "../commands.js";
2
+ import { formatHuman } from "../check/report.js";
3
+ import { findWorkspaceRoot } from "../workspace.js";
4
+ import { TERMINAL_STATES } from "./wire.js";
5
+ import { publicationClient } from "./client.js";
6
+ import { assessFreshness } from "./freshness.js";
7
+ import { readSourceFacts } from "./git.js";
8
+ import { packArtifact } from "./pack.js";
9
+ import { API_URL_VARIABLE, TOKEN_VARIABLE, TargetError, maskToken, resolveTarget } from "./target.js";
10
+ import { adoptText, builtText, freshnessText, refusalText, stageLine, summaryText, targetText, uploadText, writeText } from "./report.js";
11
+ import { join, resolve } from "node:path";
12
+ import { mkdtemp, rm, stat } from "node:fs/promises";
13
+ import { parseArgs } from "node:util";
14
+ import { tmpdir } from "node:os";
15
+
16
+ //#region src/cli/publish/index.ts
17
+ const EXIT_OK = 0;
18
+ const EXIT_REFUSED = 1;
19
+ const EXIT_USAGE = 2;
20
+ /** The record is read this often while a publication runs. */
21
+ const POLL_INTERVAL_MS = 2e3;
22
+ /** Consecutive unanswered polls before the endpoint counts as lost: a minute at the default interval. */
23
+ const POLL_FAILURES_TOLERATED = 30;
24
+ const DEFAULT_DEPS = {
25
+ build: async (options) => (await import("../build/artifact.js")).buildArtifact(options),
26
+ client: publicationClient,
27
+ sourceFacts: readSourceFacts,
28
+ sleep: (ms) => new Promise((done) => setTimeout(done, ms)),
29
+ now: () => /* @__PURE__ */ new Date(),
30
+ pollIntervalMs: POLL_INTERVAL_MS
31
+ };
32
+ /** A run that ends here: the exit code, and the sentence (with its newline) to print first. */
33
+ var Ending = class extends Error {
34
+ code;
35
+ sentence;
36
+ constructor(code, sentence) {
37
+ super(sentence);
38
+ this.code = code;
39
+ this.sentence = sentence;
40
+ }
41
+ };
42
+ const say = (sentence) => `concrete publish: ${sentence}\n`;
43
+ /** The ending an answer that is not `ok` calls for. */
44
+ function endingFor(answer, target, doing) {
45
+ switch (answer.kind) {
46
+ case "unreachable": return new Ending(EXIT_USAGE, say(`could not reach ${target.endpoint} while ${doing} (${answer.reason}); check the connection${target.overridden ? ` and ${API_URL_VARIABLE}` : ""}, then run again.`));
47
+ case "unexpected": return new Ending(EXIT_USAGE, say(`${target.endpoint} did not answer as the publication endpoint while ${doing} (${answer.reason}); ${target.overridden ? `check that ${API_URL_VARIABLE} names the HomePages API` : "run again, and report it if it repeats"}.`));
48
+ case "refused": {
49
+ if (answer.status === 401) return new Ending(EXIT_USAGE, say(`${target.endpoint} did not accept ${TOKEN_VARIABLE} (${maskToken(target.token)}): the key is unknown or revoked; ask a HomePages admin for a key.`));
50
+ const detail = answer.problem?.detail;
51
+ if (answer.problem?.code === "publisher_token_wrong_environment") return new Ending(EXIT_USAGE, say(detail ?? `${"CONCRETE_TOKEN"} is a key for another environment than ${target.endpoint} serves.`));
52
+ return new Ending(EXIT_REFUSED, say(detail ?? `${target.endpoint} refused the publication while ${doing} (HTTP ${String(answer.status)}); run again, and report it if it repeats.`));
53
+ }
54
+ }
55
+ }
56
+ function unwrap(answer, target, doing) {
57
+ if (answer.kind === "ok") return answer.value;
58
+ throw endingFor(answer, target, doing);
59
+ }
60
+ /** The artifact to publish: the one on disk when the tree still matches it, else a fresh build. */
61
+ async function ensureArtifact(run, root, out, rebuild) {
62
+ const { io, deps } = run;
63
+ const freshness = await assessFreshness({
64
+ root,
65
+ out,
66
+ rebuild
67
+ });
68
+ io.stderr.write(stageLine("build", freshnessText(freshness, deps.now())));
69
+ if (freshness.kind === "reuse") return freshness.manifest;
70
+ let outcome;
71
+ try {
72
+ outcome = await deps.build({
73
+ root,
74
+ out
75
+ });
76
+ } catch (cause) {
77
+ throw new Ending(EXIT_REFUSED, say(`the build failed: ${cause instanceof Error ? cause.message : String(cause)}`));
78
+ }
79
+ if (!outcome.ok) {
80
+ io.stderr.write(formatHuman(outcome.report));
81
+ throw new Ending(EXIT_REFUSED, say("check is not green, so nothing was built or published; fix the findings above and run again."));
82
+ }
83
+ io.stderr.write(stageLine("build", builtText(outcome.manifest)));
84
+ return outcome.manifest;
85
+ }
86
+ /** Follow the record to a terminal state, printing each stage as it settles. */
87
+ async function follow(run, client, target, first) {
88
+ const { io, deps } = run;
89
+ const printed = /* @__PURE__ */ new Set();
90
+ const print = (stage, text) => {
91
+ if (printed.has(stage)) return;
92
+ printed.add(stage);
93
+ io.stderr.write(stageLine(stage, text));
94
+ };
95
+ let record = first;
96
+ let failures = 0;
97
+ for (;;) {
98
+ const { state } = record;
99
+ if (state === "writing" || state === "adopting" || state === "published" || state === "dry_run") print("verify", "ok");
100
+ if (state === "adopting" || state === "published" || state === "dry_run") print("write", writeText(record));
101
+ if (state === "published") print("adopt", adoptText(record));
102
+ if (TERMINAL_STATES.includes(state)) {
103
+ if (state === "refused" || state === "failed") print([
104
+ "verify",
105
+ "write",
106
+ "adopt"
107
+ ].find((candidate) => !printed.has(candidate)) ?? "adopt", `${state}${record.refusal === null ? "" : ` (${record.refusal.code})`}`);
108
+ return record;
109
+ }
110
+ await deps.sleep(deps.pollIntervalMs);
111
+ const answer = await client.read(record.id);
112
+ if (answer.kind === "unreachable" && failures < POLL_FAILURES_TOLERATED) {
113
+ failures += 1;
114
+ continue;
115
+ }
116
+ if (answer.kind !== "ok") {
117
+ const ending = endingFor(answer, target, `following publication ${record.id}`);
118
+ throw new Ending(ending.code, `${ending.sentence.trimEnd()} The publication may still finish; a later run reports it already current if it did.\n`);
119
+ }
120
+ failures = 0;
121
+ record = answer.value;
122
+ }
123
+ }
124
+ async function publishWorkspace(run, root, target, rebuild) {
125
+ const { io, deps } = run;
126
+ io.stderr.write(stageLine("target", targetText(target)));
127
+ const out = resolve(root, DEFAULT_BUILD_DIR);
128
+ const manifest = await ensureArtifact(run, root, out, rebuild);
129
+ const scratch = await mkdtemp(join(tmpdir(), "concrete-publish-"));
130
+ try {
131
+ const tarball = join(scratch, "artifact.tar.gz");
132
+ await packArtifact(out, tarball);
133
+ const size = (await stat(tarball)).size;
134
+ const facts = await deps.sourceFacts(root);
135
+ const client = deps.client(target.endpoint, target.token);
136
+ const created = unwrap(await client.create({
137
+ key: manifest.key,
138
+ artifact_hash: manifest.template.content_hash,
139
+ artifact_schema: manifest.artifact_schema,
140
+ framework_version: manifest.framework_version,
141
+ scope: manifest.scope,
142
+ size_bytes: size,
143
+ source_digest: manifest.source_digest,
144
+ source_commit: facts.commit,
145
+ source_remote: facts.remote
146
+ }), target, "creating the publication");
147
+ unwrap(await client.upload(created.upload, tarball), target, "uploading the artifact");
148
+ io.stderr.write(stageLine("upload", uploadText(manifest, size, created.publication.publisher.name)));
149
+ const settled = await follow(run, client, target, unwrap(await client.submit(created.publication.id, run.dryRun ? { dry_run: true } : null), target, "submitting the publication").publication);
150
+ if (run.json) io.stdout.write(`${JSON.stringify(settled, null, 2)}\n`);
151
+ if (settled.state === "refused" || settled.state === "failed") {
152
+ io.stderr.write(refusalText(settled));
153
+ return EXIT_REFUSED;
154
+ }
155
+ if (settled.review_url !== null) io.stderr.write(stageLine("review", settled.review_url));
156
+ io.stderr.write(`${summaryText(settled)}\n`);
157
+ return EXIT_OK;
158
+ } finally {
159
+ await rm(scratch, {
160
+ recursive: true,
161
+ force: true
162
+ });
163
+ }
164
+ }
165
+ async function publish(argv, io, deps) {
166
+ let values;
167
+ try {
168
+ ({values} = parseArgs({
169
+ args: [...argv],
170
+ ...parseSpec("publish")
171
+ }));
172
+ } catch (cause) {
173
+ io.stderr.write(say(`${cause instanceof Error ? cause.message : String(cause)}; run \`concrete --help\` for the flags publish takes.`));
174
+ return EXIT_USAGE;
175
+ }
176
+ try {
177
+ let root;
178
+ try {
179
+ root = await findWorkspaceRoot(io.cwd);
180
+ } catch (cause) {
181
+ throw new Ending(EXIT_USAGE, say(cause instanceof Error ? cause.message : String(cause)));
182
+ }
183
+ let target;
184
+ try {
185
+ target = await resolveTarget(root, io.env);
186
+ } catch (cause) {
187
+ if (cause instanceof TargetError) throw new Ending(EXIT_USAGE, say(cause.message));
188
+ throw cause;
189
+ }
190
+ return await publishWorkspace({
191
+ io,
192
+ deps,
193
+ json: booleanFlag(values, "json"),
194
+ dryRun: booleanFlag(values, "dry-run")
195
+ }, root, target, booleanFlag(values, "rebuild"));
196
+ } catch (cause) {
197
+ if (cause instanceof Ending) {
198
+ io.stderr.write(cause.sentence);
199
+ return cause.code;
200
+ }
201
+ throw cause;
202
+ }
203
+ }
204
+ const runPublish = (argv, io) => publish(argv, io, DEFAULT_DEPS);
205
+
206
+ //#endregion
207
+ export { DEFAULT_DEPS, POLL_INTERVAL_MS, publish, runPublish };
@@ -0,0 +1,78 @@
1
+ import { createWriteStream } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { lstat, readFile, readdir } from "node:fs/promises";
4
+ import { createGzip } from "node:zlib";
5
+ import { Readable } from "node:stream";
6
+ import { pipeline } from "node:stream/promises";
7
+
8
+ //#region src/cli/publish/pack.ts
9
+ const BLOCK = 512;
10
+ const NAME_FIELD = 100;
11
+ async function listFiles(dir) {
12
+ const out = [];
13
+ const visit = async (relative) => {
14
+ const entries = await readdir(join(dir, relative), { withFileTypes: true });
15
+ for (const entry of entries) {
16
+ const path = relative === "" ? entry.name : `${relative}/${entry.name}`;
17
+ if (entry.isDirectory()) await visit(path);
18
+ else if (entry.isFile()) out.push(path);
19
+ else throw new Error(`The artifact holds ${path}, which is not a regular file; run \`concrete publish --rebuild\` to write a clean artifact.`);
20
+ }
21
+ };
22
+ if (!(await lstat(dir)).isDirectory()) throw new Error(`${dir} is not a directory.`);
23
+ await visit("");
24
+ return out.sort();
25
+ }
26
+ function octal(value, width) {
27
+ return `${value.toString(8).padStart(width - 1, "0")}\0`;
28
+ }
29
+ function header(name, size, type) {
30
+ const block = Buffer.alloc(BLOCK);
31
+ block.write(name, 0, NAME_FIELD, "utf8");
32
+ block.write(octal(420, 8), 100, "ascii");
33
+ block.write(octal(0, 8), 108, "ascii");
34
+ block.write(octal(0, 8), 116, "ascii");
35
+ block.write(octal(size, 12), 124, "ascii");
36
+ block.write(octal(0, 12), 136, "ascii");
37
+ block.write(" ", 148, "ascii");
38
+ block.write(type, 156, "ascii");
39
+ block.write("ustar\0", 257, "ascii");
40
+ block.write("00", 263, "ascii");
41
+ let sum = 0;
42
+ for (const byte of block) sum += byte;
43
+ block.write(`${sum.toString(8).padStart(6, "0")}\0 `, 148, "ascii");
44
+ return block;
45
+ }
46
+ const padding = (size) => Buffer.alloc((BLOCK - size % BLOCK) % BLOCK);
47
+ /** One pax record, `<length> path=<value>\n`, whose length counts its own digits. */
48
+ function paxRecord(path) {
49
+ const body = ` path=${path}\n`;
50
+ const bodyBytes = Buffer.byteLength(body, "utf8");
51
+ let length = bodyBytes + 1;
52
+ while (String(length).length + bodyBytes !== length) length = String(length).length + bodyBytes;
53
+ return Buffer.from(`${String(length)}${body}`, "utf8");
54
+ }
55
+ async function* entries(dir, paths) {
56
+ for (const path of paths) {
57
+ const body = await readFile(join(dir, ...path.split("/")));
58
+ if (Buffer.byteLength(path, "utf8") > NAME_FIELD) {
59
+ const record = paxRecord(path);
60
+ yield header("PaxHeader", record.length, "x");
61
+ yield record;
62
+ yield padding(record.length);
63
+ }
64
+ yield header(Buffer.from(path, "utf8").subarray(0, NAME_FIELD).toString("utf8"), body.length, "0");
65
+ yield body;
66
+ yield padding(body.length);
67
+ }
68
+ yield Buffer.alloc(BLOCK * 2);
69
+ }
70
+ /** Pack `dir` into a gzipped tar at `file`. */
71
+ async function packArtifact(dir, file) {
72
+ const paths = await listFiles(dir);
73
+ await pipeline(Readable.from(entries(dir, paths)), createGzip(), createWriteStream(file));
74
+ return { files: paths.length };
75
+ }
76
+
77
+ //#endregion
78
+ export { packArtifact };
@@ -0,0 +1,98 @@
1
+ import { maskToken } from "./target.js";
2
+
3
+ //#region src/cli/publish/report.ts
4
+ const LABEL_WIDTH = 9;
5
+ function stageLine(stage, text) {
6
+ return `${stage.padEnd(LABEL_WIDTH)}${text}\n`;
7
+ }
8
+ /** The first 12 characters of a content hash, as `concrete build` prints one. */
9
+ const shortHash = (hash) => hash.slice(0, 12);
10
+ function formatBytes(bytes) {
11
+ if (bytes < 1024) return `${String(bytes)} B`;
12
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
13
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
14
+ }
15
+ /** `just now`, `4m ago`, `3h ago`, `2 days ago`. */
16
+ function formatAge(then, now) {
17
+ const seconds = Math.max(0, Math.round((now.getTime() - then.getTime()) / 1e3));
18
+ if (seconds < 60) return "just now";
19
+ if (seconds < 3600) return `${String(Math.floor(seconds / 60))}m ago`;
20
+ if (seconds < 86400) return `${String(Math.floor(seconds / 3600))}h ago`;
21
+ const days = Math.floor(seconds / 86400);
22
+ return `${String(days)} ${days === 1 ? "day" : "days"} ago`;
23
+ }
24
+ const plural = (count, one, many) => `${String(count)} ${count === 1 ? one : many}`;
25
+ function targetText(target) {
26
+ return `${target.environmentName} · key ${maskToken(target.token)} · ${target.endpoint}${target.overridden ? " (CONCRETE_API_URL)" : ""}`;
27
+ }
28
+ /** The build line before any build runs: what the tree was compared to, and the decision. */
29
+ function freshnessText(freshness, now) {
30
+ if (freshness.kind === "reuse") return `tree matches artifact ${shortHash(freshness.manifest.template.content_hash)} (built ${formatAge(freshness.builtAt, now)}), reusing`;
31
+ const previous = freshness.previous === null ? "" : ` ${shortHash(freshness.previous.template.content_hash)}`;
32
+ switch (freshness.reason) {
33
+ case "forced": return "--rebuild, building";
34
+ case "missing": return "no artifact yet, building";
35
+ case "unreadable": return "the artifact on disk cannot be read, rebuilding";
36
+ case "framework": return `artifact${previous} was built by @homepages/concrete ${freshness.previous?.framework_version ?? "?"}, rebuilding`;
37
+ case "changed": return `tree changed since artifact${previous}, rebuilding`;
38
+ }
39
+ }
40
+ function builtText(manifest) {
41
+ return `built ${shortHash(manifest.template.content_hash)} · ${plural(manifest.sections.length, "section", "sections")}`;
42
+ }
43
+ function uploadText(manifest, bytes, publisher) {
44
+ return `${manifest.key} ${shortHash(manifest.template.content_hash)} · ${formatBytes(bytes)} · publisher "${publisher}"`;
45
+ }
46
+ function versionsOf(record) {
47
+ const entries = record.section_versions ?? {};
48
+ return {
49
+ template: entries[record.template_key],
50
+ sections: Object.entries(entries).filter(([key]) => key !== record.template_key).map(([, entry]) => entry)
51
+ };
52
+ }
53
+ /** Whether the write minted nothing and moved nothing: the environment already held this artifact as current. */
54
+ function isAlreadyCurrent(record) {
55
+ const { template, sections } = versionsOf(record);
56
+ return template !== void 0 && template.status === "unchanged" && !template.latest_moved && sections.every((entry) => entry.status === "unchanged" && !entry.latest_moved);
57
+ }
58
+ function sectionCounts(sections) {
59
+ const created = sections.filter((entry) => entry.status === "new").length;
60
+ return `sections: ${String(created)} new, ${String(sections.length - created)} unchanged`;
61
+ }
62
+ function writeText(record) {
63
+ const hash = shortHash(record.artifact_hash);
64
+ const { template, sections } = versionsOf(record);
65
+ if (record.state === "dry_run") {
66
+ if (template?.status === "new") return `would write template version ${hash} as new · ${sectionCounts(sections)}`;
67
+ return `would write nothing new · template version ${hash} already exists`;
68
+ }
69
+ if (isAlreadyCurrent(record)) return `already current · template version ${hash}`;
70
+ return `${template?.status === "new" ? `template version ${hash} is new` : template?.latest_moved === true ? `template version ${hash} is current again` : `template version ${hash} unchanged`} · ${sectionCounts(sections)}`;
71
+ }
72
+ function adoptText(record) {
73
+ const summary = record.adopt_summary;
74
+ if (summary === null) return "nothing reported";
75
+ const checked = plural(summary.scanned, "deliverable checked", "deliverables checked");
76
+ if (summary.enqueued === 0) return `no deliverable to move · ${checked}`;
77
+ return `${plural(summary.enqueued, "deliverable", "deliverables")} adopting this version · ${checked}`;
78
+ }
79
+ function summaryText(record) {
80
+ if (record.state === "dry_run") return `Dry run passed: ${record.template_key} verified, and nothing was written.`;
81
+ if (isAlreadyCurrent(record)) return `${record.template_key} is already current.`;
82
+ return `Published ${record.template_key}.`;
83
+ }
84
+ /** How many of a refusal's problems are listed before the rest are counted. */
85
+ const PROBLEMS_SHOWN = 20;
86
+ /** The refusal's sentence, then each problem the server named, indented. */
87
+ function refusalText(record) {
88
+ const refusal = record.refusal;
89
+ if (refusal === null) return `concrete publish: the publication ended ${record.state} without saying why; run \`concrete publish\` again.\n`;
90
+ const lines = [`concrete publish: ${refusal.detail}`];
91
+ const problems = refusal.problems ?? [];
92
+ for (const problem of problems.slice(0, PROBLEMS_SHOWN)) lines.push(` ${problem.path}: ${problem.message}`);
93
+ if (problems.length > PROBLEMS_SHOWN) lines.push(` …and ${String(problems.length - PROBLEMS_SHOWN)} more`);
94
+ return `${lines.join("\n")}\n`;
95
+ }
96
+
97
+ //#endregion
98
+ export { adoptText, builtText, formatAge, formatBytes, freshnessText, isAlreadyCurrent, refusalText, shortHash, stageLine, summaryText, targetText, uploadText, writeText };
@@ -0,0 +1,87 @@
1
+ import { join } from "node:path";
2
+ import { readFile } from "node:fs/promises";
3
+
4
+ //#region src/cli/publish/target.ts
5
+ const TOKEN_VARIABLE = "CONCRETE_TOKEN";
6
+ const API_URL_VARIABLE = "CONCRETE_API_URL";
7
+ /** The endpoint each key prefix publishes to. Changing it is a release of this package. */
8
+ const ENDPOINTS = {
9
+ prod: "https://api.homepages.io",
10
+ staging: "https://api.homepages.christmas",
11
+ dev: "http://localhost:8000"
12
+ };
13
+ const ENVIRONMENT_NAMES = {
14
+ prod: "production",
15
+ staging: "staging",
16
+ dev: "dev"
17
+ };
18
+ /** `cpt_<env>_` then a 43-character base62 secret: the shape a key is minted in. */
19
+ const TOKEN = /^cpt_(prod|staging|dev)_[0-9A-Za-z]{43}$/;
20
+ /** A key or endpoint this command cannot use: exit 2, with the sentence to print. */
21
+ var TargetError = class extends Error {};
22
+ /**
23
+ * The `KEY=value` pairs of a dotenv file: blank lines and `#` comments skipped, an
24
+ * optional `export ` prefix, one layer of matching quotes removed. No interpolation.
25
+ */
26
+ function parseDotenv(text) {
27
+ const values = /* @__PURE__ */ new Map();
28
+ for (const raw of text.split(/\r?\n/)) {
29
+ const line = raw.trim();
30
+ if (line === "" || line.startsWith("#")) continue;
31
+ const match = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
32
+ if (match === null) continue;
33
+ let value = match[2] ?? "";
34
+ const quote = value[0];
35
+ if ((quote === "\"" || quote === "'") && value.length >= 2 && value.endsWith(quote)) value = value.slice(1, -1);
36
+ else value = value.replace(/\s+#.*$/, "");
37
+ values.set(match[1] ?? "", value);
38
+ }
39
+ return values;
40
+ }
41
+ async function readWorkspaceDotenv(root) {
42
+ try {
43
+ return parseDotenv(await readFile(join(root, ".env"), "utf8"));
44
+ } catch (cause) {
45
+ if (cause.code === "ENOENT") return /* @__PURE__ */ new Map();
46
+ throw cause;
47
+ }
48
+ }
49
+ /** `cpt_prod_…a41c`: enough to tell two keys apart, never enough to use one. */
50
+ function maskToken(token) {
51
+ return `${/^cpt_[a-z]+_/.exec(token)?.[0] ?? ""}…${token.slice(-4)}`;
52
+ }
53
+ /** Resolve the target from the process environment, then the workspace `.env`. */
54
+ async function resolveTarget(root, env) {
55
+ const dotenv = await readWorkspaceDotenv(root);
56
+ const read = (name) => {
57
+ const value = env[name] ?? dotenv.get(name);
58
+ return value === void 0 || value.trim() === "" ? void 0 : value.trim();
59
+ };
60
+ const token = read(TOKEN_VARIABLE);
61
+ if (token === void 0) throw new TargetError(`${TOKEN_VARIABLE} is not set; set it in the environment or in this workspace's .env to the publisher key a HomePages admin issued you.`);
62
+ const match = TOKEN.exec(token);
63
+ if (match === null) throw new TargetError(`${TOKEN_VARIABLE} is not a publisher key (a key reads cpt_prod_…, cpt_staging_… or cpt_dev_… followed by 43 letters and digits); set it to the key a HomePages admin issued you.`);
64
+ const environment = match[1];
65
+ const override = read(API_URL_VARIABLE);
66
+ let endpoint = ENDPOINTS[environment];
67
+ if (override !== void 0) {
68
+ let url;
69
+ try {
70
+ url = new URL(override);
71
+ } catch {
72
+ throw new TargetError(`${API_URL_VARIABLE} is not a URL ("${override}"); set it to an API origin such as http://localhost:8000, or unset it.`);
73
+ }
74
+ if (url.protocol !== "http:" && url.protocol !== "https:") throw new TargetError(`${API_URL_VARIABLE} must be an http or https URL ("${override}"); set it to an API origin, or unset it.`);
75
+ endpoint = override;
76
+ }
77
+ return {
78
+ environment,
79
+ environmentName: ENVIRONMENT_NAMES[environment],
80
+ token,
81
+ endpoint: endpoint.replace(/\/+$/, ""),
82
+ overridden: override !== void 0
83
+ };
84
+ }
85
+
86
+ //#endregion
87
+ export { API_URL_VARIABLE, ENDPOINTS, TOKEN_VARIABLE, TargetError, maskToken, parseDotenv, resolveTarget };
@@ -0,0 +1,29 @@
1
+ //#region src/cli/publish/wire.ts
2
+ /** The states a poll stops at. */
3
+ const TERMINAL_STATES = [
4
+ "published",
5
+ "refused",
6
+ "failed",
7
+ "dry_run"
8
+ ];
9
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
10
+ /**
11
+ * Whether a body is a publication record, to the depth this command reads one. The
12
+ * endpoint's own schema is the contract; this only keeps a proxy's HTML page or an
13
+ * unrelated JSON body from being read as one.
14
+ */
15
+ function isPublicationRecord(value) {
16
+ return isObject(value) && typeof value.id === "string" && typeof value.state === "string" && typeof value.template_key === "string" && isObject(value.publisher) && typeof value.publisher.name === "string";
17
+ }
18
+ function isCreateResponse(value) {
19
+ return isObject(value) && isPublicationRecord(value.publication) && isObject(value.upload) && typeof value.upload.url === "string" && isObject(value.upload.headers);
20
+ }
21
+ function isSubmitResponse(value) {
22
+ return isObject(value) && isPublicationRecord(value.publication);
23
+ }
24
+ function asProblem(value) {
25
+ return isObject(value) && (typeof value.detail === "string" || typeof value.code === "string") ? value : null;
26
+ }
27
+
28
+ //#endregion
29
+ export { TERMINAL_STATES, asProblem, isCreateResponse, isPublicationRecord, isSubmitResponse };
@@ -0,0 +1,87 @@
1
+ import { posix } from "node:path";
2
+ import { gunzipSync } from "node:zlib";
3
+
4
+ //#region src/cli/tar.ts
5
+ const BLOCK = 512;
6
+ /** A NUL-terminated header field. */
7
+ function field(bytes, offset, length) {
8
+ const raw = bytes.subarray(offset, offset + length);
9
+ const end = raw.indexOf(0);
10
+ return raw.subarray(0, end === -1 ? raw.length : end).toString("utf8");
11
+ }
12
+ function octal(header, offset, length) {
13
+ const digits = field(header, offset, length).trim();
14
+ const value = digits === "" ? 0 : Number.parseInt(digits, 8);
15
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error("the tarball has an entry whose size cannot be read");
16
+ return value;
17
+ }
18
+ /** A pax extended header's `path` record, if it carries one. Each record is `<len> <key>=<value>\n`. */
19
+ function paxPath(body) {
20
+ let found;
21
+ let offset = 0;
22
+ while (offset < body.length) {
23
+ const space = body.indexOf(32, offset);
24
+ if (space === -1) break;
25
+ const length = Number.parseInt(body.subarray(offset, space).toString("utf8"), 10);
26
+ if (!Number.isSafeInteger(length) || length <= space - offset) break;
27
+ const record = body.subarray(space + 1, offset + length - 1).toString("utf8");
28
+ const equals = record.indexOf("=");
29
+ if (equals !== -1 && record.slice(0, equals) === "path") found = record.slice(equals + 1);
30
+ offset += length;
31
+ }
32
+ return found;
33
+ }
34
+ /** `package/properties/x` → `properties/x`; `null` for the top directory itself. */
35
+ function withinPackage(path) {
36
+ const unsafe = () => /* @__PURE__ */ new Error(`the tarball has an entry outside its package directory: ${path}`);
37
+ if (path.startsWith("/") || path.includes("\\") || /^[A-Za-z]:/.test(path)) throw unsafe();
38
+ const slash = path.indexOf("/");
39
+ if (slash === -1) return null;
40
+ const relative = posix.normalize(path.slice(slash + 1));
41
+ if (relative === "." || relative === "") return null;
42
+ if (relative === ".." || relative.startsWith("../")) throw unsafe();
43
+ return relative.endsWith("/") ? relative.slice(0, -1) : relative;
44
+ }
45
+ /**
46
+ * Every regular file in a gzipped npm tarball, top-level directory stripped, in archive
47
+ * order. Throws on anything that is not one: bad gzip, a truncated entry, an escaping path.
48
+ */
49
+ function readTarball(gzipped) {
50
+ const archive = gunzipSync(gzipped);
51
+ const files = [];
52
+ let longPath;
53
+ let offset = 0;
54
+ while (offset + BLOCK <= archive.length) {
55
+ const header = archive.subarray(offset, offset + BLOCK);
56
+ if (header.every((byte) => byte === 0)) break;
57
+ const size = octal(header, 124, 12);
58
+ const type = String.fromCharCode(header[156] ?? 0);
59
+ const start = offset + BLOCK;
60
+ if (start + size > archive.length) throw new Error("the tarball ends inside an entry");
61
+ const body = archive.subarray(start, start + size);
62
+ offset = start + Math.ceil(size / BLOCK) * BLOCK;
63
+ if (type === "x") {
64
+ longPath = paxPath(body) ?? longPath;
65
+ continue;
66
+ }
67
+ if (type === "L") {
68
+ longPath = field(body, 0, body.length);
69
+ continue;
70
+ }
71
+ if (type === "g") continue;
72
+ const name = field(header, 0, 100);
73
+ const prefix = field(header, 257, 6).startsWith("ustar") ? field(header, 345, 155) : "";
74
+ const path = longPath ?? (prefix === "" ? name : `${prefix}/${name}`);
75
+ longPath = void 0;
76
+ if (type !== "0" && type !== "\0" && type !== "7") continue;
77
+ const relative = withinPackage(path);
78
+ if (relative !== null) files.push({
79
+ path: relative,
80
+ body: Buffer.from(body)
81
+ });
82
+ }
83
+ return files;
84
+ }
85
+
86
+ //#endregion
87
+ export { readTarball };
@@ -0,0 +1,56 @@
1
+ import { CODEMODS_DIR } from "./manifest.js";
2
+ import { join } from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { stat } from "node:fs/promises";
5
+ import { z } from "zod";
6
+
7
+ //#region src/cli/upgrade/codemod.ts
8
+ const REPORT_SCHEMA = z.object({
9
+ rewritten: z.array(z.string()),
10
+ notRewritten: z.array(z.object({
11
+ file: z.string(),
12
+ reason: z.string()
13
+ }))
14
+ });
15
+ /** `codemods/<slug>.mjs` under a package directory. */
16
+ function codemodPath(packageDir, slug) {
17
+ return join(packageDir, CODEMODS_DIR, `${slug}.mjs`);
18
+ }
19
+ function messageOf(cause) {
20
+ return cause instanceof Error ? cause.message : String(cause);
21
+ }
22
+ /**
23
+ * Runs the codemod `slug` shipped in `packageDir` over the workspace at `root`.
24
+ *
25
+ * Throws, with a sentence naming the codemod, when the file is missing, has no function
26
+ * as its default export, throws itself, or returns something that is not a report. The
27
+ * caller decides what a throw means; nothing here catches one silently.
28
+ */
29
+ async function runCodemod(packageDir, slug, root) {
30
+ const file = codemodPath(packageDir, slug);
31
+ try {
32
+ await stat(file);
33
+ } catch {
34
+ throw new Error(`${slug}: the package lists this codemod but does not carry ${CODEMODS_DIR}/${slug}.mjs`);
35
+ }
36
+ let loaded;
37
+ try {
38
+ loaded = await import(pathToFileURL(file).href);
39
+ } catch (cause) {
40
+ throw new Error(`${slug}: could not be loaded (${messageOf(cause)})`, { cause });
41
+ }
42
+ const codemod = loaded.default;
43
+ if (typeof codemod !== "function") throw new Error(`${slug}: its default export is not a function`);
44
+ let returned;
45
+ try {
46
+ returned = await codemod(root);
47
+ } catch (cause) {
48
+ throw new Error(`${slug}: ${messageOf(cause)}`, { cause });
49
+ }
50
+ const parsed = REPORT_SCHEMA.safeParse(returned);
51
+ if (!parsed.success) throw new Error(`${slug}: returned something that is not a report ({ rewritten, notRewritten })`);
52
+ return parsed.data;
53
+ }
54
+
55
+ //#endregion
56
+ export { codemodPath, runCodemod };