@lizard-build/cli 4.0.98 → 4.0.100
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/commands/fn.d.ts +7 -0
- package/dist/commands/fn.js +221 -130
- package/dist/commands/fn.js.map +1 -1
- package/dist/lib/skills-data.generated.js +1 -1
- package/dist/lib/skills-data.generated.js.map +1 -1
- package/dist/lib/updater.d.ts +1 -1
- package/dist/lib/updater.js +1 -1
- package/dist/lib/updater.js.map +1 -1
- package/package.json +1 -1
- package/skill-data/core/references/functions.md +61 -30
- package/src/commands/fn.ts +177 -110
- package/src/lib/updater.ts +1 -1
|
@@ -9,39 +9,69 @@ Use a function for: an API endpoint or webhook (`--url`), a cron job (`--schedul
|
|
|
9
9
|
scraper or a data job you call from code, work queued from elsewhere. Use `lizard up` (a
|
|
10
10
|
service) instead for a long-running server or anything with its own process manager.
|
|
11
11
|
|
|
12
|
-
##
|
|
12
|
+
## The whole loop, for agents
|
|
13
|
+
|
|
14
|
+
1. Write the handler file (Python, Node.js, TypeScript, Ruby, Go or Rust).
|
|
15
|
+
2. Run `lizard fn deploy <path> --json` (add `--schedule "every hour"` for a job, `--test` to call it once).
|
|
16
|
+
3. If `status` is not `"ready"`, run the `remediation` command exactly, then go back to 2.
|
|
17
|
+
|
|
18
|
+
Deploy is idempotent by name and checks that the code **starts** before it takes traffic: an
|
|
19
|
+
update that fails to start leaves the previous version serving (`serving.unchanged: true`).
|
|
20
|
+
|
|
21
|
+
## `lizard fn deploy`
|
|
13
22
|
|
|
14
23
|
```bash
|
|
15
|
-
lizard fn deploy
|
|
24
|
+
lizard fn deploy scraper.py --schedule "every hour" --json
|
|
16
25
|
```
|
|
17
26
|
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
unchanged file and unchanged packages are a no-op (about 2 s), a code change about 4 s.
|
|
21
|
-
|
|
22
|
-
- **Source**: a file (`handler.py`, `index.mjs`, `lambda_function.rb`, `main.go`,
|
|
23
|
-
`bootstrap`), a directory, or `-` for stdin (with `--name` and `--runtime`).
|
|
24
|
-
- **Language and runtime**: from the file extension (Python 3.13, Node.js 22, Ruby 3.3) or
|
|
25
|
-
`--runtime` (`python3.9`-`3.13`, `nodejs18.x`-`24.x`, `ruby3.2`-`3.4`, `java11/17/21`,
|
|
26
|
-
`provided.al2023`). Go (`main.go` / `go.mod`) and Rust (`Cargo.toml`) are compiled on
|
|
27
|
-
Lizard into an Amazon Linux 2023 `bootstrap`. TypeScript: compile to `.js` first.
|
|
28
|
-
- **Handler**: found in the source (`def lambda_handler(event, context)` / `handler`,
|
|
27
|
+
- **Source**: a file, a directory, or `-` (stdin, with `--name` and `--runtime`). Language,
|
|
28
|
+
runtime and handler come from the source (`def handler(event, context)`,
|
|
29
29
|
`export const handler = async (event) => ...`); `--handler module.function` overrides.
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
30
|
+
TypeScript (`index.ts`), Go (`main.go` / `go.mod`) and Rust (`Cargo.toml`) are compiled on Lizard.
|
|
31
|
+
- **Packages, one rule** (the result's `packages.source` says which applied):
|
|
32
|
+
1. a dependency file in the source (`requirements.txt`, `package.json` with dependencies,
|
|
33
|
+
`Gemfile`, `go.mod`, `Cargo.toml`) is built into the code (`"file"`);
|
|
34
|
+
2. otherwise `--packages a,b==1.2` (`"flag"`; `--packages ''` removes them);
|
|
35
|
+
3. otherwise the packages the imports need are installed (`"imports"`: `bs4` ->
|
|
36
|
+
`beautifulsoup4`, `PIL` -> `pillow`, `yaml` -> `pyyaml`...); `--no-infer` turns it off.
|
|
37
|
+
Exact versions come back in `packages.resolved`; an unchanged list is not reinstalled
|
|
38
|
+
(`"cache": "hit"`). A dependency file and `--packages` together fail with `PACKAGES_CONFLICT`;
|
|
39
|
+
`import google` fails with `AMBIGUOUS_IMPORT` (name the package).
|
|
40
|
+
- **URL**: on by default for handlers that read HTTP events (`statusCode`, `rawPath`,
|
|
41
|
+
`queryStringParameters`...); `--url` / `--no-url`; `--auth key` requires signed requests.
|
|
42
|
+
The event is a function-URL event; return `{"statusCode": 200, "headers": {...}, "body": "..."}`.
|
|
43
|
+
- **Schedule**: `--schedule` takes `"every 15 minutes"`, `"hourly"`, `"daily at 09:00"`,
|
|
44
|
+
`"weekdays at 9am"`, `"every monday at 18:30"`, a 5-field cron (`"*/5 * * * *"`),
|
|
45
|
+
`rate(...)` or `cron(...)`; times are UTC; the result shows the expression and the next
|
|
46
|
+
runs. `--schedule off` removes it.
|
|
47
|
+
- **Settings**: `--env KEY=VALUE` (repeatable), `--memory <MB>`, `--timeout <s>`,
|
|
48
|
+
`--region us|eu`, `--project <id>`. `--test [event]` calls it after deploying (GET / for URL
|
|
49
|
+
functions) and fails with `TEST_FAILED` if it errors. `--no-check` skips the start check.
|
|
50
|
+
- Every deploy that changes something is a numbered **version** (`version` in the result).
|
|
51
|
+
|
|
52
|
+
Success (`--json`, stdout):
|
|
53
|
+
```json
|
|
54
|
+
{"schemaVersion": 1, "status": "ready", "name": "scraper", "region": "us-east-1", "version": 1, "created": true,
|
|
55
|
+
"changed": ["code", "packages", "schedule"], "runtime": "python3.13", "handler": "scraper.handler",
|
|
56
|
+
"packages": {"source": "imports", "resolved": {"requests": "2.34.2", "beautifulsoup4": "4.15.0"}, "cache": "miss"},
|
|
57
|
+
"check": {"kind": "start", "ok": true}, "url": null,
|
|
58
|
+
"schedule": {"input": "every hour", "expression": "rate(1 hour)", "timezone": "UTC", "nextRuns": ["..."]},
|
|
59
|
+
"next": [{"label": "run the schedule now", "command": "lizard fn invoke scraper --as-schedule --json"}]}
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
Failure (stdout empty, one JSON object on stderr, exit code below):
|
|
63
|
+
```json
|
|
64
|
+
{"schemaVersion": 1, "status": "failed", "phase": "check", "code": "IMPORT_ERROR",
|
|
65
|
+
"error": "The function failed to start: No module named 'yaml'", "missing": ["pyyaml"],
|
|
66
|
+
"serving": {"version": 1, "unchanged": true}, "logTail": "...",
|
|
67
|
+
"remediation": "lizard fn deploy scraper.py --packages requests,pyyaml --json"}
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
Codes: `INVALID_INPUT`, `INVALID_SCHEDULE`, `NOT_FOUND`, `REGION_REQUIRED`, `SOURCE_TOO_LARGE`,
|
|
71
|
+
`IMPORT_ERROR` (with `missing`), `HANDLER_NOT_FOUND` (with `candidates`), `START_FAILED`,
|
|
72
|
+
`BUILD_FAILED` (with `logTail`), `PACKAGES_CONFLICT`, `AMBIGUOUS_IMPORT`, `TEST_FAILED`,
|
|
73
|
+
`BUSY`, `TIMEOUT`. Exit codes: 0 ready, 1 build / start / test failure, 2 not signed in,
|
|
74
|
+
3 invalid input or not found, 4 timeout.
|
|
45
75
|
|
|
46
76
|
## Calling and watching
|
|
47
77
|
|
|
@@ -49,6 +79,7 @@ unchanged file and unchanged packages are a no-op (about 2 s), a code change abo
|
|
|
49
79
|
lizard fn invoke <name> '{"url": "https://example.com"}' --json # result (+ --logs)
|
|
50
80
|
lizard fn invoke <name> - < event.json
|
|
51
81
|
lizard fn invoke <name> '{}' --async # queued, returns at once
|
|
82
|
+
lizard fn invoke <name> --as-schedule --json # the event its schedule sends (run a job now)
|
|
52
83
|
lizard fn logs <name> --since 10m [-f] # print() / console.log output
|
|
53
84
|
lizard fn ls --json # every region
|
|
54
85
|
lizard fn rm <name>
|
|
@@ -106,7 +137,7 @@ func main() { lambda.Start(handler) }
|
|
|
106
137
|
|
|
107
138
|
- The first function of a runtime in a region takes up to a minute (the runtime image is
|
|
108
139
|
pulled once); later ones start in seconds. Idle functions pause and resume in about a second.
|
|
109
|
-
- Calls keep working during deploys and package installs
|
|
110
|
-
|
|
140
|
+
- Calls keep working during deploys and package installs: the new code starts next to the
|
|
141
|
+
running one and takes over once it has started.
|
|
111
142
|
- Billing is the sandbox time the function's environments use (paused is free).
|
|
112
143
|
- The dashboard's Functions page shows the same functions (code editor, test, logs, packages).
|
package/src/commands/fn.ts
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
import * as fs from "node:fs";
|
|
2
2
|
import * as path from "node:path";
|
|
3
|
+
import * as os from "node:os";
|
|
3
4
|
import * as zlib from "node:zlib";
|
|
5
|
+
import * as crypto from "node:crypto";
|
|
4
6
|
import { createHash } from "node:crypto";
|
|
5
7
|
import chalk from "chalk";
|
|
6
8
|
import { Command } from "commander";
|
|
@@ -51,8 +53,8 @@ export function detectSource(p: string, opts: { runtime?: string; handler?: stri
|
|
|
51
53
|
const names = files.map((f) => f.name);
|
|
52
54
|
const lang: Lang = langOfRuntime(opts.runtime) ?? (names.includes("Cargo.toml") ? "rust" : names.includes("go.mod") || entry.endsWith(".go") ? "go"
|
|
53
55
|
: /\.py$/.test(entry) ? "python" : /\.(m?js|cjs)$/.test(entry) ? "node" : /\.rb$/.test(entry) ? "ruby" : entry === "bootstrap" ? "shell"
|
|
54
|
-
: /\.ts$/.test(entry) ?
|
|
55
|
-
: (
|
|
56
|
+
: /\.(ts|mts|cts)$/.test(entry) ? "node" // compiled on Lizard (esbuild)
|
|
57
|
+
: (() => { throw Object.assign(new Error(`Can't tell the language of ${entry}: pass --runtime (e.g. python3.13, nodejs22.x, ruby3.3, provided.al2023)`), { code: "INVALID_INPUT", remediation: `lizard fn deploy ${entry} --runtime python3.13 --json` }); })());
|
|
56
58
|
const text = files.find((f) => f.name === entry)?.data.toString("utf8") ?? "";
|
|
57
59
|
const handler = opts.handler ?? (lang === "go" || lang === "rust" || lang === "shell" ? "bootstrap" : findHandler(lang, entry, text));
|
|
58
60
|
const deps = names.some((n) => ["requirements.txt", "Gemfile", "go.mod", "Cargo.toml"].includes(n))
|
|
@@ -82,7 +84,7 @@ function walk(root: string, rel = ""): Source["files"] {
|
|
|
82
84
|
out.push({ name: r, data: fs.readFileSync(path.join(root, r)), mode: st.mode & 0o111 ? 0o100755 : undefined });
|
|
83
85
|
}
|
|
84
86
|
const size = out.reduce((n, f) => n + f.data.length, 0);
|
|
85
|
-
if (size > 50 * 1024 * 1024)
|
|
87
|
+
if (size > 50 * 1024 * 1024) throw Object.assign(new Error(`${root} is ${Math.round(size / 1048576)} MB; a function's source is at most 50 MB (dependencies are installed by Lizard: don't ship node_modules or venv)`), { code: "SOURCE_TOO_LARGE", remediation: "lizard fn deploy <smaller directory> --json" });
|
|
86
88
|
return out;
|
|
87
89
|
}
|
|
88
90
|
|
|
@@ -90,15 +92,16 @@ function pickEntry(names: string[]): string {
|
|
|
90
92
|
for (const n of ["Cargo.toml", "go.mod", "lambda_function.py", "handler.py", "app.py", "main.py", "index.mjs", "index.js", "handler.mjs", "handler.js", "app.js", "lambda_function.rb", "handler.rb", "bootstrap"]) {
|
|
91
93
|
if (names.includes(n)) return n === "Cargo.toml" ? "src/main.rs" : n === "go.mod" ? (names.find((x) => !x.includes("/") && x.endsWith(".go")) ?? "main.go") : n;
|
|
92
94
|
}
|
|
95
|
+
for (const n of ["index.ts", "handler.ts", "app.ts"]) if (names.includes(n)) return n;
|
|
93
96
|
const top = names.filter((n) => !n.includes("/"));
|
|
94
|
-
const guess = top.find((n) => /\.(py|m?js|cjs|rb|go)$/.test(n));
|
|
95
|
-
if (!guess)
|
|
97
|
+
const guess = top.find((n) => /\.(py|m?js|cjs|rb|go|ts)$/.test(n) && !n.endsWith(".d.ts"));
|
|
98
|
+
if (!guess) throw Object.assign(new Error("No function file found: name it handler.py, index.mjs, index.ts, lambda_function.rb, main.go (or pass a file)"), { code: "INVALID_INPUT", remediation: "lizard fn deploy handler.py --json" });
|
|
96
99
|
return guess!;
|
|
97
100
|
}
|
|
98
101
|
|
|
99
102
|
/** The handler (module.function) from the source, as Lambda names it. */
|
|
100
103
|
export function findHandler(lang: Lang, entry: string, text: string): string {
|
|
101
|
-
const mod = entry.replace(/\.(py|m?js|cjs|rb)$/, "");
|
|
104
|
+
const mod = entry.replace(/\.(py|m?js|cjs|rb|ts|mts|cts)$/, "");
|
|
102
105
|
if (lang === "python") {
|
|
103
106
|
const names = [...text.matchAll(/^(?:async\s+)?def\s+([A-Za-z_]\w*)\s*\(\s*(\w+)\s*,\s*(\w+)\s*\)/gm)].map((m) => m[1]);
|
|
104
107
|
const fn = ["lambda_handler", "handler", "main"].find((n) => names.includes(n)) ?? names[0] ?? "lambda_handler";
|
|
@@ -156,7 +159,7 @@ async function resolveRegion(flag?: string): Promise<string> {
|
|
|
156
159
|
const all = await regions();
|
|
157
160
|
if (!flag) return all.includes("us-east-1") ? "us-east-1" : all[0] ?? "us-east-1";
|
|
158
161
|
const r = REGION_ALIASES[flag] ?? flag;
|
|
159
|
-
if (all.length && !all.includes(r)) fail(`Lizard Functions runs in ${all.join(", ")} (aliases: us, eu); not in ${flag}`,
|
|
162
|
+
if (all.length && !all.includes(r)) fail(`Lizard Functions runs in ${all.join(", ")} (aliases: us, eu); not in ${flag}`, 3, "INVALID_INPUT");
|
|
160
163
|
return r;
|
|
161
164
|
}
|
|
162
165
|
async function accounts(projectId: string): Promise<Account[]> {
|
|
@@ -220,7 +223,7 @@ async function waitBuild(acct: Account, id: string, spinner: (s: string) => void
|
|
|
220
223
|
function parseEnv(list: string[] | undefined): Record<string, string> | undefined {
|
|
221
224
|
if (!list?.length) return undefined;
|
|
222
225
|
const out: Record<string, string> = {};
|
|
223
|
-
for (const kv of list) { const i = kv.indexOf("="); if (i < 1) fail(`--env takes KEY=VALUE (got ${kv})`,
|
|
226
|
+
for (const kv of list) { const i = kv.indexOf("="); if (i < 1) fail(`--env takes KEY=VALUE (got ${kv})`, 3, "INVALID_INPUT"); out[kv.slice(0, i)] = kv.slice(i + 1); }
|
|
224
227
|
return out;
|
|
225
228
|
}
|
|
226
229
|
const splitList = (v?: string[] | string) => (Array.isArray(v) ? v : v ? [v] : []).flatMap((x) => x.split(/[,\s]+/)).map((x) => x.trim()).filter(Boolean);
|
|
@@ -247,120 +250,119 @@ Examples:
|
|
|
247
250
|
eval "$(lizard fn env)" # AWS SDK / CLI credentials and endpoint`);
|
|
248
251
|
|
|
249
252
|
fn.command("deploy")
|
|
250
|
-
.description("Create or update a function from a file, a directory or stdin (-)
|
|
253
|
+
.description("Create or update a function from a file, a directory or stdin (-): packages, build, start check, URL, schedule; waits until it is ready")
|
|
251
254
|
.argument("[path]", "file, directory or - for stdin", ".")
|
|
252
255
|
.option("--name <name>", "function name (default: from the file or directory)")
|
|
253
256
|
.option("--runtime <runtime>", "e.g. python3.13, nodejs22.x, ruby3.3, provided.al2023 (default: from the source)")
|
|
254
257
|
.option("--handler <handler>", "e.g. app.handler (default: found in the source)")
|
|
255
|
-
.option("--packages <list...>", "libraries
|
|
258
|
+
.option("--packages <list...>", "libraries, e.g. requests numpy==2.1.3 (comma or space separated; '' removes them). Default: a requirements.txt / package.json in the source, else what the imports need")
|
|
259
|
+
.option("--no-infer", "don't install packages from the imports when none are declared")
|
|
256
260
|
.option("--env <KEY=VALUE...>", "environment variables")
|
|
257
261
|
.option("--memory <mb>", "memory in MB", (v) => parseInt(v, 10))
|
|
258
262
|
.option("--timeout <seconds>", "timeout in seconds", (v) => parseInt(v, 10))
|
|
259
|
-
.option("--url", "give it a public HTTPS URL")
|
|
260
|
-
.option("--
|
|
263
|
+
.option("--url", "give it a public HTTPS URL (default: on for handlers that read HTTP events)")
|
|
264
|
+
.option("--no-url", "no URL")
|
|
265
|
+
.option("--auth <mode>", "URL access: none (public, default) or key (requests must be signed with an access key)")
|
|
266
|
+
.option("--schedule <when>", 'run it on a schedule: "every hour", "daily at 09:00", "*/5 * * * *", rate(...) or cron(...); "off" removes it')
|
|
267
|
+
.option("--test [event]", "after deploying, call it with this event (default {} / GET / for URL functions) and fail if it errors")
|
|
268
|
+
.option("--no-check", "skip the start check (the new code takes traffic without being started first)")
|
|
261
269
|
.option("--region <region>", "us-east-1 (us) or eu-west-lim-a (eu)")
|
|
262
270
|
.option("--project <id>", "project (default: the linked one)")
|
|
263
271
|
.action(async (p: string, o: any) => {
|
|
264
272
|
const t0 = Date.now(); tStart = t0;
|
|
265
273
|
const stdin = p === "-" ? fs.readFileSync(0, "utf8") : undefined;
|
|
266
|
-
if (p !== "-" && !fs.existsSync(p))
|
|
267
|
-
if (stdin !== undefined && !o.name)
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
const
|
|
272
|
-
|
|
274
|
+
if (p !== "-" && !fs.existsSync(p)) failEnv({ code: "INVALID_INPUT", error: `${p} does not exist`, remediation: "lizard fn deploy <file or directory> --json" }, 3);
|
|
275
|
+
if (stdin !== undefined && !o.name) failEnv({ code: "INVALID_INPUT", error: "--name is required with stdin", remediation: "echo '...' | lizard fn deploy - --name <name> --runtime python3.13 --json" }, 3);
|
|
276
|
+
let src: Source;
|
|
277
|
+
try { src = detectSource(p, { runtime: o.runtime, handler: o.handler, stdin }); }
|
|
278
|
+
catch (e: any) { failEnv({ code: e.code || "INVALID_INPUT", error: e.message, remediation: e.remediation || "lizard fn deploy <path> --runtime python3.13 --json" }, 3); }
|
|
279
|
+
const name: string = o.name ?? defaultName(p, src!);
|
|
280
|
+
if (!/^[A-Za-z0-9_-]{1,64}$/.test(name)) failEnv({ code: "INVALID_INPUT", error: `Function name ${name}: letters, numbers, hyphens and underscores, up to 64`, remediation: `lizard fn deploy ${p} --name my-function --json` }, 3);
|
|
281
|
+
const runtime = o.runtime && !/^(go|rust)$/.test(o.runtime) ? o.runtime : DEFAULT_RUNTIME[src!.lang];
|
|
273
282
|
const { projectId } = await resolveProjectScope(o.project);
|
|
274
283
|
const region = await resolveRegion(o.region);
|
|
275
284
|
status(`account in ${region}…`);
|
|
276
285
|
const acct = (await accountFor(projectId, region, true))!;
|
|
277
|
-
const
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
if (o.memory)
|
|
282
|
-
if (o.timeout)
|
|
286
|
+
const body: Record<string, unknown> = { ZipFile: zipFiles(src!.files).toString("base64"), Runtime: runtime, Handler: src!.handler };
|
|
287
|
+
if (o.packages !== undefined) body.Packages = splitList(o.packages);
|
|
288
|
+
if (o.infer === false) body.Infer = false;
|
|
289
|
+
if (o.check === false) body.Check = false;
|
|
290
|
+
if (o.memory) body.MemorySize = o.memory;
|
|
291
|
+
if (o.timeout) body.Timeout = o.timeout;
|
|
283
292
|
const env = parseEnv(o.env);
|
|
284
|
-
if (env)
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
status(existing ? "building…" : "creating (building)…");
|
|
292
|
-
if (existing) await waitReady(acct, name);
|
|
293
|
-
if (existing) await aws(acct, "PUT", `${fnPath(name)}/configuration`, config);
|
|
294
|
-
if (existing) await waitReady(acct, name);
|
|
295
|
-
const job = (await aws(acct, "POST", `lizard/functions/${encodeURIComponent(name)}/build`, {
|
|
296
|
-
ZipFile: zip, Runtime: runtime, ...(compiled && packages.length ? { Packages: packages } : {}),
|
|
297
|
-
...(existing ? {} : { Create: { Role: "arn:aws:iam::000000000000:role/lizard-function", MemorySize: 512, Timeout: 30, ...config } }),
|
|
298
|
-
})).data;
|
|
299
|
-
const b = await waitBuild(acct, job.BuildId, status);
|
|
300
|
-
if (b.Status !== "Succeeded") { statusDone(); fail(`Build failed: ${b.Error}\n${String(b.Log || "").slice(-3000)}`, 1, "BUILD_FAILED"); }
|
|
301
|
-
created = !existing;
|
|
302
|
-
} else if (existing) {
|
|
303
|
-
// Only what changed is sent: the same code (by SHA-256) and the same settings are no-ops.
|
|
304
|
-
const c = existing.Configuration ?? {};
|
|
305
|
-
if (c.LastUpdateStatus === "InProgress") await waitReady(acct, name);
|
|
306
|
-
if (c.CodeSha256 !== zipSha) {
|
|
307
|
-
status("updating code…");
|
|
308
|
-
await aws(acct, "PUT", `${fnPath(name)}/code`, { ZipFile: zip });
|
|
309
|
-
}
|
|
310
|
-
const changed = Object.entries(config).some(([k, v]) => JSON.stringify(k === "Environment" ? { Variables: c.Environment?.Variables ?? {} } : c[k]) !== JSON.stringify(v));
|
|
311
|
-
if (changed) {
|
|
312
|
-
status("updating settings…");
|
|
313
|
-
await waitReady(acct, name);
|
|
314
|
-
await aws(acct, "PUT", `${fnPath(name)}/configuration`, config);
|
|
315
|
-
}
|
|
316
|
-
} else {
|
|
317
|
-
status("creating…");
|
|
318
|
-
await aws(acct, "POST", "2015-03-31/functions", { FunctionName: name, Role: "arn:aws:iam::000000000000:role/lizard-function", MemorySize: 512, Timeout: 30, ...config, Code: { ZipFile: zip } });
|
|
319
|
-
created = true;
|
|
293
|
+
if (env) body.Environment = { Variables: env };
|
|
294
|
+
// --url / --no-url / default: "auto" (the service decides from the handler).
|
|
295
|
+
if (process.argv.includes("--no-url")) body.Url = false; else if (process.argv.includes("--url")) body.Url = true;
|
|
296
|
+
if (o.auth) {
|
|
297
|
+
if (!["none", "key", "public", "iam"].includes(o.auth)) failEnv({ code: "INVALID_INPUT", error: "--auth is none or key", remediation: `lizard fn deploy ${p} --auth key --json` }, 3);
|
|
298
|
+
body.UrlAuth = ["key", "iam"].includes(o.auth) ? "AWS_IAM" : "NONE";
|
|
299
|
+
if (!body.Url) body.Url = true;
|
|
320
300
|
}
|
|
301
|
+
if (o.schedule !== undefined) body.Schedule = /^(off|none|no)$/i.test(o.schedule) ? "" : o.schedule;
|
|
321
302
|
|
|
322
|
-
|
|
323
|
-
let
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
}
|
|
336
|
-
|
|
303
|
+
status("deploying…");
|
|
304
|
+
let start;
|
|
305
|
+
try { start = (await aws(acct, "POST", `lizard/functions/${encodeURIComponent(name)}/deploy`, body)).data; }
|
|
306
|
+
catch (e) {
|
|
307
|
+
if (e instanceof APIError && e.status === 400) failEnv({ code: /schedule/i.test(e.message) ? "INVALID_SCHEDULE" : "INVALID_INPUT", error: e.message, remediation: /schedule/i.test(e.message) ? `lizard fn deploy ${p} --schedule "every hour" --json` : `lizard fn deploy ${p} --json` }, 3);
|
|
308
|
+
if (e instanceof APIError && e.status === 409) failEnv({ code: "BUSY", error: e.message, remediation: `lizard fn deploy ${p} --json` }, 1);
|
|
309
|
+
throw e;
|
|
310
|
+
}
|
|
311
|
+
let d: any;
|
|
312
|
+
const end = Date.now() + 20 * 60_000;
|
|
313
|
+
for (;;) {
|
|
314
|
+
d = (await aws(acct, "GET", `lizard/deploys/${start.deployId}`)).data;
|
|
315
|
+
if (d.status !== "deploying") break;
|
|
316
|
+
status({ prepare: "preparing…", build: "building…", packages: "installing packages…", check: "starting the new code…" }[d.phase as string] ?? "deploying…");
|
|
317
|
+
if (Date.now() > end) failEnv({ code: "TIMEOUT", error: "The deploy did not finish in 20 minutes", remediation: `lizard fn deploy ${p} --json` }, 4);
|
|
318
|
+
await sleep(500);
|
|
319
|
+
}
|
|
320
|
+
statusDone();
|
|
321
|
+
const where = o.region ? ` --region ${region}` : "";
|
|
322
|
+
if (d.status !== "ready") {
|
|
323
|
+
failEnv({ ...d, phase: d.phase, remediation: remediationFor(d, p, src!, o), next: undefined }, 1);
|
|
337
324
|
}
|
|
338
|
-
const cfg = await waitReady(acct, name, 15 * 60_000, (c) => status(c.State === "Pending" ? "preparing the runtime (the first one in a region takes up to a minute)…" : "starting…"));
|
|
339
325
|
|
|
340
|
-
// URL
|
|
341
|
-
let
|
|
342
|
-
if (o.
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
326
|
+
// --test: call it now (a URL function gets a GET / unless an event is given).
|
|
327
|
+
let test: any = null;
|
|
328
|
+
if (o.test !== undefined) {
|
|
329
|
+
status("testing…");
|
|
330
|
+
if (d.url?.value && o.test === true) {
|
|
331
|
+
const r = await fetch(d.url.value, { signal: AbortSignal.timeout(60_000) }).catch((e) => ({ ok: false, status: 0, text: async () => String(e) } as any));
|
|
332
|
+
const text = await r.text();
|
|
333
|
+
test = { kind: "http", request: "GET /", status: r.status, ok: r.status > 0 && r.status < 500, body: text.slice(0, 2000) };
|
|
334
|
+
} else {
|
|
335
|
+
let ev: unknown = {};
|
|
336
|
+
if (typeof o.test === "string") { try { ev = JSON.parse(o.test); } catch { failEnv({ code: "INVALID_INPUT", error: "--test takes event JSON", remediation: `lizard fn deploy ${p} --test '{}' --json` }, 3); } }
|
|
337
|
+
const r = await aws(acct, "POST", `${fnPath(name)}/invocations`, ev, { headers: { "x-amz-log-type": "Tail" } });
|
|
338
|
+
const err = r.headers.get("x-amz-function-error");
|
|
339
|
+
const tail = r.headers.get("x-amz-log-result");
|
|
340
|
+
test = { kind: "invoke", ok: !err, error: err || undefined, result: r.data ?? null, logTail: tail ? Buffer.from(tail, "base64").toString("utf8").slice(-3000) : undefined };
|
|
347
341
|
}
|
|
342
|
+
statusDone();
|
|
343
|
+
if (!test.ok) failEnv({ schemaVersion: 1, status: "failed", phase: "test", code: "TEST_FAILED", name, region, version: d.version,
|
|
344
|
+
error: test.kind === "http" ? `GET / answered ${test.status}` : `The test invocation raised ${test.error}`, test, remediation: `lizard fn logs ${name}${where} --since 5m --json`,
|
|
345
|
+
serving: { version: d.version, unchanged: false } }, 1);
|
|
348
346
|
}
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
const
|
|
356
|
-
|
|
357
|
-
seconds: Number(secs), invoke: `lizard fn invoke ${name}${o.region ? ` --region ${region}` : ""} '{}'` };
|
|
347
|
+
|
|
348
|
+
const next = [
|
|
349
|
+
d.schedule ? { label: "run the schedule now", command: `lizard fn invoke ${name}${where} --as-schedule --json` } : { label: "call it", command: `lizard fn invoke ${name}${where} '{}' --json` },
|
|
350
|
+
...(d.url?.value ? [{ label: "call the URL", command: `curl -s ${d.url.value}` }] : []),
|
|
351
|
+
{ label: "logs", command: `lizard fn logs ${name}${where} --since 5m --json` },
|
|
352
|
+
];
|
|
353
|
+
const out = { schemaVersion: 1, status: "ready", name, region, version: d.version, created: d.created, changed: d.changed, runtime: d.runtime, handler: d.handler, language: d.language,
|
|
354
|
+
packages: d.packages, check: d.check, test, url: d.url ?? null, schedule: d.schedule ?? null, seconds: Number(((Date.now() - t0) / 1000).toFixed(1)), next };
|
|
358
355
|
if (isJSONMode()) return printJSON(out);
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
if (
|
|
363
|
-
|
|
356
|
+
const pk = d.packages ?? {};
|
|
357
|
+
const resolved = pk.resolved ? Object.entries(pk.resolved).map(([k, v]) => `${k} ${v}`).join(", ") : (pk.requested ?? []).join(", ");
|
|
358
|
+
const srcLabel = { file: "from the dependency file", flag: "from --packages", imports: "from the imports", none: "" }[pk.source as string] ?? "";
|
|
359
|
+
if (pk.source !== "none" && resolved) console.log(`${chalk.dim("Packages ")} ${resolved} ${chalk.dim(`(${srcLabel}${pk.cache === "hit" ? ", cached" : pk.installSeconds ? `, installed in ${pk.installSeconds}s` : ""})`)}`);
|
|
360
|
+
console.log(`${chalk.green(d.created ? "Created " : d.changed?.length ? "Updated " : "Unchanged")} ${chalk.bold(name)} in ${region} · ${d.runtime} · ${d.handler} · version ${d.version} · ${out.seconds}s`);
|
|
361
|
+
if (d.check?.kind === "start") console.log(`${chalk.dim("Checked ")} module loads and handler found${d.check.coldStartMs ? ` (cold start ${d.check.coldStartMs} ms)` : ""}`);
|
|
362
|
+
if (test) console.log(`${chalk.dim("Tested ")} ${test.kind === "http" ? `GET / -> ${test.status}` : "invoked, no error"}`);
|
|
363
|
+
if (d.url?.value) console.log(`${chalk.dim("URL ")} ${chalk.cyan(d.url.value)} ${d.url.auth === "none" ? "public (--auth key to require a key)" : "requires a signed request"}`);
|
|
364
|
+
if (d.schedule) console.log(`${chalk.dim("Schedule ")} ${d.schedule.input !== d.schedule.expression ? `${d.schedule.input} = ` : ""}${d.schedule.expression} ${d.schedule.timezone} · next ${d.schedule.nextRuns?.[0] ?? "-"}`);
|
|
365
|
+
console.log(`${chalk.dim("Next ")} ${next.map((n) => n.command).join("\n ")}`);
|
|
364
366
|
});
|
|
365
367
|
|
|
366
368
|
fn.command("invoke")
|
|
@@ -369,17 +371,25 @@ Examples:
|
|
|
369
371
|
.argument("[event]", "event JSON (default {}; - reads stdin)", "{}")
|
|
370
372
|
.option("--logs", "print the invocation's log")
|
|
371
373
|
.option("--async", "queue it (InvocationType Event) and return at once")
|
|
374
|
+
.option("--as-schedule", "send the event its schedule sends (run a scheduled job now)")
|
|
372
375
|
.option("--region <region>").option("--project <id>")
|
|
373
376
|
.action(async (name: string, event: string, o: any) => {
|
|
374
377
|
const acct = await existingAccount(o, name);
|
|
375
378
|
const body = event === "-" ? fs.readFileSync(0, "utf8") : event;
|
|
376
379
|
let parsed: unknown;
|
|
377
|
-
try { parsed = JSON.parse(body); } catch { fail("The event must be JSON",
|
|
380
|
+
try { parsed = JSON.parse(body); } catch { fail("The event must be JSON", 3, "INVALID_INPUT"); }
|
|
381
|
+
if (o.asSchedule) {
|
|
382
|
+
// EventBridge Scheduler's event for a function, as `lizard fn deploy --schedule` sets it.
|
|
383
|
+
const s = await aws(acct, "GET", `schedules/${encodeURIComponent(name)}`).catch(() => null);
|
|
384
|
+
let input: any = { source: "lizard.schedule", "detail-type": "Scheduled Event", detail: {} };
|
|
385
|
+
try { if (s?.data?.Target?.Input) input = JSON.parse(s.data.Target.Input); } catch { /* default */ }
|
|
386
|
+
parsed = { ...input, time: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"), id: crypto.randomUUID() };
|
|
387
|
+
}
|
|
378
388
|
const r = await aws(acct, "POST", `${fnPath(name)}/invocations`, parsed, { headers: { "x-amz-log-type": "Tail", ...(o.async ? { "x-amz-invocation-type": "Event" } : {}) } });
|
|
379
389
|
const err = r.headers.get("x-amz-function-error");
|
|
380
390
|
const tail = r.headers.get("x-amz-log-result");
|
|
381
391
|
const logs = tail ? Buffer.from(tail, "base64").toString("utf8") : "";
|
|
382
|
-
if (isJSONMode()) { if (err) process.exitCode =
|
|
392
|
+
if (isJSONMode()) { if (err) process.exitCode = EXIT.FAILED; return printJSON({ status: o.async ? "queued" : err ? "error" : "ok", error: err || undefined, result: r.data ?? null, logs: o.logs ? logs : undefined }); }
|
|
383
393
|
if (o.logs && logs) process.stderr.write(chalk.dim(logs.endsWith("\n") ? logs : logs + "\n"));
|
|
384
394
|
if (o.async) return success("Queued");
|
|
385
395
|
process.stdout.write((typeof r.data === "string" ? r.data : JSON.stringify(r.data ?? null, null, 2)) + "\n");
|
|
@@ -441,20 +451,77 @@ Examples:
|
|
|
441
451
|
|
|
442
452
|
fn.command("env")
|
|
443
453
|
.description("Print AWS credentials and endpoints for the project's functions (for the AWS SDKs / CLI): eval \"$(lizard fn env)\"")
|
|
454
|
+
.option("--new", "create a new access key instead of reusing this machine's")
|
|
444
455
|
.option("--region <region>").option("--project <id>")
|
|
445
456
|
.action(async (o: any) => {
|
|
446
457
|
const { projectId } = await resolveProjectScope(o.project);
|
|
447
458
|
const region = await resolveRegion(o.region);
|
|
448
459
|
await accountFor(projectId, region, true);
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
460
|
+
// One key per project on this machine, reused (eval'd in a shell profile, a key per run
|
|
461
|
+
// would pile up); kept only while the project still lists it.
|
|
462
|
+
const file = path.join(os.homedir(), ".lizard", "functions-keys.json");
|
|
463
|
+
let saved: Record<string, { accessKeyId: string; secretAccessKey: string; endpoints: Record<string, string> }> = {};
|
|
464
|
+
try { saved = JSON.parse(fs.readFileSync(file, "utf8")); } catch { saved = {}; }
|
|
465
|
+
let k = o.new ? null : saved[projectId] ?? null;
|
|
466
|
+
if (k) {
|
|
467
|
+
const live = await api.get<any>(`/api/functions/projects/${encodeURIComponent(projectId)}/keys`).catch(() => null);
|
|
468
|
+
if (!live?.keys?.some((x: any) => x.accessKeyId === k!.accessKeyId)) k = null;
|
|
469
|
+
else k.endpoints = live.endpoints ?? k.endpoints;
|
|
470
|
+
}
|
|
471
|
+
let created = false;
|
|
472
|
+
if (!k) {
|
|
473
|
+
k = await api.post<any>(`/api/functions/projects/${encodeURIComponent(projectId)}/keys`);
|
|
474
|
+
saved[projectId] = { accessKeyId: k!.accessKeyId, secretAccessKey: k!.secretAccessKey, endpoints: k!.endpoints };
|
|
475
|
+
fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
|
|
476
|
+
fs.writeFileSync(file, JSON.stringify(saved, null, 2), { mode: 0o600 });
|
|
477
|
+
created = true;
|
|
478
|
+
}
|
|
479
|
+
const ep = k!.endpoints?.[region];
|
|
480
|
+
if (!ep) fail(`No Functions endpoint for ${region}`, 1);
|
|
481
|
+
const sh = (v: string) => `'${String(v).replace(/'/g, "'\\''")}'`;
|
|
482
|
+
// Shell exports by default even when stdout is a pipe: `eval "$(lizard fn env)"` is the point.
|
|
483
|
+
if (process.argv.includes("--json")) return printJSON({ AWS_ACCESS_KEY_ID: k!.accessKeyId, AWS_SECRET_ACCESS_KEY: k!.secretAccessKey, AWS_REGION: region, AWS_ENDPOINT_URL_LAMBDA: ep, endpoints: k!.endpoints, created });
|
|
484
|
+
const vars: [string, string][] = [["AWS_ACCESS_KEY_ID", k!.accessKeyId], ["AWS_SECRET_ACCESS_KEY", k!.secretAccessKey], ["AWS_REGION", region], ["AWS_DEFAULT_REGION", region],
|
|
485
|
+
...["LAMBDA", "SQS", "SCHEDULER", "EVENTBRIDGE", "CLOUDWATCH_LOGS"].map((s2) => [`AWS_ENDPOINT_URL_${s2}`, ep] as [string, string])];
|
|
486
|
+
process.stdout.write(vars.map(([n, v]) => `export ${n}=${sh(v)}`).join("\n") + "\n");
|
|
487
|
+
if (created && process.stderr.isTTY) warn(`Created an access key for this project (saved in ${file}; Access keys in the dashboard lists and deletes keys).`);
|
|
455
488
|
});
|
|
456
489
|
}
|
|
457
490
|
|
|
491
|
+
// One table of exit codes for the whole CLI: 0 ok, 1 build/check/test failure, 2 authentication,
|
|
492
|
+
// 3 invalid input or not found, 4 timeout.
|
|
493
|
+
export const EXIT = { OK: 0, FAILED: 1, AUTH: 2, INVALID: 3, TIMEOUT: 4 } as const;
|
|
494
|
+
|
|
495
|
+
/** A failure for people and agents: stdout empty, one JSON envelope on stderr (--json / no TTY), or readable text. */
|
|
496
|
+
function failEnv(e: Record<string, any>, exit: number): never {
|
|
497
|
+
statusDone();
|
|
498
|
+
const env: Record<string, any> = { schemaVersion: 1, status: "failed", ...e };
|
|
499
|
+
for (const k of Object.keys(env)) if (env[k] === undefined || k === "deployId" || k === "log" || k === "startedAt" || k === "endedAt") delete (env as any)[k];
|
|
500
|
+
if (isJSONMode()) process.stderr.write(JSON.stringify(env, null, 2) + "\n");
|
|
501
|
+
else {
|
|
502
|
+
process.stderr.write(chalk.red(`Error (${env.code}): ${env.error}\n`));
|
|
503
|
+
if (env.serving?.unchanged) process.stderr.write(chalk.dim(`Version ${env.serving.version} is still serving: nothing changed.\n`));
|
|
504
|
+
if (env.logTail) process.stderr.write(chalk.dim(String(env.logTail).trim().split("\n").slice(-12).join("\n") + "\n"));
|
|
505
|
+
if (env.remediation) process.stderr.write(`Fix: ${chalk.cyan(env.remediation)}\n`);
|
|
506
|
+
}
|
|
507
|
+
process.exit(exit);
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
/** The exact command that fixes a failed deploy (every one is a command the CLI's tests run). */
|
|
511
|
+
function remediationFor(d: any, p: string, src: Source, o: any): string {
|
|
512
|
+
const base = `lizard fn deploy ${p}${o.name ? ` --name ${o.name}` : ""}${o.region ? ` --region ${o.region}` : ""}`;
|
|
513
|
+
const have: string[] = d.packages?.requested ?? splitList(o.packages);
|
|
514
|
+
switch (d.code) {
|
|
515
|
+
case "IMPORT_ERROR": return d.missing?.length ? `${base} --packages ${[...new Set([...have, ...d.missing])].join(",")} --json` : `${base} --json # fix the error in the log, then deploy again`;
|
|
516
|
+
case "HANDLER_NOT_FOUND": return d.candidates?.length ? `${base} --handler ${d.candidates[0]} --json` : `${base} --handler <module>.<function> --json`;
|
|
517
|
+
case "PACKAGES_CONFLICT": return `${base} --json # list packages in ${d.packages?.file ?? "the dependency file"} only (drop --packages)`;
|
|
518
|
+
case "AMBIGUOUS_IMPORT": return `${base} --packages <the package you need, e.g. ${String(d.ambiguous?.[0]?.choices ?? "").split(",")[0].trim()}> --json`;
|
|
519
|
+
case "BUILD_FAILED": return d.packages?.notFound ? `${base} --packages ${have.filter((x) => x !== d.packages.notFound).join(",") || "''"} --json # ${d.packages.notFound} does not exist` : `${base} --json # fix the build error in logTail`;
|
|
520
|
+
case "INVALID_SCHEDULE": return `${base} --schedule "every hour" --json`;
|
|
521
|
+
default: return `${base} --json`;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
|
|
458
525
|
function defaultName(p: string, src: Source): string {
|
|
459
526
|
const base = p === "." ? path.basename(process.cwd()) : fs.existsSync(p) && fs.statSync(p).isDirectory() ? path.basename(path.resolve(p)) : path.basename(p).replace(/\.[^.]+$/, "");
|
|
460
527
|
const n = (["handler", "lambda_function", "index", "main", "app", "bootstrap"].includes(base) ? path.basename(path.resolve(path.dirname(p === "." ? "./x" : p))) : base)
|
|
@@ -469,18 +536,18 @@ async function existingAccount(o: any, name: string): Promise<Account> {
|
|
|
469
536
|
if (o.region) {
|
|
470
537
|
const region = await resolveRegion(o.region);
|
|
471
538
|
const a = all.find((x) => x.region === region);
|
|
472
|
-
if (!a) fail(`No functions in ${region} for this project`,
|
|
539
|
+
if (!a) fail(`No functions in ${region} for this project`, 3, "NOT_FOUND");
|
|
473
540
|
return a!;
|
|
474
541
|
}
|
|
475
542
|
const holding: Account[] = [];
|
|
476
543
|
for (const a of all) if (await getFn(a, name).catch(() => null)) holding.push(a);
|
|
477
|
-
if (!holding.length) fail(`Function ${name} not found (lizard fn ls)`,
|
|
478
|
-
if (holding.length > 1) fail(`${name} exists in ${holding.map((a) => a.region).join(" and ")}: pass --region`,
|
|
544
|
+
if (!holding.length) fail(`Function ${name} not found (lizard fn ls)`, 3, "NOT_FOUND");
|
|
545
|
+
if (holding.length > 1) fail(`${name} exists in ${holding.map((a) => a.region).join(" and ")}: pass --region`, 3, "REGION_REQUIRED");
|
|
479
546
|
return holding[0];
|
|
480
547
|
}
|
|
481
548
|
|
|
482
549
|
function parseDuration(s: string): number {
|
|
483
550
|
const m = String(s).match(/^(\d+)\s*(s|m|h|d)?$/);
|
|
484
|
-
if (!m) fail(`--since takes e.g. 30s, 10m, 2h, 1d (got ${s})`,
|
|
551
|
+
if (!m) fail(`--since takes e.g. 30s, 10m, 2h, 1d (got ${s})`, 3, "INVALID_INPUT");
|
|
485
552
|
return Number(m![1]) * ({ s: 1e3, m: 6e4, h: 36e5, d: 864e5 } as Record<string, number>)[m![2] ?? "m"];
|
|
486
553
|
}
|
package/src/lib/updater.ts
CHANGED
|
@@ -5,7 +5,7 @@ import { join, dirname } from "node:path";
|
|
|
5
5
|
import os from "node:os";
|
|
6
6
|
import { spawn } from "node:child_process";
|
|
7
7
|
|
|
8
|
-
export const CURRENT_VERSION = "4.0.
|
|
8
|
+
export const CURRENT_VERSION = "4.0.100";
|
|
9
9
|
const RELEASES_API = "https://api.github.com/repos/lizard-build/lizard-cli/releases/latest";
|
|
10
10
|
const RELEASE_BASE = "https://github.com/lizard-build/lizard-cli/releases/latest/download";
|
|
11
11
|
|