rastack 0.0.45 → 0.0.47

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,203 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * `rastack import` — load external data (CSV, Excel, PDF) into the shape of a
5
+ * compiled resource and run every row through the resource's constraint state
6
+ * machine.
7
+ *
8
+ * rastack import <file> --resource app.model
9
+ * [--schema .rastack/schema.rastack.json] the compiled manifest
10
+ * [--related app.model=<file>] ids to resolve FKs against (repeatable)
11
+ * [--out cleaned.json] write the coerced valid records
12
+ * [--report report.json] write the full validation report
13
+ * [--max-errors 20] issues to print before summarising
14
+ * [--allow-invalid] exit 0 even when rows fail
15
+ *
16
+ * The validation is the same machine the form hooks run per keystroke and the
17
+ * API enforces on writes: `present → typed → bounded → member → unique →
18
+ * resolved`. Here it runs with the full dataset context, so in-file duplicate
19
+ * `unique` values and dangling foreign keys are rejected with row-located
20
+ * errors. Exit status is non-zero when any row fails (like the seed PII gate)
21
+ * unless `--allow-invalid` is passed.
22
+ */
23
+
24
+ import fs from "fs";
25
+ import path from "path";
26
+ import type { Manifest, ResourceModel } from "./compile/model";
27
+ import { specsFromResource } from "./validate";
28
+ import {
29
+ formatOf,
30
+ idsFromTabular,
31
+ parseTabular,
32
+ validateDataset,
33
+ type ImportReport,
34
+ type TabularData,
35
+ } from "./import";
36
+
37
+ // ---------------------------------------------------------------------------
38
+ // Args
39
+ // ---------------------------------------------------------------------------
40
+
41
+ const args = process.argv.slice(2);
42
+
43
+ function getArg(flag: string): string | null {
44
+ const i = args.indexOf(flag);
45
+ return i !== -1 && args[i + 1] ? args[i + 1] : null;
46
+ }
47
+
48
+ function getArgs(flag: string): string[] {
49
+ const values: string[] = [];
50
+ for (let i = 0; i < args.length - 1; i++) {
51
+ if (args[i] === flag) values.push(args[i + 1]);
52
+ }
53
+ return values;
54
+ }
55
+
56
+ const USAGE =
57
+ "Usage: rastack import <file.csv|.xlsx|.pdf> --resource app.model\n" +
58
+ " [--schema .rastack/schema.rastack.json] [--related app.model=<file>]\n" +
59
+ " [--out cleaned.json] [--report report.json] [--max-errors n] [--allow-invalid]";
60
+
61
+ function fail(message: string): never {
62
+ console.error(`✗ ${message}\n\n${USAGE}`);
63
+ process.exit(1);
64
+ }
65
+
66
+ // ---------------------------------------------------------------------------
67
+ // Load
68
+ // ---------------------------------------------------------------------------
69
+
70
+ function loadFile(filePath: string): TabularData {
71
+ const format = formatOf(filePath);
72
+ if (!format) fail(`unsupported file type: ${filePath} (use .csv, .xlsx or .pdf)`);
73
+ if (!fs.existsSync(filePath)) fail(`file not found: ${filePath}`);
74
+ return parseTabular(format, fs.readFileSync(filePath));
75
+ }
76
+
77
+ function loadManifest(schemaPath: string): Manifest {
78
+ if (!fs.existsSync(schemaPath)) {
79
+ fail(
80
+ `manifest not found at ${schemaPath} — run \`rastack compile\` first, ` +
81
+ `or point --schema at a schema.rastack.json`,
82
+ );
83
+ }
84
+ return JSON.parse(fs.readFileSync(schemaPath, "utf-8")) as Manifest;
85
+ }
86
+
87
+ function findResource(manifest: Manifest, name: string): ResourceModel {
88
+ const resource = manifest.resources.find(
89
+ (r) => `${r.app}.${r.model}` === name,
90
+ );
91
+ if (!resource) {
92
+ fail(
93
+ `unknown resource "${name}" — available: ` +
94
+ manifest.resources.map((r) => `${r.app}.${r.model}`).join(", "),
95
+ );
96
+ }
97
+ return resource;
98
+ }
99
+
100
+ // ---------------------------------------------------------------------------
101
+ // Main
102
+ // ---------------------------------------------------------------------------
103
+
104
+ const VALUE_FLAGS = new Set([
105
+ "--resource",
106
+ "--schema",
107
+ "--related",
108
+ "--out",
109
+ "--report",
110
+ "--max-errors",
111
+ ]);
112
+
113
+ /** The first token that is neither a flag nor a flag's value. */
114
+ function positionalArg(): string | null {
115
+ for (let i = 0; i < args.length; i++) {
116
+ if (VALUE_FLAGS.has(args[i])) {
117
+ i++; // skip the flag's value
118
+ } else if (!args[i].startsWith("--")) {
119
+ return args[i];
120
+ }
121
+ }
122
+ return null;
123
+ }
124
+
125
+ function main(): void {
126
+ const file = positionalArg();
127
+ const resourceName = getArg("--resource");
128
+ if (!file || !resourceName) fail("a source file and --resource are required");
129
+
130
+ const schemaPath =
131
+ getArg("--schema") ??
132
+ path.join(process.cwd(), ".rastack", "schema.rastack.json");
133
+ const manifest = loadManifest(schemaPath);
134
+ const resource = findResource(manifest, resourceName);
135
+ const specs = specsFromResource(resource);
136
+
137
+ // Related id sets for FK resolution: --related airports.airport=airports.csv
138
+ const relatedIds: Record<string, Set<string>> = {};
139
+ for (const spec of getArgs("--related")) {
140
+ const eq = spec.indexOf("=");
141
+ if (eq === -1) fail(`--related expects app.model=<file>, got "${spec}"`);
142
+ relatedIds[spec.slice(0, eq)] = idsFromTabular(loadFile(spec.slice(eq + 1)));
143
+ }
144
+
145
+ const data = loadFile(file);
146
+ console.log(
147
+ `\nrastack import ${path.basename(file)} → ${resourceName} ` +
148
+ `[${data.headers.length} column(s), ${data.rows.length} row(s)]\n`,
149
+ );
150
+
151
+ const report = validateDataset(specs, data, { relatedIds });
152
+ printReport(report);
153
+
154
+ const outPath = getArg("--out");
155
+ if (outPath) {
156
+ fs.writeFileSync(outPath, JSON.stringify(report.records, null, 2) + "\n");
157
+ console.log(`✓ ${report.records.length} valid record(s) → ${outPath}`);
158
+ }
159
+ const reportPath = getArg("--report");
160
+ if (reportPath) {
161
+ // Keep the on-disk report data-shaped: drop the per-row machine runs.
162
+ const { rows: _rows, ...summary } = report;
163
+ fs.writeFileSync(reportPath, JSON.stringify(summary, null, 2) + "\n");
164
+ console.log(`✓ validation report → ${reportPath}`);
165
+ }
166
+
167
+ if (report.invalid > 0 && !args.includes("--allow-invalid")) {
168
+ process.exit(1);
169
+ }
170
+ }
171
+
172
+ function printReport(report: ImportReport): void {
173
+ for (const col of report.columns) {
174
+ console.log(
175
+ col.field
176
+ ? ` ${col.header} → ${col.field}`
177
+ : ` ${col.header} → (ignored — no matching field)`,
178
+ );
179
+ }
180
+ for (const missing of report.missingFields) {
181
+ console.log(` (no column) → ${missing}`);
182
+ }
183
+ console.log("");
184
+
185
+ const maxErrors = Number(getArg("--max-errors") ?? 20);
186
+ for (const issue of report.issues.slice(0, maxErrors)) {
187
+ console.log(
188
+ ` ✗ row ${issue.row + 1} ${issue.field}: ${issue.message}` +
189
+ ` [failed at "${issue.gate}" — ${issue.constraint}]`,
190
+ );
191
+ }
192
+ if (report.issues.length > maxErrors) {
193
+ console.log(` … and ${report.issues.length - maxErrors} more issue(s)`);
194
+ }
195
+ if (report.issues.length) console.log("");
196
+
197
+ console.log(
198
+ `${report.invalid === 0 ? "✓" : "✗"} ${report.valid}/${report.total} row(s) valid` +
199
+ (report.invalid ? `, ${report.invalid} rejected` : ""),
200
+ );
201
+ }
202
+
203
+ main();
package/src/rastack.ts CHANGED
@@ -13,6 +13,7 @@
13
13
  * rastack design [input] [--port n] Live design-system studio (showcase + edit)
14
14
  * rastack dev [--port n] [--warehouse d] Local dev: run the app + admin in-browser over WASM
15
15
  * rastack admin [--warehouse dir] [--port n] Full admin console — React UI (rastack/components) over the native server
16
+ * rastack import <file> --resource app.model Load CSV/XLSX/PDF data and validate it (state machine)
16
17
  * rastack scan [files...] [--fail-on-pii] Scan CSVs for PII and schema info
17
18
  * rastack seed [--env dev] [--source gs://] Load CSVs into Iceberg namespace
18
19
  * rastack bootstrap [--owner o] [--repo r] Stand the tier-0 AWS account stack up (once per account+region)
@@ -90,6 +91,11 @@ switch (command) {
90
91
  // Live design-system studio (showcase + inspect + edit).
91
92
  run("rastack-design.js", rest);
92
93
  break;
94
+ case "import":
95
+ // Load external data (CSV / Excel / PDF) and validate it row-by-row
96
+ // through the resource's constraint state machine.
97
+ run("rastack-import.js", rest);
98
+ break;
93
99
  case "scan":
94
100
  run("scan.js");
95
101
  break;
@@ -135,6 +141,7 @@ switch (command) {
135
141
  ` rastack design [input] [--port n] Live design-system studio (showcase + edit)\n` +
136
142
  ` rastack dev [--port n] [--warehouse dir] [--no-open] Run the app + admin in-browser over WASM (local dev)\n` +
137
143
  ` rastack admin [--warehouse dir] [--port n] [--no-open] Full admin console (React UI over the native server; needs a built rastack-server)\n` +
144
+ ` rastack import <file.csv|.xlsx|.pdf> --resource app.model [--related app.model=<file>] [--out cleaned.json]\n` +
138
145
  ` rastack scan [files...] [--fail-on-pii]\n` +
139
146
  ` rastack seed [--env dev|staging] [--source gs://bucket/ | ./myapp-dev/]\n` +
140
147
  ` rastack bootstrap [--owner o] [--repo r] [--region r] [--prefix p] [--reuse-oidc] [--print] Stand the AWS account stack up\n` +
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The two adapters that lower a field definition into a {@link FieldSpec} —
3
+ * the normalised constraint set the state machine is compiled from.
4
+ *
5
+ * - {@link specFromManifestField} reads `schema.rastack.json` (the compiler's
6
+ * canonical manifest) — what the data-import pipeline uses. It sees the
7
+ * *full* constraint set, including `unique` and the FK relation.
8
+ * - {@link specFromSchemaProperty} reads a write JSON Schema property (the
9
+ * dereferenced `Deref{Name}Request` the form hooks validate against) — what
10
+ * `getFormField` uses in the browser. It sees whatever the OpenAPI emitter
11
+ * carries: type/format/maxLength/enum/nullable/`x-rastack-relation`.
12
+ *
13
+ * Both lower to the same `FieldSpec`, so the *same* compiled machine (same
14
+ * states, same gate order, same messages) validates a keystroke in a form and
15
+ * a row in an imported spreadsheet.
16
+ */
17
+
18
+ import type { FieldModel } from "../compile/model";
19
+ import type { FieldSpec, SpecType } from "./machine";
20
+
21
+ /**
22
+ * Lower a manifest field (`schema.rastack.json`) to a field spec. Mirrors the
23
+ * OpenAPI emitter's semantics: a field is required iff it is not nullable and
24
+ * carries no default; primary keys are server-assigned and never validated on
25
+ * input.
26
+ */
27
+ export function specFromManifestField(field: FieldModel): FieldSpec {
28
+ const spec: FieldSpec = {
29
+ name: field.name,
30
+ type: (field.type as SpecType) ?? "string",
31
+ required: !field.null && field.default === undefined && !field.primaryKey,
32
+ nullable: field.null === true,
33
+ };
34
+ if (field.maxLength !== undefined) spec.maxLength = field.maxLength;
35
+ if (field.unique) spec.unique = true;
36
+ if (field.default !== undefined) spec.default = field.default;
37
+ if (field.type === "fk" && field.relation) spec.relation = field.relation;
38
+ return spec;
39
+ }
40
+
41
+ /**
42
+ * Lower every input-validated field of a manifest resource — primary keys are
43
+ * skipped, matching the write schema the OpenAPI emitter produces.
44
+ */
45
+ export function specsFromResource(resource: {
46
+ fields: FieldModel[];
47
+ }): FieldSpec[] {
48
+ return resource.fields
49
+ .filter((f) => !f.primaryKey)
50
+ .map(specFromManifestField);
51
+ }
52
+
53
+ /** Map a JSON-Schema scalar (`type` + `format`) back to a manifest scalar kind. */
54
+ function schemaScalar(typeList: string[], format?: string): SpecType {
55
+ if (typeList.includes("integer")) return "int";
56
+ if (typeList.includes("number")) return "float";
57
+ if (typeList.includes("boolean")) return "bool";
58
+ if (format === "date-time") return "datetime";
59
+ if (format === "uuid") return "uuid";
60
+ return "string";
61
+ }
62
+
63
+ /**
64
+ * Lower one property of a write JSON Schema to a field spec. `schema` is the
65
+ * object schema (so requiredness can be read from its `required` list);
66
+ * returns `undefined` when the property does not exist.
67
+ */
68
+ export function specFromSchemaProperty(
69
+ schema:
70
+ | {
71
+ properties?: Record<string, any>;
72
+ required?: unknown;
73
+ [key: string]: unknown;
74
+ }
75
+ | undefined,
76
+ fieldName: string,
77
+ ): FieldSpec | undefined {
78
+ const property: any = schema?.properties?.[fieldName];
79
+ if (!property) return undefined;
80
+
81
+ const rawType = property.type;
82
+ const typeList: string[] =
83
+ typeof rawType === "string"
84
+ ? [rawType]
85
+ : Array.isArray(rawType)
86
+ ? rawType
87
+ : [];
88
+ const nullable = typeList.includes("null") || property.nullable === true;
89
+ const required =
90
+ Array.isArray(schema?.required) && schema!.required!.includes(fieldName);
91
+
92
+ const relation = property["x-rastack-relation"];
93
+ const format = typeof property.format === "string" ? property.format : undefined;
94
+
95
+ const spec: FieldSpec = {
96
+ name: fieldName,
97
+ type:
98
+ relation && typeof relation === "object"
99
+ ? "fk"
100
+ : schemaScalar(typeList, format),
101
+ required,
102
+ nullable,
103
+ };
104
+
105
+ if (relation && typeof relation === "object") spec.relation = relation;
106
+ // `format` refines strings (`email`/`url`/`date`/`date-time`/`uuid`); the
107
+ // scalar kinds already encode datetime/uuid, so only keep it for strings.
108
+ if (spec.type === "string" && format) spec.format = format;
109
+ if (typeof property.maxLength === "number") spec.maxLength = property.maxLength;
110
+ if (Array.isArray(property.enum) && property.enum.length > 0) {
111
+ spec.options = property.enum.filter(
112
+ (v: unknown): v is string | number => v !== null && v !== undefined,
113
+ );
114
+ }
115
+ if (property.default !== undefined) spec.default = property.default;
116
+
117
+ return spec;
118
+ }
@@ -0,0 +1,2 @@
1
+ export * from "./machine";
2
+ export * from "./adapters";