@typecad/cuttlefish 1.0.0-alpha.12 → 1.0.0-alpha.14
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/assets/editor-extensions/typecad-debug/README.md +142 -0
- package/assets/editor-extensions/typecad-debug/out/extension.js +347 -0
- package/assets/editor-extensions/typecad-debug/out/extension.js.map +1 -0
- package/assets/editor-extensions/typecad-debug/package.json +76 -0
- package/assets/editor-extensions/typecad-ui/LICENSE +27 -0
- package/assets/editor-extensions/typecad-ui/README.md +52 -0
- package/assets/editor-extensions/typecad-ui/file-icon-dark.png +0 -0
- package/assets/editor-extensions/typecad-ui/file-icon-light.png +0 -0
- package/assets/editor-extensions/typecad-ui/icon.png +0 -0
- package/assets/editor-extensions/typecad-ui/language-configuration.json +43 -0
- package/assets/editor-extensions/typecad-ui/package.json +54 -0
- package/assets/editor-extensions/typecad-ui/snippets/typecad-ui.json +80 -0
- package/assets/editor-extensions/typecad-ui/syntaxes/markdown-ui.json +45 -0
- package/assets/editor-extensions/typecad-ui/syntaxes/typecad-ui.tmLanguage.json +1269 -0
- package/dist/add-preset.d.ts +4 -0
- package/dist/add-preset.js +74 -0
- package/dist/api/config.d.ts +8 -5
- package/dist/api/shared/display-adapters/sdl.js +1 -1
- package/dist/api/shared/display-profile.d.ts +11 -0
- package/dist/api/shared/display-profile.js +3 -0
- package/dist/api/shared/framework-manifest.d.ts +61 -504
- package/dist/api/shared/hal-op-ir.d.ts +19 -0
- package/dist/api/shared/toolchain-types.d.ts +0 -1
- package/dist/cli.js +31 -9
- package/dist/config-loader.d.ts +0 -2
- package/dist/config-loader.js +13 -6
- package/dist/config-schema.d.ts +17 -230
- package/dist/config-schema.js +1 -3
- package/dist/contract/contract-parser.d.ts +9 -127
- package/dist/create/board-checklist.js +1 -1
- package/dist/create/board-codegen.js +4 -4
- package/dist/create/board-spec.d.ts +74 -530
- package/dist/create/debug-artifacts.d.ts +20 -0
- package/dist/create/debug-artifacts.js +69 -0
- package/dist/create/editor-integration.d.ts +30 -0
- package/dist/create/editor-integration.js +218 -0
- package/dist/create/eslint-rules-template.d.ts +2 -2
- package/dist/create/framework-catalog.d.ts +8 -0
- package/dist/create/framework-catalog.js +28 -5
- package/dist/create/index.d.ts +9 -6
- package/dist/create/index.js +6 -4
- package/dist/create/{init-scaffold.d.ts → scaffold.d.ts} +5 -4
- package/dist/create/{init-scaffold.js → scaffold.js} +38 -2
- package/dist/create/templates.d.ts +29 -0
- package/dist/create/{init-templates.js → templates.js} +15 -2
- package/dist/create/wizard.d.ts +8 -0
- package/dist/create/{init-wizard.js → wizard.js} +11 -4
- package/dist/emit/compliance/rules.js +18 -4
- package/dist/emit/emitters/function-emitter-impl.js +7 -1
- package/dist/emit/emitters/line-appender.js +6 -0
- package/dist/emit/emitters/setup.js +22 -0
- package/dist/emit/emitters/ui-emitter.js +40 -15
- package/dist/emit/route-hal-op.js +55 -1
- package/dist/emit/statement-renderer.js +5 -2
- package/dist/ir/build-ir.js +46 -4
- package/dist/ir/expression-to-ir.js +17 -0
- package/dist/ir/hal/hal-emitter.js +23 -5
- package/dist/ir/hal/hal-plugins.js +11 -0
- package/dist/ir/pin-mode-validation.js +32 -9
- package/dist/ir/pin-state-tracking.d.ts +58 -0
- package/dist/ir/pin-state-tracking.js +182 -0
- package/dist/ir/program-analysis.d.ts +6 -0
- package/dist/ir/program-analysis.js +38 -0
- package/dist/ir/statement-to-ir.js +14 -0
- package/dist/ir/transformers/control-flow.js +29 -0
- package/dist/ir/transformers/ui-call-resolver.js +105 -1
- package/dist/ir/ui-element-auto-wire.js +7 -4
- package/dist/library/catalog.d.ts +35 -0
- package/dist/library/catalog.js +67 -0
- package/dist/library/cli.d.ts +2 -0
- package/dist/library/cli.js +168 -0
- package/dist/library/init.d.ts +25 -0
- package/dist/library/init.js +397 -0
- package/dist/library/install.d.ts +9 -0
- package/dist/library/install.js +80 -0
- package/dist/library/registry-search.d.ts +34 -0
- package/dist/library/registry-search.js +50 -0
- package/dist/library/validate.d.ts +17 -0
- package/dist/library/validate.js +175 -0
- package/dist/library-packages.d.ts +95 -0
- package/dist/library-packages.js +275 -0
- package/dist/orchestrator/graph-builder.d.ts +4 -1
- package/dist/orchestrator/graph-builder.js +23 -1
- package/dist/preview/api-shared-shim.d.ts +1 -0
- package/dist/preview/api-shared-shim.js +7 -0
- package/dist/preview/client.js +235 -2
- package/dist/preview/server.js +154 -62
- package/dist/testing.d.ts +2 -2
- package/dist/testing.js +1 -1
- package/dist/theme-tokens.d.ts +22 -0
- package/dist/theme-tokens.js +172 -0
- package/dist/transpile.js +90 -5
- package/dist/types.d.ts +24 -0
- package/dist/ui-hook.d.ts +7 -0
- package/dist/utils/cli.d.ts +2 -2
- package/dist/utils/cli.js +77 -3
- package/dist/utils/ui.d.ts +5 -0
- package/dist/utils/ui.js +7 -0
- package/package.json +18 -9
- package/dist/create/init-templates.d.ts +0 -28
- package/dist/create/init-wizard.d.ts +0 -8
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// Cuttlefish library catalog — the category taxonomy and npm keyword
|
|
3
|
+
// conventions behind `cuttlefish library search/init/validate`.
|
|
4
|
+
//
|
|
5
|
+
// The catalog has no registry service: npm keywords ARE the catalog. Every
|
|
6
|
+
// library package carries the marker keyword LIBRARY_MARKER_KEYWORD plus one
|
|
7
|
+
// category keyword (e.g. 'cuttlefish-led'). npm's search endpoint ANDs
|
|
8
|
+
// `keywords:` terms, so queries compose:
|
|
9
|
+
//
|
|
10
|
+
// keywords:cuttlefish-library → every library
|
|
11
|
+
// keywords:cuttlefish-library keywords:cuttlefish-led → the led category
|
|
12
|
+
// keywords:cuttlefish-library ws2812 → free-text within libraries
|
|
13
|
+
// ---------------------------------------------------------------------------
|
|
14
|
+
/** The one keyword every cuttlefish library package must carry. */
|
|
15
|
+
export const LIBRARY_MARKER_KEYWORD = "cuttlefish-library";
|
|
16
|
+
/** Prefix for category keywords (`cuttlefish-<id>`). */
|
|
17
|
+
export const CATEGORY_KEYWORD_PREFIX = "cuttlefish-";
|
|
18
|
+
/**
|
|
19
|
+
* The category taxonomy. Shared by search (query building + result shaping),
|
|
20
|
+
* init (scaffold choices + keywords), validate (keyword consistency), and the
|
|
21
|
+
* website's Library Packages page (rendered from the same list).
|
|
22
|
+
*/
|
|
23
|
+
export const LIBRARY_CATEGORIES = [
|
|
24
|
+
{ id: "led", label: "LEDs", description: "LEDs, addressable strips, LED drivers", examples: "WS2812-class pixels, LED drivers, bar graphs" },
|
|
25
|
+
{ id: "display", label: "Displays", description: "Panels and panel drivers", examples: "TFT, OLED, e-ink" },
|
|
26
|
+
{ id: "sensor", label: "Sensors", description: "Measurement parts", examples: "environmental, motion, IMU, light, distance" },
|
|
27
|
+
{ id: "actuator", label: "Actuators", description: "Things that move or switch", examples: "motors, servos, steppers, relays" },
|
|
28
|
+
{ id: "comms", label: "Communications", description: "Radios and networking beyond built-in WiFi/BLE", examples: "LoRa, GSM, satellite, CAN add-ons" },
|
|
29
|
+
{ id: "storage", label: "Storage", description: "Persistent storage parts", examples: "SD cards, flash chips, FRAM" },
|
|
30
|
+
{ id: "audio", label: "Audio", description: "Sound input and output", examples: "microphones, amplifiers, codecs" },
|
|
31
|
+
{ id: "power", label: "Power", description: "Power management and monitoring", examples: "PMICs, battery gauges, chargers" },
|
|
32
|
+
{ id: "input", label: "Input", description: "Add-on human input", examples: "keypads, rotary encoders, add-on touch" },
|
|
33
|
+
{ id: "io", label: "I/O Expanders", description: "Extra I/O and simple drivers", examples: "port expanders, matrix drivers, 7-segment" },
|
|
34
|
+
{ id: "timing", label: "Timing", description: "Clocks and time sources", examples: "RTCs, precision clocks, GPS time" },
|
|
35
|
+
{ id: "utility", label: "Utility", description: "Pure-code helpers with no hardware of their own", examples: "formats, algorithms, protocol codecs" },
|
|
36
|
+
];
|
|
37
|
+
/** Look up a category by id (case-insensitive). */
|
|
38
|
+
export function libraryCategory(id) {
|
|
39
|
+
const lower = id.toLowerCase();
|
|
40
|
+
return LIBRARY_CATEGORIES.find((c) => c.id === lower);
|
|
41
|
+
}
|
|
42
|
+
/** The npm keyword for a category (`cuttlefish-<id>`). */
|
|
43
|
+
export function categoryKeyword(id) {
|
|
44
|
+
return `${CATEGORY_KEYWORD_PREFIX}${id.toLowerCase()}`;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Derive the category of an npm search result from its keywords. A package may
|
|
48
|
+
* carry several category keywords; the first match in taxonomy order wins so
|
|
49
|
+
* results are stable.
|
|
50
|
+
*/
|
|
51
|
+
export function categoryFromKeywords(keywords) {
|
|
52
|
+
if (!keywords || keywords.length === 0)
|
|
53
|
+
return null;
|
|
54
|
+
const set = new Set(keywords.map((k) => k.toLowerCase()));
|
|
55
|
+
for (const category of LIBRARY_CATEGORIES) {
|
|
56
|
+
if (set.has(categoryKeyword(category.id)))
|
|
57
|
+
return category.id;
|
|
58
|
+
}
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
/**
|
|
62
|
+
* The keywords a library package should carry: the marker plus its category
|
|
63
|
+
* keyword. Used by `library init` and checked by `library validate`.
|
|
64
|
+
*/
|
|
65
|
+
export function requiredLibraryKeywords(categoryId) {
|
|
66
|
+
return [LIBRARY_MARKER_KEYWORD, categoryKeyword(categoryId)];
|
|
67
|
+
}
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// `cuttlefish library <subcommand>` — CLI glue for the library manager.
|
|
3
|
+
// Subcommands: search, install, init, validate. The catalog modules own the
|
|
4
|
+
// logic; this module owns argument interpretation and presentation.
|
|
5
|
+
// ---------------------------------------------------------------------------
|
|
6
|
+
import chalk from "chalk";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { LIBRARY_CATEGORIES, libraryCategory } from "./catalog.js";
|
|
9
|
+
import { searchLibraryPackages } from "./registry-search.js";
|
|
10
|
+
import { findProjectPackageJson, installedDependencyVersion, npmInstall } from "./install.js";
|
|
11
|
+
import { runLibraryInit } from "./init.js";
|
|
12
|
+
import { validateLibraryPackage, printValidationReport } from "./validate.js";
|
|
13
|
+
function requireCategory(category, command) {
|
|
14
|
+
if (category === undefined)
|
|
15
|
+
return undefined;
|
|
16
|
+
if (!libraryCategory(category)) {
|
|
17
|
+
throw new Error(`Unknown category '${category}' for 'library ${command}'. Known categories: ` +
|
|
18
|
+
LIBRARY_CATEGORIES.map((c) => c.id).join(", ") +
|
|
19
|
+
".");
|
|
20
|
+
}
|
|
21
|
+
return category.toLowerCase();
|
|
22
|
+
}
|
|
23
|
+
function stripVersionPrefix(v) {
|
|
24
|
+
return v.replace(/^[^0-9]*/, "");
|
|
25
|
+
}
|
|
26
|
+
async function runSearch(options) {
|
|
27
|
+
const category = requireCategory(options.category, "search");
|
|
28
|
+
const text = options.positionals.join(" ");
|
|
29
|
+
let results;
|
|
30
|
+
try {
|
|
31
|
+
results = await searchLibraryPackages(text || undefined, category);
|
|
32
|
+
}
|
|
33
|
+
catch (e) {
|
|
34
|
+
throw new Error(`Failed to search npm: ${e instanceof Error ? e.message : String(e)}`);
|
|
35
|
+
}
|
|
36
|
+
if (options.json) {
|
|
37
|
+
const pkgPath = findProjectPackageJson();
|
|
38
|
+
console.log(JSON.stringify(results.map((r) => ({
|
|
39
|
+
name: r.name,
|
|
40
|
+
version: r.version,
|
|
41
|
+
description: r.description,
|
|
42
|
+
category: r.category,
|
|
43
|
+
npmUrl: r.npmUrl,
|
|
44
|
+
installed: pkgPath ? installedDependencyVersion(pkgPath, r.name) !== undefined : false,
|
|
45
|
+
})), null, 2));
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const header = category
|
|
49
|
+
? `cuttlefish libraries — category: ${libraryCategory(category).label}`
|
|
50
|
+
: "cuttlefish libraries";
|
|
51
|
+
console.log(chalk.green("+") + " " + chalk.white.bold(header) + chalk.gray(` (npm keyword: cuttlefish-library${category ? ` + cuttlefish-${category}` : ""})`));
|
|
52
|
+
console.log();
|
|
53
|
+
if (results.length === 0) {
|
|
54
|
+
console.log(chalk.yellow("No matching library packages on npm yet."));
|
|
55
|
+
console.log(` Scaffold the first one: ${chalk.cyan("cuttlefish library init")}`);
|
|
56
|
+
return;
|
|
57
|
+
}
|
|
58
|
+
const pkgPath = findProjectPackageJson();
|
|
59
|
+
for (const r of results) {
|
|
60
|
+
const cat = r.category ? libraryCategory(r.category) : undefined;
|
|
61
|
+
const installedSpec = pkgPath ? installedDependencyVersion(pkgPath, r.name) : undefined;
|
|
62
|
+
const state = installedSpec
|
|
63
|
+
? stripVersionPrefix(installedSpec) === r.version
|
|
64
|
+
? chalk.gray(" (installed)")
|
|
65
|
+
: chalk.yellow(` (installed v${stripVersionPrefix(installedSpec)}, latest v${r.version})`)
|
|
66
|
+
: "";
|
|
67
|
+
console.log(` ${chalk.white.bold(r.name)} ${chalk.dim(`v${r.version}`)}${state}`);
|
|
68
|
+
if (cat) {
|
|
69
|
+
console.log(` ${chalk.cyan(`[${cat.label}]`)} ${r.description ?? ""}`);
|
|
70
|
+
}
|
|
71
|
+
else {
|
|
72
|
+
console.log(` ${r.description ?? ""}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
console.log();
|
|
76
|
+
console.log(chalk.gray(` Install with: cuttlefish library install <name>`));
|
|
77
|
+
}
|
|
78
|
+
function runInstall(options) {
|
|
79
|
+
const names = options.positionals;
|
|
80
|
+
if (names.length === 0) {
|
|
81
|
+
throw new Error("Usage: cuttlefish library install <package...>");
|
|
82
|
+
}
|
|
83
|
+
const pkgPath = findProjectPackageJson();
|
|
84
|
+
if (!pkgPath) {
|
|
85
|
+
throw new Error("No package.json found in this directory or any parent — run inside a cuttlefish project.");
|
|
86
|
+
}
|
|
87
|
+
const pkgDir = path.dirname(pkgPath);
|
|
88
|
+
if (options.json) {
|
|
89
|
+
const before = Object.fromEntries(names.map((n) => [n, installedDependencyVersion(pkgPath, n) ?? null]));
|
|
90
|
+
try {
|
|
91
|
+
npmInstall(names, pkgDir);
|
|
92
|
+
}
|
|
93
|
+
catch (e) {
|
|
94
|
+
const err = e;
|
|
95
|
+
const detail = err.stderr?.toString().trim() || (e instanceof Error ? e.message : String(e));
|
|
96
|
+
throw new Error(`Failed to install packages: ${detail}`);
|
|
97
|
+
}
|
|
98
|
+
console.log(JSON.stringify({ installed: names, projectRoot: pkgDir, previous: before }, null, 2));
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
console.log(chalk.green("+") + ` Installing ${names.join(", ")}...`);
|
|
102
|
+
try {
|
|
103
|
+
npmInstall(names, pkgDir);
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
const err = e;
|
|
107
|
+
const detail = err.stderr?.toString().trim() || (e instanceof Error ? e.message : String(e));
|
|
108
|
+
throw new Error(`Failed to install packages: ${detail}`);
|
|
109
|
+
}
|
|
110
|
+
for (const name of names) {
|
|
111
|
+
console.log(chalk.green("+") + ` ${name}`);
|
|
112
|
+
console.log(chalk.gray(` https://www.npmjs.com/package/${name}`));
|
|
113
|
+
}
|
|
114
|
+
console.log(chalk.green("✔") + " Done");
|
|
115
|
+
}
|
|
116
|
+
async function runInit(options) {
|
|
117
|
+
if (options.category !== undefined) {
|
|
118
|
+
requireCategory(options.category, "init");
|
|
119
|
+
}
|
|
120
|
+
await runLibraryInit({
|
|
121
|
+
name: options.positionals[0],
|
|
122
|
+
framework: options.framework,
|
|
123
|
+
category: options.category,
|
|
124
|
+
targets: options.targets,
|
|
125
|
+
dir: options.dir,
|
|
126
|
+
yes: options.yes,
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
function runValidate(options) {
|
|
130
|
+
const dir = options.positionals[0] ?? process.cwd();
|
|
131
|
+
const report = validateLibraryPackage(dir);
|
|
132
|
+
if (options.json) {
|
|
133
|
+
console.log(JSON.stringify({
|
|
134
|
+
valid: report.valid,
|
|
135
|
+
dir: report.dir,
|
|
136
|
+
errors: report.errors,
|
|
137
|
+
warnings: report.warnings,
|
|
138
|
+
autosarFindings: report.autosarFindings,
|
|
139
|
+
}, null, 2));
|
|
140
|
+
}
|
|
141
|
+
else {
|
|
142
|
+
console.log(chalk.white.bold(`cuttlefish library validate`) + chalk.gray(` ${report.dir}`));
|
|
143
|
+
console.log();
|
|
144
|
+
const code = printValidationReport(report);
|
|
145
|
+
if (code !== 0) {
|
|
146
|
+
process.exitCode = code;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
if (!report.valid && options.json) {
|
|
150
|
+
process.exitCode = 1;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
export async function runLibraryCommand(options) {
|
|
154
|
+
switch (options.subcommand) {
|
|
155
|
+
case "search":
|
|
156
|
+
await runSearch(options);
|
|
157
|
+
return;
|
|
158
|
+
case "install":
|
|
159
|
+
runInstall(options);
|
|
160
|
+
return;
|
|
161
|
+
case "init":
|
|
162
|
+
await runInit(options);
|
|
163
|
+
return;
|
|
164
|
+
case "validate":
|
|
165
|
+
runValidate(options);
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export interface LibraryInitOptions {
|
|
2
|
+
/** Full package name (e.g. '@acme/esp32-led-ring' or 'my-lib'). */
|
|
3
|
+
name?: string;
|
|
4
|
+
/** Framework id from FRAMEWORK_CATALOG ('zephyr', 'arduino', ...). */
|
|
5
|
+
framework?: string;
|
|
6
|
+
/** Category id from LIBRARY_CATEGORIES. */
|
|
7
|
+
category?: string;
|
|
8
|
+
/** Comma-separated board-target prefixes (e.g. 'esp32s3_devkitc'). */
|
|
9
|
+
targets?: string;
|
|
10
|
+
/** Directory to scaffold into (default: ./<package basename>). */
|
|
11
|
+
dir?: string;
|
|
12
|
+
/** Skip prompts; take defaults for anything not provided by flags. */
|
|
13
|
+
yes?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface LibraryInitResult {
|
|
16
|
+
packageDir: string;
|
|
17
|
+
packageName: string;
|
|
18
|
+
/** The library id (slug of the package basename). */
|
|
19
|
+
id: string;
|
|
20
|
+
}
|
|
21
|
+
/** Slug of a package basename: lowercase, runs of non-alphanumerics → '-'. */
|
|
22
|
+
export declare function libraryIdFromPackageName(packageName: string): string;
|
|
23
|
+
/** '__tc_my_lib' for id 'my-lib' — a valid C++ identifier prefix. */
|
|
24
|
+
export declare function tokenBaseFromId(id: string): string;
|
|
25
|
+
export declare function runLibraryInit(options: LibraryInitOptions): Promise<LibraryInitResult>;
|
|
@@ -0,0 +1,397 @@
|
|
|
1
|
+
// ---------------------------------------------------------------------------
|
|
2
|
+
// `cuttlefish library init` — scaffold a new cuttlefish library package.
|
|
3
|
+
//
|
|
4
|
+
// Generates everything a library author needs to reach a valid, publishable
|
|
5
|
+
// package: the typed API skeleton, the cuttlefish.library.json manifest,
|
|
6
|
+
// AUTOSAR C++14-compliant shim stubs, (for Zephyr) an overlay fragment, a
|
|
7
|
+
// README, and a starter compliance test. The scaffold is deliberately tiny —
|
|
8
|
+
// it must pass `cuttlefish library validate` the moment it lands.
|
|
9
|
+
//
|
|
10
|
+
// Prompts follow the create-wizard's readline pattern (no prompt dependency);
|
|
11
|
+
// flags override prompts, and --yes takes defaults for anything unanswered.
|
|
12
|
+
// ---------------------------------------------------------------------------
|
|
13
|
+
import fs from "node:fs";
|
|
14
|
+
import path from "node:path";
|
|
15
|
+
import readline from "node:readline/promises";
|
|
16
|
+
import { stdin as input, stdout as output } from "node:process";
|
|
17
|
+
import chalk from "chalk";
|
|
18
|
+
import { LIBRARY_CATEGORIES, libraryCategory, requiredLibraryKeywords } from "./catalog.js";
|
|
19
|
+
import { FRAMEWORK_CATALOG } from "../create/framework-catalog.js";
|
|
20
|
+
// ── Naming derivations ──────────────────────────────────────────────────────
|
|
21
|
+
/** Slug of a package basename: lowercase, runs of non-alphanumerics → '-'. */
|
|
22
|
+
export function libraryIdFromPackageName(packageName) {
|
|
23
|
+
const base = packageName.includes("/") ? packageName.split("/").pop() : packageName;
|
|
24
|
+
const slug = base.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-+|-+$/g, "");
|
|
25
|
+
if (slug.length === 0) {
|
|
26
|
+
throw new Error(`Cannot derive a library id from '${packageName}'.`);
|
|
27
|
+
}
|
|
28
|
+
return slug;
|
|
29
|
+
}
|
|
30
|
+
/** '__tc_my_lib' for id 'my-lib' — a valid C++ identifier prefix. */
|
|
31
|
+
export function tokenBaseFromId(id) {
|
|
32
|
+
return id.replace(/-/g, "_");
|
|
33
|
+
}
|
|
34
|
+
function pascalCase(id) {
|
|
35
|
+
return id.split("-").filter(Boolean).map((s) => s.charAt(0).toUpperCase() + s.slice(1)).join("");
|
|
36
|
+
}
|
|
37
|
+
function camelCase(id) {
|
|
38
|
+
const pascal = pascalCase(id);
|
|
39
|
+
return pascal.charAt(0).toLowerCase() + pascal.slice(1);
|
|
40
|
+
}
|
|
41
|
+
function isValidNpmName(name) {
|
|
42
|
+
// Conservative check: optional @scope/ + url-safe segments.
|
|
43
|
+
return /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/i.test(name);
|
|
44
|
+
}
|
|
45
|
+
async function promptText(rl, prompt, defaultValue, validate) {
|
|
46
|
+
for (;;) {
|
|
47
|
+
const suffix = defaultValue ? ` (${defaultValue})` : "";
|
|
48
|
+
const answer = await rl.question(`${chalk.cyan("?")} ${prompt}${suffix}: `);
|
|
49
|
+
const value = (answer.trim() || (defaultValue ?? "")).trim();
|
|
50
|
+
if (validate) {
|
|
51
|
+
const error = validate(value);
|
|
52
|
+
if (error) {
|
|
53
|
+
console.log(` ${chalk.red("✗")} ${error}`);
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return value;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
async function promptSelect(rl, prompt, options) {
|
|
61
|
+
console.log(`${chalk.cyan("?")} ${prompt}:`);
|
|
62
|
+
for (let i = 0; i < options.length; i++) {
|
|
63
|
+
console.log(` ${chalk.dim(`${i + 1})`)} ${options[i].label}`);
|
|
64
|
+
}
|
|
65
|
+
for (;;) {
|
|
66
|
+
const answer = await rl.question(` Enter number (1-${options.length}): `);
|
|
67
|
+
const idx = parseInt(answer.trim(), 10) - 1;
|
|
68
|
+
if (idx >= 0 && idx < options.length) {
|
|
69
|
+
return options[idx].value;
|
|
70
|
+
}
|
|
71
|
+
console.log(` ${chalk.red("✗")} Please enter a number between 1 and ${options.length}.`);
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
function renderPackageJson(m) {
|
|
75
|
+
return JSON.stringify({
|
|
76
|
+
name: m.packageName,
|
|
77
|
+
version: "1.0.0",
|
|
78
|
+
description: `${m.category.label} library for cuttlefish (${m.framework} framework)`,
|
|
79
|
+
type: "module",
|
|
80
|
+
main: "./dist/index.js",
|
|
81
|
+
types: "./dist/index.d.ts",
|
|
82
|
+
files: ["dist", "src", "shims", "cuttlefish.library.json"],
|
|
83
|
+
scripts: {
|
|
84
|
+
build: "tsc",
|
|
85
|
+
prepublishOnly: "npm run build",
|
|
86
|
+
},
|
|
87
|
+
license: "MIT",
|
|
88
|
+
keywords: [
|
|
89
|
+
"cuttlefish",
|
|
90
|
+
...requiredLibraryKeywords(m.category.id),
|
|
91
|
+
m.framework,
|
|
92
|
+
...m.id.split("-"),
|
|
93
|
+
],
|
|
94
|
+
engines: { node: ">=18" },
|
|
95
|
+
sideEffects: false,
|
|
96
|
+
exports: {
|
|
97
|
+
".": { types: "./dist/index.d.ts", default: "./dist/index.js" },
|
|
98
|
+
"./package.json": "./package.json",
|
|
99
|
+
},
|
|
100
|
+
devDependencies: {
|
|
101
|
+
"@typecad/cuttlefish": "*",
|
|
102
|
+
vitest: "^4.0.0",
|
|
103
|
+
},
|
|
104
|
+
}, null, 2) + "\n";
|
|
105
|
+
}
|
|
106
|
+
function renderTsconfig() {
|
|
107
|
+
return JSON.stringify({
|
|
108
|
+
compilerOptions: {
|
|
109
|
+
composite: true,
|
|
110
|
+
target: "ES2021",
|
|
111
|
+
module: "Node16",
|
|
112
|
+
moduleResolution: "Node16",
|
|
113
|
+
strict: true,
|
|
114
|
+
esModuleInterop: true,
|
|
115
|
+
skipLibCheck: true,
|
|
116
|
+
forceConsistentCasingInFileNames: true,
|
|
117
|
+
declaration: true,
|
|
118
|
+
declarationMap: false,
|
|
119
|
+
sourceMap: false,
|
|
120
|
+
rootDir: "src",
|
|
121
|
+
outDir: "dist",
|
|
122
|
+
},
|
|
123
|
+
include: ["src/**/*.ts"],
|
|
124
|
+
}, null, 2) + "\n";
|
|
125
|
+
}
|
|
126
|
+
function renderApi(m) {
|
|
127
|
+
return `// ---------------------------------------------------------------------------
|
|
128
|
+
// ${m.packageName} — cuttlefish library package (${m.category.label.toLowerCase()}).
|
|
129
|
+
//
|
|
130
|
+
// This file is the typed API contract: it is never executed. The cuttlefish
|
|
131
|
+
// transpiler lowers the import to the shim header (shims/__tc_${m.tokenBase}.h),
|
|
132
|
+
// and calls on the exported instance render verbatim into the generated C++.
|
|
133
|
+
// Two rules keep that contract intact:
|
|
134
|
+
//
|
|
135
|
+
// 1. Method names are load-bearing. The C++ class in the shim must define
|
|
136
|
+
// exactly these names — 'rgbLed'-style call sites appear in the C++ as-is.
|
|
137
|
+
// 2. Export a singleton instance, not a constructor. A bare 'new' in user
|
|
138
|
+
// code renders as a C++ heap allocation, which the AUTOSAR C++14 rules
|
|
139
|
+
// the shims follow forbid.
|
|
140
|
+
// ---------------------------------------------------------------------------
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* ${m.category.description} (${m.category.examples}).
|
|
144
|
+
*/
|
|
145
|
+
export class ${m.className} {
|
|
146
|
+
/**
|
|
147
|
+
* Prepare the hardware. Call once from setup(). The stub in the shim is a
|
|
148
|
+
* no-op — replace it with your initialization code.
|
|
149
|
+
*/
|
|
150
|
+
begin(): this {
|
|
151
|
+
return this;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Add your API here. Every method needs a matching member on the C++ class.
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** The instance to use — a preconstructed singleton (see rule 2 above). */
|
|
158
|
+
export const ${m.instanceName}: ${m.className} = new ${m.className}();
|
|
159
|
+
`;
|
|
160
|
+
}
|
|
161
|
+
function renderManifest(m) {
|
|
162
|
+
const manifest = {
|
|
163
|
+
id: m.id,
|
|
164
|
+
module: m.packageName,
|
|
165
|
+
framework: m.framework,
|
|
166
|
+
include: `"__tc_${m.tokenBase}.h"`,
|
|
167
|
+
gateToken: `__tc_${m.tokenBase}`,
|
|
168
|
+
shims: [
|
|
169
|
+
{ path: `shims/__tc_${m.tokenBase}.h`, outName: `__tc_${m.tokenBase}.h` },
|
|
170
|
+
{ path: `shims/__tc_${m.tokenBase}.cpp`, outName: `__tc_${m.tokenBase}.cpp` },
|
|
171
|
+
],
|
|
172
|
+
};
|
|
173
|
+
if (m.targets.length > 0) {
|
|
174
|
+
manifest.targets = m.targets;
|
|
175
|
+
}
|
|
176
|
+
if (m.isZephyr) {
|
|
177
|
+
manifest.kconfig = ["# TODO: the CONFIG_ lines your library needs, e.g. CONFIG_LED_STRIP=y"];
|
|
178
|
+
manifest.overlay = `shims/${m.id}.overlay`;
|
|
179
|
+
}
|
|
180
|
+
return JSON.stringify(manifest, null, 2) + "\n";
|
|
181
|
+
}
|
|
182
|
+
function renderShimHeader(m) {
|
|
183
|
+
return `// ---------------------------------------------------------------------------
|
|
184
|
+
// __tc_${m.tokenBase}.h — ${m.packageName} shim.
|
|
185
|
+
//
|
|
186
|
+
// The implementation behind the TypeScript API in src/index.ts. Calls on the
|
|
187
|
+
// exported instance render verbatim, so the class name, the instance name,
|
|
188
|
+
// and the method names must match src/index.ts exactly.
|
|
189
|
+
//
|
|
190
|
+
// AUTOSAR C++14 by construction: fixed-width integers, static_cast only (no
|
|
191
|
+
// C-style casts), no heap, 'final' on the leaf class. The generated
|
|
192
|
+
// application's compliance check runs over these bytes.
|
|
193
|
+
// ---------------------------------------------------------------------------
|
|
194
|
+
|
|
195
|
+
#ifndef TC_${m.tokenBase.toUpperCase()}_H_
|
|
196
|
+
#define TC_${m.tokenBase.toUpperCase()}_H_
|
|
197
|
+
|
|
198
|
+
#include <cstdint>
|
|
199
|
+
${m.isZephyr ? "#include <zephyr/kernel.h>\n" : ""}class ${m.className} final
|
|
200
|
+
{
|
|
201
|
+
public:
|
|
202
|
+
${m.className}& begin();
|
|
203
|
+
|
|
204
|
+
private:
|
|
205
|
+
bool initialized_ = false;
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
extern ${m.className} ${m.instanceName};
|
|
209
|
+
|
|
210
|
+
#endif // TC_${m.tokenBase.toUpperCase()}_H_
|
|
211
|
+
`;
|
|
212
|
+
}
|
|
213
|
+
function renderShimSource(m) {
|
|
214
|
+
return `// ---------------------------------------------------------------------------
|
|
215
|
+
// __tc_${m.tokenBase}.cpp — ${m.packageName} shim implementation.
|
|
216
|
+
// See __tc_${m.tokenBase}.h for the contract. AUTOSAR C++14 compliant.
|
|
217
|
+
// ---------------------------------------------------------------------------
|
|
218
|
+
|
|
219
|
+
#include "__tc_${m.tokenBase}.h"
|
|
220
|
+
|
|
221
|
+
${m.className}& ${m.className}::begin()
|
|
222
|
+
{
|
|
223
|
+
initialized_ = true;
|
|
224
|
+
return *this;
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
${m.className} ${m.instanceName};
|
|
228
|
+
`;
|
|
229
|
+
}
|
|
230
|
+
function renderOverlay(m) {
|
|
231
|
+
return `/*
|
|
232
|
+
* ${m.id} — devicetree overlay fragment (${m.category.label.toLowerCase()}).
|
|
233
|
+
*
|
|
234
|
+
* Appended to the generated boards/<board>.overlay when this library's import
|
|
235
|
+
* is used. Describe the hardware here: controllers, pins, binding properties.
|
|
236
|
+
* When upstream Zephyr ships a sample overlay for your part, adapt it and
|
|
237
|
+
* credit it in a comment.
|
|
238
|
+
*/
|
|
239
|
+
|
|
240
|
+
/ {
|
|
241
|
+
\t/* aliases { your-alias = &your_node; }; */
|
|
242
|
+
};
|
|
243
|
+
`;
|
|
244
|
+
}
|
|
245
|
+
function renderReadme(m) {
|
|
246
|
+
return `# ${m.packageName}
|
|
247
|
+
|
|
248
|
+
A cuttlefish library package — ${m.category.label.toLowerCase()} (${m.category.description}),
|
|
249
|
+
for the **${m.framework}** framework${m.targets.length > 0 ? ` (targets: ${m.targets.join(", ")})` : ""}.
|
|
250
|
+
|
|
251
|
+
## Use it
|
|
252
|
+
|
|
253
|
+
\`\`\`ts
|
|
254
|
+
import { ${m.instanceName} } from '${m.packageName}';
|
|
255
|
+
|
|
256
|
+
${m.instanceName}.begin();
|
|
257
|
+
\`\`\`
|
|
258
|
+
|
|
259
|
+
## Carry the hardware facts
|
|
260
|
+
|
|
261
|
+
This library owns the facts so projects don't have to. Document, in this
|
|
262
|
+
README, everything a user would otherwise hunt through datasheets for:
|
|
263
|
+
|
|
264
|
+
- which board revisions and targets are supported (and which pins they use),
|
|
265
|
+
- which peripherals the library borrows (say so — a user may want them),
|
|
266
|
+
- wiring requirements (I2C address straps, level shifting, pull-ups).
|
|
267
|
+
|
|
268
|
+
## Authoring checklist
|
|
269
|
+
|
|
270
|
+
- Method names in src/index.ts match the C++ shim names exactly; calls render verbatim.
|
|
271
|
+
- Export a singleton instance, not a constructor.
|
|
272
|
+
- Shims pass \`cuttlefish library validate\` (AUTOSAR C++14, strict).
|
|
273
|
+
- \`cuttlefish.library.json\` declares framework${m.isZephyr ? ", kconfig, overlay" : ""} and the shim files.
|
|
274
|
+
- package.json keywords include the marker (\`cuttlefish-library\`) and category (\`cuttlefish-${m.category.id}\`) keywords.
|
|
275
|
+
|
|
276
|
+
Validate with \`cuttlefish library validate .\` from this directory.
|
|
277
|
+
`;
|
|
278
|
+
}
|
|
279
|
+
function renderStarterTest(m) {
|
|
280
|
+
return `import { describe, it, expect } from "vitest";
|
|
281
|
+
import { readFileSync } from "node:fs";
|
|
282
|
+
import { join, dirname } from "node:path";
|
|
283
|
+
import { fileURLToPath } from "node:url";
|
|
284
|
+
import { ComplianceContext, runSelfCheck } from "@typecad/cuttlefish/compliance";
|
|
285
|
+
|
|
286
|
+
// The shipped shim bytes must pass --autosar=strict, exactly like framework
|
|
287
|
+
// shims — the generated application's compliance check runs over them.
|
|
288
|
+
|
|
289
|
+
const here = dirname(fileURLToPath(import.meta.url));
|
|
290
|
+
|
|
291
|
+
describe("${m.packageName} shims under --autosar=strict", () => {
|
|
292
|
+
it("__tc_${m.tokenBase}.h/.cpp produce no unrecorded AUTOSAR violations", () => {
|
|
293
|
+
const header = readFileSync(join(here, "..", "shims", "__tc_${m.tokenBase}.h"), "utf8").split("\\n");
|
|
294
|
+
const source = readFileSync(join(here, "..", "shims", "__tc_${m.tokenBase}.cpp"), "utf8").split("\\n");
|
|
295
|
+
const ctx = new ComplianceContext("strict");
|
|
296
|
+
const findings = runSelfCheck(ctx, source, header);
|
|
297
|
+
expect(findings).toEqual([]);
|
|
298
|
+
});
|
|
299
|
+
});
|
|
300
|
+
`;
|
|
301
|
+
}
|
|
302
|
+
// ── Scaffolding ─────────────────────────────────────────────────────────────
|
|
303
|
+
function writeIfChanged(filePath, content) {
|
|
304
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
305
|
+
fs.writeFileSync(filePath, content);
|
|
306
|
+
}
|
|
307
|
+
export async function runLibraryInit(options) {
|
|
308
|
+
const interactive = options.yes !== true;
|
|
309
|
+
let packageName = options.name;
|
|
310
|
+
let framework = options.framework;
|
|
311
|
+
let categoryId = options.category;
|
|
312
|
+
let targetsRaw = options.targets;
|
|
313
|
+
const missing = packageName === undefined || framework === undefined || categoryId === undefined;
|
|
314
|
+
if (interactive && missing) {
|
|
315
|
+
const rl = readline.createInterface({ input, output });
|
|
316
|
+
try {
|
|
317
|
+
if (packageName === undefined) {
|
|
318
|
+
packageName = await promptText(rl, "Package name (npm name, e.g. @acme/my-lib)", "my-lib", (v) => isValidNpmName(v) ? null : "Not a valid npm package name.");
|
|
319
|
+
}
|
|
320
|
+
if (framework === undefined) {
|
|
321
|
+
framework = await promptSelect(rl, "Framework", FRAMEWORK_CATALOG.map((f) => ({ label: f.label, value: f.id })));
|
|
322
|
+
}
|
|
323
|
+
if (categoryId === undefined) {
|
|
324
|
+
categoryId = await promptSelect(rl, "Category", LIBRARY_CATEGORIES.map((c) => ({ label: `${c.label} — ${c.description}`, value: c.id })));
|
|
325
|
+
}
|
|
326
|
+
if (targetsRaw === undefined) {
|
|
327
|
+
targetsRaw = await promptText(rl, "Board targets (comma-separated build-target prefixes, empty for any)", "");
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
finally {
|
|
331
|
+
rl.close();
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
packageName = (packageName ?? "my-lib").trim();
|
|
335
|
+
framework = (framework ?? "zephyr").trim();
|
|
336
|
+
categoryId = (categoryId ?? "utility").trim();
|
|
337
|
+
if (!isValidNpmName(packageName)) {
|
|
338
|
+
throw new Error(`'${packageName}' is not a valid npm package name.`);
|
|
339
|
+
}
|
|
340
|
+
const frameworkEntry = FRAMEWORK_CATALOG.find((f) => f.id === framework);
|
|
341
|
+
if (!frameworkEntry) {
|
|
342
|
+
throw new Error(`Unknown framework '${framework}'. Known: ${FRAMEWORK_CATALOG.map((f) => f.id).join(", ")}.`);
|
|
343
|
+
}
|
|
344
|
+
const category = libraryCategory(categoryId);
|
|
345
|
+
if (!category) {
|
|
346
|
+
throw new Error(`Unknown category '${categoryId}'. Known: ${LIBRARY_CATEGORIES.map((c) => c.id).join(", ")}.`);
|
|
347
|
+
}
|
|
348
|
+
const id = libraryIdFromPackageName(packageName);
|
|
349
|
+
const targets = (targetsRaw ?? "")
|
|
350
|
+
.split(",")
|
|
351
|
+
.map((t) => t.trim())
|
|
352
|
+
.filter((t) => t.length > 0);
|
|
353
|
+
const model = {
|
|
354
|
+
packageName,
|
|
355
|
+
id,
|
|
356
|
+
className: pascalCase(id),
|
|
357
|
+
instanceName: camelCase(id),
|
|
358
|
+
tokenBase: tokenBaseFromId(id),
|
|
359
|
+
framework,
|
|
360
|
+
category,
|
|
361
|
+
targets,
|
|
362
|
+
isZephyr: framework === "zephyr",
|
|
363
|
+
};
|
|
364
|
+
const packageDir = path.resolve(options.dir ?? path.join(process.cwd(), id));
|
|
365
|
+
if (fs.existsSync(packageDir) && fs.readdirSync(packageDir).length > 0) {
|
|
366
|
+
throw new Error(`Directory ${packageDir} exists and is not empty.`);
|
|
367
|
+
}
|
|
368
|
+
writeIfChanged(path.join(packageDir, "package.json"), renderPackageJson(model));
|
|
369
|
+
writeIfChanged(path.join(packageDir, "tsconfig.json"), renderTsconfig());
|
|
370
|
+
writeIfChanged(path.join(packageDir, ".gitignore"), "node_modules/\ndist/\n");
|
|
371
|
+
writeIfChanged(path.join(packageDir, "src", "index.ts"), renderApi(model));
|
|
372
|
+
writeIfChanged(path.join(packageDir, "cuttlefish.library.json"), renderManifest(model));
|
|
373
|
+
writeIfChanged(path.join(packageDir, "shims", `__tc_${model.tokenBase}.h`), renderShimHeader(model));
|
|
374
|
+
writeIfChanged(path.join(packageDir, "shims", `__tc_${model.tokenBase}.cpp`), renderShimSource(model));
|
|
375
|
+
if (model.isZephyr) {
|
|
376
|
+
writeIfChanged(path.join(packageDir, "shims", `${id}.overlay`), renderOverlay(model));
|
|
377
|
+
}
|
|
378
|
+
writeIfChanged(path.join(packageDir, "README.md"), renderReadme(model));
|
|
379
|
+
writeIfChanged(path.join(packageDir, "tests", "library.test.ts"), renderStarterTest(model));
|
|
380
|
+
console.log(chalk.green("+") + ` Scaffolded ${chalk.white.bold(packageName)} in ${packageDir}`);
|
|
381
|
+
console.log();
|
|
382
|
+
console.log(` Framework: ${frameworkEntry.label}`);
|
|
383
|
+
console.log(` Category: ${category.label} (keyword: cuttlefish-${category.id})`);
|
|
384
|
+
console.log(` Library id: ${id} (shim __tc_${model.tokenBase}.h, gate token __tc_${model.tokenBase})`);
|
|
385
|
+
console.log();
|
|
386
|
+
console.log(" Next steps:");
|
|
387
|
+
console.log(` 1. Replace the stubs in shims/ with your implementation.`);
|
|
388
|
+
console.log(` 2. Fill in cuttlefish.library.json${model.isZephyr ? " (kconfig + overlay)" : ""} as you go.`);
|
|
389
|
+
console.log(` 3. Validate: npx cuttlefish library validate ${packageDir}`);
|
|
390
|
+
console.log(` 4. Use it in a project: npm install <path-or-published-name>, then`);
|
|
391
|
+
console.log(` import { ${model.instanceName} } from '${packageName}';`);
|
|
392
|
+
if (model.isZephyr) {
|
|
393
|
+
console.log();
|
|
394
|
+
console.log(chalk.dim(" Note: for Zephyr, document the peripherals your overlay borrows in the README."));
|
|
395
|
+
}
|
|
396
|
+
return { packageDir, packageName, id };
|
|
397
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** Walk up from `fromDir` to the nearest package.json. */
|
|
2
|
+
export declare function findProjectPackageJson(fromDir?: string): string | null;
|
|
3
|
+
/** Installed version spec for a dependency name, or undefined. */
|
|
4
|
+
export declare function installedDependencyVersion(packageJsonPath: string, name: string): string | undefined;
|
|
5
|
+
/**
|
|
6
|
+
* Install npm packages into the project owning `cwd`. Returns the directory
|
|
7
|
+
* the install ran in. Throws with npm's stderr on failure.
|
|
8
|
+
*/
|
|
9
|
+
export declare function npmInstall(packageNames: string[], cwd: string): void;
|