@40rty/ams-cli 0.0.0-stage → 0.2.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.
@@ -0,0 +1,86 @@
1
+ // Where this app's OWN production deploys to, read from the repository.
2
+ //
3
+ // `forty deploy` hosts the app on 40rty right away; this says where it will
4
+ // live once the developer ships it themselves, so the CLI can tell them which
5
+ // origin to allow then. Exported for `forty doctor` and the setup skill.
6
+ import { access, readdir, readFile } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+
9
+ async function exists(file) {
10
+ try {
11
+ await access(file);
12
+ return true;
13
+ } catch (err) {
14
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return false;
15
+ throw err;
16
+ }
17
+ }
18
+
19
+ async function list(dir) {
20
+ try {
21
+ return await readdir(dir);
22
+ } catch (err) {
23
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return [];
24
+ throw err;
25
+ }
26
+ }
27
+
28
+ /** This directory and its parents up to the repository root — an app may sit in a monorepo's subfolder, its CI at the root. */
29
+ async function upToRepoRoot(cwd) {
30
+ const dirs = [];
31
+ for (let dir = cwd; ; dir = path.dirname(dir)) {
32
+ dirs.push(dir);
33
+ if ((await exists(path.join(dir, '.git'))) || path.dirname(dir) === dir) return dirs;
34
+ }
35
+ }
36
+
37
+ /**
38
+ * The developer's own deploy target: `{ target, label, evidence }`, or `null`
39
+ * when the repository names none. `target` is one of oxygen, vercel, netlify,
40
+ * cloudflare, fly, docker. Explicit signals win; Hydrogen's default `oxygen()`
41
+ * vite plugin is the last resort, because every Hydrogen app starts with it.
42
+ */
43
+ export async function detectDeployTarget(cwd) {
44
+ let manifest = {};
45
+ try {
46
+ manifest = JSON.parse(await readFile(path.join(cwd, 'package.json'), 'utf8'));
47
+ } catch (err) {
48
+ if (err.code !== 'ENOENT') throw err;
49
+ }
50
+ const deps = { ...manifest.dependencies, ...manifest.devDependencies };
51
+ const scripts = Object.values(manifest.scripts === undefined ? {} : manifest.scripts).join('\n');
52
+ const found = (target, label, evidence) => ({ target, label, evidence });
53
+
54
+ for (const dir of await upToRepoRoot(cwd)) {
55
+ const workflows = (await list(path.join(dir, '.github', 'workflows'))).filter((f) => /^oxygen-deployment-.*\.ya?ml$/.test(f));
56
+ if (workflows.length > 0) return found('oxygen', 'Shopify Oxygen', path.relative(cwd, path.join(dir, '.github', 'workflows', workflows[0])));
57
+ }
58
+ if (/hydrogen deploy/.test(scripts)) return found('oxygen', 'Shopify Oxygen', 'package.json script runs `shopify hydrogen deploy`');
59
+
60
+ const files = [
61
+ ['vercel.json', 'vercel', 'Vercel'],
62
+ ['.vercel/project.json', 'vercel', 'Vercel'],
63
+ ['netlify.toml', 'netlify', 'Netlify'],
64
+ ['wrangler.toml', 'cloudflare', 'Cloudflare Workers'],
65
+ ['wrangler.json', 'cloudflare', 'Cloudflare Workers'],
66
+ ['wrangler.jsonc', 'cloudflare', 'Cloudflare Workers'],
67
+ ['fly.toml', 'fly', 'Fly.io'],
68
+ ];
69
+ for (const [file, target, label] of files) if (await exists(path.join(cwd, file))) return found(target, label, file);
70
+ for (const [dep, target, label] of [
71
+ ['@vercel/remix', 'vercel', 'Vercel'],
72
+ ['@vercel/react-router', 'vercel', 'Vercel'],
73
+ ['@netlify/remix-adapter', 'netlify', 'Netlify'],
74
+ ['@netlify/vite-plugin-react-router', 'netlify', 'Netlify'],
75
+ ]) if (deps[dep] !== undefined) return found(target, label, `package.json depends on ${dep}`);
76
+ if (await exists(path.join(cwd, 'Dockerfile'))) return found('docker', 'a container (Dockerfile)', 'Dockerfile');
77
+
78
+ for (const config of ['vite.config.ts', 'vite.config.js', 'vite.config.mts']) {
79
+ const text = await readFile(path.join(cwd, config), 'utf8').catch((err) => {
80
+ if (err.code === 'ENOENT') return '';
81
+ throw err;
82
+ });
83
+ if (/\boxygen\(/.test(text)) return found('oxygen', 'Shopify Oxygen', `${config} uses the oxygen() plugin (Hydrogen's default)`);
84
+ }
85
+ return null;
86
+ }
@@ -0,0 +1,116 @@
1
+ // `forty deploy`'s build: a Hydrogen app as Vercel's Build Output (v3) — the
2
+ // client as static files, the Oxygen worker as one Edge Function — plus the
3
+ // env the hosted site runs with.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { createHash } from 'node:crypto';
6
+ import { cp, mkdir, readdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { fail } from './context.mjs';
9
+ import { findCredential } from './credentials.mjs';
10
+
11
+ /** Inside `dist/`, which a Hydrogen app already ignores — never the developer's own `.vercel/`. */
12
+ const OUTPUT_DIR = path.join('dist', 'forty-output');
13
+
14
+ // The Oxygen worker (`export default { fetch(request, env, ctx) }`) as a Vercel
15
+ // Edge Function. Vercel Edge has no Cache API, so Hydrogen's cache is a no-op
16
+ // there: every storefront query goes to Shopify uncached.
17
+ const EDGE_ENTRY = `import worker from './server.js';
18
+ const noCache = {match: async () => undefined, put: async () => {}, delete: async () => false};
19
+ globalThis.caches ??= {open: async () => noCache, default: noCache};
20
+ export default function handler(request, context) {
21
+ return worker.fetch(request, process.env, {waitUntil: (p) => context?.waitUntil?.(p), passThroughOnException() {}});
22
+ }
23
+ `;
24
+
25
+ /** `shopify hydrogen build`, in this app, with its output on the terminal. */
26
+ export function buildHydrogen(cwd) {
27
+ const run = spawnSync('npx', ['--no-install', 'shopify', 'hydrogen', 'build', '--no-lockfile-check'], { cwd, stdio: 'inherit' });
28
+ if (run.error !== undefined) fail(`could not run \`shopify hydrogen build\` (${run.error.message})`);
29
+ if (run.status !== 0) fail('`shopify hydrogen build` failed — fix the build, then run `forty deploy` again');
30
+ }
31
+
32
+ /** Lay `dist/client` + `dist/server` out as a Build Output under OUTPUT_DIR. */
33
+ export async function assembleBuildOutput(cwd) {
34
+ const out = path.join(cwd, OUTPUT_DIR);
35
+ const func = path.join(out, 'functions', 'index.func');
36
+ await rm(out, { recursive: true, force: true });
37
+ await mkdir(func, { recursive: true });
38
+ await cp(path.join(cwd, 'dist', 'client'), path.join(out, 'static'), { recursive: true });
39
+ // The worker and any chunk or wasm it imports — not its source map, metafile or bundle report. Its entry becomes server.js.
40
+ const runtime = (src) => !/\.[a-z]+$/.test(src) || /\.(m?js|wasm)$/.test(src);
41
+ await cp(path.join(cwd, 'dist', 'server'), func, { recursive: true, filter: runtime });
42
+ await rename(path.join(func, 'index.js'), path.join(func, 'server.js'));
43
+ await writeFile(path.join(func, 'index.js'), EDGE_ENTRY);
44
+ await writeFile(path.join(func, '.vc-config.json'), JSON.stringify({ runtime: 'edge', entrypoint: 'index.js' }));
45
+ await writeFile(path.join(out, 'config.json'), JSON.stringify({ version: 3, routes: [{ handle: 'filesystem' }, { src: '/(.*)', dest: '/index' }] }));
46
+ return out;
47
+ }
48
+
49
+ /** Every file under `dir` as `{ file, sha, size, abs }`, `file` relative with forward slashes. */
50
+ export async function listOutputFiles(dir) {
51
+ const entries = await readdir(dir, { recursive: true, withFileTypes: true });
52
+ const files = [];
53
+ for (const entry of entries) {
54
+ if (!entry.isFile()) continue;
55
+ const abs = path.join(entry.parentPath, entry.name);
56
+ const bytes = await readFile(abs);
57
+ files.push({ file: path.relative(dir, abs).split(path.sep).join('/'), sha: createHash('sha1').update(bytes).digest('hex'), size: bytes.byteLength, abs });
58
+ }
59
+ return files;
60
+ }
61
+
62
+ /** What a Hydrogen app cannot start without. */
63
+ const REQUIRED = ['SESSION_SECRET', 'PUBLIC_STORE_DOMAIN', 'PUBLIC_STOREFRONT_API_TOKEN'];
64
+ /** Read by Hydrogen when present; public by Shopify's own naming. */
65
+ const KNOWN = ['PUBLIC_CHECKOUT_DOMAIN', 'SHOP_ID', 'PUBLIC_STOREFRONT_ID'];
66
+ const LOOKS_SECRET = /SECRET|TOKEN|PRIVATE|PASSWORD|PASSWD|CREDENTIAL|(^|_)KEY$|(^|_)AUTH/;
67
+
68
+ /**
69
+ * The env the hosted site runs with, from the app's `.env`: what Hydrogen
70
+ * needs, anything `PUBLIC_`, anything that does not look like a secret, and
71
+ * whatever the developer opted in with `--env KEY`. `FORTY_*` never — the site
72
+ * is the space's published face, and `FORTY_DEV_TOKEN` would turn it into a
73
+ * developer's preview.
74
+ */
75
+ export function pickDeployEnv(dotenv, optIn) {
76
+ for (const key of REQUIRED) if (typeof dotenv[key] !== 'string' || dotenv[key] === '') fail(`.env must set ${key} — the app cannot start without it`);
77
+ const env = {};
78
+ const withheld = [];
79
+ for (const [key, value] of Object.entries(dotenv)) {
80
+ if (key.startsWith('FORTY_')) continue;
81
+ if (REQUIRED.includes(key) || KNOWN.includes(key) || key.startsWith('PUBLIC_') || optIn.includes(key) || !LOOKS_SECRET.test(key)) env[key] = value;
82
+ else withheld.push(key);
83
+ }
84
+ for (const key of optIn) {
85
+ if (key.startsWith('FORTY_')) fail(`--env ${key}: 40rty credentials are never deployed`);
86
+ if (env[key] === undefined) fail(`--env ${key}: not set in .env`);
87
+ }
88
+ return { env, withheld };
89
+ }
90
+
91
+ /** PUT one file's bytes to the api. */
92
+ async function putFile(apiUrl, route, key, file) {
93
+ const bytes = await readFile(file.abs);
94
+ const res = await fetch(`${apiUrl}${route}/files/${file.sha}`, {
95
+ method: 'PUT',
96
+ headers: { 'content-type': 'application/octet-stream', 'x-api-key': key },
97
+ body: bytes,
98
+ });
99
+ if (!res.ok) {
100
+ const body = await res.json().catch(() => ({ error: `HTTP ${res.status}` }));
101
+ fail(`uploading ${file.file} → ${res.status}: ${body.error}`);
102
+ }
103
+ }
104
+
105
+ /** Upload the files the api asked for, a few at a time. */
106
+ export async function uploadFiles(apiUrl, route, files, shas) {
107
+ const credential = await findCredential(apiUrl);
108
+ if (credential === null) fail('not signed in — run `forty login`, or set FORTY_API_KEY in CI');
109
+ const wanted = new Set(shas);
110
+ // One upload per sha, even when two paths share content.
111
+ const queue = [...new Map(files.filter((f) => wanted.has(f.sha)).map((f) => [f.sha, f])).values()];
112
+ const worker = async () => {
113
+ for (let file = queue.shift(); file !== undefined; file = queue.shift()) await putFile(apiUrl, route, credential.key, file);
114
+ };
115
+ await Promise.all(Array.from({ length: 6 }, worker));
116
+ }
@@ -0,0 +1,28 @@
1
+ // The last command that failed on this machine, so `forty feedback` can say
2
+ // what broke without the reporter retyping it. Kept beside the credentials;
3
+ // holds the error message only — never arguments, which may carry secrets.
4
+ import { mkdir, readFile, writeFile } from 'node:fs/promises';
5
+ import os from 'node:os';
6
+ import path from 'node:path';
7
+
8
+ const FILE = path.join(os.homedir(), '.config', 'forty', 'last-failure.json');
9
+
10
+ export async function recordFailure(command, message) {
11
+ try {
12
+ await mkdir(path.dirname(FILE), { recursive: true, mode: 0o700 });
13
+ await writeFile(FILE, `${JSON.stringify({ command, message, at: new Date().toISOString() })}\n`, { mode: 0o600 });
14
+ } catch (err) {
15
+ // Bookkeeping for a later report: never worth failing the command over.
16
+ console.warn(`forty: could not record the failure (${err.message})`);
17
+ }
18
+ }
19
+
20
+ export async function readLastFailure() {
21
+ try {
22
+ return JSON.parse(await readFile(FILE, 'utf8'));
23
+ } catch (err) {
24
+ if (err.code === 'ENOENT') return null;
25
+ console.warn(`forty: could not read the last failure (${err.message})`);
26
+ return null;
27
+ }
28
+ }
@@ -0,0 +1,41 @@
1
+ // A package's own Tailwind utilities, for its published bundle.
2
+ //
3
+ // A bundle is loaded into a page the package's author does not control, so the
4
+ // utility classes its components use have to travel with it. With
5
+ // `bundle.tailwind` in forty.config.json naming the package's Tailwind input
6
+ // CSS, that file is compiled here — with the Tailwind the PACKAGE depends on,
7
+ // resolved from the package itself — and the result is appended to the bundle's
8
+ // stylesheet. The input decides what is emitted: theme variables and utilities,
9
+ // never a preflight, because base styles belong to the page that hosts it.
10
+ //
11
+ // Tailwind is resolved from the INPUT FILE's location (as its own `@import`s
12
+ // are), and sources are detected from the package being published — so one
13
+ // shared input can serve many packages.
14
+ import { createRequire } from 'node:module';
15
+ import { readFile } from 'node:fs/promises';
16
+ import path from 'node:path';
17
+ import { cwd, fail } from './context.mjs';
18
+
19
+ const NEEDS = ['postcss', '@tailwindcss/postcss'];
20
+
21
+ export async function compileTailwind(input) {
22
+ const file = path.resolve(cwd, input);
23
+ const require = createRequire(file);
24
+ const modules = {};
25
+ for (const name of NEEDS) {
26
+ try {
27
+ modules[name] = require(name);
28
+ } catch (err) {
29
+ fail(`bundle.tailwind needs "${name}" installed where ${input} lives (${err.code})`);
30
+ }
31
+ }
32
+ let source;
33
+ try {
34
+ source = await readFile(file, 'utf8');
35
+ } catch (err) {
36
+ fail(`cannot read bundle.tailwind ${input} (${err.code})`);
37
+ }
38
+ const plugin = modules['@tailwindcss/postcss']({ base: cwd, optimize: { minify: true } });
39
+ const result = await modules.postcss([plugin]).process(source, { from: file });
40
+ return result.css;
41
+ }