sizuku 0.0.6 → 0.1.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 (102) hide show
  1. package/README.md +88 -342
  2. package/dist/config/index.d.ts +18 -0
  3. package/dist/config/index.js +13 -0
  4. package/dist/generator/mermaid-er/config/index.d.ts +4 -4
  5. package/dist/generator/mermaid-er/config/index.js +4 -10
  6. package/dist/generator/mermaid-er/core/extract-relations.d.ts +1 -1
  7. package/dist/generator/mermaid-er/core/extract-relations.js +3 -6
  8. package/dist/generator/mermaid-er/generator/{generate-er-content.d.ts → er-content.d.ts} +2 -3
  9. package/dist/generator/mermaid-er/generator/{generate-er-content.js → er-content.js} +3 -7
  10. package/dist/generator/mermaid-er/generator/index.d.ts +2 -0
  11. package/dist/generator/mermaid-er/generator/index.js +2 -0
  12. package/dist/generator/mermaid-er/generator/{generate-relation-line.d.ts → relation-line.d.ts} +2 -2
  13. package/dist/generator/mermaid-er/generator/{generate-relation-line.js → relation-line.js} +3 -6
  14. package/dist/generator/mermaid-er/index.d.ts +6 -5
  15. package/dist/generator/mermaid-er/index.js +15 -76
  16. package/dist/generator/mermaid-er/relationship/build-relation-line.js +3 -6
  17. package/dist/generator/mermaid-er/types.js +1 -0
  18. package/dist/generator/mermaid-er/validator/index.d.ts +4 -0
  19. package/dist/generator/mermaid-er/validator/index.js +4 -0
  20. package/dist/generator/mermaid-er/validator/is-relationship.d.ts +1 -1
  21. package/dist/generator/mermaid-er/validator/is-relationship.js +1 -4
  22. package/dist/generator/mermaid-er/validator/parse-relation-line.js +1 -4
  23. package/dist/generator/mermaid-er/validator/parse-table-info.d.ts +1 -7
  24. package/dist/generator/mermaid-er/validator/parse-table-info.js +69 -89
  25. package/dist/generator/mermaid-er/validator/remove-duplicate-relations.js +1 -4
  26. package/dist/generator/valibot/config/index.d.ts +2 -2
  27. package/dist/generator/valibot/config/index.js +6 -12
  28. package/dist/generator/valibot/core/extract-schema.d.ts +2 -5
  29. package/dist/generator/valibot/core/extract-schema.js +162 -81
  30. package/dist/generator/valibot/generator/infer-input.d.ts +5 -0
  31. package/dist/generator/valibot/generator/infer-input.js +8 -0
  32. package/dist/generator/valibot/generator/valibot-code.d.ts +8 -0
  33. package/dist/generator/valibot/generator/valibot-code.js +16 -0
  34. package/dist/generator/valibot/generator/valibot.d.ts +7 -0
  35. package/dist/generator/valibot/generator/valibot.js +11 -0
  36. package/dist/generator/valibot/index.d.ts +9 -3
  37. package/dist/generator/valibot/index.js +21 -76
  38. package/dist/generator/zod/config/index.d.ts +2 -2
  39. package/dist/generator/zod/config/index.js +6 -12
  40. package/dist/generator/zod/core/extract-schema.d.ts +1 -2
  41. package/dist/generator/zod/core/extract-schema.js +228 -81
  42. package/dist/generator/zod/generator/infer.d.ts +5 -0
  43. package/dist/generator/zod/generator/infer.js +8 -0
  44. package/dist/generator/zod/generator/{generate-zod-code.d.ts → zod-code.d.ts} +2 -3
  45. package/dist/generator/zod/generator/zod-code.js +18 -0
  46. package/dist/generator/zod/generator/{generate-zod-schema.d.ts → zod.d.ts} +2 -4
  47. package/dist/generator/zod/generator/zod.js +12 -0
  48. package/dist/generator/zod/index.d.ts +10 -3
  49. package/dist/generator/zod/index.js +29 -76
  50. package/dist/index.d.ts +3 -0
  51. package/dist/index.js +54 -0
  52. package/dist/shared/config/index.d.ts +13 -0
  53. package/dist/{common → shared}/config/index.js +1 -4
  54. package/dist/shared/format/index.d.ts +2 -0
  55. package/dist/shared/format/index.js +10 -0
  56. package/dist/shared/fs/index.d.ts +2 -0
  57. package/dist/shared/fs/index.js +10 -0
  58. package/dist/shared/fsp/index.d.ts +3 -0
  59. package/dist/shared/fsp/index.js +8 -0
  60. package/dist/shared/generator/field-definitions.d.ts +6 -0
  61. package/dist/shared/generator/field-definitions.js +12 -0
  62. package/dist/shared/types.js +1 -0
  63. package/dist/{common/text → shared/utils}/capitalize.js +1 -4
  64. package/dist/shared/utils/compose.d.ts +101 -0
  65. package/dist/shared/utils/compose.js +124 -0
  66. package/dist/shared/utils/file.d.ts +92 -0
  67. package/dist/shared/utils/file.js +177 -0
  68. package/dist/shared/utils/functional.d.ts +118 -0
  69. package/dist/shared/utils/functional.js +96 -0
  70. package/package.json +11 -10
  71. package/dist/common/config/index.d.ts +0 -13
  72. package/dist/common/format/index.d.ts +0 -1
  73. package/dist/common/format/index.js +0 -12
  74. package/dist/common/generator/generate-field-definitions.d.ts +0 -8
  75. package/dist/common/generator/generate-field-definitions.js +0 -16
  76. package/dist/common/helper/get-camel-case-schema-name-helper.d.ts +0 -7
  77. package/dist/common/helper/get-camel-case-schema-name-helper.js +0 -14
  78. package/dist/common/helper/get-pascal-case-schema-name-helper.d.ts +0 -8
  79. package/dist/common/helper/get-pascal-case-schema-name-helper.js +0 -15
  80. package/dist/common/helper/get-variable-name-helper.d.ts +0 -9
  81. package/dist/common/helper/get-variable-name-helper.js +0 -15
  82. package/dist/common/helper/get-variable-schema-name-helper.d.ts +0 -9
  83. package/dist/common/helper/get-variable-schema-name-helper.js +0 -17
  84. package/dist/common/text/decapitalize.d.ts +0 -17
  85. package/dist/common/text/decapitalize.js +0 -22
  86. package/dist/common/type/index.js +0 -2
  87. package/dist/generator/mermaid-er/type/index.js +0 -2
  88. package/dist/generator/mermaid-er/validator/is-relation.d.ts +0 -7
  89. package/dist/generator/mermaid-er/validator/is-relation.js +0 -40
  90. package/dist/generator/valibot/generator/generate-valibot-code.d.ts +0 -11
  91. package/dist/generator/valibot/generator/generate-valibot-code.js +0 -21
  92. package/dist/generator/valibot/generator/generate-valibot-infer-input.d.ts +0 -9
  93. package/dist/generator/valibot/generator/generate-valibot-infer-input.js +0 -16
  94. package/dist/generator/valibot/generator/generate-valibot-schema.d.ts +0 -9
  95. package/dist/generator/valibot/generator/generate-valibot-schema.js +0 -16
  96. package/dist/generator/zod/generator/generate-z-infer.d.ts +0 -11
  97. package/dist/generator/zod/generator/generate-z-infer.js +0 -18
  98. package/dist/generator/zod/generator/generate-zod-code.js +0 -21
  99. package/dist/generator/zod/generator/generate-zod-schema.js +0 -17
  100. /package/dist/generator/mermaid-er/{type/index.d.ts → types.d.ts} +0 -0
  101. /package/dist/{common/type/index.d.ts → shared/types.d.ts} +0 -0
  102. /package/dist/{common/text → shared/utils}/capitalize.d.ts +0 -0
@@ -1,92 +1,173 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.extractSchemas = extractSchemas;
1
+ import { Node, Project } from 'ts-morph';
4
2
  /**
5
- * Check if line contains metadata
3
+ * Check if the comment line is metadata (Zod / Valibot / relation helper)
6
4
  */
7
- const isMetadataComment = (line) => {
8
- return line.includes('@z.') || line.includes('@v.') || line.includes('@relation.');
5
+ const isMetadataComment = (text) => {
6
+ return text.includes('@z.') || text.includes('@v.') || text.includes('@relation.');
9
7
  };
10
8
  /**
11
- * Extract schemas from lines of code
12
- * @function extractSchemas
13
- * @param lines - Lines of code
14
- * @returns Schemas
9
+ * Collect consecutive `///` comment lines that appear immediately above a field.
15
10
  */
16
- function extractSchemas(lines) {
17
- const process = (i, acc) => {
18
- if (i >= lines.length) {
11
+ const extractFieldComments = (sourceText, fieldStartPos) => {
12
+ const beforeField = sourceText.substring(0, fieldStartPos);
13
+ const lines = beforeField.split('\n');
14
+ return lines
15
+ .map((line) => line.trim())
16
+ .reverse()
17
+ .reduce((acc, line) => {
18
+ if (acc.stop)
19
19
  return acc;
20
+ if (line.startsWith('///')) {
21
+ return { commentLines: [line, ...acc.commentLines], stop: false };
20
22
  }
21
- const line = lines[i];
22
- // extract schema name
23
- const schemaMatch = line.match(/export const (\w+)\s*=/);
24
- if (schemaMatch) {
25
- if (acc.currentSchema) {
26
- acc.schemas.push(acc.currentSchema);
27
- }
28
- acc.currentSchema = { name: schemaMatch[1], fields: [] };
29
- acc.pendingDescription = undefined;
30
- return process(i + 1, acc);
31
- }
32
- // handle comment line
33
- if (line.trim().startsWith('///')) {
34
- // detect valibot comment
35
- const valibotComment = line.match(/\/\/\/\s*@(v\.[^\n]+)/);
36
- if (valibotComment && acc.currentSchema) {
37
- // find next field definition line
38
- const remainingCandidates = lines.slice(i + 1);
39
- const foundRelative = remainingCandidates.findIndex((candidate) => {
40
- const trimmed = candidate.trim();
41
- return trimmed !== '' && !trimmed.startsWith('///');
42
- });
43
- if (foundRelative !== -1) {
44
- const j = i + 1 + foundRelative;
45
- const candidate = lines[j].trim();
46
- const fieldMatch = candidate.match(/^(\w+)\s*:/);
47
- if (fieldMatch) {
48
- const newField = {
49
- name: fieldMatch[1],
50
- definition: valibotComment[1],
51
- description: acc.pendingDescription,
52
- };
53
- acc.currentSchema.fields.push(newField);
54
- acc.pendingDescription = undefined;
55
- return process(i + 1, acc);
56
- }
57
- }
58
- }
59
- else {
60
- // ignore comment line except metadata
61
- if (!isMetadataComment(line)) {
62
- const commentText = line.replace('///', '').trim();
63
- acc.pendingDescription = acc.pendingDescription
64
- ? `${acc.pendingDescription} ${commentText}`
65
- : commentText;
66
- return process(i + 1, acc);
67
- }
68
- }
69
- return process(i + 1, acc);
70
- }
71
- // if field definition is found in non-comment line, use pending comment as field information
72
- if (acc.currentSchema && acc.pendingDescription) {
73
- const fieldMatch = line.match(/^(\w+)\s*:/);
74
- if (fieldMatch) {
75
- const newField = {
76
- name: fieldMatch[1],
77
- definition: '',
78
- description: acc.pendingDescription,
79
- };
80
- acc.currentSchema.fields.push(newField);
81
- acc.pendingDescription = undefined;
82
- return process(i + 1, acc);
23
+ if (line === '')
24
+ return acc;
25
+ return { commentLines: acc.commentLines, stop: true };
26
+ }, { commentLines: [], stop: false }).commentLines;
27
+ };
28
+ /**
29
+ * Parse the collected comment lines -> { valibotDefinition, description }
30
+ */
31
+ const parseFieldComments = (commentLines) => {
32
+ const cleaned = commentLines.map((l) => l.replace(/^\/\/\/\s*/, '').trim()).filter(Boolean);
33
+ const valibotDefinition = cleaned.find((l) => l.startsWith('@v.'))?.replace(/^@/, '') ?? '';
34
+ const descriptionLines = cleaned.filter((l) => !isMetadataComment(l));
35
+ const description = descriptionLines.length ? descriptionLines.join(' ') : undefined;
36
+ return { valibotDefinition, description };
37
+ };
38
+ /**
39
+ * Convert table name to Schema name (e.g. `user` -> `UserSchema`)
40
+ */
41
+ const toSchemaName = (table) => `${table.charAt(0).toUpperCase() + table.slice(1)}Schema`;
42
+ /**
43
+ * Extract an ordinary column field.
44
+ */
45
+ const extractFieldFromProperty = (property, sourceText) => {
46
+ if (!Node.isPropertyAssignment(property))
47
+ return null;
48
+ const name = property.getName();
49
+ if (!name)
50
+ return null;
51
+ const commentLines = extractFieldComments(sourceText, property.getStart());
52
+ const { valibotDefinition, description } = parseFieldComments(commentLines);
53
+ return { name, definition: valibotDefinition, description };
54
+ };
55
+ /**
56
+ * Extract a relation field (many / one) and infer Valibot schema.
57
+ */
58
+ const extractRelationFieldFromProperty = (property, sourceText) => {
59
+ if (!Node.isPropertyAssignment(property))
60
+ return null;
61
+ const name = property.getName();
62
+ if (!name)
63
+ return null;
64
+ const init = property.getInitializer();
65
+ if (!Node.isCallExpression(init))
66
+ return { name, definition: '', description: undefined };
67
+ const expr = init.getExpression();
68
+ if (!Node.isIdentifier(expr))
69
+ return { name, definition: '', description: undefined };
70
+ const fnName = expr.getText();
71
+ const args = init.getArguments();
72
+ if (!(args.length && Node.isIdentifier(args[0])))
73
+ return { name, definition: '', description: undefined };
74
+ const refTable = args[0].getText();
75
+ const schemaName = toSchemaName(refTable);
76
+ const definition = fnName === 'many' ? `v.array(${schemaName})` : fnName === 'one' ? schemaName : '';
77
+ const commentLines = extractFieldComments(sourceText, property.getStart());
78
+ const { description } = parseFieldComments(commentLines);
79
+ return { name, definition, description };
80
+ };
81
+ /** Utility: unwrap arrow / paren / etc. until ObjectLiteralExpression or null */
82
+ const extractObjectLiteralFromExpression = (expr) => {
83
+ if (Node.isObjectLiteralExpression(expr))
84
+ return expr;
85
+ if (Node.isParenthesizedExpression(expr))
86
+ return extractObjectLiteralFromExpression(expr.getExpression());
87
+ if (Node.isArrowFunction(expr)) {
88
+ const body = expr.getBody();
89
+ if (Node.isObjectLiteralExpression(body))
90
+ return body;
91
+ if (Node.isParenthesizedExpression(body))
92
+ return extractObjectLiteralFromExpression(body.getExpression());
93
+ if (Node.isBlock(body)) {
94
+ const ret = body.getStatements().find(Node.isReturnStatement);
95
+ if (ret && Node.isReturnStatement(ret)) {
96
+ const re = ret.getExpression();
97
+ return re && Node.isObjectLiteralExpression(re) ? re : null;
83
98
  }
84
99
  }
85
- return process(i + 1, acc);
86
- };
87
- const finalAcc = process(0, { currentSchema: null, pendingDescription: undefined, schemas: [] });
88
- if (finalAcc.currentSchema) {
89
- finalAcc.schemas.push(finalAcc.currentSchema);
90
100
  }
91
- return finalAcc.schemas;
101
+ return null;
102
+ };
103
+ /** find the first object literal among call expression arguments */
104
+ const findObjectLiteralInArgs = (call) => {
105
+ for (const arg of call.getArguments()) {
106
+ const obj = extractObjectLiteralFromExpression(arg);
107
+ if (obj)
108
+ return obj;
109
+ }
110
+ return null;
111
+ };
112
+ /** recognise `relations()` / `somethingRelation*` helpers */
113
+ const isRelationFunction = (call) => {
114
+ const expr = call.getExpression();
115
+ return (Node.isIdentifier(expr) &&
116
+ (expr.getText() === 'relations' || expr.getText().includes('relation')));
117
+ };
118
+ /** extract fields from mysqlTable / relations call expression */
119
+ const extractFieldsFromCallExpression = (call, sourceText) => {
120
+ const obj = findObjectLiteralInArgs(call);
121
+ if (!obj)
122
+ return [];
123
+ const relation = isRelationFunction(call);
124
+ return obj
125
+ .getProperties()
126
+ .map((p) => relation
127
+ ? extractRelationFieldFromProperty(p, sourceText)
128
+ : extractFieldFromProperty(p, sourceText))
129
+ .filter((f) => f !== null);
130
+ };
131
+ /** extract a single schema from variable declaration */
132
+ const extractSchemaFromDeclaration = (decl, sourceText) => {
133
+ if (!Node.isVariableDeclaration(decl))
134
+ return null;
135
+ const name = decl.getName();
136
+ if (!name)
137
+ return null;
138
+ const init = decl.getInitializer();
139
+ // Handle call expressions (mysqlTable, relations, etc.)
140
+ if (Node.isCallExpression(init)) {
141
+ // ⛔ Skip relation helper exports (userRelations / postRelations ...)
142
+ if (isRelationFunction(init))
143
+ return null;
144
+ const fields = extractFieldsFromCallExpression(init, sourceText);
145
+ return { name, fields };
146
+ }
147
+ // Direct object literal export
148
+ if (Node.isObjectLiteralExpression(init)) {
149
+ const fields = init
150
+ .getProperties()
151
+ .map((p) => extractFieldFromProperty(p, sourceText))
152
+ .filter((f) => f !== null);
153
+ return { name, fields };
154
+ }
155
+ return { name, fields: [] };
156
+ };
157
+ /**
158
+ * Public API: extract schemas from code lines
159
+ */
160
+ export function extractSchemas(lines) {
161
+ const project = new Project({
162
+ useInMemoryFileSystem: true,
163
+ compilerOptions: { allowJs: true, skipLibCheck: true },
164
+ });
165
+ const file = project.createSourceFile('temp.ts', lines.join('\n'));
166
+ const fullText = file.getFullText();
167
+ return file
168
+ .getVariableStatements()
169
+ .filter((s) => s.hasExportKeyword())
170
+ .flatMap((s) => s.getDeclarations())
171
+ .map((d) => extractSchemaFromDeclaration(d, fullText))
172
+ .filter((s) => s !== null);
92
173
  }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * @param name
3
+ * @returns
4
+ */
5
+ export declare function inferInput(name: string): string;
@@ -0,0 +1,8 @@
1
+ import { capitalize } from '../../../shared/utils/capitalize.js';
2
+ /**
3
+ * @param name
4
+ * @returns
5
+ */
6
+ export function inferInput(name) {
7
+ return `export type ${capitalize(name)} = v.InferInput<typeof ${capitalize(name)}Schema>`;
8
+ }
@@ -0,0 +1,8 @@
1
+ import type { Schema } from '../../../shared/types.js';
2
+ /**
3
+ * @param schema
4
+ * @param comment
5
+ * @param type
6
+ * @returns
7
+ */
8
+ export declare function valibotCode(schema: Schema, comment: boolean, type: boolean): string;
@@ -0,0 +1,16 @@
1
+ import { valibot } from './valibot.js';
2
+ import { inferInput } from './infer-input.js';
3
+ /**
4
+ * @param schema
5
+ * @param comment
6
+ * @param type
7
+ * @returns
8
+ */
9
+ export function valibotCode(schema, comment, type) {
10
+ const valibotSchema = valibot(schema, comment);
11
+ if (type) {
12
+ const valibotInfer = inferInput(schema.name);
13
+ return `${valibotSchema}\n\n${valibotInfer}\n`;
14
+ }
15
+ return `${valibotSchema}\n`;
16
+ }
@@ -0,0 +1,7 @@
1
+ import type { Schema } from '../../../shared/types.js';
2
+ /**
3
+ * @param schema
4
+ * @param config
5
+ * @returns
6
+ */
7
+ export declare function valibot(schema: Schema, comment: boolean): string;
@@ -0,0 +1,11 @@
1
+ import { capitalize } from '../../../shared/utils/capitalize.js';
2
+ import { fieldDefinitions } from '../../../shared/generator/field-definitions.js';
3
+ /**
4
+ * @param schema
5
+ * @param config
6
+ * @returns
7
+ */
8
+ export function valibot(schema, comment) {
9
+ const res = fieldDefinitions(schema, comment);
10
+ return `export const ${capitalize(schema.name)}Schema = v.object({${res}})`;
11
+ }
@@ -1,3 +1,9 @@
1
- #!/usr/bin/env node
2
- import type { Config } from '../../common/config';
3
- export declare function main(dev?: boolean, config?: Config): Promise<boolean>;
1
+ import type { Result } from 'neverthrow';
2
+ /**
3
+ * Generate Valibot schema
4
+ * @param code - The code to generate Valibot schema from
5
+ * @param output - The output file path
6
+ * @param comment - Whether to include comments in the generated code
7
+ * @param type - Whether to include type information in the generated code
8
+ */
9
+ export declare function sizukuValibot(code: string[], output: `${string}.ts`, comment?: boolean, type?: boolean): Promise<Result<void, Error>>;
@@ -1,77 +1,22 @@
1
- #!/usr/bin/env node
2
- "use strict";
3
- var __importDefault = (this && this.__importDefault) || function (mod) {
4
- return (mod && mod.__esModule) ? mod : { "default": mod };
5
- };
6
- Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.main = main;
8
- const node_fs_1 = require("node:fs");
9
- const node_path_1 = __importDefault(require("node:path"));
10
- const extract_schema_1 = require("./core/extract-schema");
11
- const format_1 = require("../../common/format");
12
- const config_1 = require("./config");
13
- const node_process_1 = require("node:process");
14
- const generate_valibot_code_1 = require("./generator/generate-valibot-code");
15
- const IMPORT_VALIBOT = 'import * as v from "valibot"';
16
- async function main(dev = false, config = (0, config_1.getConfig)()) {
17
- // 1. argv ['**/bin/node', ''/workspaces/sizuku-test/packages/sizuku/dist/generator/zod/index.js',', 'db/schema.ts', '-o', 'zod/index.ts']
18
- if (config.output === undefined && !node_process_1.argv.includes('-o')) {
19
- console.error('Error: -o is not found');
20
- return false;
21
- }
22
- // 2. slice ['db/schema.ts', '-o', 'zod/index.ts']
23
- const args = process.argv.slice(2);
24
- // 3. input = args[0] = 'db/schema.ts'
25
- const input = config.input ?? args[0];
26
- config.input = input;
27
- // 4. output = 'zod/index.ts'
28
- const output = config.output ?? args[args.indexOf('-o') + 1];
29
- config.output = output;
30
- try {
31
- // 5. read db/schema.ts
32
- const content = (0, node_fs_1.readFileSync)(input, 'utf-8');
33
- // 6. split lines
34
- const lines = content.split('\n');
35
- // 7. create output directory
36
- const outputDir = node_path_1.default.dirname(output);
37
- if (!(0, node_fs_1.existsSync)(outputDir)) {
38
- (0, node_fs_1.mkdirSync)(outputDir, { recursive: true });
39
- }
40
- // 8. skip import section
41
- const codeStart = lines.findIndex((line) => !line.trim().startsWith('import') && line.trim() !== '');
42
- // 9. extract schemas
43
- const schemas = (0, extract_schema_1.extractSchemas)(lines.slice(codeStart));
44
- // 10. generate zod code
45
- const generatedCode = [
46
- IMPORT_VALIBOT,
47
- '',
48
- ...schemas.map((schema) => (0, generate_valibot_code_1.generateValibotCode)(schema, config)),
49
- ].join('\n');
50
- // 11. format code
51
- const code = await (0, format_1.formatCode)(generatedCode);
52
- // 12. write to output file
53
- (0, node_fs_1.writeFileSync)(output, code);
54
- console.log(`Generated Valibot schema at: ${output}`);
55
- return true;
56
- }
57
- catch (e) {
58
- if (e instanceof Error) {
59
- console.error(e.message);
60
- if (dev) {
61
- throw e;
62
- }
63
- process.exit(1);
64
- }
65
- if (dev) {
66
- throw new Error('Unknown error occurred');
67
- }
68
- return false;
69
- }
70
- }
71
- if (require.main === module) {
72
- main().then((success) => {
73
- if (!success) {
74
- process.exit(1);
75
- }
76
- });
1
+ import path from 'node:path';
2
+ import { extractSchemas } from './core/extract-schema.js';
3
+ import { valibotCode } from './generator/valibot-code.js';
4
+ import { fmt } from '../../shared/format/index.js';
5
+ import { mkdir, writeFile } from '../../shared/fsp/index.js';
6
+ /**
7
+ * Generate Valibot schema
8
+ * @param code - The code to generate Valibot schema from
9
+ * @param output - The output file path
10
+ * @param comment - Whether to include comments in the generated code
11
+ * @param type - Whether to include type information in the generated code
12
+ */
13
+ export async function sizukuValibot(code, output, comment, type) {
14
+ const valibotGeneratedCode = [
15
+ 'import * as v from "valibot"',
16
+ '',
17
+ ...extractSchemas(code).map((schema) => valibotCode(schema, comment ?? false, type ?? false)),
18
+ ].join('\n');
19
+ return await mkdir(path.dirname(output))
20
+ .andThen(() => fmt(valibotGeneratedCode))
21
+ .andThen((formatted) => writeFile(output, formatted));
77
22
  }
@@ -1,8 +1,8 @@
1
- import type { Config } from '../../../common/config';
1
+ import type { Config } from '../../../shared/config/index.js'
2
2
  /**
3
3
  * Loads the configuration from the `sizuku.json` file or returns the default configuration.
4
4
  *
5
5
  * @function getConfig
6
6
  * @returns The configuration object.
7
7
  */
8
- export declare function getConfig(): Config;
8
+ export declare function getConfig(): Config
@@ -1,20 +1,14 @@
1
- "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
5
- Object.defineProperty(exports, "__esModule", { value: true });
6
- exports.getConfig = getConfig;
7
- const node_fs_1 = __importDefault(require("node:fs"));
8
- const config_1 = require("../../../common/config");
1
+ import fs from 'node:fs';
2
+ import { DEFAULT_CONFIG } from '../../../shared/config/index.js';
9
3
  /**
10
4
  * Loads the configuration from the `sizuku.json` file or returns the default configuration.
11
5
  *
12
6
  * @function getConfig
13
7
  * @returns The configuration object.
14
8
  */
15
- function getConfig() {
16
- const config = node_fs_1.default.existsSync('sizuku-zod.json')
17
- ? { ...config_1.DEFAULT_CONFIG, ...JSON.parse(node_fs_1.default.readFileSync('sizuku-zod.json', 'utf-8')) }
18
- : config_1.DEFAULT_CONFIG;
9
+ export function getConfig() {
10
+ const config = fs.existsSync('sizuku-zod.json')
11
+ ? { ...DEFAULT_CONFIG, ...JSON.parse(fs.readFileSync('sizuku-zod.json', 'utf-8')) }
12
+ : DEFAULT_CONFIG;
19
13
  return config;
20
14
  }
@@ -1,7 +1,6 @@
1
- import type { Schema } from '../../../common/type';
1
+ import type { Schema } from '../../../shared/types.js';
2
2
  /**
3
3
  * Extract schemas from lines of code
4
- * @function extractSchemas
5
4
  * @param lines - Lines of code
6
5
  * @returns Schemas
7
6
  */