@olivervea/pipelines 0.0.0-stage → 2.0.0-beta.10

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.
Files changed (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +467 -2
  3. package/manifest.schema.json +674 -0
  4. package/package.json +60 -4
  5. package/src/assets.d.ts +10 -0
  6. package/src/build/build.ts +127 -0
  7. package/src/build/cli.ts +52 -0
  8. package/src/build/elf.ts +35 -0
  9. package/src/build/hashes.ts +96 -0
  10. package/src/build/project.ts +107 -0
  11. package/src/builder/pipeline.ts +373 -0
  12. package/src/builder/refs.ts +26 -0
  13. package/src/core/brands.ts +15 -0
  14. package/src/core/config-refs.ts +77 -0
  15. package/src/core/config.ts +147 -0
  16. package/src/core/handlers.ts +50 -0
  17. package/src/core/models.ts +69 -0
  18. package/src/core/origin.ts +20 -0
  19. package/src/core/secrets.ts +13 -0
  20. package/src/core/steps.ts +138 -0
  21. package/src/core/types.ts +6 -0
  22. package/src/core/webhooks.ts +30 -0
  23. package/src/ctx/files.ts +161 -0
  24. package/src/ctx/index.ts +122 -0
  25. package/src/ctx/sh.ts +197 -0
  26. package/src/ctx/types.ts +116 -0
  27. package/src/describe/describe.ts +565 -0
  28. package/src/describe/manifest-schema.ts +179 -0
  29. package/src/describe/mapper-source.ts +238 -0
  30. package/src/describe/record.ts +107 -0
  31. package/src/dev/cli.ts +87 -0
  32. package/src/harness/env.ts +58 -0
  33. package/src/harness/execute.ts +97 -0
  34. package/src/harness/exit.ts +19 -0
  35. package/src/harness/index.ts +9 -0
  36. package/src/harness/main.ts +270 -0
  37. package/src/harness/result.ts +75 -0
  38. package/src/harness/validate.ts +92 -0
  39. package/src/index.ts +15 -0
  40. package/src/library/checks.ts +23 -0
  41. package/src/library/compose-deploy.ts +96 -0
  42. package/src/library/github-source.ts +100 -0
  43. package/src/library/helm-deploy-ssh.ts +358 -0
  44. package/src/library/helm-deploy.ts +271 -0
  45. package/src/library/http-health.ts +34 -0
  46. package/src/library/image-build.ts +418 -0
  47. package/src/library/index.ts +18 -0
  48. package/src/library/models.ts +79 -0
  49. package/src/library/ssh.ts +50 -0
  50. package/src/testing/index.ts +82 -0
  51. package/src/util/canonical.ts +19 -0
  52. package/src/util/handler-hash.ts +22 -0
  53. package/src/util/hash.ts +22 -0
  54. package/src/util/tar.ts +167 -0
@@ -0,0 +1,179 @@
1
+ // The manifest format, defined once in zod. `manifest.schema.json` is generated from this
2
+ // (bun scripts/gen-manifest-schema.ts) and describe validates every manifest against it.
3
+ import { z } from "zod";
4
+
5
+ export const API_VERSION = "2.0";
6
+
7
+ const stepName = z.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/).describe("Step name: lower-case kebab, 1-63 chars. The step's identity.");
8
+ const modelName = z.string().regex(/^[A-Za-z][A-Za-z0-9_]*$/).describe("Model name (key of `models`).");
9
+ const secretName = z.string().regex(/^[A-Z_][A-Z0-9_]*$/).describe("Secret name; also the env var name in the step container.");
10
+ const configName = z.string().regex(/^[a-z][a-zA-Z0-9]*$/).describe("Config entry name; a key of the pipeline's config document.");
11
+ const hash = z.string().regex(/^sha256:[0-9a-f]{64}$/);
12
+ const Json = z.json().meta({ id: "Json", description: "Any JSON value." });
13
+ const jsonSchema = z.record(z.string(), z.unknown()).describe("A JSON Schema (draft 2020-12) object, canonical (sorted keys, no $schema).");
14
+
15
+ export const RefMapping = z
16
+ .strictObject({
17
+ ref: z
18
+ .string()
19
+ .regex(/^(?:input|failure|[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[^.]+)*$/)
20
+ .describe("'<root>' or '<root>.<field>.<field>…'. Root: 'input' (pipeline input), a step name (that step's output) or 'failure' (FailureContext, failure handlers only)."),
21
+ })
22
+ .describe("Value taken from the run pool. A ref whose root step was skipped yields no value (only allowed for optional inputs).");
23
+ export const ConstMapping = z.strictObject({ const: Json }).describe("A JSON constant.");
24
+
25
+ export type Mapping = { ref: string } | { const: unknown } | { [field: string]: Mapping };
26
+ export const Mapping: z.ZodType<Mapping> = z
27
+ .union([
28
+ RefMapping,
29
+ ConstMapping,
30
+ z.record(z.string(), z.lazy(() => Mapping)).describe(
31
+ "An object built field by field. Discrimination: an object whose only key is 'ref' (string value) is a ref, whose only key is 'const' is a constant, anything else is a nested object (describe never emits a nested object whose only key is 'ref' or 'const').",
32
+ ),
33
+ ])
34
+ .meta({ id: "Mapping" });
35
+
36
+ export const ModelSchemas = z
37
+ .strictObject({
38
+ output: jsonSchema.describe("z.output view: validates step outputs, trigger results and the pool. Every object has additionalProperties: false."),
39
+ input: jsonSchema.optional().describe("z.input view (defaults make fields optional; `default` values are listed). Present only when it differs from `output`."),
40
+ })
41
+ .meta({ id: "ModelSchemas" });
42
+
43
+ export const InputType = z
44
+ .union([
45
+ z.strictObject({ model: modelName, optional: z.boolean().describe("optional(Model): may be absent because its producer was skipped.") }),
46
+ z.strictObject({ schema: ModelSchemas.describe("A plain (unnamed) zod schema. Such inputs always have an explicit mapping.") }),
47
+ ])
48
+ .meta({ id: "InputType" });
49
+
50
+ export const StepDescriptor = z
51
+ .strictObject({
52
+ name: stepName,
53
+ description: z.string().describe("What the step does, shown in the UI (may be empty)."),
54
+ kind: z.string().min(1).describe("'custom' = the handler is a handlers/*.ts file; any other kind is a step that carries its implementation (an SDK or package step). A label: the service accepts any kind."),
55
+ image: z.string().min(1).describe("Container image the step runs in."),
56
+ inputTypes: z.record(z.string(), InputType).describe("Declared input entries, keyed like input.json."),
57
+ input: z.record(z.string(), Mapping).describe("How the service assembles input.json: one mapping per input key (same keys as inputTypes)."),
58
+ output: modelName.nullable().describe("Output model, or null if the step produces no output."),
59
+ secrets: z.array(secretName).describe("Declared secrets (sorted). Mount exactly these, as env vars of the same name."),
60
+ handlerHash: hash.describe("Implementation identity: handler bundle (contract files excluded) + harness (bun + sdkHash); for a step that carries its implementation kind + config + harness + the hash of the code of its kind."),
61
+ timeoutSeconds: z.number().int().positive().optional(),
62
+ retries: z.number().int().nonnegative().optional(),
63
+ config: z
64
+ .record(z.string(), Json)
65
+ .optional()
66
+ .describe("The step's settings (display only; already covered by handlerHash). A config reference is recorded as {\"$config\": \"<entry>.<field>…\"}; the entry is in configEntries."),
67
+ configEntries: z
68
+ .array(configName)
69
+ .optional()
70
+ .describe("Config entries the step receives (sorted; omitted when none). The service delivers them in input.json under '$config'."),
71
+ clusterAccess: z
72
+ .literal(true)
73
+ .optional()
74
+ .describe("The step pod gets the instance's step ServiceAccount token (Kubernetes:StepServiceAccount), if the instance grants one. Omitted = no token."),
75
+ })
76
+ .meta({ id: "Step" });
77
+
78
+ export type Stage =
79
+ | { steps: z.infer<typeof StepDescriptor>[] }
80
+ | { when: Record<string, (string | number | boolean)[]>; stages: Stage[] }
81
+ | { select: string; discriminator: string; cases: Record<string, Stage[]> };
82
+ export const Stage: z.ZodType<Stage> = z
83
+ .union([
84
+ z.strictObject({ steps: z.array(StepDescriptor).min(1).describe("Steps run in parallel; the stage is a barrier.") }),
85
+ z.strictObject({
86
+ when: z.record(z.string(), z.array(z.union([z.string(), z.number(), z.boolean()])).min(1)).describe(
87
+ "Pipeline-input field → accepted values (all fields must match). Empty object = always.",
88
+ ),
89
+ stages: z.array(z.lazy(() => Stage)),
90
+ }),
91
+ z.strictObject({
92
+ select: z.string().min(1).describe("Config reference (`<entry>.<field>…`) to a discriminated union; the run's config snapshot picks the case."),
93
+ discriminator: z.string().min(1).describe("The union's literal field whose value names the case."),
94
+ cases: z
95
+ .record(z.string(), z.array(z.lazy(() => Stage)))
96
+ .describe("Discriminator value → stages. Exactly one case runs; a step name may repeat across cases, nowhere else."),
97
+ }),
98
+ ])
99
+ .meta({ id: "Stage" });
100
+
101
+ export const Trigger = z
102
+ .discriminatedUnion("kind", [
103
+ z.strictObject({ kind: z.literal("push"), name: z.literal("push") }).describe("GitHub push. Event = the webhook payload."),
104
+ z
105
+ .strictObject({
106
+ kind: z.literal("poll"),
107
+ name: z.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/),
108
+ url: z.string(),
109
+ headers: z.record(z.string(), z.string()).describe("Values may contain '$SECRET:NAME' (NAME ∈ secrets)."),
110
+ secrets: z.array(secretName),
111
+ valuePath: z.string().describe("Dot path into the JSON response; a change triggers map-trigger with {\"value\": <string>}."),
112
+ intervalSeconds: z.number().int().positive(),
113
+ })
114
+ .describe("Background poller."),
115
+ z
116
+ .strictObject({
117
+ kind: z.literal("webhook"),
118
+ name: z.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/),
119
+ verify: z.discriminatedUnion("scheme", [
120
+ z.strictObject({
121
+ scheme: z.literal("hmac-sha256"),
122
+ secret: secretName,
123
+ header: z.string().min(1),
124
+ prefix: z.string().describe("Text before the hex digest in the header, e.g. 'sha256='."),
125
+ }),
126
+ z.strictObject({ scheme: z.literal("bearer"), secret: secretName }),
127
+ ]),
128
+ })
129
+ .describe("Inbound HTTP delivery to /api/hooks/<pipeline id>/<name>. Event = {headers, body}; a null mapping ignores it."),
130
+ ])
131
+ .meta({ id: "Trigger" });
132
+
133
+ export const Manifest = z
134
+ .strictObject({
135
+ apiVersion: z.literal(API_VERSION),
136
+ name: z.string().min(1),
137
+ description: z.string().optional(),
138
+ input: modelName.describe("Pipeline input model."),
139
+ harness: z
140
+ .strictObject({
141
+ bun: z.string().describe("Bun runtime version compiled into the binary."),
142
+ sdk: z.string().describe("@olivervea/pipelines package version."),
143
+ sdkHash: hash.describe("Hash of the SDK runtime sources + zod version."),
144
+ })
145
+ .describe("Harness identity. Already folded into every handlerHash."),
146
+ models: z.record(modelName, ModelSchemas).describe("Every model referenced by the pipeline (input, step inputs/outputs)."),
147
+ secrets: z.array(z.strictObject({ name: secretName, description: z.string() })).describe("All declared secrets (steps + poll triggers), sorted by name."),
148
+ config: z
149
+ .array(
150
+ z.strictObject({
151
+ name: configName,
152
+ description: z.string(),
153
+ required: z.boolean().describe("False when the schema accepts a missing value (optional, or a default)."),
154
+ schema: jsonSchema.describe("z.input view: validates the config document's value for this entry (defaults listed)."),
155
+ }),
156
+ )
157
+ .optional()
158
+ .describe("Config entries used by steps, sorted by name (omitted when none). Fields of kind secretRef ({secret: NAME}) name a secret."),
159
+ triggers: z.array(Trigger),
160
+ stages: z.array(Stage),
161
+ failureHandlers: z.array(
162
+ z.strictObject({
163
+ step: StepDescriptor.describe("The handler step. Not part of any stage; its inputs are all FailureContext ({ref: 'failure'})."),
164
+ steps: z.array(stepName).nullable().describe("Steps whose failure triggers the handler (null = any step)."),
165
+ }),
166
+ ),
167
+ })
168
+ .meta({ id: "Manifest", title: "Olve.Pipelines v2 manifest" });
169
+
170
+ export type ManifestT = z.infer<typeof Manifest>;
171
+ export type StepDescriptorT = z.infer<typeof StepDescriptor>;
172
+ export type TriggerT = z.infer<typeof Trigger>;
173
+ export type ModelSchemasT = z.infer<typeof ModelSchemas>;
174
+
175
+ /** The JSON Schema document written to manifest.schema.json. */
176
+ export function manifestJsonSchema(): Record<string, unknown> {
177
+ const js = z.toJSONSchema(Manifest, { target: "draft-2020-12" }) as Record<string, unknown>;
178
+ return { ...js, $id: "https://olve.dev/schemas/pipelines/manifest-2.0.json" };
179
+ }
@@ -0,0 +1,238 @@
1
+ // Static analysis of mapper source (`fn.toString()`), an allowlist parser.
2
+ //
3
+ // Recording proxies cannot observe truthiness, `!`, `??`, `||`, `&&`, ternaries or `===` against a
4
+ // value: they silently record a constant. So describe also checks the mapper's *source*: its body
5
+ // must be an object literal whose values are member chains, literals, constant arrays or nested
6
+ // object literals. Everything else is rejected with the offending construct named.
7
+ //
8
+ // Accepted shapes (after Bun's TypeScript transpilation):
9
+ // from => ({ a: from.input.sha, b: from["deploy-beta"].url, c: "lit", d: 1, e: { f: from.build } })
10
+ // (from) => { return { … }; }
11
+ // ({ input, "deploy-beta": beta }) => ({ sha: input.sha, url: beta.url })
12
+ // function (from) { return { … }; }
13
+ // Free identifiers (`RELEASE`, `CONFIG.url`) are allowed: they are module constants, recorded as
14
+ // `{const}` by the proxy. This requires the harness bundle not to be minified.
15
+ import { MapperError } from "./record.ts";
16
+
17
+ type Tok =
18
+ | { t: "ident"; v: string; pos: number }
19
+ | { t: "str"; v: string; pos: number }
20
+ | { t: "num"; v: string; pos: number }
21
+ | { t: "punc"; v: string; pos: number }
22
+ | { t: "op"; v: string; pos: number }
23
+ | { t: "eof"; v: ""; pos: number };
24
+
25
+ const PUNCS = ["...", "=>", "?.", "(", ")", "{", "}", "[", "]", ",", ":", ".", ";"];
26
+ const OPS = ["===", "!==", "**=", "??=", "&&=", "||=", "==", "!=", "<=", ">=", "&&", "||", "??", "++", "--", "**", "<<", ">>", "+=", "-=", "*=", "/=", "?", "!", "+", "-", "*", "/", "%", "<", ">", "=", "&", "|", "^", "~", "@", "#"];
27
+
28
+ function describeOp(op: string): string {
29
+ if (op === "?") return "a ternary (`? :`)";
30
+ if (op === "??") return "nullish coalescing (`??`)";
31
+ if (op === "&&" || op === "||") return `a logical operator (\`${op}\`)`;
32
+ if (op === "!") return "negation (`!`)";
33
+ if (["===", "!==", "==", "!=", "<", ">", "<=", ">="].includes(op)) return `a comparison (\`${op}\`)`;
34
+ if (["+", "-", "*", "/", "%", "**"].includes(op)) return `arithmetic/concatenation (\`${op}\`)`;
35
+ if (op.endsWith("=") || op === "++" || op === "--") return `an assignment (\`${op}\`)`;
36
+ return `the operator \`${op}\``;
37
+ }
38
+
39
+ const KEYWORDS = new Set([
40
+ "typeof", "void", "delete", "new", "await", "yield", "this", "super", "class", "function", "async",
41
+ "if", "else", "for", "while", "do", "switch", "case", "try", "catch", "throw", "var", "let", "const",
42
+ "in", "instanceof", "import", "export", "return", "arguments", "eval",
43
+ ]);
44
+
45
+ function tokenize(src: string): Tok[] {
46
+ const toks: Tok[] = [];
47
+ let i = 0;
48
+ while (i < src.length) {
49
+ const c = src[i]!;
50
+ if (/\s/.test(c)) { i++; continue; }
51
+ if (src.startsWith("//", i)) { const e = src.indexOf("\n", i); i = e < 0 ? src.length : e + 1; continue; }
52
+ if (src.startsWith("/*", i)) {
53
+ const e = src.indexOf("*/", i + 2);
54
+ if (e < 0) throw new MapperError("mapper source has an unterminated comment");
55
+ i = e + 2;
56
+ continue;
57
+ }
58
+ if (c === "`") throw new MapperError("mapper uses a template string");
59
+ if (c === '"' || c === "'") {
60
+ let j = i + 1;
61
+ let v = "";
62
+ for (;;) {
63
+ if (j >= src.length) throw new MapperError("mapper source has an unterminated string");
64
+ const d = src[j]!;
65
+ if (d === c) break;
66
+ if (d === "\\") { v += src.slice(j, j + 2); j += 2; continue; }
67
+ v += d;
68
+ j++;
69
+ }
70
+ toks.push({ t: "str", v, pos: i });
71
+ i = j + 1;
72
+ continue;
73
+ }
74
+ const num = /^(?:0[xXoObB][0-9a-fA-F_]+|(?:\d[\d_]*)?\.?\d[\d_]*(?:[eE][+-]?\d+)?)n?/.exec(src.slice(i));
75
+ if (num && /[\d.]/.test(c) && num[0] !== ".") {
76
+ toks.push({ t: "num", v: num[0], pos: i });
77
+ i += num[0].length;
78
+ continue;
79
+ }
80
+ const id = /^[\p{ID_Start}$_][\p{ID_Continue}$‌‍]*/u.exec(src.slice(i));
81
+ if (id) {
82
+ toks.push({ t: "ident", v: id[0], pos: i });
83
+ i += id[0].length;
84
+ continue;
85
+ }
86
+ const p = PUNCS.find((x) => src.startsWith(x, i));
87
+ if (p && !(p === "?." && /\d/.test(src[i + 2] ?? ""))) {
88
+ toks.push({ t: "punc", v: p, pos: i });
89
+ i += p.length;
90
+ continue;
91
+ }
92
+ const o = OPS.find((x) => src.startsWith(x, i));
93
+ if (o) {
94
+ toks.push({ t: "op", v: o, pos: i });
95
+ i += o.length;
96
+ continue;
97
+ }
98
+ throw new MapperError(`mapper source has an unexpected character '${c}'`);
99
+ }
100
+ toks.push({ t: "eof", v: "", pos: src.length });
101
+ return toks;
102
+ }
103
+
104
+ /** Throws MapperError unless `src` is an allowed mapper. */
105
+ export function analyzeMapperSource(src: string): void {
106
+ const toks = tokenize(src);
107
+ let k = 0;
108
+ const peek = (o = 0) => toks[Math.min(k + o, toks.length - 1)]!;
109
+ const next = () => toks[k++]!;
110
+ const is = (t: Tok["t"], v?: string, o = 0) => peek(o).t === t && (v === undefined || peek(o).v === v);
111
+ const unexpected = (what = "here"): never => {
112
+ const tok = peek();
113
+ if (tok.t === "op") throw new MapperError(`mapper uses ${describeOp(tok.v)}; mappers may only contain property access and literals — move logic into the handler or a when block`);
114
+ if (tok.t === "punc" && tok.v === "?.") throw new MapperError("mapper uses optional chaining (`?.`); declare the input optional(...) and map the whole ref instead");
115
+ if (tok.t === "punc" && tok.v === "...") throw new MapperError("mapper uses spread (`...`); list the fields explicitly");
116
+ if (tok.t === "punc" && tok.v === "(") throw new MapperError("mapper calls a function or method; mappers may only contain property access and literals");
117
+ if (tok.t === "ident" && KEYWORDS.has(tok.v)) throw new MapperError(`mapper uses \`${tok.v}\`; mappers may only contain property access and literals`);
118
+ throw new MapperError(`mapper source is not an object literal of property accesses and literals (unexpected ${tok.t === "eof" ? "end" : `'${tok.v}'`} ${what})`);
119
+ };
120
+ const expect = (t: Tok["t"], v?: string) => (is(t, v) ? next() : unexpected(`(expected ${v ?? t})`));
121
+
122
+ const identifier = () => {
123
+ if (!is("ident") || KEYWORDS.has(peek().v)) unexpected("(expected an identifier)");
124
+ return next();
125
+ };
126
+
127
+ // ── parameters ──
128
+ const params = () => {
129
+ if (is("ident")) { identifier(); return; }
130
+ expect("punc", "(");
131
+ if (is("punc", ")")) { next(); return; }
132
+ if (is("punc", "{")) destructuring();
133
+ else identifier();
134
+ if (is("punc", ",")) next();
135
+ if (is("op", "=")) throw new MapperError("mapper parameter has a default value");
136
+ expect("punc", ")");
137
+ };
138
+ const destructuring = () => {
139
+ expect("punc", "{");
140
+ while (!is("punc", "}")) {
141
+ if (is("str")) { next(); expect("punc", ":"); identifier(); }
142
+ else {
143
+ identifier();
144
+ if (is("punc", ":")) { next(); identifier(); }
145
+ }
146
+ if (is("op", "=")) throw new MapperError("mapper parameter destructuring has a default value");
147
+ if (!is("punc", ",")) break;
148
+ next();
149
+ }
150
+ expect("punc", "}");
151
+ };
152
+
153
+ // ── values ──
154
+ const value = (): void => {
155
+ if (is("punc", "(")) { next(); value(); expect("punc", ")"); return; }
156
+ if (is("punc", "{")) return object();
157
+ if (is("punc", "[")) return array();
158
+ if (is("str") || is("num")) { next(); return; }
159
+ if (is("op", "-") && is("num", undefined, 1)) { next(); next(); return; }
160
+ if (is("ident", "true") || is("ident", "false") || is("ident", "null")) { next(); return; }
161
+ if (is("ident", "undefined")) throw new MapperError("mapper uses `undefined`; leave optional fields out instead");
162
+ chain();
163
+ };
164
+ const chain = () => {
165
+ identifier();
166
+ for (;;) {
167
+ if (is("punc", ".")) { next(); if (!is("ident")) unexpected("(expected a property name)"); next(); continue; }
168
+ if (is("punc", "[")) {
169
+ next();
170
+ if (!is("str") && !is("num")) throw new MapperError("mapper uses a computed property access; only literal keys (from[\"step-name\"]) are allowed");
171
+ next();
172
+ expect("punc", "]");
173
+ continue;
174
+ }
175
+ break;
176
+ }
177
+ };
178
+ const array = () => {
179
+ expect("punc", "[");
180
+ while (!is("punc", "]")) {
181
+ if (is("punc", ",")) unexpected("(array holes are not allowed)");
182
+ value();
183
+ if (!is("punc", ",")) break;
184
+ next();
185
+ }
186
+ expect("punc", "]");
187
+ };
188
+ const object = () => {
189
+ expect("punc", "{");
190
+ while (!is("punc", "}")) {
191
+ if (is("punc", "...")) unexpected();
192
+ if (is("punc", "[")) throw new MapperError("mapper uses a computed key; only literal keys are allowed");
193
+ if (is("ident") && (is("punc", ",", 1) || is("punc", "}", 1))) {
194
+ // shorthand `{ input }` — a destructured root or a module constant
195
+ identifier();
196
+ } else {
197
+ if (is("ident") || is("str") || is("num")) next();
198
+ else unexpected("(expected a property name)");
199
+ if (is("punc", "(")) throw new MapperError("mapper defines a method; mappers may only contain property access and literals");
200
+ expect("punc", ":");
201
+ value();
202
+ }
203
+ if (!is("punc", ",")) break;
204
+ next();
205
+ }
206
+ expect("punc", "}");
207
+ };
208
+ const returnBody = () => {
209
+ expect("punc", "{");
210
+ if (!is("ident", "return")) unexpected("(a block-bodied mapper must consist of a single `return { … }`)");
211
+ next();
212
+ object();
213
+ if (is("punc", ";")) next();
214
+ expect("punc", "}");
215
+ };
216
+
217
+ // ── function ──
218
+ if (is("ident", "async")) throw new MapperError("mapper must not be async");
219
+ if (is("ident", "function")) {
220
+ next();
221
+ if (is("op", "*")) throw new MapperError("mapper must not be a generator");
222
+ if (is("ident")) next();
223
+ params();
224
+ returnBody();
225
+ } else {
226
+ params();
227
+ expect("punc", "=>");
228
+ if (is("punc", "(")) {
229
+ next();
230
+ object();
231
+ expect("punc", ")");
232
+ } else if (is("punc", "{")) {
233
+ returnBody();
234
+ } else unexpected("(the mapper body must be an object literal: from => ({ … }))");
235
+ }
236
+ if (is("punc", ";")) next();
237
+ if (!is("eof")) unexpected("after the mapper body");
238
+ }
@@ -0,0 +1,107 @@
1
+ // Records a mapper as a tagged mapping by calling it with recording proxies.
2
+ //
3
+ // The proxy throws on coercion (template strings, `+`, String()), method calls, spreading,
4
+ // `in`, assignment and JSON.stringify. It CANNOT see truthiness, `!`, `??`, `||`, ternaries or
5
+ // `===` against a value — those are rejected by the static source analysis (mapper-source.ts),
6
+ // and primarily by the `Ref<T>` types.
7
+ import { REF_PATH } from "../core/brands.ts";
8
+
9
+ export class MapperError extends Error {
10
+ override name = "MapperError";
11
+ }
12
+
13
+ /** Manifest mapping node: `{ref}` | `{const}` | a nested object of mappings. */
14
+ export type Mapping = { ref: string } | { const: unknown } | { [key: string]: Mapping };
15
+
16
+ function refProxy(path: string): unknown {
17
+ const fail = (what: string): never => {
18
+ throw new MapperError(
19
+ `mapper ${what} on reference '${path}'; mappers may only use property access and literals ` +
20
+ `(no template strings, arithmetic, method calls or logic) — move computation into the handler`,
21
+ );
22
+ };
23
+ const target = function () {}; // function target so calls hit the `apply` trap
24
+ return new Proxy(target, {
25
+ get(_t, prop) {
26
+ if (prop === REF_PATH) return path;
27
+ if (prop === "then") return undefined; // `await ref` must not recurse
28
+ if (prop === Symbol.toPrimitive || prop === "toString" || prop === "valueOf")
29
+ return fail("coerces a value (template string / concatenation / arithmetic / comparison)");
30
+ if (prop === "toJSON") return fail("serializes a reference (JSON.stringify)");
31
+ if (typeof prop === "symbol") return fail(`uses ${String(prop)} (iteration/spread/inspection)`);
32
+ if (prop.includes(".")) return fail(`accesses field '${prop}' (field names containing '.' cannot be mapped)`);
33
+ return refProxy(`${path}.${prop}`);
34
+ },
35
+ apply: () => fail("calls a function/method"),
36
+ construct: () => fail("constructs"),
37
+ set: () => fail("assigns"),
38
+ deleteProperty: () => fail("deletes"),
39
+ has: () => fail("uses the `in` operator"),
40
+ ownKeys: () => fail("enumerates/spreads"),
41
+ defineProperty: () => fail("defines a property"),
42
+ getPrototypeOf: () => fail("inspects the prototype (instanceof)"),
43
+ });
44
+ }
45
+
46
+ /** The `from` argument: `from.input`, `from.<step-name>`. */
47
+ export function rootProxy(available: ReadonlySet<string>): unknown {
48
+ return new Proxy(
49
+ {},
50
+ {
51
+ get(_t, prop) {
52
+ if (typeof prop === "symbol" || prop === "then") return undefined;
53
+ if (!available.has(prop))
54
+ throw new MapperError(`mapper references '${prop}', which is not available at this stage (available: ${[...available].sort().join(", ") || "none"})`);
55
+ return refProxy(prop);
56
+ },
57
+ has: () => {
58
+ throw new MapperError("mapper uses the `in` operator on its argument");
59
+ },
60
+ ownKeys: () => {
61
+ throw new MapperError("mapper enumerates/spreads its argument");
62
+ },
63
+ },
64
+ );
65
+ }
66
+
67
+ export const refPathOf = (v: unknown): string | undefined =>
68
+ typeof v === "function" ? ((v as unknown as Record<symbol, unknown>)[REF_PATH] as string | undefined) : undefined;
69
+
70
+ function toMapping(v: unknown, at: string): Mapping {
71
+ const path = refPathOf(v);
72
+ if (path !== undefined) return { ref: path };
73
+ if (typeof v === "function") throw new MapperError(`mapper returns a function at '${at}'`);
74
+ if (v === undefined) throw new MapperError(`mapper returns undefined at '${at}'`);
75
+ if (v === null || typeof v === "string" || typeof v === "boolean") return { const: v };
76
+ if (typeof v === "number") {
77
+ if (!Number.isFinite(v)) throw new MapperError(`mapper returns a non-finite number at '${at}'`);
78
+ return { const: v };
79
+ }
80
+ if (Array.isArray(v)) {
81
+ const items = v.map((x, i) => toMapping(x, `${at}[${i}]`));
82
+ if (items.every((e) => "const" in e && Object.keys(e).length === 1)) return { const: items.map((e) => (e as { const: unknown }).const) };
83
+ throw new MapperError(`mapper puts references inside an array at '${at}' (only constant arrays are supported)`);
84
+ }
85
+ if (typeof v === "object") {
86
+ if (Object.getPrototypeOf(v) !== Object.prototype && Object.getPrototypeOf(v) !== null)
87
+ throw new MapperError(`mapper returns a non-plain object at '${at}'`);
88
+ const keys = Object.keys(v);
89
+ if (keys.length === 1 && (keys[0] === "ref" || keys[0] === "const"))
90
+ throw new MapperError(`mapper builds an object whose only field is '${keys[0]}' at '${at}'; that is reserved by the manifest's mapping encoding — map the whole object with a ref instead`);
91
+ const out: Record<string, Mapping> = {};
92
+ for (const k of keys) out[k] = toMapping((v as Record<string, unknown>)[k], at ? `${at}.${k}` : k);
93
+ return out;
94
+ }
95
+ throw new MapperError(`mapper returns an unsupported value (${typeof v}) at '${at}'`);
96
+ }
97
+
98
+ /** Calls `fn` with recording proxies and returns `{ inputKey: Mapping }`. */
99
+ export function recordMapper(fn: (from: unknown) => unknown, available: ReadonlySet<string>): Record<string, Mapping> {
100
+ const result = fn(rootProxy(available));
101
+ if (refPathOf(result) !== undefined || typeof result !== "object" || result === null || Array.isArray(result))
102
+ throw new MapperError("mapper must return an object literal");
103
+ if (result instanceof Promise) throw new MapperError("mapper must be synchronous");
104
+ const out: Record<string, Mapping> = {};
105
+ for (const k of Object.keys(result)) out[k] = toMapping((result as Record<string, unknown>)[k], k);
106
+ return out;
107
+ }
package/src/dev/cli.ts ADDED
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env bun
2
+ // olve-dev — run a pipeline from source through the same harness path as the compiled binary.
3
+ // olve-dev describe <dir> [--sentinels]
4
+ // olve-dev run <dir> <step> [--input-file f] [--config-file f] [--olve-dir d] [--secret NAME=value]...
5
+ // olve-dev map-trigger <dir> <trigger> --event-file f [--olve-dir d]
6
+ // $OLVE_DIR defaults to <dir>/.olve; outputs land in <dir>/.olve/work/.
7
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
+ import { join, resolve } from "node:path";
9
+ import { parseArgs } from "node:util";
10
+ import { runHarness, type HarnessConfig } from "../harness/main.ts";
11
+ import { EXIT } from "../harness/exit.ts";
12
+ import { handlerHashes, kindHashes } from "../build/hashes.ts";
13
+ import { harnessInfo, loadPipeline, loadProject, ProjectError } from "../build/project.ts";
14
+
15
+ const USAGE = `usage: olve-dev describe <dir> [--sentinels]
16
+ olve-dev run <dir> <step> [--input-file f] [--config-file f] [--olve-dir d] [--secret NAME=value]...
17
+ olve-dev map-trigger <dir> <trigger> --event-file f [--olve-dir d]`;
18
+
19
+ export async function devConfig(dir: string, withHashes: boolean): Promise<HarnessConfig> {
20
+ const project = await loadProject(dir);
21
+ const pipeline = await loadPipeline(project);
22
+ const harness = harnessInfo();
23
+ const hashes = withHashes ? await handlerHashes(project, harness) : {};
24
+ return {
25
+ pipeline,
26
+ handlers: Object.fromEntries(project.handlers.map(([name, file]) => [name, () => import(file) as Promise<{ default: unknown }>])),
27
+ handlerHashes: Object.fromEntries(Object.entries(hashes).map(([k, v]) => [k, v.handlerHash])),
28
+ ...(withHashes ? { kindHashes: await kindHashes(project, pipeline) } : {}),
29
+ harness,
30
+ };
31
+ }
32
+
33
+ export async function devMain(argv: string[]): Promise<number> {
34
+ let parsed;
35
+ try {
36
+ parsed = parseArgs({
37
+ args: argv,
38
+ allowPositionals: true,
39
+ options: {
40
+ "input-file": { type: "string" },
41
+ "config-file": { type: "string" },
42
+ "event-file": { type: "string" },
43
+ "olve-dir": { type: "string" },
44
+ secret: { type: "string", multiple: true },
45
+ sentinels: { type: "boolean", default: false },
46
+ help: { type: "boolean", short: "h", default: false },
47
+ },
48
+ });
49
+ } catch (e) {
50
+ console.error(`${(e as Error).message}\n${USAGE}`);
51
+ return EXIT.usage;
52
+ }
53
+ const { values, positionals } = parsed;
54
+ if (values.help) return console.log(USAGE), 0;
55
+ const [mode, dir, name] = positionals;
56
+ if (!mode || !dir) return console.error(USAGE), EXIT.usage;
57
+ try {
58
+ if (mode === "describe") return await runHarness(await devConfig(dir, true), ["describe", ...(values.sentinels ? ["--sentinels"] : [])]);
59
+ if (mode !== "run" && mode !== "map-trigger") return console.error(USAGE), EXIT.usage;
60
+ if (!name) return console.error(USAGE), EXIT.usage;
61
+ const olveDir = resolve(values["olve-dir"] ?? join(dir, ".olve"));
62
+ mkdirSync(olveDir, { recursive: true });
63
+ process.env.OLVE_DIR = olveDir;
64
+ process.env.TMPDIR ??= join(olveDir, "tmp");
65
+ for (const s of values.secret ?? []) {
66
+ const i = s.indexOf("=");
67
+ if (i <= 0) return console.error(`--secret expects NAME=value, got '${s}'`), EXIT.usage;
68
+ process.env[s.slice(0, i)] = s.slice(i + 1);
69
+ }
70
+ const file = mode === "run" ? values["input-file"] : values["event-file"];
71
+ if (file) copyFileSync(resolve(file), join(olveDir, "input.json"));
72
+ if (mode === "run" && values["config-file"]) {
73
+ const inputFile = join(olveDir, "input.json");
74
+ const input = (existsSync(inputFile) ? JSON.parse(readFileSync(inputFile, "utf8")) : {}) as Record<string, unknown>;
75
+ input.$config = JSON.parse(readFileSync(resolve(values["config-file"]), "utf8"));
76
+ writeFileSync(inputFile, JSON.stringify(input));
77
+ }
78
+ else if (mode === "map-trigger") return console.error("--event-file is required"), EXIT.usage;
79
+ return await runHarness(await devConfig(dir, false), [mode, name]);
80
+ } catch (e) {
81
+ if (e instanceof ProjectError) return console.error(e.message), EXIT.configInvalid;
82
+ console.error((e as Error)?.stack ?? String(e));
83
+ return EXIT.configInvalid;
84
+ }
85
+ }
86
+
87
+ if (import.meta.main) process.exit(await devMain(process.argv.slice(2)));