embarko 0.0.0-stage → 0.1.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,189 @@
1
+ // Packaging rules ported from the skill's deploy.sh — keep the two in step.
2
+ import { execFileSync, spawnSync } from "node:child_process";
3
+ import { existsSync, readdirSync, readFileSync, statSync, mkdtempSync } from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+
7
+ const MANIFESTS = ["package.json", "requirements.txt", "pyproject.toml", "go.mod", "Gemfile", "composer.json", "Cargo.toml"];
8
+
9
+ // Names that are never source in any language Railpack builds. .env* is never
10
+ // sent: whatever is uploaded ends up in the image.
11
+ export const TAR_EXCLUDES = [
12
+ ".git", ".env*", ".DS_Store",
13
+ "node_modules", ".next", ".nuxt", ".svelte-kit", ".cache", ".parcel-cache", ".turbo",
14
+ "venv", ".venv", "__pycache__", ".pytest_cache", ".mypy_cache", ".ruff_cache", "*.pyc",
15
+ "vendor", ".bundle", "target", "_build", ".elixir_ls",
16
+ ];
17
+
18
+ const SKIP_WALK = new Set(["node_modules", ".git", "dist", "build", ".next", "venv", ".venv", "__pycache__", "vendor", "target"]);
19
+
20
+ export function readPackageJson(dir) {
21
+ try {
22
+ return JSON.parse(readFileSync(path.join(dir, "package.json"), "utf8"));
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+
28
+ export function slugifyAppName(raw) {
29
+ let name = String(raw).toLowerCase().replace(/[^a-z0-9]+/g, "-");
30
+ name = name.replace(/^-/, "").slice(0, 63).replace(/-$/, "");
31
+ return name;
32
+ }
33
+
34
+ // What's wrong with a name, or null if the API will accept it. The name is
35
+ // the live subdomain, so it has to be a DNS label.
36
+ export function appNameProblem(name) {
37
+ if (!name) return "it is empty";
38
+ if (!/^[a-z0-9-]+$/.test(name)) return "it may only contain lowercase letters, digits and dashes";
39
+ if (name.length < 3) return "it must be at least 3 characters";
40
+ if (name.length > 63) return "it must be at most 63 characters";
41
+ if (name.startsWith("-") || name.endsWith("-")) return "it can't start or end with a dash";
42
+ if (name.startsWith("xn--")) return "it can't start with xn--";
43
+ return null;
44
+ }
45
+
46
+ // A name passed in is checked as is, never rewritten.
47
+ export function resolveAppName(dir, explicit) {
48
+ if (explicit) return { name: explicit, source: "--name" };
49
+ const fromPkg = readPackageJson(dir)?.name;
50
+ if (fromPkg) return { name: slugifyAppName(fromPkg.replace(/^@[^/]+\//, "")), source: "package.json" };
51
+ return { name: slugifyAppName(path.basename(path.resolve(dir))), source: "the folder name" };
52
+ }
53
+
54
+ export function resolveVersion(dir, explicit) {
55
+ if (explicit) return explicit;
56
+ try {
57
+ return execFileSync("git", ["-C", dir, "rev-parse", "--short", "HEAD"], { stdio: ["ignore", "pipe", "ignore"] })
58
+ .toString()
59
+ .trim();
60
+ } catch {
61
+ const d = new Date();
62
+ const p = (n) => String(n).padStart(2, "0");
63
+ return `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}${p(d.getSeconds())}`;
64
+ }
65
+ }
66
+
67
+ // Fail fast on what the build would reject minutes later. Returns an error
68
+ // message, or null.
69
+ export function preflight(dir) {
70
+ const storageHits = findWindowStorage(dir);
71
+ if (storageHits.length) {
72
+ return `found window.storage usage (not supported on Embarko) in:\n ${storageHits.join("\n ")}\nUse SQLite (better-sqlite3) instead, writing under DATA_DIR. Details: https://embarko.ai/docs/data`;
73
+ }
74
+
75
+ const pkg = readPackageJson(dir);
76
+ if (pkg) {
77
+ const delegate = delegatingRoot(dir, pkg);
78
+ if (delegate) {
79
+ return `${path.join(dir, "package.json")} has no dependencies of its own and hands its build to '${delegate}/'.\nEmbarko installs dependencies only at the root of what you upload, so the build would fail.\nDeploy the app itself, not the folder above it: embarko deploy ${path.join(dir, delegate)}\nOne deploy = one app: deploy a separate backend under its own name.`;
80
+ }
81
+ }
82
+
83
+ const hasManifest = MANIFESTS.some((m) => existsSync(path.join(dir, m)));
84
+ const hasIndex = existsSync(path.join(dir, "index.html"));
85
+ if (!hasManifest && !hasIndex) {
86
+ for (const entry of safeReaddir(dir)) {
87
+ if (!entry.isDirectory() || SKIP_WALK.has(entry.name)) continue;
88
+ const hit = [...MANIFESTS, "index.html"].find((m) => existsSync(path.join(dir, entry.name, m)));
89
+ if (hit) {
90
+ return `no app manifest (package.json, requirements.txt, ...) or index.html at the root of ${dir}, but found ${path.join(entry.name, hit)}.\nThe app looks nested one folder too deep. Deploy that folder instead: embarko deploy ${path.join(dir, entry.name)}`;
91
+ }
92
+ }
93
+ const html = safeReaddir(dir).filter((e) => e.isFile() && e.name.endsWith(".html")).map((e) => e.name);
94
+ if (html.length) {
95
+ return `this looks like a static site with no index.html at its root (found ${html.join(", ")}).\nRename or copy the main page to index.html and deploy again.`;
96
+ }
97
+ }
98
+ return null;
99
+ }
100
+
101
+ // Mirrors detectDelegatingRoot in the server's detect-manifest-root.js.
102
+ function delegatingRoot(dir, pkg) {
103
+ if (Object.keys(pkg.dependencies || {}).length + Object.keys(pkg.devDependencies || {}).length > 0) return null;
104
+ const patterns = [/--prefix[= ]+(\S+)/, /--cwd[= ]+(\S+)/, /--dir[= ]+(\S+)/, /(?:^|&&|;|\|)\s*cd\s+([^\s&;|]+)/];
105
+ const candidates = [];
106
+ for (const name of ["build", "start"]) {
107
+ const text = (pkg.scripts || {})[name];
108
+ if (typeof text !== "string") continue;
109
+ for (const p of patterns) {
110
+ const m = p.exec(text);
111
+ if (m) candidates.push(m[1]);
112
+ }
113
+ }
114
+ const ws = Array.isArray(pkg.workspaces) ? pkg.workspaces : Array.isArray(pkg.workspaces?.packages) ? pkg.workspaces.packages : [];
115
+ for (const w of ws) if (typeof w === "string") candidates.push(w);
116
+ for (let c of candidates) {
117
+ c = c.replace(/^\.\//, "").replace(/\/+$/, "");
118
+ if (!c || c === "." || c.includes("..") || path.isAbsolute(c)) continue;
119
+ if (existsSync(path.join(dir, c, "package.json"))) return c;
120
+ }
121
+ return null;
122
+ }
123
+
124
+ function findWindowStorage(dir) {
125
+ const hits = [];
126
+ const walk = (d, depth) => {
127
+ if (depth > 8 || hits.length >= 10) return;
128
+ for (const e of safeReaddir(d)) {
129
+ const p = path.join(d, e.name);
130
+ if (e.isDirectory()) {
131
+ if (!SKIP_WALK.has(e.name) && !e.name.startsWith(".")) walk(p, depth + 1);
132
+ } else if (/\.(jsx?|tsx?)$/.test(e.name)) {
133
+ try {
134
+ if (statSync(p).size < 2_000_000 && readFileSync(p, "utf8").includes("window.storage")) hits.push(path.relative(dir, p));
135
+ } catch {}
136
+ }
137
+ }
138
+ };
139
+ walk(dir, 0);
140
+ return hits;
141
+ }
142
+
143
+ function safeReaddir(d) {
144
+ try {
145
+ return readdirSync(d, { withFileTypes: true });
146
+ } catch {
147
+ return [];
148
+ }
149
+ }
150
+
151
+ // Python virtualenvs can have any name but always hold a pyvenv.cfg.
152
+ function findVenvs(dir) {
153
+ const out = [];
154
+ const walk = (d, depth) => {
155
+ if (depth > 4) return;
156
+ for (const e of safeReaddir(d)) {
157
+ if (!e.isDirectory() || e.name === "node_modules" || e.name === ".git") continue;
158
+ const p = path.join(d, e.name);
159
+ if (existsSync(path.join(p, "pyvenv.cfg"))) out.push(path.relative(dir, p));
160
+ else walk(p, depth + 1);
161
+ }
162
+ };
163
+ walk(dir, 1);
164
+ return out;
165
+ }
166
+
167
+ // Builds the tar.gz with the system tar (bsdtar on macOS and Windows 10+,
168
+ // GNU tar on Linux). Returns { file, venvs }.
169
+ export function packDir(dir, appName) {
170
+ const venvs = findVenvs(dir);
171
+ const excludes = [...TAR_EXCLUDES.map((e) => `--exclude=${e}`), ...venvs.map((v) => `--exclude=./${v}`)];
172
+
173
+ // Root dist is dropped only when package.json has a build script (the
174
+ // platform regenerates it). An --exclude can't anchor to the root in bsdtar,
175
+ // so the top-level entries are listed instead.
176
+ const dropRootDist = typeof readPackageJson(dir)?.scripts?.build === "string";
177
+ let entries = safeReaddir(dir)
178
+ .map((e) => e.name)
179
+ .filter((n) => !(n === "dist" && dropRootDist))
180
+ .map((n) => `./${n}`);
181
+ if (!entries.length) entries = ["."];
182
+
183
+ const tmp = mkdtempSync(path.join(os.tmpdir(), "embarko-"));
184
+ const file = path.join(tmp, `${appName}.tar.gz`);
185
+ const res = spawnSync("tar", ["-czf", file, ...excludes, "-C", dir, ...entries], { stdio: ["ignore", "ignore", "pipe"] });
186
+ if (res.error) throw new Error(`could not run tar: ${res.error.message}`);
187
+ if (res.status !== 0) throw new Error(`tar failed: ${res.stderr.toString().trim()}`);
188
+ return { file, tmp, venvs };
189
+ }
@@ -0,0 +1,21 @@
1
+ import { request } from "./api.js";
2
+
3
+ export const FINAL = new Set(["live", "failed", "crashed", "not_deployed"]);
4
+ export const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
5
+
6
+ // Polls a status URL until a final status or the time limit. Embarko sets no
7
+ // build timeout; the limit is ours so we don't wait forever.
8
+ export async function pollStatus(statusUrl, { token, kind, onTick, limitMs = 15 * 60_000 } = {}) {
9
+ const every = kind === "static" ? 2_000 : 10_000;
10
+ const deadline = Date.now() + limitMs;
11
+ let last = null;
12
+ while (Date.now() < deadline) {
13
+ const { status, data } = await request(statusUrl, { token });
14
+ last = data;
15
+ if (status === 401 || status === 404) return { timedOut: false, data, httpStatus: status };
16
+ if (FINAL.has(data.status)) return { timedOut: false, data };
17
+ onTick?.(data.status);
18
+ await sleep(every);
19
+ }
20
+ return { timedOut: true, data: last };
21
+ }