@verikit/cli 0.2.3 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/bin/verikit.js +4 -0
  2. package/dist/cli.d.ts +10 -0
  3. package/dist/cli.d.ts.map +1 -0
  4. package/dist/cli.js +97 -0
  5. package/dist/field-spec.d.ts +17 -0
  6. package/dist/field-spec.d.ts.map +1 -0
  7. package/dist/field-spec.js +64 -0
  8. package/dist/imports.d.ts +14 -0
  9. package/dist/imports.d.ts.map +1 -0
  10. package/dist/imports.js +12 -0
  11. package/dist/index.d.ts +3 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +7 -52
  14. package/dist/load-resources.d.ts +38 -0
  15. package/dist/load-resources.d.ts.map +1 -0
  16. package/dist/load-resources.js +71 -0
  17. package/dist/names.d.ts +21 -0
  18. package/dist/names.d.ts.map +1 -0
  19. package/dist/names.js +73 -0
  20. package/dist/project.d.ts +41 -0
  21. package/dist/project.d.ts.map +1 -0
  22. package/dist/project.js +196 -0
  23. package/dist/render-registry.d.ts +20 -0
  24. package/dist/render-registry.d.ts.map +1 -0
  25. package/dist/render-registry.js +86 -0
  26. package/dist/render-resource.d.ts +26 -0
  27. package/dist/render-resource.d.ts.map +1 -0
  28. package/dist/render-resource.js +141 -0
  29. package/dist/render-schema.d.ts +13 -0
  30. package/dist/render-schema.d.ts.map +1 -0
  31. package/dist/render-schema.js +172 -0
  32. package/dist/wire-actions.d.ts +18 -0
  33. package/dist/wire-actions.d.ts.map +1 -0
  34. package/dist/wire-actions.js +32 -0
  35. package/package.json +30 -32
  36. package/README.md +0 -73
  37. package/dist/commands/init.js +0 -235
  38. package/dist/detect/database.js +0 -7
  39. package/dist/detect/framework.js +0 -25
  40. package/dist/detect/package-manager.js +0 -41
  41. package/dist/detect/project.js +0 -22
  42. package/dist/generators/route.js +0 -22
  43. package/dist/generators/server.js +0 -38
  44. package/dist/generators/theme.js +0 -25
  45. package/dist/install/capabilities.js +0 -45
  46. package/dist/install/dependencies.js +0 -21
  47. package/dist/utils/banner.js +0 -6
  48. package/dist/utils/fs.js +0 -29
@@ -0,0 +1,196 @@
1
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { assertUniqueFields, parseFieldSpec } from "./field-spec.js";
4
+ import { META_IMPORTS, SCOPED_IMPORTS } from "./imports.js";
5
+ import { loadResources, REGISTRY_FILE } from "./load-resources.js";
6
+ import { camelCase, importSpecifier, invalidIdentifier, kebabCase, } from "./names.js";
7
+ import { findActions, renderActionRegistry, renderResourceRegistry, } from "./render-registry.js";
8
+ import { renderActionDeclaration, renderActionDeclarationsFile, renderActionHandler, renderResource, } from "./render-resource.js";
9
+ import { wireResourceActions } from "./wire-actions.js";
10
+ import { renderSchema } from "./render-schema.js";
11
+ const DEFAULTS = {
12
+ dialect: "sqlite",
13
+ resources: "resources",
14
+ actions: "actions",
15
+ schema: "db/schema.ts",
16
+ permissions: "server/permissions.ts",
17
+ };
18
+ /** Reads the optional `"verikit"` key of `root/package.json`. */
19
+ export function readConfig(root) {
20
+ const packageJson = path.join(root, "package.json");
21
+ const manifest = existsSync(packageJson)
22
+ ? JSON.parse(readFileSync(packageJson, "utf8"))
23
+ : {};
24
+ const raw = manifest.verikit ?? {};
25
+ const usesMeta = [manifest.dependencies, manifest.devDependencies].some((deps) => deps !== undefined && Object.hasOwn(deps, "verikit"));
26
+ const config = { ...DEFAULTS, ...raw };
27
+ if (config.dialect !== "sqlite" && config.dialect !== "postgresql") {
28
+ throw new Error(`package.json "verikit.dialect" must be "sqlite" or "postgresql", not ${JSON.stringify(config.dialect)}.`);
29
+ }
30
+ return {
31
+ root,
32
+ dialect: config.dialect,
33
+ resourcesDir: path.resolve(root, config.resources),
34
+ actionsDir: path.resolve(root, config.actions),
35
+ schemaFile: path.resolve(root, config.schema),
36
+ permissionsFile: path.resolve(root, config.permissions),
37
+ imports: usesMeta ? META_IMPORTS : SCOPED_IMPORTS,
38
+ };
39
+ }
40
+ function emptyReport() {
41
+ return { created: [], updated: [], stale: [], warnings: [], notes: [] };
42
+ }
43
+ /** Ignores formatting, so running Prettier on generated files isn't drift. */
44
+ function normalize(source) {
45
+ return source.replace(/\s+/g, "").replace(/,([\]})>])/g, "$1");
46
+ }
47
+ function relative(config, file) {
48
+ return path.relative(config.root, file).split(path.sep).join("/");
49
+ }
50
+ /**
51
+ * Regenerates the resource registry, action registry, and Drizzle schema from
52
+ * the resources directory. With `check`, reports out-of-date files instead.
53
+ */
54
+ export async function generate(config, { check = false } = {}, report = emptyReport()) {
55
+ const resources = await loadResources(config.resourcesDir);
56
+ const customSchema = path.join(path.dirname(config.schemaFile), "custom-schema.ts");
57
+ const schema = renderSchema(resources, config.dialect, {
58
+ customSchema: existsSync(customSchema) ? "custom-schema.ts" : undefined,
59
+ });
60
+ const files = [
61
+ [
62
+ path.join(config.resourcesDir, REGISTRY_FILE),
63
+ renderResourceRegistry(resources),
64
+ ],
65
+ [
66
+ path.join(config.actionsDir, REGISTRY_FILE),
67
+ renderActionRegistry(findActions(config.actionsDir, resources), config.imports),
68
+ ],
69
+ [config.schemaFile, schema.source],
70
+ ];
71
+ report.warnings.push(...schema.warnings);
72
+ for (const [file, source] of files) {
73
+ const current = existsSync(file) ? readFileSync(file, "utf8") : undefined;
74
+ if (current !== undefined && normalize(current) === normalize(source)) {
75
+ continue;
76
+ }
77
+ if (check) {
78
+ report.stale.push(relative(config, file));
79
+ continue;
80
+ }
81
+ mkdirSync(path.dirname(file), { recursive: true });
82
+ writeFileSync(file, source);
83
+ (current === undefined ? report.created : report.updated).push(relative(config, file));
84
+ if (file === config.schemaFile) {
85
+ report.notes.push("The database schema changed: run `npm run db:generate` to create a migration.");
86
+ }
87
+ }
88
+ return report;
89
+ }
90
+ function writeNewFile(config, file, source, force, report) {
91
+ const exists = existsSync(file);
92
+ if (exists && !force) {
93
+ throw new Error(`${relative(config, file)} already exists. Pass --force to overwrite it.`);
94
+ }
95
+ mkdirSync(path.dirname(file), { recursive: true });
96
+ writeFileSync(file, source);
97
+ (exists ? report.updated : report.created).push(relative(config, file));
98
+ }
99
+ /** Adds `name: "open"` to the `permissions` map, if the file has one. */
100
+ export function addOpenPermission(file, name) {
101
+ if (!existsSync(file)) {
102
+ return false;
103
+ }
104
+ const source = readFileSync(file, "utf8");
105
+ if (new RegExp(`^\\s+${name}:`, "m").test(source)) {
106
+ return true;
107
+ }
108
+ const opening = /export const permissions\b[^=]*=\s*\{\n/.exec(source);
109
+ if (!opening) {
110
+ return false;
111
+ }
112
+ const at = opening.index + opening[0].length;
113
+ writeFileSync(file, `${source.slice(0, at)} ${name}: "open",\n${source.slice(at)}`);
114
+ return true;
115
+ }
116
+ /** `make:resource <Name> [field:type ...]`. */
117
+ export async function makeResource(config, rawName, fieldArgs, { force = false } = {}) {
118
+ const name = camelCase(rawName);
119
+ const invalid = invalidIdentifier(name, ["resources", "tables", "actions"]);
120
+ if (invalid) {
121
+ throw new Error(`Resource name ${invalid}`);
122
+ }
123
+ const specs = fieldArgs.map(parseFieldSpec);
124
+ assertUniqueFields(specs);
125
+ const targets = {};
126
+ const external = specs.filter((spec) => spec.type === "belongsTo" && spec.target !== name);
127
+ const existing = external.length > 0 ? await loadResources(config.resourcesDir) : [];
128
+ for (const spec of external) {
129
+ const target = existing.find((resource) => resource.name === spec.target);
130
+ if (!target) {
131
+ throw new Error(`Field "${spec.name}" belongs to "${spec.target}", which doesn't exist yet. Create it first: verikit make:resource ${spec.target}`);
132
+ }
133
+ targets[target.name] = {
134
+ exportName: target.exportName,
135
+ file: target.file,
136
+ displayField: Object.entries(target.fields).find(([, field]) => field.fieldType === "text" || field.fieldType === "email")?.[0],
137
+ };
138
+ }
139
+ const report = emptyReport();
140
+ writeNewFile(config, path.join(config.resourcesDir, `${kebabCase(name)}.ts`), renderResource(name, specs, targets, config.imports), force, report);
141
+ if (addOpenPermission(config.permissionsFile, name)) {
142
+ report.updated.push(relative(config, config.permissionsFile));
143
+ report.notes.push(`"${name}" is open to everyone. Restrict it in ${relative(config, config.permissionsFile)}.`);
144
+ }
145
+ else {
146
+ report.notes.push(`Add "${name}" to the permissions passed to createServer, e.g. permissions: "open".`);
147
+ }
148
+ return generate(config, {}, report);
149
+ }
150
+ /** `make:action <resource> <name>`. */
151
+ export async function makeAction(config, resourceArg, rawName, { force = false } = {}) {
152
+ const resources = await loadResources(config.resourcesDir);
153
+ const wanted = camelCase(resourceArg);
154
+ const resource = resources.find((candidate) => candidate.name === wanted || candidate.exportName === wanted);
155
+ if (!resource) {
156
+ const known = resources.map((candidate) => candidate.name).join(", ");
157
+ throw new Error(`No resource named "${resourceArg}". Known resources: ${known || "none"}.`);
158
+ }
159
+ const name = camelCase(rawName);
160
+ const invalid = invalidIdentifier(name);
161
+ if (invalid) {
162
+ throw new Error(`Action name ${invalid}`);
163
+ }
164
+ const report = emptyReport();
165
+ const kebab = kebabCase(resource.name);
166
+ const declarationsFile = path.join(config.resourcesDir, `${kebab}.actions.ts`);
167
+ const existing = existsSync(declarationsFile)
168
+ ? readFileSync(declarationsFile, "utf8")
169
+ : undefined;
170
+ const declared = existing !== undefined &&
171
+ new RegExp(`^export const ${name}\\b`, "m").test(existing);
172
+ if (declared && !force) {
173
+ throw new Error(`"${name}" is already declared in ${relative(config, declarationsFile)}. Pass --force to rewrite its handler.`);
174
+ }
175
+ if (!declared) {
176
+ writeFileSync(declarationsFile, (existing ??
177
+ renderActionDeclarationsFile(resource.name, config.imports)) +
178
+ renderActionDeclaration(name));
179
+ (existing === undefined ? report.created : report.updated).push(relative(config, declarationsFile));
180
+ }
181
+ // The resource lists its declarations once; later actions need no edit.
182
+ const resourceFile = path.join(config.resourcesDir, resource.file);
183
+ const namespace = `${camelCase(resource.name)}Actions`;
184
+ const wired = wireResourceActions(readFileSync(resourceFile, "utf8"), resource.name, `./${kebab}.actions.ts`, namespace);
185
+ if (wired.status === "wired") {
186
+ writeFileSync(resourceFile, wired.source);
187
+ report.updated.push(relative(config, resourceFile));
188
+ }
189
+ else if (wired.status === "manual") {
190
+ report.notes.push(`Couldn't connect ${relative(config, resourceFile)} to its actions (${wired.reason}). Add:\n import * as ${namespace} from "./${kebab}.actions.ts";\nand in defineResource("${resource.name}", { ... }):\n actions: Object.values(${namespace}),`);
191
+ }
192
+ const handlerFile = path.join(config.actionsDir, kebab, `${kebabCase(name)}.ts`);
193
+ const declarationsImport = importSpecifier(path.relative(path.dirname(handlerFile), declarationsFile));
194
+ writeNewFile(config, handlerFile, renderActionHandler(resource.name, name, declarationsImport), force, report);
195
+ return generate(config, {}, report);
196
+ }
@@ -0,0 +1,20 @@
1
+ import { type ImportSources } from "./imports.js";
2
+ import type { LoadedResource } from "./load-resources.js";
3
+ /** Source for `resources/index.ts`: every resource, in file order. */
4
+ export declare function renderResourceRegistry(resources: readonly LoadedResource[]): string;
5
+ /** An action file found under `actions/<resource>/`. */
6
+ export interface ActionFile {
7
+ resource: string;
8
+ exportName: string;
9
+ /** Path relative to the actions directory, e.g. "post/publish.ts". */
10
+ file: string;
11
+ }
12
+ /**
13
+ * Finds `actions/<resource-kebab>/<action>.ts` files. Each must export a
14
+ * camelCase const named after its file, which `make:action` writes. Files
15
+ * aren't imported, because action modules may connect to the database.
16
+ */
17
+ export declare function findActions(dir: string, resources: readonly LoadedResource[]): ActionFile[];
18
+ /** Source for `actions/index.ts`: each resource's action handlers for `createServer`. */
19
+ export declare function renderActionRegistry(actions: readonly ActionFile[], imports?: ImportSources): string;
20
+ //# sourceMappingURL=render-registry.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-registry.d.ts","sourceRoot":"","sources":["../src/render-registry.ts"],"names":[],"mappings":"AAEA,OAAO,EAAkB,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAClE,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAK1D,sEAAsE;AACtE,wBAAgB,sBAAsB,CACpC,SAAS,EAAE,SAAS,cAAc,EAAE,GACnC,MAAM,CAuBR;AAED,wDAAwD;AACxD,MAAM,WAAW,UAAU;IACzB,QAAQ,EAAE,MAAM,CAAC;IACjB,UAAU,EAAE,MAAM,CAAC;IACnB,sEAAsE;IACtE,IAAI,EAAE,MAAM,CAAC;CACd;AAED;;;;GAIG;AACH,wBAAgB,WAAW,CACzB,GAAG,EAAE,MAAM,EACX,SAAS,EAAE,SAAS,cAAc,EAAE,GACnC,UAAU,EAAE,CAoCd;AAED,yFAAyF;AACzF,wBAAgB,oBAAoB,CAClC,OAAO,EAAE,SAAS,UAAU,EAAE,EAC9B,OAAO,GAAE,aAA8B,GACtC,MAAM,CAmCR"}
@@ -0,0 +1,86 @@
1
+ import { existsSync, readdirSync, statSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { SCOPED_IMPORTS } from "./imports.js";
4
+ import { moduleFiles } from "./load-resources.js";
5
+ import { camelCase, invalidIdentifier, kebabCase } from "./names.js";
6
+ import { GENERATED_HEADER } from "./render-schema.js";
7
+ /** Source for `resources/index.ts`: every resource, in file order. */
8
+ export function renderResourceRegistry(resources) {
9
+ const imports = new Map();
10
+ for (const resource of resources) {
11
+ imports.set(resource.file, [
12
+ ...(imports.get(resource.file) ?? []),
13
+ resource.exportName,
14
+ ]);
15
+ }
16
+ const importLines = [...imports]
17
+ .map(([file, names]) => `import { ${names.join(", ")} } from "./${file}";\n`)
18
+ .join("");
19
+ const list = resources.map((resource) => resource.exportName).join(", ");
20
+ return `${GENERATED_HEADER("resources/*.ts")}${importLines}
21
+ /** Every resource, in navigation order. */
22
+ export const resources = [${list}] as const;
23
+
24
+ export type ResourceName = (typeof resources)[number]["name"];
25
+ `;
26
+ }
27
+ /**
28
+ * Finds `actions/<resource-kebab>/<action>.ts` files. Each must export a
29
+ * camelCase const named after its file, which `make:action` writes. Files
30
+ * aren't imported, because action modules may connect to the database.
31
+ */
32
+ export function findActions(dir, resources) {
33
+ if (!existsSync(dir)) {
34
+ return [];
35
+ }
36
+ const byFolder = new Map(resources.map((resource) => [kebabCase(resource.name), resource.name]));
37
+ const found = [];
38
+ for (const folder of readdirSync(dir).sort()) {
39
+ if (!statSync(path.join(dir, folder)).isDirectory()) {
40
+ continue;
41
+ }
42
+ const resource = byFolder.get(folder);
43
+ if (!resource) {
44
+ throw new Error(`actions/${folder}/ doesn't match a resource. Name action folders after a resource, e.g. actions/${kebabCase(resources[0]?.name ?? "post")}/.`);
45
+ }
46
+ for (const file of moduleFiles(path.join(dir, folder))) {
47
+ const exportName = camelCase(file.slice(0, -".ts".length));
48
+ const invalid = invalidIdentifier(exportName);
49
+ if (invalid) {
50
+ throw new Error(`actions/${folder}/${file}: ${invalid}`);
51
+ }
52
+ found.push({ resource, exportName, file: `${folder}/${file}` });
53
+ }
54
+ }
55
+ return found;
56
+ }
57
+ /** Source for `actions/index.ts`: each resource's action handlers for `createServer`. */
58
+ export function renderActionRegistry(actions, imports = SCOPED_IMPORTS) {
59
+ const alias = (action) => camelCase(`${action.resource} ${action.exportName}`);
60
+ const importLines = actions
61
+ .map((action) => `import { ${action.exportName} as ${alias(action)} } from "./${action.file}";\n`)
62
+ .join("");
63
+ const byResource = new Map();
64
+ for (const action of actions) {
65
+ byResource.set(action.resource, [
66
+ ...(byResource.get(action.resource) ?? []),
67
+ alias(action),
68
+ ]);
69
+ }
70
+ const entries = [...byResource]
71
+ .map(([resource, names]) => ` ${resource}: [${names.join(", ")}],\n`)
72
+ .join("");
73
+ return `${GENERATED_HEADER("actions/*/*.ts")}import type { ServerResourceConfig } from "${imports.server}";
74
+ ${importLines}
75
+ /**
76
+ * Server-side action handlers, by resource name, for createServer's
77
+ * \`handlers\`. Typed for any actor, so they fit a createServer whose
78
+ * \`context\` returns your own actor type.
79
+ */
80
+ export const handlers: Partial<
81
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
82
+ Record<string, NonNullable<ServerResourceConfig<any>["handlers"]>>
83
+ > = {
84
+ ${entries}};
85
+ `;
86
+ }
@@ -0,0 +1,26 @@
1
+ import type { FieldSpec } from "./field-spec.js";
2
+ import { type ImportSources } from "./imports.js";
3
+ /** How a `belongsTo` field refers to its target resource. */
4
+ export interface RelationTarget {
5
+ /** Exported const to import, e.g. "user". */
6
+ exportName: string;
7
+ /** File in the resources directory, e.g. "user.ts". */
8
+ file: string;
9
+ /** Field shown in the picker instead of the record id. */
10
+ displayField?: string;
11
+ }
12
+ /**
13
+ * Source for `resources/<name>.ts`. `resourceName` is already camelCase.
14
+ * `targets` describes every `belongsTo` target other than the resource itself.
15
+ */
16
+ export declare function renderResource(resourceName: string, specs: readonly FieldSpec[], targets?: Readonly<Record<string, RelationTarget>>, imports?: ImportSources): string;
17
+ /** Source for a new `resources/<resource>.actions.ts` declarations file, without any actions. */
18
+ export declare function renderActionDeclarationsFile(resourceName: string, imports?: ImportSources): string;
19
+ /** One action declaration, appended to a declarations file. `actionName` is already camelCase. */
20
+ export declare function renderActionDeclaration(actionName: string): string;
21
+ /**
22
+ * Source for `actions/<resource>/<action>.ts`: the server-side handler, built
23
+ * from the declaration so the server and browser always agree on it.
24
+ */
25
+ export declare function renderActionHandler(resourceName: string, actionName: string, declarationsImport: string): string;
26
+ //# sourceMappingURL=render-resource.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-resource.d.ts","sourceRoot":"","sources":["../src/render-resource.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AACjD,OAAO,EAAkB,KAAK,aAAa,EAAE,MAAM,cAAc,CAAC;AAgElE,6DAA6D;AAC7D,MAAM,WAAW,cAAc;IAC7B,6CAA6C;IAC7C,UAAU,EAAE,MAAM,CAAC;IACnB,uDAAuD;IACvD,IAAI,EAAE,MAAM,CAAC;IACb,0DAA0D;IAC1D,YAAY,CAAC,EAAE,MAAM,CAAC;CACvB;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,YAAY,EAAE,MAAM,EACpB,KAAK,EAAE,SAAS,SAAS,EAAE,EAC3B,OAAO,GAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,cAAc,CAAC,CAAM,EACtD,OAAO,GAAE,aAA8B,GACtC,MAAM,CA2DR;AAED,iGAAiG;AACjG,wBAAgB,4BAA4B,CAC1C,YAAY,EAAE,MAAM,EACpB,OAAO,GAAE,aAA8B,GACtC,MAAM,CAQR;AAED,kGAAkG;AAClG,wBAAgB,uBAAuB,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAIlE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,YAAY,EAAE,MAAM,EACpB,UAAU,EAAE,MAAM,EAClB,kBAAkB,EAAE,MAAM,GACzB,MAAM,CAcR"}
@@ -0,0 +1,141 @@
1
+ import { SCOPED_IMPORTS } from "./imports.js";
2
+ import { sentenceCase } from "./names.js";
3
+ const BUILDERS = {
4
+ text: { call: "text()", import: "text", extras: ".searchable().sortable()" },
5
+ textarea: { call: "textarea()", import: "textarea", extras: ".searchable()" },
6
+ email: {
7
+ call: "email()",
8
+ import: "email",
9
+ extras: ".searchable().sortable()",
10
+ },
11
+ number: {
12
+ call: "number()",
13
+ import: "number",
14
+ extras: ".sortable().filterable()",
15
+ },
16
+ integer: {
17
+ call: "number().step(1)",
18
+ import: "number",
19
+ extras: ".sortable().filterable()",
20
+ },
21
+ boolean: { call: "boolean()", import: "boolean", extras: ".filterable()" },
22
+ date: { call: "date()", import: "date", extras: ".sortable().filterable()" },
23
+ datetime: {
24
+ call: "datetime()",
25
+ import: "datetime",
26
+ extras: ".sortable().filterable()",
27
+ },
28
+ select: { call: "select()", import: "select", extras: ".filterable()" },
29
+ };
30
+ function presence(spec) {
31
+ if (spec.nullable) {
32
+ return ".nullable()";
33
+ }
34
+ // A checkbox always has a value, so default it instead of requiring it.
35
+ return spec.type === "boolean" ? ".default(false)" : ".required()";
36
+ }
37
+ function fieldLine(spec) {
38
+ if (spec.type === "belongsTo") {
39
+ // The relationship picker edits this key, so keep the raw id out of forms and tables.
40
+ return {
41
+ line: `${spec.name}Id: text().label(${JSON.stringify(sentenceCase(spec.name))})${presence(spec)}.formHidden().tableHidden(),`,
42
+ imports: ["text"],
43
+ };
44
+ }
45
+ const builder = BUILDERS[spec.type];
46
+ const options = spec.type === "select"
47
+ ? `.options([${spec.options.map((option) => JSON.stringify(option)).join(", ")}])`
48
+ : "";
49
+ return {
50
+ line: `${spec.name}: ${builder.call}${options}.label(${JSON.stringify(sentenceCase(spec.name))})${presence(spec)}${builder.extras},`,
51
+ imports: [builder.import],
52
+ };
53
+ }
54
+ /**
55
+ * Source for `resources/<name>.ts`. `resourceName` is already camelCase.
56
+ * `targets` describes every `belongsTo` target other than the resource itself.
57
+ */
58
+ export function renderResource(resourceName, specs, targets = {}, imports = SCOPED_IMPORTS) {
59
+ const names = new Set(["defineResource"]);
60
+ const lines = specs.map((spec) => {
61
+ const field = fieldLine(spec);
62
+ field.imports.forEach((name) => names.add(name));
63
+ return ` ${field.line}`;
64
+ });
65
+ const relations = specs.filter((spec) => spec.type === "belongsTo");
66
+ const self = {
67
+ exportName: resourceName,
68
+ file: "",
69
+ displayField: specs.find((spec) => spec.type === "text" || spec.type === "email")?.name,
70
+ };
71
+ const targetOf = (spec) => spec.target === resourceName ? self : targets[spec.target];
72
+ if (relations.length > 0) {
73
+ names.add("belongsTo");
74
+ }
75
+ const fields = lines.length > 0
76
+ ? ` fields: {\n${lines.join("\n")}\n },`
77
+ : " fields: {},";
78
+ const relationships = relations.length > 0
79
+ ? `\n relationships: (field) => ({\n${relations
80
+ .map((spec) => {
81
+ const target = targetOf(spec);
82
+ const display = target.displayField
83
+ ? `.displayField(${JSON.stringify(target.displayField)})`
84
+ : "";
85
+ return ` ${spec.name}: belongsTo(() => ${target.exportName}).label(${JSON.stringify(sentenceCase(spec.name))})${display}.via(field(${JSON.stringify(`${spec.name}Id`)})),`;
86
+ })
87
+ .join("\n")}\n }),`
88
+ : "";
89
+ const importsByFile = new Map();
90
+ for (const spec of relations) {
91
+ const target = targetOf(spec);
92
+ if (target !== self) {
93
+ importsByFile.set(target.file, target.exportName);
94
+ }
95
+ }
96
+ const targetImports = [...importsByFile]
97
+ .sort(([a], [b]) => a.localeCompare(b))
98
+ .map(([file, name]) => `import { ${name} } from "./${file}";\n`)
99
+ .join("");
100
+ return `import { ${[...names].sort().join(", ")} } from "${imports.core}";
101
+ ${targetImports}
102
+ export const ${resourceName} = defineResource(${JSON.stringify(resourceName)}, {
103
+ ${fields}${relationships}
104
+ });
105
+ `;
106
+ }
107
+ /** Source for a new `resources/<resource>.actions.ts` declarations file, without any actions. */
108
+ export function renderActionDeclarationsFile(resourceName, imports = SCOPED_IMPORTS) {
109
+ return `import { action } from "${imports.runtime}";
110
+
111
+ // Actions for "${resourceName}", declared where the browser can see them: the
112
+ // admin panel shows each one as a button, using its label, confirmation, and
113
+ // form. Their server-side handlers are in actions/. Add more with
114
+ // npx verikit make:action ${resourceName} <name>
115
+ `;
116
+ }
117
+ /** One action declaration, appended to a declarations file. `actionName` is already camelCase. */
118
+ export function renderActionDeclaration(actionName) {
119
+ return `
120
+ export const ${actionName} = action(${JSON.stringify(actionName)}).label(${JSON.stringify(sentenceCase(actionName))});
121
+ `;
122
+ }
123
+ /**
124
+ * Source for `actions/<resource>/<action>.ts`: the server-side handler, built
125
+ * from the declaration so the server and browser always agree on it.
126
+ */
127
+ export function renderActionHandler(resourceName, actionName, declarationsImport) {
128
+ return `import { ${actionName} as declaration } from "${declarationsImport}";
129
+
130
+ // Runs on the server only, so it can use the database and secrets. Change the
131
+ // action's label, confirmation, or form in its declaration, not here.
132
+ // Call it from the browser with:
133
+ // client.resource(${JSON.stringify(resourceName)}).action(${JSON.stringify(actionName)}, input, { recordId })
134
+ export const ${actionName} = declaration.execute(async ({ record, input }) => {
135
+ // TODO: implement "${actionName}" for ${resourceName}. \`record\` is set
136
+ // when the client passes a recordId; \`input\` holds the form's values.
137
+ console.log(${JSON.stringify(actionName)}, record, input);
138
+ return { ok: true };
139
+ });
140
+ `;
141
+ }
@@ -0,0 +1,13 @@
1
+ import type { LoadedResource } from "./load-resources.js";
2
+ export type Dialect = "sqlite" | "postgresql";
3
+ export declare const GENERATED_HEADER: (source: string) => string;
4
+ /** Generated Drizzle schema plus warnings about resource/storage mismatches. */
5
+ export interface RenderedSchema {
6
+ source: string;
7
+ warnings: string[];
8
+ }
9
+ /** Source for `db/schema.ts`: one table per resource plus a `tables` map. */
10
+ export declare function renderSchema(resources: readonly LoadedResource[], dialect: Dialect, options?: {
11
+ customSchema?: string;
12
+ }): RenderedSchema;
13
+ //# sourceMappingURL=render-schema.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"render-schema.d.ts","sourceRoot":"","sources":["../src/render-schema.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAEV,cAAc,EAEf,MAAM,qBAAqB,CAAC;AAG7B,MAAM,MAAM,OAAO,GAAG,QAAQ,GAAG,YAAY,CAAC;AAE9C,eAAO,MAAM,gBAAgB,GAAI,QAAQ,MAAM,WAC0G,CAAC;AAyF1J,gFAAgF;AAChF,MAAM,WAAW,cAAc;IAC7B,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB;AAED,6EAA6E;AAC7E,wBAAgB,YAAY,CAC1B,SAAS,EAAE,SAAS,cAAc,EAAE,EACpC,OAAO,EAAE,OAAO,EAChB,OAAO,GAAE;IAAE,YAAY,CAAC,EAAE,MAAM,CAAA;CAAO,GACtC,cAAc,CAqEhB"}
@@ -0,0 +1,172 @@
1
+ import { pluralCamelCase, pluralSnakeCase, snakeCase } from "./names.js";
2
+ export const GENERATED_HEADER = (source) => `// Generated by \`verikit generate:schema\` from ${source}. Don't edit this\n// file: your changes would be overwritten. Change the source instead.\n`;
3
+ function optionKinds(field) {
4
+ return new Set((field.options ?? []).map((option) => typeof option.value));
5
+ }
6
+ function isInteger(field) {
7
+ if (field.fieldType === "select") {
8
+ // Only reached for a select whose options are all numbers.
9
+ return field.options.every((option) => Number.isInteger(option.value));
10
+ }
11
+ return field.step !== undefined && Number.isInteger(field.step);
12
+ }
13
+ const SQLITE = {
14
+ boolean: (c) => ({
15
+ call: `integer("${c}", { mode: "boolean" })`,
16
+ imports: ["integer"],
17
+ }),
18
+ number: (c, f) => isInteger(f)
19
+ ? { call: `integer("${c}")`, imports: ["integer"] }
20
+ : { call: `real("${c}")`, imports: ["real"] },
21
+ json: (c) => ({
22
+ call: `text("${c}", { mode: "json" }).$type<string[]>()`,
23
+ imports: ["text"],
24
+ }),
25
+ text: (c) => ({ call: `text("${c}")`, imports: ["text"] }),
26
+ date: (c) => ({ call: `text("${c}")`, imports: ["text"] }),
27
+ datetime: (c) => ({ call: `text("${c}")`, imports: ["text"] }),
28
+ };
29
+ const POSTGRES = {
30
+ boolean: (c) => ({ call: `boolean("${c}")`, imports: ["boolean"] }),
31
+ number: (c, f) => isInteger(f)
32
+ ? { call: `integer("${c}")`, imports: ["integer"] }
33
+ : { call: `doublePrecision("${c}")`, imports: ["doublePrecision"] },
34
+ json: (c) => ({
35
+ call: `jsonb("${c}").$type<string[]>()`,
36
+ imports: ["jsonb"],
37
+ }),
38
+ text: (c) => ({ call: `text("${c}")`, imports: ["text"] }),
39
+ date: (c) => ({
40
+ call: `date("${c}", { mode: "string" })`,
41
+ imports: ["date"],
42
+ }),
43
+ datetime: (c) => ({
44
+ call: `timestamp("${c}", { mode: "string", withTimezone: true })`,
45
+ imports: ["timestamp"],
46
+ }),
47
+ };
48
+ /** Which column kind stores a field's values. */
49
+ function columnKind(field) {
50
+ switch (field.fieldType) {
51
+ case "boolean":
52
+ case "number":
53
+ case "date":
54
+ case "datetime":
55
+ return field.fieldType;
56
+ case "file":
57
+ case "image":
58
+ return field.multiple ? "json" : "text";
59
+ case "select": {
60
+ const kinds = optionKinds(field);
61
+ if (kinds.size === 1 && kinds.has("number"))
62
+ return "number";
63
+ if (kinds.size === 1 && kinds.has("boolean"))
64
+ return "boolean";
65
+ return "text";
66
+ }
67
+ default:
68
+ return "text";
69
+ }
70
+ }
71
+ function isPrimitive(value) {
72
+ return ["string", "number", "boolean"].includes(typeof value);
73
+ }
74
+ /** Source for `db/schema.ts`: one table per resource plus a `tables` map. */
75
+ export function renderSchema(resources, dialect, options = {}) {
76
+ const mappers = dialect === "sqlite" ? SQLITE : POSTGRES;
77
+ const tableFn = dialect === "sqlite" ? "sqliteTable" : "pgTable";
78
+ const imports = new Set([tableFn, "text", "integer"]);
79
+ const warnings = [];
80
+ const tableNames = new Map(resources.map((resource) => [
81
+ resource.name,
82
+ pluralCamelCase(resource.name),
83
+ ]));
84
+ const owners = new Map([["tables", "the tables map"]]);
85
+ for (const [resource, table] of tableNames) {
86
+ const owner = owners.get(table);
87
+ if (owner) {
88
+ throw new Error(`Resource "${resource}" would generate the table export "${table}", which ${owner} already uses. Rename the resource.`);
89
+ }
90
+ owners.set(table, `resource "${resource}"`);
91
+ }
92
+ const tables = resources.map((resource) => {
93
+ if (resource.hasTable) {
94
+ throw new Error(`Resource "${resource.name}" (${resource.file}) sets \`table\`. generate:schema creates tables from resources, so remove \`table\` and let the server pass the generated one.`);
95
+ }
96
+ const references = foreignKeyReferences(resource, tableNames, warnings);
97
+ const columns = Object.entries(resource.fields).map(([name, field]) => {
98
+ const column = mappers[columnKind(field)](snakeCase(name), field);
99
+ column.imports.forEach((fn) => imports.add(fn));
100
+ return ` ${name}: ${column.call}${modifiers(resource, name, field, warnings)}${references.get(name) ?? ""},`;
101
+ });
102
+ return `export const ${tableNames.get(resource.name)} = ${tableFn}("${pluralSnakeCase(resource.name)}", {
103
+ id: text("id")
104
+ .primaryKey()
105
+ .$defaultFn(() => crypto.randomUUID()),
106
+ ${columns.join("\n")}
107
+ // Lets the server reject stale writes to protected resources.
108
+ revision: integer("revision").notNull().default(0),
109
+ });
110
+ `;
111
+ });
112
+ const map = resources
113
+ .map((resource) => ` ${resource.name}: ${tableNames.get(resource.name)},`)
114
+ .join("\n");
115
+ const custom = options.customSchema
116
+ ? `\nexport * from "./${options.customSchema}";\n`
117
+ : "";
118
+ return {
119
+ source: `${GENERATED_HEADER("resources/")}// After it changes, run \`npm run db:generate\` to create a migration.
120
+ import { ${[...imports].sort().join(", ")} } from "drizzle-orm/${dialect === "sqlite" ? "sqlite" : "pg"}-core";
121
+ ${custom}
122
+ ${tables.join("\n")}
123
+ /** Each resource's table, by resource name. */
124
+ export const tables = {
125
+ ${map}
126
+ };
127
+ `,
128
+ warnings,
129
+ };
130
+ }
131
+ function modifiers(resource, name, field, warnings) {
132
+ const hasDefault = isPrimitive(field.defaultValue);
133
+ const parts = [];
134
+ if (!field.nullable && (field.required || hasDefault)) {
135
+ parts.push(".notNull()");
136
+ }
137
+ else if (!field.nullable) {
138
+ warnings.push(`${resource.name}.${name} is optional but not nullable: a row saved without it is read back as null, which the field rejects when editing. Add .nullable() or .required() to the field.`);
139
+ }
140
+ if (hasDefault) {
141
+ parts.push(`.default(${JSON.stringify(field.defaultValue)})`);
142
+ }
143
+ if (field.unique) {
144
+ parts.push(".unique()");
145
+ }
146
+ return parts.join("");
147
+ }
148
+ function foreignKeyReferences(resource, tableNames, warnings) {
149
+ const references = new Map();
150
+ for (const [name, relationship] of Object.entries(resource.relationships)) {
151
+ const reference = foreignKeyReference(relationship, tableNames);
152
+ if (reference) {
153
+ references.set(reference.field, reference.call);
154
+ }
155
+ else if (relationship.relationshipType === "belongsToMany") {
156
+ warnings.push(`${resource.name}.${name} is belongsToMany: generate:schema doesn't create join tables. Define it in db/custom-schema.ts.`);
157
+ }
158
+ }
159
+ return references;
160
+ }
161
+ function foreignKeyReference(relationship, tableNames) {
162
+ const target = tableNames.get(relationship.resource);
163
+ if (relationship.relationshipType !== "belongsTo" ||
164
+ typeof relationship.foreignKey !== "string" ||
165
+ !target) {
166
+ return undefined;
167
+ }
168
+ return {
169
+ field: relationship.foreignKey,
170
+ call: `.references(() => ${target}.id)`,
171
+ };
172
+ }