@solidactions/cli 3.31.0 → 3.33.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.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema_version": 1,
3
3
  "cli_name": "solidactions",
4
- "cli_version": "3.31.0",
4
+ "cli_version": "3.33.0",
5
5
  "global_options": [
6
6
  {
7
7
  "flags": "-V, --version",
@@ -3,7 +3,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
3
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
4
4
  };
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.PLAN_LIMIT_NON_INTERACTIVE_HINT = exports.SKILLS_TIP_LINES = void 0;
6
+ exports.PLAN_LIMIT_NON_INTERACTIVE_HINT = exports.SKILLS_TIP_LINES = exports.archiveMd5 = void 0;
7
7
  exports.validateProject = validateProject;
8
8
  exports.cacheBusterEntry = cacheBusterEntry;
9
9
  exports.projectStatusUrl = projectStatusUrl;
@@ -34,6 +34,7 @@ const functions_sync_1 = require("../utils/functions-sync");
34
34
  const api_1 = require("../utils/api");
35
35
  const host_display_1 = require("../utils/host-display");
36
36
  const deploy_ignore_1 = require("../utils/deploy-ignore");
37
+ const sandbox_base_1 = require("../utils/sandbox-base");
37
38
  const slug_1 = require("../utils/slug");
38
39
  const project_ref_1 = require("../utils/project-ref");
39
40
  const skills_1 = require("../utils/skills");
@@ -41,6 +42,7 @@ const tar_archive_1 = require("../utils/tar-archive");
41
42
  const deploy_status_poll_1 = require("../utils/deploy-status-poll");
42
43
  const source_provenance_1 = require("../utils/source-provenance");
43
44
  const project_view_1 = require("./project-view");
45
+ exports.archiveMd5 = null;
44
46
  /** Printed when a deploy target has no SolidActions skill files installed. */
45
47
  exports.SKILLS_TIP_LINES = [
46
48
  'Tip: no SolidActions skill files found (.claude/skills/solidactions-*). Your AI assistant',
@@ -288,7 +290,7 @@ function formatSyncYamlWarnings(warnings) {
288
290
  * (PM round #1127 finding 14: a failed sync must never be reported as
289
291
  * success by the caller).
290
292
  */
291
- async function pushYamlDeclarations(config, projectSlug, yamlConfig) {
293
+ async function pushYamlDeclarations(config, projectSlug, yamlConfig, baseSourceHash) {
292
294
  const parsedVars = (0, env_1.parseYamlEnvVars)(yamlConfig);
293
295
  // Build the declarations array
294
296
  const declarations = parsedVars.map(v => ({
@@ -299,7 +301,7 @@ async function pushYamlDeclarations(config, projectSlug, yamlConfig) {
299
301
  yaml_default_docs_path: v.docsPath,
300
302
  source: 'yaml',
301
303
  }));
302
- const response = await axios_1.default.post(`${config.host}/api/v1/projects/${projectSlug}/variable-mappings/sync-yaml`, { declarations }, {
304
+ const response = await axios_1.default.post(`${config.host}/api/v1/projects/${projectSlug}/variable-mappings/sync-yaml`, { declarations, ...(baseSourceHash !== undefined ? { base_source_hash: baseSourceHash } : {}) }, {
303
305
  headers: (0, api_1.getApiHeaders)(config, 'application/json'),
304
306
  });
305
307
  // Non-fatal: a warning means a declared resource doesn't exist in the
@@ -525,6 +527,25 @@ async function deploy(projectName, sourcePath, options = {}) {
525
527
  process.exit(1);
526
528
  }
527
529
  console.log(chalk_1.default.green('✓ Project structure validated'));
530
+ // Bundle tsx code pages before any project lookup or creation: a page
531
+ // that fails to bundle must not create a remote project (or sync
532
+ // anything); nothing is uploaded on this path. --config-only syncs
533
+ // YAML env declarations without building and never touches pages, so
534
+ // it skips bundling (a broken tsx page must not block a config-only
535
+ // sync); the empty map keeps the later payload call compiling on
536
+ // that path (unreachable after the early return below).
537
+ const pageFiles = (0, pages_sync_1.listCodePages)(yamlConfig ?? {});
538
+ let bundledPages = new Map();
539
+ if (!options.configOnly) {
540
+ const bundled = await (0, pages_sync_1.bundleCodePages)(sourceDir, pageFiles);
541
+ if (bundled.errors.length > 0) {
542
+ console.error(chalk_1.default.red('Page bundling failed; nothing was uploaded:'));
543
+ for (const line of bundled.errors)
544
+ console.error(chalk_1.default.red(line));
545
+ process.exit(1);
546
+ }
547
+ bundledPages = bundled.bundles;
548
+ }
528
549
  // Check if the target environment's project record exists; create if needed.
529
550
  // For production deploys where we already confirmed existence above, reuse
530
551
  // the cached slug to avoid a duplicate GET.
@@ -591,6 +612,10 @@ async function deploy(projectName, sourcePath, options = {}) {
591
612
  process.exit(1);
592
613
  }
593
614
  }
615
+ const base = (0, sandbox_base_1.readSandboxBase)(sourceDir);
616
+ const guardedBase = base?.slug === projectSlug ? base : null;
617
+ const guardedBaseWire = guardedBase ? (0, sandbox_base_1.baseWireValue)(guardedBase) : null;
618
+ const staleBaseLine = () => `The dev copy moved since you pulled. Run "solidactions project pull ${projectSlug} . --yes" and redo your change.`;
594
619
  // --config-only: sync YAML env declarations without building
595
620
  if (options.configOnly) {
596
621
  if (!yamlConfig) {
@@ -598,10 +623,13 @@ async function deploy(projectName, sourcePath, options = {}) {
598
623
  process.exit(1);
599
624
  }
600
625
  try {
601
- await pushYamlDeclarations(config, projectSlug, yamlConfig);
626
+ await pushYamlDeclarations(config, projectSlug, yamlConfig, guardedBaseWire ?? undefined);
602
627
  }
603
628
  catch (error) {
604
- if (error.response?.status === 401) {
629
+ if (error.response?.status === 409 && error.response.data?.code === 'stale_base') {
630
+ console.error(chalk_1.default.red(staleBaseLine()));
631
+ }
632
+ else if (error.response?.status === 401) {
605
633
  console.error(chalk_1.default.red((0, api_1.authFailedLine)(config.host)));
606
634
  }
607
635
  else {
@@ -620,10 +648,9 @@ async function deploy(projectName, sourcePath, options = {}) {
620
648
  if (sourceMetadata && yamlConfig?.workflows) {
621
649
  console.log(chalk_1.default.gray(`Revision to upload (client-reported): ${(0, source_provenance_1.formatRevisionSummary)(sourceMetadata)}`));
622
650
  }
623
- const pageFiles = (0, pages_sync_1.listCodePages)(yamlConfig ?? {});
624
651
  let pageBodies;
625
652
  try {
626
- pageBodies = (0, pages_sync_1.readPageBodies)(sourceDir, pageFiles);
653
+ pageBodies = (0, pages_sync_1.readPageBodies)(sourceDir, pageFiles.filter(page => !bundledPages.has(page.slug)));
627
654
  }
628
655
  catch (error) {
629
656
  console.error(chalk_1.default.red(`Failed to read page: ${error.message}`));
@@ -648,7 +675,13 @@ async function deploy(projectName, sourcePath, options = {}) {
648
675
  process.exit(1);
649
676
  }
650
677
  const functionsPayload = (0, functions_sync_1.buildFunctionsSyncPayload)(functionFiles, functionSources, codeRef);
678
+ if (guardedBaseWire !== null)
679
+ functionsPayload.base_source_hash = guardedBaseWire;
651
680
  const functionsResult = await (0, functions_sync_1.syncFunctions)(config, projectSlug, functionsPayload);
681
+ if (functionsResult.httpStatus === 409 && functionsResult.body?.code === 'stale_base') {
682
+ console.error(chalk_1.default.red(staleBaseLine()));
683
+ process.exit(1);
684
+ }
652
685
  const functionRows = functionsResult.body?.functions ?? [];
653
686
  const retiredFunctions = functionsResult.body?.retired ?? [];
654
687
  const retireErrors = functionsResult.body?.retire_errors ?? [];
@@ -688,7 +721,7 @@ async function deploy(projectName, sourcePath, options = {}) {
688
721
  console.log(line.startsWith('✓') ? chalk_1.default.green(line) : line);
689
722
  }
690
723
  yamlSyncFailed = yamlSyncFailed || appSummary.failed;
691
- const payload = (0, pages_sync_1.buildPagesSyncPayload)(pageFiles, pageBodies, deploymentId, codeRef);
724
+ const payload = (0, pages_sync_1.buildPagesSyncPayload)(pageFiles, pageBodies, deploymentId, codeRef, bundledPages);
692
725
  const result = await (0, pages_sync_1.syncPages)(config, projectSlug, payload);
693
726
  const rows = result.body?.pages ?? [];
694
727
  const trashed = result.body?.trashed ?? [];
@@ -703,9 +736,6 @@ async function deploy(projectName, sourcePath, options = {}) {
703
736
  const outcome = (0, functions_sync_1.joinSyncOutcomes)(functionsOutcome, pagesOutcome);
704
737
  process.exit((0, pages_sync_1.terminalExitCode)({ buildFailed, yamlSyncFailed, outcome }));
705
738
  };
706
- if (!yamlConfig?.workflows) {
707
- return finishDeploy({ deploymentId: null, buildFailed: false });
708
- }
709
739
  // Plan the file list BEFORE creating the archive write stream so a walk error
710
740
  // (permission error, unreadable dir) aborts cleanly with no orphan tarball.
711
741
  let plan;
@@ -743,7 +773,19 @@ async function deploy(projectName, sourcePath, options = {}) {
743
773
  output.on('close', async () => {
744
774
  console.log(chalk_1.default.gray(`Archived ${archive.pointer()} total bytes`));
745
775
  try {
776
+ const hash = (0, crypto_1.createHash)('md5');
777
+ for await (const chunk of fs_1.default.createReadStream(archivePath)) {
778
+ hash.update(chunk);
779
+ }
780
+ const uploadedArchiveMd5 = hash.digest('hex');
781
+ exports.archiveMd5 = uploadedArchiveMd5;
746
782
  const form = (0, source_provenance_1.buildDeployForm)(archivePath, sourceMetadata);
783
+ if (guardedBaseWire !== null) {
784
+ form.append('base_source_hash', guardedBaseWire);
785
+ }
786
+ if (!yamlConfig?.workflows) {
787
+ form.append('build', '0');
788
+ }
747
789
  if (options.paused) {
748
790
  form.append('paused', '1');
749
791
  }
@@ -759,6 +801,19 @@ async function deploy(projectName, sourcePath, options = {}) {
759
801
  maxContentLength: Infinity,
760
802
  maxBodyLength: Infinity
761
803
  });
804
+ if (guardedBase) {
805
+ if (deployResponse.data?.source_hash === uploadedArchiveMd5) {
806
+ (0, sandbox_base_1.writeSandboxBase)(sourceDir, { source_hash: uploadedArchiveMd5, slug: guardedBase.slug, restored_at: new Date().toISOString() });
807
+ }
808
+ else {
809
+ console.log(chalk_1.default.yellow('The server stored different bytes than this deploy uploaded; base.json was left unchanged.'));
810
+ }
811
+ }
812
+ if (!yamlConfig?.workflows) {
813
+ console.log(chalk_1.default.green('Source archived.'));
814
+ cleanupArchive();
815
+ return await finishDeploy({ deploymentId: null, buildFailed: false });
816
+ }
762
817
  const acceptedDeployment = (0, source_provenance_1.parseDeployAcceptance)(deployResponse.data);
763
818
  if (acceptedDeployment.sourceMetadataRejected) {
764
819
  console.log(chalk_1.default.yellow(`Warning: optional source metadata was not accepted (${acceptedDeployment.sourceMetadataRejected}); deployment continues.`));
@@ -837,7 +892,10 @@ async function deploy(projectName, sourcePath, options = {}) {
837
892
  catch (error) {
838
893
  console.error(chalk_1.default.red('Deployment failed:'));
839
894
  if (error.response) {
840
- if (error.response.status === 404) {
895
+ if (error.response.status === 409 && error.response.data?.code === 'stale_base') {
896
+ console.error(chalk_1.default.red(staleBaseLine()));
897
+ }
898
+ else if (error.response.status === 404) {
841
899
  console.error("Project not found.");
842
900
  }
843
901
  else if (error.response.status === 401) {
@@ -15,6 +15,7 @@ const chalk_1 = __importDefault(require("chalk"));
15
15
  const prompts_1 = __importDefault(require("prompts"));
16
16
  const api_1 = require("../utils/api");
17
17
  const project_ref_1 = require("../utils/project-ref");
18
+ const sandbox_base_1 = require("../utils/sandbox-base");
18
19
  async function pull(projectName, destPath, options = {}) {
19
20
  const config = await (0, api_1.requireConfigWithWorkspace)();
20
21
  const destination = destPath ? path_1.default.resolve(destPath) : process.cwd();
@@ -61,9 +62,15 @@ async function pull(projectName, destPath, options = {}) {
61
62
  // version of the `tar` package).
62
63
  filter: (entryPath) => {
63
64
  const top = entryPath.split('/')[0];
64
- return top === 'tenantcode' && !/\/sa-nocache-[0-9a-f-]+$/.test(entryPath);
65
+ // Belt and braces with the server strip: never lay the
66
+ // server-managed .solidactions/ down, at any depth.
67
+ return top === 'tenantcode' && !/\/sa-nocache-[0-9a-f-]+$/.test(entryPath) && !entryPath.split('/').includes('.solidactions');
65
68
  },
66
69
  }));
70
+ const sourceHash = response.headers['x-source-hash'];
71
+ if ((0, sandbox_base_1.isAppSandbox)() && typeof sourceHash === 'string') {
72
+ (0, sandbox_base_1.writeSandboxBase)(destination, { source_hash: sourceHash, slug: projectSlug, restored_at: new Date().toISOString() });
73
+ }
67
74
  console.log(chalk_1.default.green(`Project "${projectName}" pulled successfully!`));
68
75
  }
69
76
  catch (error) {
@@ -33,10 +33,11 @@ exports.DEFAULT_DEPLOY_IGNORES = [
33
33
  * re-includable by any matcher negation. Covers:
34
34
  * - `.env` and any `.env.*` (secret-leak fix). Anchored so `.envrc` and
35
35
  * `environment.ts` do NOT match.
36
+ * - `.solidactions` (local CLI state at any depth).
36
37
  * - `.steps-deploy.tar.gz` / `.steps-deploy.zip` (our own deploy artifacts,
37
38
  * written into sourceDir while we walk).
38
39
  */
39
- exports.HARD_DENY_BASENAMES = /^(?:\.env(?:$|\..*)|\.steps-deploy\.(?:tar\.gz|zip))$/;
40
+ exports.HARD_DENY_BASENAMES = /^(?:\.env(?:$|\..*)|\.solidactions|\.steps-deploy\.(?:tar\.gz|zip))$/;
40
41
  /**
41
42
  * True if a path is hard-denied (Layer 1). Checked before the matcher so that
42
43
  * no `!` negation in deploy.exclude or .gitignore can re-include it.
@@ -0,0 +1,398 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.PageBundleError = exports.SOURCES_MAX_BYTES = exports.SOURCES_MAX_FILES = exports.COMPILED_LIMIT_BYTES = exports.PLATFORM_MODULES = void 0;
7
+ exports.assembleSources = assembleSources;
8
+ exports.readAdmitted = readAdmitted;
9
+ exports.bundlePage = bundlePage;
10
+ const fs_1 = __importDefault(require("fs"));
11
+ const path_1 = __importDefault(require("path"));
12
+ const esbuild_1 = require("esbuild");
13
+ exports.PLATFORM_MODULES = ['react', 'react-dom', 'recharts', '@tanstack/react-table', 'sa', '@solidactions/sa'];
14
+ exports.COMPILED_LIMIT_BYTES = 2 * 1024 * 1024;
15
+ exports.SOURCES_MAX_FILES = 50;
16
+ exports.SOURCES_MAX_BYTES = 1024 * 1024;
17
+ class PageBundleError extends Error {
18
+ }
19
+ exports.PageBundleError = PageBundleError;
20
+ const MAIN = 'sa-page:main';
21
+ const PLATFORM_NAMESPACE = 'sa-platform';
22
+ const WRAP_PREFIX = 'globalThis.__saPlatform.define(function () {\n';
23
+ const WRAP_SUFFIX = '});\n';
24
+ const NO_DEFAULT_EXPORT = 'a page must export its component as the default export';
25
+ const COMPUTED_SPECIFIER = 'import() and require() of a computed specifier are not allowed in a page; import platform modules by name: react, react-dom, recharts, @tanstack/react-table, sa';
26
+ const PLATFORM_LIST = 'react, react-dom, recharts, @tanstack/react-table, sa, @solidactions/sa';
27
+ function platformPlugin() {
28
+ return {
29
+ name: 'sa-platform',
30
+ setup(b) {
31
+ b.onResolve({ filter: /^[^./]/ }, (args) => {
32
+ if (exports.PLATFORM_MODULES.includes(args.path)) {
33
+ return { path: args.path, namespace: PLATFORM_NAMESPACE };
34
+ }
35
+ if (exports.PLATFORM_MODULES.some(name => args.path.startsWith(`${name}/`))) {
36
+ return { errors: [{ text: `import "${args.path}" is not available: platform modules are imported by name only (${PLATFORM_LIST})` }] };
37
+ }
38
+ return null;
39
+ });
40
+ b.onLoad({ filter: /.*/, namespace: PLATFORM_NAMESPACE }, (args) => ({
41
+ contents: `module.exports = globalThis.__saPlatform.modules[${JSON.stringify(args.path)}];\n`,
42
+ loader: 'js',
43
+ }));
44
+ },
45
+ };
46
+ }
47
+ function toPosix(value) {
48
+ return value.split(path_1.default.sep).join('/').replace(/\\/g, '/');
49
+ }
50
+ function loaderForExtension(ext) {
51
+ switch (ext) {
52
+ case '.ts':
53
+ case '.mts':
54
+ case '.cts':
55
+ return 'ts';
56
+ case '.tsx':
57
+ return 'tsx';
58
+ case '.js':
59
+ case '.mjs':
60
+ case '.cjs':
61
+ return 'js';
62
+ case '.jsx':
63
+ return 'jsx';
64
+ case '.json':
65
+ return 'json';
66
+ case '.css':
67
+ return 'css';
68
+ case '.txt':
69
+ return 'text';
70
+ default:
71
+ return null;
72
+ }
73
+ }
74
+ // True when a project-relative path escapes the project root. A leading
75
+ // `..` path component means outside; a mere `..` prefix does not (files
76
+ // like `lib/..shared.ts` or dirs like `..lib/` are valid project paths).
77
+ // Check both separators: metafile keys are posix, but path.relative
78
+ // speaks the OS separator — and on Windows it returns an absolute drive
79
+ // path when the target is on another drive, which no prefix check sees.
80
+ function isOutsideRoot(relative) {
81
+ const posix = toPosix(relative);
82
+ return path_1.default.isAbsolute(relative) || posix === '..' || posix.startsWith('../') || relative === '..' || relative.startsWith(`..${path_1.default.sep}`);
83
+ }
84
+ function describe(message, projectDir) {
85
+ // esbuild keeps the returning plugin's name on a plugin error
86
+ // (probed on 0.28.2: pluginName "sa-capture"/"sa-platform", id "").
87
+ // A plugin error is classified by what it IS — its own text — never
88
+ // by where it is reported: the entry's outside-root refusal is
89
+ // reported from the virtual sa-page:main import, where a
90
+ // location-based rule misreads it as a missing default export.
91
+ const pluginError = message.pluginName === 'sa-platform' || message.pluginName === 'sa-capture';
92
+ const reportedFromMain = message.location?.file === MAIN || message.location?.file === '<stdin>';
93
+ if (pluginError && reportedFromMain)
94
+ return message.text;
95
+ const fromMain = reportedFromMain;
96
+ const computed = message.id === 'unsupported-dynamic-import' || message.id === 'unsupported-require-call';
97
+ const text = fromMain ? NO_DEFAULT_EXPORT : computed ? COMPUTED_SPECIFIER : message.text;
98
+ if (fromMain || !message.location?.file)
99
+ return text;
100
+ const file = toPosix(path_1.default.relative(projectDir, path_1.default.resolve(projectDir, message.location.file)));
101
+ return `${file}:${message.location.line}:${message.location.column}: ${text}`;
102
+ }
103
+ // Source assembly is a pure function of the bytes captured during the
104
+ // build and the build's metafile: it walks the captured map (keyed by the
105
+ // exact path esbuild passed to onLoad) and the metafile decides which of
106
+ // those paths were part of the build. Nothing here may consult the live
107
+ // tree, so a file replaced after compilation cannot change the published
108
+ // snapshot. The sweep row `keeps source assembly free of filesystem
109
+ // calls` pins that shape at the source level.
110
+ function assembleSources(captured, metafile, realRoot, entryKey) {
111
+ if (metafile.inputs[entryKey]?.format !== 'esm')
112
+ throw new PageBundleError(NO_DEFAULT_EXPORT);
113
+ const builtKeys = new Set(Object.keys(metafile.inputs).map(toPosix));
114
+ const sources = {};
115
+ let totalBytes = 0;
116
+ for (const [absPath, text] of captured) {
117
+ const key = toPosix(path_1.default.relative(realRoot, absPath));
118
+ if (key.split('/').includes('node_modules'))
119
+ continue;
120
+ if (!builtKeys.has(key))
121
+ continue;
122
+ sources[key] = text;
123
+ totalBytes += Buffer.byteLength(text);
124
+ }
125
+ for (const key of Object.keys(metafile.inputs)) {
126
+ if (key.startsWith(`${PLATFORM_NAMESPACE}:`) || key === MAIN || key === '<stdin>')
127
+ continue;
128
+ const posix = toPosix(key);
129
+ // An absolute key is never skipped as node_modules: outside-root
130
+ // is the outside refusal, inside-root is an unexpected-path refusal.
131
+ if (path_1.default.isAbsolute(key) || /^[A-Za-z]:[\\/]/.test(key) || posix.startsWith('/')) {
132
+ if (isOutsideRoot(path_1.default.relative(realRoot, key))) {
133
+ throw new PageBundleError(`${posix}: imported from outside the project directory; a page can only import files inside its project`);
134
+ }
135
+ throw new PageBundleError(`${posix}: unexpected absolute input path`);
136
+ }
137
+ // Containment first: a `..`-prefixed key is never skipped as
138
+ // node_modules, it is a refusal.
139
+ if (isOutsideRoot(path_1.default.relative(realRoot, path_1.default.resolve(realRoot, key)))) {
140
+ throw new PageBundleError(`${toPosix(key)}: imported from outside the project directory; a page can only import files inside its project`);
141
+ }
142
+ if (posix.split('/').includes('node_modules'))
143
+ continue;
144
+ if (!(posix in sources))
145
+ throw new PageBundleError(`${posix}: unsupported file type for a page`);
146
+ }
147
+ if (Object.keys(sources).length > exports.SOURCES_MAX_FILES)
148
+ throw new PageBundleError(`the page reads ${Object.keys(sources).length} project files, over the ${exports.SOURCES_MAX_FILES} file limit`);
149
+ if (totalBytes > exports.SOURCES_MAX_BYTES)
150
+ throw new PageBundleError(`the page's project files total ${totalBytes} bytes, over the 1 MiB (${exports.SOURCES_MAX_BYTES} bytes) limit`);
151
+ const entrySource = sources[entryKey];
152
+ if (entrySource === undefined)
153
+ throw new PageBundleError(`${entryKey}: unsupported file type for a page`);
154
+ return { sources, entrySource };
155
+ }
156
+ // ONE reader serves every file esbuild loads, project files and in-root
157
+ // node_modules alike: onLoad always returns contents for a file-namespace
158
+ // path, never null, so esbuild never reads a file from disk itself. The
159
+ // returned bytes are read from the open handle whose post-open
160
+ // verification matches the admitted file; anything else is a refusal
161
+ // naming the path. Nothing is re-read.
162
+ function readAdmitted(requestedPath, realRoot, hooks) {
163
+ const requestedDisplay = toPosix(path_1.default.relative(realRoot, requestedPath));
164
+ let real;
165
+ try {
166
+ real = fs_1.default.realpathSync(requestedPath);
167
+ }
168
+ catch {
169
+ throw new PageBundleError(`${requestedDisplay}: could not resolve the real path`);
170
+ }
171
+ const display = toPosix(path_1.default.relative(realRoot, real));
172
+ if (isOutsideRoot(path_1.default.relative(realRoot, real))) {
173
+ throw new PageBundleError(`${display}: imported from outside the project directory; a page can only import files inside its project`);
174
+ }
175
+ // TEST SEAM beforeStat: strictly between the containment check and
176
+ // the pre-open stat.
177
+ hooks?.beforeStat?.(real);
178
+ // The pre-open stat records the admitted identity AND the regular-file
179
+ // gate. A swap of the admitted file for another IN-ROOT regular file
180
+ // here is not detectable and is harmless to the outside-root rule: the
181
+ // read bytes still come from a file inside the root and are the bytes
182
+ // captured.
183
+ let before;
184
+ try {
185
+ before = fs_1.default.statSync(real);
186
+ }
187
+ catch {
188
+ throw new PageBundleError(`${display}: changed while it was being read; deploy again`);
189
+ }
190
+ if (!before.isFile()) {
191
+ throw new PageBundleError(`${display}: not a regular file`);
192
+ }
193
+ // TEST SEAM beforeOpen: after the pre-open stat, before the open.
194
+ hooks?.beforeOpen?.(real);
195
+ let fd;
196
+ try {
197
+ fd = fs_1.default.openSync(real, fs_1.default.constants.O_RDONLY | (fs_1.default.constants.O_NOFOLLOW ?? 0));
198
+ }
199
+ catch {
200
+ throw new PageBundleError(`${display}: changed while it was being read; deploy again`);
201
+ }
202
+ try {
203
+ const after = fs_1.default.fstatSync(fd);
204
+ if (!after.isFile()) {
205
+ throw new PageBundleError(`${display}: changed while it was being read; deploy again`);
206
+ }
207
+ // Where the OPEN HANDLE really lives, asked from the kernel: an
208
+ // intermediate directory swapped for an outside symlink between
209
+ // the admission realpath and the open lands here, while
210
+ // O_NOFOLLOW only guards the final component.
211
+ let fdReal = null;
212
+ try {
213
+ fdReal = fs_1.default.realpathSync(`/proc/self/fd/${fd}`);
214
+ }
215
+ catch (error) {
216
+ const code = error.code;
217
+ const failedPath = String(error.path ?? '');
218
+ if (failedPath.endsWith(' (deleted)')) {
219
+ throw new PageBundleError(`${display}: changed while it was being read; deploy again`);
220
+ }
221
+ // No /proc on this platform (macOS, Windows, restricted
222
+ // containers): skip the kernel check and rely on the fallback
223
+ // layer below. Node has no openat/F_GETPATH; where /proc is
224
+ // unavailable a directory swapped twice in a few microseconds
225
+ // is the documented residual; the resolver's own path stats
226
+ // only choose paths, never bytes. Never skip silently on
227
+ // Linux: any other readlink failure refuses.
228
+ if (process.platform === 'linux' && code !== 'ENOENT' && code !== 'ENOTDIR') {
229
+ throw new PageBundleError(`${display}: changed while it was being read; deploy again`);
230
+ }
231
+ fdReal = null;
232
+ }
233
+ if (fdReal !== null && isOutsideRoot(path_1.default.relative(realRoot, fdReal))) {
234
+ throw new PageBundleError(`${display}: imported from outside the project directory; a page can only import files inside its project`);
235
+ }
236
+ // The open handle must still match the pre-open identity: this
237
+ // catches a swap in the beforeOpen window above.
238
+ if (after.dev !== before.dev || after.ino !== before.ino || after.size !== before.size) {
239
+ throw new PageBundleError(`${display}: changed while it was being read; deploy again`);
240
+ }
241
+ // TEST SEAM afterOpen: after the open, before the post-open
242
+ // verification below.
243
+ hooks?.afterOpen?.(real);
244
+ // The comparison stat is taken AFTER the open: it must describe
245
+ // the same file the handle does. Best-effort fallback layer for
246
+ // platforms without /proc: the path must still resolve to the
247
+ // admitted file.
248
+ let post;
249
+ try {
250
+ post = fs_1.default.statSync(real);
251
+ }
252
+ catch {
253
+ throw new PageBundleError(`${display}: changed while it was being read; deploy again`);
254
+ }
255
+ // dev+ino is the identity; size is compared too because ino is 0
256
+ // or otherwise unreliable on some platforms. Windows is
257
+ // best-effort: the predicates above are source-level there and the
258
+ // suite skips symlink rows on win32.
259
+ if (!post.isFile() || after.dev !== post.dev || after.ino !== post.ino || after.size !== post.size) {
260
+ throw new PageBundleError(`${display}: changed while it was being read; deploy again`);
261
+ }
262
+ let reread;
263
+ try {
264
+ reread = fs_1.default.realpathSync(real);
265
+ }
266
+ catch {
267
+ throw new PageBundleError(`${display}: changed while it was being read; deploy again`);
268
+ }
269
+ if (reread !== real) {
270
+ throw new PageBundleError(`${display}: changed while it was being read; deploy again`);
271
+ }
272
+ return fs_1.default.readFileSync(fd, 'utf8');
273
+ }
274
+ finally {
275
+ fs_1.default.closeSync(fd);
276
+ }
277
+ }
278
+ async function bundlePage(entryPath, projectDir, hooks) {
279
+ // test seam: the window between compilation and result assembly
280
+ const root = path_1.default.resolve(projectDir);
281
+ const entry = path_1.default.resolve(root, entryPath);
282
+ // The root and entry are resolved ONCE before the build: realRoot is
283
+ // the compilation directory and realEntry feeds the entry key. No
284
+ // project path is resolved again after the build starts. A missing
285
+ // entry keeps the lexical path so the refusal below reports it exactly
286
+ // as before.
287
+ const realRoot = fs_1.default.realpathSync(root);
288
+ const realEntry = fs_1.default.existsSync(entry) ? fs_1.default.realpathSync(entry) : entry;
289
+ const entryKey = toPosix(path_1.default.relative(realRoot, realEntry));
290
+ // Keyed by the exact path esbuild passes to onLoad: the association
291
+ // between a compiled input and its bytes is fixed at capture time and
292
+ // never re-resolved from the live tree.
293
+ const captured = new Map();
294
+ const capturePlugin = {
295
+ name: 'sa-capture',
296
+ setup(b) {
297
+ b.onLoad({ filter: /.*/, namespace: 'file' }, (args) => {
298
+ // Every file-namespace path — project files, in-root
299
+ // node_modules files, any unmapped extension — is read
300
+ // through the single admitted reader, and this handler
301
+ // always returns its contents: it never returns null, so
302
+ // esbuild never reads a file from disk itself. A real path
303
+ // outside the root is refused naming its path (this
304
+ // deliberately refuses hoisted/workspace packages resolving
305
+ // above the project root), and its bytes never reach esbuild.
306
+ // The plugin's contents come ONLY from this one admitted-reader
307
+ // call: there is no other byte source in this handler, so
308
+ // esbuild never reads a file from disk itself.
309
+ let contents;
310
+ try {
311
+ contents = readAdmitted(args.path, realRoot, hooks);
312
+ }
313
+ catch (error) {
314
+ if (error instanceof PageBundleError)
315
+ return { errors: [{ text: error.message }] };
316
+ throw error;
317
+ }
318
+ // esbuild defaults *.module.css to the local-css loader (scoped
319
+ // class names); return the same loader so capture is behavior-preserving.
320
+ const loader = args.path.endsWith('.module.css')
321
+ ? 'local-css'
322
+ : loaderForExtension(path_1.default.extname(args.path));
323
+ if (loader === null) {
324
+ return { errors: [{ text: `${toPosix(path_1.default.relative(realRoot, args.path))}: unsupported file type for a page` }] };
325
+ }
326
+ // Bytes the reader returns for a project file are recorded
327
+ // in the captured map exactly as before (keyed by the path
328
+ // esbuild passes) and are the bytes esbuild compiles;
329
+ // node_modules bytes are consumed once and not recorded.
330
+ if (!toPosix(args.path).split('/').includes('node_modules')) {
331
+ captured.set(args.path, contents);
332
+ }
333
+ hooks?.onLoaded?.(args.path, contents);
334
+ return { contents, loader };
335
+ });
336
+ },
337
+ };
338
+ let result;
339
+ try {
340
+ result = await (0, esbuild_1.build)({
341
+ stdin: {
342
+ contents: `import Page from ${JSON.stringify(entry)};\nglobalThis.__saPlatform.mount(Page);\n`,
343
+ resolveDir: root,
344
+ sourcefile: MAIN,
345
+ loader: 'js',
346
+ },
347
+ absWorkingDir: realRoot,
348
+ outdir: path_1.default.join(root, '.sa-page-out'),
349
+ bundle: true,
350
+ write: false,
351
+ metafile: true,
352
+ logLevel: 'silent',
353
+ format: 'iife',
354
+ target: 'es2022',
355
+ platform: 'browser',
356
+ charset: 'utf8',
357
+ legalComments: 'none',
358
+ minify: false,
359
+ jsx: 'transform',
360
+ jsxFactory: 'React.createElement',
361
+ jsxFragment: 'React.Fragment',
362
+ logOverride: { 'unsupported-dynamic-import': 'error', 'unsupported-require-call': 'error' },
363
+ tsconfigRaw: { compilerOptions: { verbatimModuleSyntax: true } },
364
+ plugins: [platformPlugin(), capturePlugin],
365
+ });
366
+ }
367
+ catch (error) {
368
+ if (error instanceof PageBundleError)
369
+ throw error;
370
+ const errors = error.errors;
371
+ if (!Array.isArray(errors) || errors.length === 0)
372
+ throw new PageBundleError(String(error.message ?? 'bundle failed'));
373
+ throw new PageBundleError([...new Set(errors.slice(0, 20).map(message => describe(message, root)))].join('\n'));
374
+ }
375
+ hooks?.onMetafile?.(result.metafile);
376
+ await hooks?.afterBundle?.();
377
+ // The resolved entry is checked against the project root before
378
+ // assembly: an entry symlink pointing outside (even to a CommonJS
379
+ // file, even across Windows drives) is an outside-the-project refusal,
380
+ // not a missing default export. A missing entry keeps its lexical
381
+ // in-project key and still reports the no-default-export message from
382
+ // assembly below.
383
+ if (isOutsideRoot(path_1.default.relative(realRoot, realEntry))) {
384
+ throw new PageBundleError(`${entryKey}: imported from outside the project directory; a page can only import files inside its project`);
385
+ }
386
+ // entrySource, sources and compiled all come from the same pre-build
387
+ // capture: assembly reads only the captured map and the metafile.
388
+ const { sources, entrySource } = assembleSources(captured, result.metafile, realRoot, entryKey);
389
+ const js = result.outputFiles.find(file => file.path.endsWith('.js'))?.text ?? '';
390
+ const css = result.outputFiles.find(file => file.path.endsWith('.css'))?.text ?? '';
391
+ const compiled = `${WRAP_PREFIX}${js}${WRAP_SUFFIX}`;
392
+ if (/<\/script/i.test(compiled))
393
+ throw new PageBundleError('the compiled page contains "</script", which would end the script tag it is served in; split the string (for example "<\\/script")');
394
+ const size = Buffer.byteLength(compiled);
395
+ if (size > exports.COMPILED_LIMIT_BYTES)
396
+ throw new PageBundleError(`the compiled page is ${size} bytes, over the 2 MiB (${exports.COMPILED_LIMIT_BYTES} bytes) limit`);
397
+ return { compiled, compiledCss: css, sources, compilerVersion: esbuild_1.version, entrySource };
398
+ }
@@ -5,6 +5,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
5
5
  Object.defineProperty(exports, "__esModule", { value: true });
6
6
  exports.listCodePages = listCodePages;
7
7
  exports.readPageBodies = readPageBodies;
8
+ exports.bundleCodePages = bundleCodePages;
8
9
  exports.buildPagesSyncPayload = buildPagesSyncPayload;
9
10
  exports.formatPagesSummary = formatPagesSummary;
10
11
  exports.pagesSyncOutcome = pagesSyncOutcome;
@@ -16,12 +17,14 @@ const path_1 = __importDefault(require("path"));
16
17
  const axios_1 = __importDefault(require("axios"));
17
18
  const api_1 = require("./api");
18
19
  const validate_items_1 = require("./validate-items");
20
+ const page_bundle_1 = require("./page-bundle");
19
21
  function listCodePages(config) {
20
22
  return (config.pages ?? []).filter(page => !(0, validate_items_1.isPagePointer)(page)).map(page => ({
21
23
  slug: page.id,
22
24
  name: page.name,
23
25
  path: page.file,
24
26
  kind: page.file.endsWith('.html') ? 'visual' : 'dashboard',
27
+ language: page.file.endsWith('.tsx') ? 'tsx' : 'html',
25
28
  home: page.home ?? false,
26
29
  ...(page.sources === undefined ? {} : { sources: page.sources }),
27
30
  }));
@@ -29,8 +32,31 @@ function listCodePages(config) {
29
32
  function readPageBodies(sourceDir, pages) {
30
33
  return new Map(pages.map(page => [page.slug, fs_1.default.readFileSync(path_1.default.join(sourceDir, page.path), 'utf8')]));
31
34
  }
32
- function buildPagesSyncPayload(pages, bodies, deploymentId, codeRef) {
33
- return { deployment_id: deploymentId, code_ref: codeRef, pages: pages.map(page => ({ ...page, body: bodies.get(page.slug) })) };
35
+ async function bundleCodePages(sourceDir, pages) {
36
+ const bundles = new Map();
37
+ const errors = [];
38
+ for (const page of pages.filter(candidate => candidate.language === 'tsx')) {
39
+ try {
40
+ bundles.set(page.slug, await (0, page_bundle_1.bundlePage)(path_1.default.join(sourceDir, page.path), sourceDir));
41
+ }
42
+ catch (error) {
43
+ const lines = String(error?.message ?? 'bundle failed').split('\n');
44
+ errors.push(`page ${page.slug} (${page.path}): ${lines[0]}`, ...lines.slice(1).map(line => ` ${line}`));
45
+ }
46
+ }
47
+ return { bundles, errors };
48
+ }
49
+ function buildPagesSyncPayload(pages, bodies, deploymentId, codeRef, bundles) {
50
+ return {
51
+ deployment_id: deploymentId,
52
+ code_ref: codeRef,
53
+ pages: pages.map(page => {
54
+ const bundle = bundles?.get(page.slug);
55
+ if (bundle === undefined)
56
+ return { ...page, body: bodies.get(page.slug) };
57
+ return { ...page, body: bundle.entrySource, source_files: bundle.sources, compiled: bundle.compiled, compiled_css: bundle.compiledCss, compiler_version: bundle.compilerVersion };
58
+ }),
59
+ };
34
60
  }
35
61
  function formatPagesSummary(rows, trashed, trashErrors) {
36
62
  return [
@@ -0,0 +1,63 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.SANDBOX_BASE_PATH = void 0;
7
+ exports.isAppSandbox = isAppSandbox;
8
+ exports.readSandboxBase = readSandboxBase;
9
+ exports.writeSandboxBase = writeSandboxBase;
10
+ exports.baseWireValue = baseWireValue;
11
+ const fs_1 = __importDefault(require("fs"));
12
+ const path_1 = __importDefault(require("path"));
13
+ const crypto_1 = require("crypto");
14
+ exports.SANDBOX_BASE_PATH = path_1.default.join('.solidactions', 'base.json');
15
+ function isAppSandbox(env = process.env) {
16
+ return env.SOLIDACTIONS_APP_SANDBOX === '1';
17
+ }
18
+ function readSandboxBase(dir) {
19
+ try {
20
+ const base = JSON.parse(fs_1.default.readFileSync(path_1.default.join(dir, exports.SANDBOX_BASE_PATH), 'utf8'));
21
+ if (base === null || typeof base !== 'object' || Array.isArray(base))
22
+ return null;
23
+ const candidate = base;
24
+ if (candidate.source_hash !== null && (typeof candidate.source_hash !== 'string' || !/^[a-f0-9]{32}$/i.test(candidate.source_hash)))
25
+ return null;
26
+ if (typeof candidate.slug !== 'string' || candidate.slug.length === 0 || typeof candidate.restored_at !== 'string' || candidate.restored_at.length === 0)
27
+ return null;
28
+ return { source_hash: candidate.source_hash, slug: candidate.slug, restored_at: candidate.restored_at };
29
+ }
30
+ catch {
31
+ return null;
32
+ }
33
+ }
34
+ function writeSandboxBase(dir, base) {
35
+ const target = path_1.default.join(dir, exports.SANDBOX_BASE_PATH);
36
+ fs_1.default.mkdirSync(path_1.default.dirname(target), { recursive: true });
37
+ const temporary = path_1.default.join(path_1.default.dirname(target), `.${path_1.default.basename(target)}.${(0, crypto_1.randomUUID)()}.tmp`);
38
+ let fd;
39
+ let owned = false;
40
+ try {
41
+ fd = fs_1.default.openSync(temporary, 'wx', 0o600);
42
+ owned = true;
43
+ fs_1.default.writeFileSync(fd, JSON.stringify(base));
44
+ fs_1.default.fsyncSync(fd);
45
+ fs_1.default.closeSync(fd);
46
+ fd = undefined;
47
+ fs_1.default.renameSync(temporary, target);
48
+ owned = false;
49
+ }
50
+ finally {
51
+ try {
52
+ if (fd !== undefined)
53
+ fs_1.default.closeSync(fd);
54
+ }
55
+ finally {
56
+ if (owned)
57
+ fs_1.default.unlinkSync(temporary);
58
+ }
59
+ }
60
+ }
61
+ function baseWireValue(base) {
62
+ return base.source_hash ?? 'none';
63
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@solidactions/cli",
3
- "version": "3.31.0",
3
+ "version": "3.33.0",
4
4
  "description": "SolidActions CLI - Deploy and manage workflow automation",
5
5
  "main": "dist/index.js",
6
6
  "bin": {
@@ -46,6 +46,7 @@
46
46
  "chalk": "^4.1.2",
47
47
  "commander": "^11.0.0",
48
48
  "dotenv": "^17.3.1",
49
+ "esbuild": "0.28.2",
49
50
  "form-data": "^4.0.6",
50
51
  "fs-extra": "^11.0.0",
51
52
  "ignore": "^7.0.5",