@fluid-app/fluid-cli-theme-dev 0.1.659 → 0.1.661

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.
package/dist/index.mjs CHANGED
@@ -1,10 +1,12 @@
1
1
  import { createRequire } from "node:module";
2
2
  import { Command, InvalidArgumentError, Option } from "commander";
3
- import prompts from "prompts";
4
- import { getAuthToken, gitSyncActorFromMe, gitSyncCommitSubject, readConfig, resolveGitSyncActor, summarizeChanges, updateConfig } from "@fluid-app/fluid-cli";
5
- import { setTimeout as setTimeout$1 } from "node:timers/promises";
6
3
  import { cpSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from "node:fs";
4
+ import { execFileSync, spawn } from "node:child_process";
7
5
  import { basename, dirname, extname, isAbsolute, join, posix, relative, resolve, sep } from "node:path";
6
+ import * as core from "@fluid-app/fluid-cli";
7
+ import { declareInputs, getAuthToken, gitSyncActorFromMe, gitSyncCommitSubject, readConfig, resolveGitSyncActor, summarizeChanges, updateConfig } from "@fluid-app/fluid-cli";
8
+ import prompts from "prompts";
9
+ import { setTimeout as setTimeout$1 } from "node:timers/promises";
8
10
  import { createHash, randomBytes, randomUUID } from "node:crypto";
9
11
  import http from "node:http";
10
12
  import { fileURLToPath, pathToFileURL } from "node:url";
@@ -12,7 +14,6 @@ import { parse, parseFragment, serialize } from "parse5";
12
14
  import https from "node:https";
13
15
  import chokidar from "chokidar";
14
16
  import net, { isIP } from "node:net";
15
- import { execFileSync, spawn } from "node:child_process";
16
17
  import { tmpdir } from "node:os";
17
18
  import chalk from "chalk";
18
19
  import ora from "ora";
@@ -22,6 +23,140 @@ import { z } from "zod";
22
23
  import { mkdir, readFile, readdir, realpath, stat, unlink, writeFile } from "node:fs/promises";
23
24
  import jpeg from "jpeg-js";
24
25
  import { PNG } from "pngjs";
26
+ //#region src/inputs.ts
27
+ const SHADOW_HEAD_REF = "theme-shadow-head";
28
+ const THEME_CONFIG_FILES = [
29
+ ".fluid-theme.json",
30
+ ".fluid-assets.json",
31
+ ".fluidignore",
32
+ join(".fluid-theme", "theme-id"),
33
+ join(".fluid-theme", "dev-baseline.json")
34
+ ];
35
+ /** A file's live bytes no longer match what this run approved or uploaded. */
36
+ var ChangedSinceApprovalError = class extends Error {
37
+ constructor(path) {
38
+ super(`${path}: changed since approval; kept the local bytes`);
39
+ this.name = "ChangedSinceApprovalError";
40
+ }
41
+ };
42
+ let current = null;
43
+ const touched = /* @__PURE__ */ new Set();
44
+ function unboundAsync(fn) {
45
+ return core.withInternalReadsAsync(fn);
46
+ }
47
+ /** Runs a read the command does not declare as an input (credentials, probes). */
48
+ function unbound(fn) {
49
+ return core.withInternalReads(fn);
50
+ }
51
+ /** Binds the declared-input reader the theme commands read through. */
52
+ function useInputs(inputs) {
53
+ current = inputs ?? null;
54
+ }
55
+ function inputsBound() {
56
+ return current != null;
57
+ }
58
+ /** True once an approved snapshot is serving this command's reads. */
59
+ function expecting() {
60
+ return current?.isExpecting() ?? false;
61
+ }
62
+ /** The shadow HEAD sha approved for this run; undefined outside expect mode. */
63
+ function approvedShadowHead() {
64
+ const value = current?.ref(SHADOW_HEAD_REF);
65
+ return value === void 0 ? void 0 : value === "none" ? null : value;
66
+ }
67
+ /**
68
+ * Records a path the CLI itself wrote or removed, so later reads of it see
69
+ * that write instead of the approved snapshot.
70
+ */
71
+ function markTouched(path) {
72
+ touched.add(resolve(path));
73
+ }
74
+ function isTouched(path) {
75
+ return touched.has(resolve(path));
76
+ }
77
+ function inputTree(root) {
78
+ if (!current) throw new Error("No command inputs are bound");
79
+ return current.tree(root, {
80
+ ignore: TREE_IGNORE,
81
+ skipDotNames: true
82
+ });
83
+ }
84
+ function isMissing(error, path) {
85
+ if (error.code === "ENOENT") return true;
86
+ if (error.name !== "InputsUndeclaredError") return false;
87
+ return !unbound(() => existsSync(path));
88
+ }
89
+ /**
90
+ * Reads a config-kind file: the approved snapshot in expect mode (unless the
91
+ * CLI has since written it), the disk otherwise. Returns null when the file
92
+ * is absent; throws when it was absent at approval but exists now.
93
+ */
94
+ function readInput(input) {
95
+ const path = resolve(input);
96
+ try {
97
+ if (current && expecting() && !isTouched(path)) return current.readFile(path);
98
+ return expecting() ? unbound(() => readFileSync(path)) : readFileSync(path);
99
+ } catch (error) {
100
+ if (isMissing(error, path)) return null;
101
+ throw error;
102
+ }
103
+ }
104
+ function readInputText(path) {
105
+ return readInput(path)?.toString("utf-8") ?? null;
106
+ }
107
+ function bindingRoot(root) {
108
+ return resolve(root);
109
+ }
110
+ const TREE_IGNORE = ["node_modules"];
111
+ function shadowHead(root) {
112
+ try {
113
+ return execFileSync("git", [
114
+ "--git-dir",
115
+ join(root, ".fluid-theme", "repo"),
116
+ "rev-parse",
117
+ "--verify",
118
+ "HEAD"
119
+ ], { stdio: [
120
+ "ignore",
121
+ "pipe",
122
+ "ignore"
123
+ ] }).toString("utf-8").trim();
124
+ } catch {
125
+ return "none";
126
+ }
127
+ }
128
+ /**
129
+ * The input specs for a theme command rooted at `root`: the theme tree, the
130
+ * config files that exist beside it, and the shadow HEAD.
131
+ */
132
+ function themeInputSpecs(rootPath, options) {
133
+ const root = bindingRoot(rootPath);
134
+ const specs = [];
135
+ if (options.workspaceFile) specs.push({
136
+ kind: "config",
137
+ path: options.workspaceFile
138
+ });
139
+ if (options.tree) specs.push({
140
+ kind: "tree",
141
+ path: root,
142
+ ignore: TREE_IGNORE,
143
+ skipDotNames: true
144
+ });
145
+ for (const file of options.files ?? THEME_CONFIG_FILES) {
146
+ const path = join(root, file);
147
+ if (existsSync(path)) specs.push({
148
+ kind: "config",
149
+ path
150
+ });
151
+ }
152
+ if (options.shadow) specs.push({
153
+ kind: "ref",
154
+ name: SHADOW_HEAD_REF,
155
+ value: shadowHead(root)
156
+ });
157
+ return specs;
158
+ }
159
+ //#endregion
25
160
  //#region ../../platform/api-client-core/src/api-error-shape.ts
26
161
  /**
27
162
  * Narrows a parsed JSON error payload to the envelope contract. Arrays and
@@ -346,6 +481,9 @@ function createFetchClient(config) {
346
481
  }
347
482
  //#endregion
348
483
  //#region src/api.ts
484
+ function getAuthToken$1() {
485
+ return unbound(() => getAuthToken());
486
+ }
349
487
  /** Base URL for all API calls. Set FLUID_API_BASE to route through a BFF. */
350
488
  function getApiBase() {
351
489
  return process.env["FLUID_API_BASE"] ?? "https://api.fluid.app";
@@ -354,12 +492,12 @@ let backgroundGate = Promise.resolve();
354
492
  async function backgroundToken(tokenOverride) {
355
493
  backgroundGate = backgroundGate.then(() => new Promise((resolve) => setTimeout(resolve, 1e3)));
356
494
  await backgroundGate;
357
- return tokenOverride ?? getAuthToken() ?? null;
495
+ return tokenOverride ?? getAuthToken$1() ?? null;
358
496
  }
359
497
  function createApiClient(tokenOverride) {
360
498
  const client = createFetchClient({
361
499
  baseUrl: getApiBase(),
362
- getAuthToken: () => process.env["FLUID_BACKGROUND_SYNC"] === "1" ? backgroundToken(tokenOverride) : tokenOverride ?? getAuthToken() ?? null
500
+ getAuthToken: () => process.env["FLUID_BACKGROUND_SYNC"] === "1" ? backgroundToken(tokenOverride) : tokenOverride ?? getAuthToken$1() ?? null
363
501
  });
364
502
  const request = async (endpoint, options = {}) => {
365
503
  for (let attempt = 0;; attempt++) {
@@ -387,7 +525,7 @@ function createApiClient(tokenOverride) {
387
525
  };
388
526
  }
389
527
  function requireToken() {
390
- const token = getAuthToken();
528
+ const token = getAuthToken$1();
391
529
  if (!token) {
392
530
  console.error("Not logged in. Run `fluid login` first.");
393
531
  process.exit(1);
@@ -430,6 +568,9 @@ function devThemeKey(company, themeRoot) {
430
568
  * the legacy fields so a second project can't adopt the same theme and collide.
431
569
  */
432
570
  function getDevTheme(key) {
571
+ return unbound(() => readDevTheme(key));
572
+ }
573
+ function readDevTheme(key) {
433
574
  const state = getState();
434
575
  const existing = state.devThemes?.[key];
435
576
  if (existing) return existing;
@@ -1030,10 +1171,9 @@ function configPath(themeRoot) {
1030
1171
  }
1031
1172
  /** Read `.fluid-theme.json` from a theme directory, or null if it doesn't exist. */
1032
1173
  function readThemeConfig(themeRoot) {
1033
- const path = configPath(themeRoot);
1034
- if (!existsSync(path)) return null;
1035
1174
  try {
1036
- const raw = readFileSync(path, "utf-8");
1175
+ const raw = readInputText(configPath(themeRoot));
1176
+ if (raw === null) return null;
1037
1177
  const config = JSON.parse(raw);
1038
1178
  if (typeof config.company === "string") config.company = normalizeCompany(config.company);
1039
1179
  return config;
@@ -1047,10 +1187,9 @@ function readThemeConfig(themeRoot) {
1047
1187
  * local content still matches their stored sha256 checksum.
1048
1188
  */
1049
1189
  function readLegacyThemeConfig(themeRoot) {
1050
- const path = configPath(themeRoot);
1051
- if (!existsSync(path)) return null;
1052
1190
  try {
1053
- const raw = readFileSync(path, "utf-8");
1191
+ const raw = readInputText(configPath(themeRoot));
1192
+ if (raw === null) return null;
1054
1193
  return JSON.parse(raw);
1055
1194
  } catch {
1056
1195
  return null;
@@ -1075,7 +1214,9 @@ function developmentThemeRefusal(existing, theme) {
1075
1214
  }
1076
1215
  /** Write `.fluid-theme.json` to a theme directory. */
1077
1216
  function writeThemeConfig(themeRoot, config) {
1078
- writeFileSync(configPath(themeRoot), JSON.stringify(config, null, 2) + "\n", "utf-8");
1217
+ const path = configPath(themeRoot);
1218
+ markTouched(path);
1219
+ writeFileSync(path, JSON.stringify(config, null, 2) + "\n", "utf-8");
1079
1220
  }
1080
1221
  //#endregion
1081
1222
  //#region src/theme/mime-type.ts
@@ -1997,7 +2138,10 @@ var ThemeFile = class {
1997
2138
  absolutePath;
1998
2139
  relativePath;
1999
2140
  mime;
2000
- constructor(absolutePath, root) {
2141
+ treePath;
2142
+ constructor(absolutePath, root, source) {
2143
+ this.source = source;
2144
+ this.treePath = relative(root, absolutePath).split(sep).join("/");
2001
2145
  this.absolutePath = absolutePath;
2002
2146
  this.relativePath = normalizeThemeResourceKey(relative(root, absolutePath));
2003
2147
  this.mime = mimeTypeFor(extname(absolutePath).toLowerCase());
@@ -2014,16 +2158,52 @@ var ThemeFile = class {
2014
2158
  get isJson() {
2015
2159
  return this.absolutePath.endsWith(".json");
2016
2160
  }
2161
+ get snapshotted() {
2162
+ return this.source && !isTouched(this.absolutePath) ? this.source : void 0;
2163
+ }
2017
2164
  get exists() {
2018
- return existsSync(this.absolutePath);
2165
+ const source = this.snapshotted;
2166
+ if (source) return source.has(this.treePath);
2167
+ return this.source ? unbound(() => existsSync(this.absolutePath)) : existsSync(this.absolutePath);
2019
2168
  }
2020
2169
  read() {
2021
- return readFileSync(this.absolutePath, "utf-8");
2170
+ return this.readBinary().toString("utf-8");
2022
2171
  }
2023
2172
  readBinary() {
2024
- return readFileSync(this.absolutePath);
2173
+ const source = this.snapshotted;
2174
+ if (source) {
2175
+ if (!source.has(this.treePath)) throw Object.assign(/* @__PURE__ */ new Error(`ENOENT: no such file, open '${this.absolutePath}'`), { code: "ENOENT" });
2176
+ return source.read(this.treePath);
2177
+ }
2178
+ return this.source ? unbound(() => readFileSync(this.absolutePath)) : readFileSync(this.absolutePath);
2179
+ }
2180
+ /** The file's bytes, or null when it does not exist. */
2181
+ readIfExists() {
2182
+ try {
2183
+ return this.readBinary();
2184
+ } catch {
2185
+ return null;
2186
+ }
2187
+ }
2188
+ /**
2189
+ * Throws ChangedSinceApprovalError unless the live bytes still equal
2190
+ * `expected` (null means the file must be absent).
2191
+ */
2192
+ assertUnchanged(expected) {
2193
+ let live;
2194
+ try {
2195
+ live = unbound(() => readFileSync(this.absolutePath));
2196
+ } catch {
2197
+ live = null;
2198
+ }
2199
+ if (!(expected === null || live === null ? expected === live : expected.equals(live))) throw new ChangedSinceApprovalError(this.absolutePath);
2200
+ }
2201
+ remove() {
2202
+ unlinkSync(this.absolutePath);
2203
+ markTouched(this.absolutePath);
2025
2204
  }
2026
2205
  write(content) {
2206
+ markTouched(this.absolutePath);
2027
2207
  mkdirSync(dirname(this.absolutePath), { recursive: true });
2028
2208
  if (typeof content === "string") writeFileSync(this.absolutePath, content, "utf-8");
2029
2209
  else writeFileSync(this.absolutePath, content);
@@ -2033,7 +2213,8 @@ var ThemeFile = class {
2033
2213
  return createHash("sha256").update(content).digest("hex");
2034
2214
  }
2035
2215
  size() {
2036
- return statSync(this.absolutePath).size;
2216
+ if (this.snapshotted) return this.readBinary().length;
2217
+ return this.source ? unbound(() => statSync(this.absolutePath).size) : statSync(this.absolutePath).size;
2037
2218
  }
2038
2219
  get isTemplate() {
2039
2220
  const parts = this.relativePath.split(/[/\\]/);
@@ -2059,8 +2240,7 @@ var FluidIgnore = class {
2059
2240
  return result;
2060
2241
  }
2061
2242
  parse(filePath) {
2062
- if (!existsSync(filePath)) return [];
2063
- return readFileSync(filePath, "utf-8").split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#")).map((l) => {
2243
+ return (readInputText(filePath) ?? "").split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("#")).map((l) => {
2064
2244
  const negated = l.startsWith("!");
2065
2245
  let pattern = negated ? l.slice(1) : l;
2066
2246
  if (pattern.startsWith("/")) pattern = pattern.slice(1);
@@ -2096,6 +2276,9 @@ var ThemeRoot = class {
2096
2276
  this.ignore = new FluidIgnore(this.root);
2097
2277
  }
2098
2278
  isValid() {
2279
+ return unbound(() => this.looksValid());
2280
+ }
2281
+ looksValid() {
2099
2282
  return existsSync(join(this.root, THEME_ASSET_MANIFEST)) || THEME_MARKERS.some((m) => {
2100
2283
  try {
2101
2284
  return statSync(join(this.root, m)).isDirectory();
@@ -2128,9 +2311,29 @@ var ThemeRoot = class {
2128
2311
  }
2129
2312
  file(pathOrFile) {
2130
2313
  if (pathOrFile instanceof ThemeFile) return pathOrFile;
2131
- return new ThemeFile(isAbsolute(pathOrFile) ? pathOrFile : join(this.root, pathOrFile), this.root);
2314
+ return new ThemeFile(isAbsolute(pathOrFile) ? pathOrFile : join(this.root, pathOrFile), this.root, this.source());
2315
+ }
2316
+ treeSource;
2317
+ source() {
2318
+ if (!expecting()) return void 0;
2319
+ if (!this.treeSource) {
2320
+ const tree = this.tree();
2321
+ const members = new Set(tree.list());
2322
+ this.treeSource = {
2323
+ has: (rel) => members.has(rel),
2324
+ read: (rel) => tree.readFile(rel)
2325
+ };
2326
+ }
2327
+ return this.treeSource;
2328
+ }
2329
+ tree() {
2330
+ return inputTree(this.root);
2132
2331
  }
2133
2332
  glob(dir) {
2333
+ if (inputsBound() && dir === this.root) {
2334
+ const source = this.source();
2335
+ return this.tree().list().map((rel) => new ThemeFile(join(this.root, rel), this.root, source));
2336
+ }
2134
2337
  const results = [];
2135
2338
  for (const entry of readdirSync(dir, { withFileTypes: true })) {
2136
2339
  if (entry.name.startsWith(".")) continue;
@@ -2954,14 +3157,17 @@ const MANAGED_ASSET_SHADOW_SENTINEL = "fluid-managed-asset\n";
2954
3157
  * request to delete its remote FileResource.
2955
3158
  */
2956
3159
  var ThemeAssetManifest = class {
2957
- assets;
3160
+ assets = {};
2958
3161
  path;
3162
+ loaded = null;
2959
3163
  constructor(themeRoot) {
2960
3164
  this.path = join(themeRoot, MANIFEST_FILE);
2961
- this.assets = readDocument(this.path).assets;
3165
+ this.reload();
2962
3166
  }
2963
3167
  reload() {
2964
- this.assets = readDocument(this.path).assets;
3168
+ const document = readDocument(this.path);
3169
+ this.assets = document.assets;
3170
+ this.loaded = document.raw;
2965
3171
  }
2966
3172
  keys() {
2967
3173
  return Object.keys(this.assets);
@@ -2992,12 +3198,24 @@ var ThemeAssetManifest = class {
2992
3198
  delete(key) {
2993
3199
  delete this.assets[key];
2994
3200
  }
3201
+ assertUnchangedSinceLoad() {
3202
+ if (!expecting() || isTouched(this.path)) return;
3203
+ let live;
3204
+ try {
3205
+ live = unbound(() => readFileSync(this.path, "utf-8"));
3206
+ } catch {
3207
+ live = null;
3208
+ }
3209
+ if (live !== this.loaded) throw new ChangedSinceApprovalError(this.path);
3210
+ }
2995
3211
  write() {
3212
+ this.assertUnchangedSinceLoad();
2996
3213
  const document = {
2997
3214
  version: MANIFEST_VERSION,
2998
3215
  assets: copyAssets(this.assets)
2999
3216
  };
3000
3217
  const tempPath = `${this.path}.${randomBytes(6).toString("hex")}.tmp`;
3218
+ markTouched(this.path);
3001
3219
  try {
3002
3220
  mkdirSync(dirname(this.path), { recursive: true });
3003
3221
  writeFileSync(tempPath, JSON.stringify(document, null, 2) + "\n", {
@@ -3014,9 +3232,16 @@ var ThemeAssetManifest = class {
3014
3232
  }
3015
3233
  };
3016
3234
  function readDocument(path) {
3017
- if (!existsSync(path)) return emptyDocument();
3018
3235
  try {
3019
- return parseDocument$1(JSON.parse(readFileSync(path, "utf-8")));
3236
+ const raw = readInputText(path);
3237
+ if (raw === null) return {
3238
+ ...emptyDocument(),
3239
+ raw
3240
+ };
3241
+ return {
3242
+ ...parseDocument$1(JSON.parse(raw)),
3243
+ raw
3244
+ };
3020
3245
  } catch (error) {
3021
3246
  const message = error instanceof Error ? error.message : String(error);
3022
3247
  throw new Error(`Could not read ${MANIFEST_FILE}: ${message}`);
@@ -3725,9 +3950,10 @@ var Syncer = class {
3725
3950
  return content;
3726
3951
  }
3727
3952
  if (isNestedBinaryThemeAsset(file)) throw new Error(`Binary assets must be directly inside assets/: ${file.relativePath}`);
3728
- const resource = await this.uploadBinaryFile(file, baseSha);
3953
+ const sent = file.readBinary();
3954
+ const resource = await this.uploadBinaryFile(file, baseSha, sent);
3729
3955
  this.setRemoteResource(resource);
3730
- if (isThemeAssetKey(file.relativePath)) this.externalizeBinaryFile(file, resource, opts.pendingAsset);
3956
+ if (isThemeAssetKey(file.relativePath)) this.externalizeBinaryFile(file, resource, opts.pendingAsset, sent);
3731
3957
  return null;
3732
3958
  }
3733
3959
  /** Canonical member bytes accepted by the server during this transfer. */
@@ -3879,7 +4105,7 @@ var Syncer = class {
3879
4105
  const meta = e?.data?.meta;
3880
4106
  return new PushConflictError(meta?.remote_sha ?? null);
3881
4107
  }
3882
- async uploadBinaryFile(file, baseSha) {
4108
+ async uploadBinaryFile(file, baseSha, bytes) {
3883
4109
  const asset = (await this.api.post("/api/dam/assets", { placeholder_asset: {
3884
4110
  description: `Uploaded via Fluid CLI: ${file.name}`,
3885
4111
  mime_type: file.mime.name,
@@ -3888,7 +4114,7 @@ var Syncer = class {
3888
4114
  const authBody = await this.api.post("/api/dam/assets/imagekit_auth", {});
3889
4115
  const folder = this.canonicalPathToImageKitFolder(asset.canonical_path);
3890
4116
  const formData = new FormData();
3891
- const blob = new Blob([file.readBinary()], { type: file.mime.name });
4117
+ const blob = new Blob([bytes], { type: file.mime.name });
3892
4118
  formData.append("file", blob, file.name);
3893
4119
  formData.append("token", authBody.token);
3894
4120
  formData.append("signature", authBody.signature);
@@ -3941,9 +4167,21 @@ var Syncer = class {
3941
4167
  }
3942
4168
  };
3943
4169
  }
3944
- externalizeBinaryFile(file, resource, pending) {
4170
+ externalizeBinaryFile(file, resource, pending, sent) {
4171
+ const key = file.relativePath;
4172
+ const changed = () => /* @__PURE__ */ new Error(`${key}: file changed during push; re-run to upload the new bytes`);
4173
+ const verify = () => {
4174
+ try {
4175
+ file.assertUnchanged(sent);
4176
+ } catch (error) {
4177
+ if (error instanceof ChangedSinceApprovalError) throw changed();
4178
+ throw error;
4179
+ }
4180
+ };
4181
+ verify();
3945
4182
  this.assetManifest.reload();
3946
- this.assetManifest.set(file.relativePath, {
4183
+ const prior = this.assetManifest.get(key);
4184
+ this.assetManifest.set(key, {
3947
4185
  sourceThemeId: this.themeId,
3948
4186
  ...resourceLink(resource),
3949
4187
  ...uploadedAssetMetadata(file, resource),
@@ -3951,7 +4189,15 @@ var Syncer = class {
3951
4189
  ...typeof resource.damAssetCode === "string" ? { damAssetCode: resource.damAssetCode } : {}
3952
4190
  });
3953
4191
  this.assetManifest.write();
3954
- unlinkSync(file.absolutePath);
4192
+ try {
4193
+ verify();
4194
+ } catch (error) {
4195
+ if (prior) this.assetManifest.set(key, prior);
4196
+ else this.assetManifest.delete(key);
4197
+ this.assetManifest.write();
4198
+ throw error;
4199
+ }
4200
+ file.remove();
3955
4201
  }
3956
4202
  canonicalPathToImageKitFolder(canonicalPath) {
3957
4203
  const parts = canonicalPath.split(".");
@@ -4199,6 +4445,7 @@ var Syncer = class {
4199
4445
  result.uploaded += 1 + (upload.memberConfiguration?.files.length ?? 0);
4200
4446
  } catch (e) {
4201
4447
  if (e instanceof PushConflictError) throw e;
4448
+ baseSha = this.lastKnownRemoteSha ?? baseSha;
4202
4449
  if (upload.memberConfiguration && opts.holdMemberConfiguration) result.memberConfigurationHeld = formatError(e);
4203
4450
  else result.errors.push(`Upload ${file.relativePath}: ${formatError(e)}`);
4204
4451
  }
@@ -4270,7 +4517,7 @@ var Syncer = class {
4270
4517
  if (remoteKeys.has(file.relativePath)) continue;
4271
4518
  if (isStylesheetKey(file.relativePath)) continue;
4272
4519
  try {
4273
- unlinkSync(file.absolutePath);
4520
+ file.remove();
4274
4521
  result.deleted++;
4275
4522
  } catch {}
4276
4523
  }
@@ -4778,7 +5025,9 @@ const BASELINE_VERSION = 1;
4778
5025
  const BASELINE_FILE = join(".fluid-theme", "dev-baseline.json");
4779
5026
  function readDevRemoteBaseline(themeRoot, themeId, assetManifestSha) {
4780
5027
  try {
4781
- const state = parseDocument(JSON.parse(readFileSync(join(themeRoot, BASELINE_FILE), "utf-8")));
5028
+ const raw = readInputText(join(themeRoot, BASELINE_FILE));
5029
+ if (raw === null) return null;
5030
+ const state = parseDocument(JSON.parse(raw));
4782
5031
  if (state.themeId !== themeId) return null;
4783
5032
  if (state.assetManifestSha !== assetManifestSha) return null;
4784
5033
  return state;
@@ -4793,6 +5042,7 @@ function writeDevRemoteBaseline(themeRoot, state) {
4793
5042
  };
4794
5043
  parseDocument(document);
4795
5044
  const path = join(themeRoot, BASELINE_FILE);
5045
+ markTouched(path);
4796
5046
  const tempPath = `${path}.${randomBytes(6).toString("hex")}.tmp`;
4797
5047
  try {
4798
5048
  mkdirSync(dirname(path), { recursive: true });
@@ -4802,12 +5052,13 @@ function writeDevRemoteBaseline(themeRoot, state) {
4802
5052
  });
4803
5053
  renameSync(tempPath, path);
4804
5054
  } catch (error) {
4805
- rmSync(tempPath, { force: true });
5055
+ unbound(() => rmSync(tempPath, { force: true }));
4806
5056
  throw error;
4807
5057
  }
4808
5058
  }
4809
5059
  function removeDevRemoteBaseline(themeRoot) {
4810
- rmSync(join(themeRoot, BASELINE_FILE), { force: true });
5060
+ markTouched(join(themeRoot, BASELINE_FILE));
5061
+ unbound(() => rmSync(join(themeRoot, BASELINE_FILE), { force: true }));
4811
5062
  }
4812
5063
  async function devRemoteStateFromSourceShadow(themeRoot, shadow, themeId, remoteSha) {
4813
5064
  try {
@@ -4919,6 +5170,8 @@ function isPositiveInteger(candidate) {
4919
5170
  */
4920
5171
  var ShadowRepo = class ShadowRepo {
4921
5172
  headExists = void 0;
5173
+ pinned = void 0;
5174
+ pinVerified = false;
4922
5175
  constructor(themeRoot, gitDir) {
4923
5176
  this.themeRoot = themeRoot;
4924
5177
  this.gitDir = gitDir;
@@ -4936,14 +5189,19 @@ var ShadowRepo = class ShadowRepo {
4936
5189
  const shadowDir = join(themeRoot, ".fluid-theme");
4937
5190
  const gitDir = join(shadowDir, "repo");
4938
5191
  const themeIdFile = join(shadowDir, "theme-id");
4939
- if (existsSync(gitDir)) {
4940
- if (readStoredThemeId(themeIdFile) !== themeId) rmSync(gitDir, {
4941
- recursive: true,
4942
- force: true
4943
- });
5192
+ let pin = approvedShadowHead();
5193
+ if (unbound(() => existsSync(gitDir))) {
5194
+ if (readStoredThemeId(themeIdFile) !== themeId) {
5195
+ unbound(() => rmSync(gitDir, {
5196
+ recursive: true,
5197
+ force: true
5198
+ }));
5199
+ if (pin !== void 0) pin = null;
5200
+ }
4944
5201
  }
4945
5202
  const repo = new ShadowRepo(themeRoot, gitDir);
4946
- if (!existsSync(gitDir)) {
5203
+ repo.pinned = pin;
5204
+ if (!unbound(() => existsSync(gitDir))) {
4947
5205
  mkdirSync(shadowDir, { recursive: true });
4948
5206
  await repo.git([
4949
5207
  "init",
@@ -4952,15 +5210,41 @@ var ShadowRepo = class ShadowRepo {
4952
5210
  "main",
4953
5211
  gitDir
4954
5212
  ], { cwd: themeRoot });
5213
+ if (pin !== void 0) repo.pinned = null;
4955
5214
  }
5215
+ markTouched(themeIdFile);
4956
5216
  writeFileSync(themeIdFile, `${themeId}\n`, "utf-8");
4957
5217
  const shadowIgnore = join(shadowDir, ".gitignore");
4958
- if (!existsSync(shadowIgnore)) writeFileSync(shadowIgnore, "# Fluid CLI shadow repo — internal state, not for version control.\n*\n");
5218
+ if (!unbound(() => existsSync(shadowIgnore))) writeFileSync(shadowIgnore, "# Fluid CLI shadow repo — internal state, not for version control.\n*\n");
4959
5219
  await ensureRootGitignoreHidesShadow(themeRoot);
4960
5220
  return repo;
4961
5221
  }
4962
5222
  /** True when the repo has at least one commit on `refs/heads/main`. */
4963
5223
  async hasHead() {
5224
+ if (this.pinned !== void 0) return this.pinnedHead() !== null;
5225
+ return this.liveHeadExists();
5226
+ }
5227
+ pinnedHead() {
5228
+ return this.pinned ?? null;
5229
+ }
5230
+ async baseline() {
5231
+ const pin = this.pinned;
5232
+ if (typeof pin !== "string") return "HEAD";
5233
+ if (!this.pinVerified) {
5234
+ try {
5235
+ await this.git([
5236
+ "rev-parse",
5237
+ "--verify",
5238
+ `${pin}^{commit}`
5239
+ ]);
5240
+ } catch (error) {
5241
+ throw new Error(`The approved shadow baseline ${pin} is no longer in the local theme shadow`, { cause: error });
5242
+ }
5243
+ this.pinVerified = true;
5244
+ }
5245
+ return pin;
5246
+ }
5247
+ async liveHeadExists() {
4964
5248
  if (this.headExists !== void 0) return this.headExists;
4965
5249
  try {
4966
5250
  await this.git([
@@ -4981,7 +5265,8 @@ var ShadowRepo = class ShadowRepo {
4981
5265
  const { stdout } = await this.git([
4982
5266
  "log",
4983
5267
  "-1",
4984
- "--format=%ae"
5268
+ "--format=%ae",
5269
+ await this.baseline()
4985
5270
  ]);
4986
5271
  return stdout.toString("utf8").trim() === "cli@fluid.app";
4987
5272
  }
@@ -4996,7 +5281,7 @@ var ShadowRepo = class ShadowRepo {
4996
5281
  "ls-tree",
4997
5282
  "-r",
4998
5283
  "-z",
4999
- "HEAD",
5284
+ await this.baseline(),
5000
5285
  "--name-only"
5001
5286
  ]);
5002
5287
  return stdout.toString("utf8").split("\0").filter((line) => line.length > 0);
@@ -5012,7 +5297,7 @@ var ShadowRepo = class ShadowRepo {
5012
5297
  const { stdout } = await this.git([
5013
5298
  "cat-file",
5014
5299
  "-p",
5015
- `HEAD:${path}`
5300
+ `${await this.baseline()}:${path}`
5016
5301
  ]);
5017
5302
  return stdout;
5018
5303
  } catch {
@@ -5053,7 +5338,7 @@ var ShadowRepo = class ShadowRepo {
5053
5338
  env: { GIT_INDEX_FILE: indexPath }
5054
5339
  });
5055
5340
  const treeSha = (await this.git(["write-tree"], { env: { GIT_INDEX_FILE: indexPath } })).stdout.toString("utf8").trim();
5056
- const parent = await this.hasHead() ? (await this.git(["rev-parse", "HEAD"])).stdout.toString("utf8").trim() : null;
5341
+ const parent = await this.liveHeadExists() ? (await this.git(["rev-parse", "HEAD"])).stdout.toString("utf8").trim() : null;
5057
5342
  const commitArgs = [
5058
5343
  "commit-tree",
5059
5344
  treeSha,
@@ -5073,13 +5358,19 @@ var ShadowRepo = class ShadowRepo {
5073
5358
  commitSha
5074
5359
  ]);
5075
5360
  this.headExists = true;
5361
+ if (this.pinned !== void 0) {
5362
+ this.pinned = commitSha;
5363
+ this.pinVerified = true;
5364
+ }
5076
5365
  return commitSha;
5077
5366
  } finally {
5078
5367
  try {
5079
- rmSync(indexPath, { force: true });
5080
- rmSync(indexPath.substring(0, indexPath.length - 6), {
5081
- recursive: true,
5082
- force: true
5368
+ unbound(() => {
5369
+ rmSync(indexPath, { force: true });
5370
+ rmSync(indexPath.substring(0, indexPath.length - 6), {
5371
+ recursive: true,
5372
+ force: true
5373
+ });
5083
5374
  });
5084
5375
  } catch {}
5085
5376
  }
@@ -5145,10 +5436,10 @@ var ShadowRepo = class ShadowRepo {
5145
5436
  }
5146
5437
  } finally {
5147
5438
  try {
5148
- rmSync(dir, {
5439
+ unbound(() => rmSync(dir, {
5149
5440
  recursive: true,
5150
5441
  force: true
5151
- });
5442
+ }));
5152
5443
  } catch {}
5153
5444
  }
5154
5445
  }
@@ -5234,7 +5525,7 @@ function readIfExists(path) {
5234
5525
  */
5235
5526
  function readStoredThemeId(themeIdFile) {
5236
5527
  try {
5237
- const stored = parseInt(readFileSync(themeIdFile, "utf-8").trim(), 10);
5528
+ const stored = parseInt(readInput(themeIdFile)?.toString("utf-8") ?? "", 10);
5238
5529
  return Number.isFinite(stored) ? stored : null;
5239
5530
  } catch {
5240
5531
  return null;
@@ -5263,7 +5554,7 @@ async function ensureRootGitignoreHidesShadow(themeRoot) {
5263
5554
  const gitignorePath = join(themeRoot, ".gitignore");
5264
5555
  let existing = "";
5265
5556
  try {
5266
- existing = readFileSync(gitignorePath, "utf-8");
5557
+ existing = unbound(() => readFileSync(gitignorePath, "utf-8"));
5267
5558
  } catch {
5268
5559
  existing = "";
5269
5560
  }
@@ -5393,13 +5684,15 @@ function findWorkspace(startDir) {
5393
5684
  let dir = resolve(startDir ?? process.cwd());
5394
5685
  while (true) {
5395
5686
  const candidate = join(dir, WORKSPACE_FILE);
5396
- if (existsSync(candidate)) try {
5397
- const raw = readFileSync(candidate, "utf-8");
5398
- const config = JSON.parse(raw);
5399
- return {
5400
- root: dir,
5401
- config
5402
- };
5687
+ try {
5688
+ const raw = readInputText(candidate);
5689
+ if (raw !== null) {
5690
+ const config = JSON.parse(raw);
5691
+ return {
5692
+ root: dir,
5693
+ config
5694
+ };
5695
+ }
5403
5696
  } catch {
5404
5697
  return null;
5405
5698
  }
@@ -5584,6 +5877,50 @@ function createDevCommand() {
5584
5877
  });
5585
5878
  }
5586
5879
  //#endregion
5880
+ //#region src/command-inputs.ts
5881
+ /** Resolvers probe which config files exist; those probes are not inputs. */
5882
+ function resolver(fn) {
5883
+ return (opts, args) => unbound(() => fn(opts, args));
5884
+ }
5885
+ function rootAndWorkspace(rootOpt) {
5886
+ const root = typeof rootOpt === "string" ? rootOpt : ".";
5887
+ if (root !== ".") return {
5888
+ root,
5889
+ workspaceFile: null
5890
+ };
5891
+ const workspace = findWorkspace();
5892
+ return {
5893
+ root: (workspace && resolveThemeRootFromCwd(workspace)) ?? root,
5894
+ workspaceFile: workspace ? join(workspace.root, ".fluid-workspace.json") : null
5895
+ };
5896
+ }
5897
+ /** Inputs of a command that reads the theme tree, its config files and the shadow HEAD. */
5898
+ const themeTreeInputs = resolver((opts) => {
5899
+ const { root, workspaceFile } = rootAndWorkspace(opts["root"]);
5900
+ return themeInputSpecs(root, {
5901
+ tree: true,
5902
+ shadow: true,
5903
+ workspaceFile
5904
+ });
5905
+ });
5906
+ /** Inputs of `staging publish`: the theme tree and the config it reads, no shadow. */
5907
+ const stagingPublishInputs = resolver((opts) => {
5908
+ const { root, workspaceFile } = rootAndWorkspace(opts["root"]);
5909
+ return themeInputSpecs(root, {
5910
+ tree: true,
5911
+ files: [".fluid-theme.json", ".fluidignore"],
5912
+ workspaceFile
5913
+ });
5914
+ });
5915
+ /** Inputs of a command that only reads which theme the project is bound to. */
5916
+ const themeBindingInputs = resolver((opts) => {
5917
+ const { root, workspaceFile } = rootAndWorkspace(opts["root"]);
5918
+ return themeInputSpecs(root, {
5919
+ files: [".fluid-theme.json"],
5920
+ workspaceFile
5921
+ });
5922
+ });
5923
+ //#endregion
5587
5924
  //#region src/theme/development-push.ts
5588
5925
  /**
5589
5926
  * Push a project to a development theme without touching the project's own
@@ -5713,7 +6050,7 @@ function findUnresolvedConflicts(files) {
5713
6050
  const flagged = [];
5714
6051
  for (const file of files) {
5715
6052
  if (!file.isText) continue;
5716
- const buf = readIfExists(file.absolutePath);
6053
+ const buf = file.readIfExists();
5717
6054
  if (!buf) continue;
5718
6055
  if (containsConflictMarker(buf)) flagged.push(file.relativePath);
5719
6056
  }
@@ -5949,7 +6286,7 @@ function actorFromMe(raw) {
5949
6286
  * this off early and await it only at commit time.
5950
6287
  */
5951
6288
  async function fetchSyncActor(api, timeoutMs = 5e3) {
5952
- return resolveGitSyncActor(() => requestSyncActor(api, timeoutMs));
6289
+ return unboundAsync(() => resolveGitSyncActor(() => requestSyncActor(api, timeoutMs)));
5953
6290
  }
5954
6291
  async function requestSyncActor(api, timeoutMs) {
5955
6292
  try {
@@ -6129,7 +6466,7 @@ function warnUnsupportedTemplateFiles(themeRoot) {
6129
6466
  console.warn(chalk.yellow(unsupportedTemplateWarning(skipped.map((file) => file.relativePath))));
6130
6467
  }
6131
6468
  function createPushCommand() {
6132
- return new Command("push").description("Push local theme files to a remote theme").option("-t, --theme <name-or-id>", "Theme name or ID to push to").option("-n, --nodelete", "Do not delete remote files missing locally").option("-f, --force", "Skip local Liquid validation and the server-side merge check").option("-p, --publish", "Publish the theme after pushing").option("-u, --unpublished", "Create a new unpublished theme and push to it").option("--auto-baseline", "When no local baseline exists, record the server's current state as the baseline and push only what differs locally (never modifies local files, never deletes server-only files)").option("--root <path>", "Theme root directory", ".").action(async (opts) => {
6469
+ return declareInputs(new Command("push").description("Push local theme files to a remote theme").option("-t, --theme <name-or-id>", "Theme name or ID to push to").option("-n, --nodelete", "Do not delete remote files missing locally").option("-f, --force", "Skip local Liquid validation and the server-side merge check").option("-p, --publish", "Publish the theme after pushing").option("-u, --unpublished", "Create a new unpublished theme and push to it").option("--auto-baseline", "When no local baseline exists, record the server's current state as the baseline and push only what differs locally (never modifies local files, never deletes server-only files)").option("--root <path>", "Theme root directory", ".").action(async (opts) => {
6133
6470
  requireToken();
6134
6471
  let rootPath = opts.root;
6135
6472
  if (rootPath === ".") {
@@ -6333,6 +6670,7 @@ function createPushCommand() {
6333
6670
  renderPullFirst(ora());
6334
6671
  process.exit(1);
6335
6672
  }
6673
+ baseSha = syncer.remoteSha() ?? baseSha;
6336
6674
  errors.push(`Upload ${file.relativePath}: ${formatError(e)}`);
6337
6675
  }
6338
6676
  progress += 1 + (upload.memberConfiguration?.files.length ?? 0);
@@ -6426,7 +6764,7 @@ function createPushCommand() {
6426
6764
  process.exitCode = 1;
6427
6765
  }
6428
6766
  }
6429
- });
6767
+ }), themeTreeInputs);
6430
6768
  }
6431
6769
  function renderPullFirst(spinner) {
6432
6770
  spinner.fail("Server has changed since your last pull. Push aborted.");
@@ -13377,7 +13715,7 @@ async function uploadContent(themeId, operationId, sha256, content) {
13377
13715
  const response = await fetch(`${getApiBase()}${base(themeId)}/branch-operations/${operationId}/content/${sha256}`, {
13378
13716
  method: "PUT",
13379
13717
  headers: {
13380
- Authorization: `Bearer ${getAuthToken() ?? ""}`,
13718
+ Authorization: `Bearer ${getAuthToken$1() ?? ""}`,
13381
13719
  "Content-Type": "application/octet-stream",
13382
13720
  Accept: "application/json"
13383
13721
  },
@@ -13864,6 +14202,10 @@ function createStagingCommand() {
13864
14202
  }
13865
14203
  console.log(`Undid the promotion of ${promotion.promoted_at}${promotion.promoted_by.name ? ` by ${promotion.promoted_by.name}` : ""}.`);
13866
14204
  }));
14205
+ declareInputs(request, themeBindingInputs);
14206
+ declareInputs(publish, stagingPublishInputs);
14207
+ declareInputs(promote, themeBindingInputs);
14208
+ declareInputs(undoPromote, themeBindingInputs);
13867
14209
  return new Command("staging").description("Use the theme's staging branch, previewed by a signed link (needs branch environments)").addCommand(status).addCommand(request).addCommand(wait).addCommand(publish).addCommand(promote).addCommand(undoPromote).addCommand(compare);
13868
14210
  }
13869
14211
  //#endregion
@@ -13977,6 +14319,7 @@ function createWidgetCommand() {
13977
14319
  //#endregion
13978
14320
  //#region src/commands/theme.ts
13979
14321
  function registerThemeCommand(ctx) {
14322
+ useInputs(ctx.inputs ?? null);
13980
14323
  const cmd = new Command("theme").description("Theme developer workflow — dev server, push, pull, lint, init, skills, crawl, compare, widget");
13981
14324
  cmd.addCommand(createDevCommand());
13982
14325
  cmd.addCommand(createPushCommand());