@atcute/lex-cli 2.2.1 → 2.3.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.
@@ -0,0 +1,37 @@
1
+ import * as v from 'valibot';
2
+ /**
3
+ * Schema for a single lexicon mapping entry
4
+ */
5
+ declare const lexiconMappingEntry: v.ObjectSchema<{
6
+ readonly type: v.PicklistSchema<["namespace", "named"], undefined>;
7
+ readonly path: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "path must be \".\" or start with \"./\"">]>;
8
+ }, undefined>;
9
+ /**
10
+ * Schema for the atcute:lexicons field in package.json
11
+ */
12
+ declare const atcuteLexiconsField: v.ObjectSchema<{
13
+ readonly mappings: v.OptionalSchema<v.RecordSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "invalid NSID pattern (must be valid NSID or end with .*)">]>, v.ObjectSchema<{
14
+ readonly type: v.PicklistSchema<["namespace", "named"], undefined>;
15
+ readonly path: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "path must be \".\" or start with \"./\"">]>;
16
+ }, undefined>, undefined>, undefined>;
17
+ }, undefined>;
18
+ /**
19
+ * Schema for package.json with atcute:lexicons field
20
+ */
21
+ export declare const packageJsonSchema: v.LooseObjectSchema<{
22
+ readonly 'atcute:lexicons': v.OptionalSchema<v.ObjectSchema<{
23
+ readonly mappings: v.OptionalSchema<v.RecordSchema<v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.CheckAction<string, "invalid NSID pattern (must be valid NSID or end with .*)">]>, v.ObjectSchema<{
24
+ readonly type: v.PicklistSchema<["namespace", "named"], undefined>;
25
+ readonly path: v.SchemaWithPipe<readonly [v.StringSchema<undefined>, v.RegexAction<string, "path must be \".\" or start with \"./\"">]>;
26
+ }, undefined>, undefined>, undefined>;
27
+ }, undefined>, undefined>;
28
+ }, undefined>;
29
+ export type LexiconMappingEntry = v.InferOutput<typeof lexiconMappingEntry>;
30
+ export type AtcuteLexiconsField = v.InferOutput<typeof atcuteLexiconsField>;
31
+ export type PackageJsonWithLexicons = v.InferOutput<typeof packageJsonSchema>;
32
+ /**
33
+ * Validates a package.json object against the schema
34
+ */
35
+ export declare const validatePackageJson: (data: unknown) => v.SafeParseResult<typeof packageJsonSchema>;
36
+ export {};
37
+ //# sourceMappingURL=lexicon-metadata.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lexicon-metadata.d.ts","sourceRoot":"","sources":["../src/lexicon-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAmB7B;;GAEG;AACH,QAAA,MAAM,mBAAmB;;;aAGvB,CAAC;AAEH;;GAEG;AACH,QAAA,MAAM,mBAAmB;;;;;aAUvB,CAAC;AAEH;;GAEG;AACH,eAAO,MAAM,iBAAiB;;;;;;;aAE5B,CAAC;AAEH,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAC5E,MAAM,MAAM,mBAAmB,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,mBAAmB,CAAC,CAAC;AAC5E,MAAM,MAAM,uBAAuB,GAAG,CAAC,CAAC,WAAW,CAAC,OAAO,iBAAiB,CAAC,CAAC;AAE9E;;GAEG;AACH,eAAO,MAAM,mBAAmB,GAAI,MAAM,OAAO,KAAG,CAAC,CAAC,eAAe,CAAC,OAAO,iBAAiB,CAE7F,CAAC"}
@@ -0,0 +1,42 @@
1
+ import * as v from 'valibot';
2
+ import { isNsid } from '@atcute/lexicons/syntax';
3
+ /**
4
+ * Validates if a string is a valid NSID pattern (exact or wildcard)
5
+ * - Exact: "com.atproto.repo.getRecord"
6
+ * - Wildcard: "com.atproto.*"
7
+ */
8
+ const isValidLexiconPattern = (pattern) => {
9
+ if (pattern.endsWith('.*')) {
10
+ // For wildcards, remove the .* and validate the prefix as an NSID segment
11
+ const prefix = pattern.slice(0, -2);
12
+ // Add a dummy segment to make it a valid NSID for validation
13
+ return isNsid(prefix + '.x');
14
+ }
15
+ return isNsid(pattern);
16
+ };
17
+ /**
18
+ * Schema for a single lexicon mapping entry
19
+ */
20
+ const lexiconMappingEntry = v.object({
21
+ type: v.picklist(['namespace', 'named']),
22
+ path: v.pipe(v.string(), v.regex(/^\.$|^\.\//, `path must be "." or start with "./"`)),
23
+ });
24
+ /**
25
+ * Schema for the atcute:lexicons field in package.json
26
+ */
27
+ const atcuteLexiconsField = v.object({
28
+ mappings: v.optional(v.record(v.pipe(v.string(), v.check(isValidLexiconPattern, `invalid NSID pattern (must be valid NSID or end with .*)`)), lexiconMappingEntry)),
29
+ });
30
+ /**
31
+ * Schema for package.json with atcute:lexicons field
32
+ */
33
+ export const packageJsonSchema = v.looseObject({
34
+ 'atcute:lexicons': v.optional(atcuteLexiconsField),
35
+ });
36
+ /**
37
+ * Validates a package.json object against the schema
38
+ */
39
+ export const validatePackageJson = (data) => {
40
+ return v.safeParse(packageJsonSchema, data);
41
+ };
42
+ //# sourceMappingURL=lexicon-metadata.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"lexicon-metadata.js","sourceRoot":"","sources":["../src/lexicon-metadata.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,CAAC,MAAM,SAAS,CAAC;AAE7B,OAAO,EAAE,MAAM,EAAE,MAAM,yBAAyB,CAAC;AAEjD;;;;GAIG;AACH,MAAM,qBAAqB,GAAG,CAAC,OAAe,EAAW,EAAE;IAC1D,IAAI,OAAO,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QAC5B,0EAA0E;QAC1E,MAAM,MAAM,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;QACpC,6DAA6D;QAC7D,OAAO,MAAM,CAAC,MAAM,GAAG,IAAI,CAAC,CAAC;IAC9B,CAAC;IACD,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC;AACxB,CAAC,CAAC;AAEF;;GAEG;AACH,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACpC,IAAI,EAAE,CAAC,CAAC,QAAQ,CAAC,CAAC,WAAW,EAAE,OAAO,CAAC,CAAC;IACxC,IAAI,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,CAAC,KAAK,CAAC,YAAY,EAAE,qCAAqC,CAAC,CAAC;CACtF,CAAC,CAAC;AAEH;;GAEG;AACH,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACpC,QAAQ,EAAE,CAAC,CAAC,QAAQ,CACnB,CAAC,CAAC,MAAM,CACP,CAAC,CAAC,IAAI,CACL,CAAC,CAAC,MAAM,EAAE,EACV,CAAC,CAAC,KAAK,CAAC,qBAAqB,EAAE,0DAA0D,CAAC,CAC1F,EACD,mBAAmB,CACnB,CACD;CACD,CAAC,CAAC;AAEH;;GAEG;AACH,MAAM,CAAC,MAAM,iBAAiB,GAAG,CAAC,CAAC,WAAW,CAAC;IAC9C,iBAAiB,EAAE,CAAC,CAAC,QAAQ,CAAC,mBAAmB,CAAC;CAClD,CAAC,CAAC;AAMH;;GAEG;AACH,MAAM,CAAC,MAAM,mBAAmB,GAAG,CAAC,IAAa,EAA+C,EAAE;IACjG,OAAO,CAAC,CAAC,SAAS,CAAC,iBAAiB,EAAE,IAAI,CAAC,CAAC;AAC7C,CAAC,CAAC"}
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "type": "module",
3
3
  "name": "@atcute/lex-cli",
4
- "version": "2.2.1",
4
+ "version": "2.3.0",
5
5
  "description": "cli tool to generate type definitions for atcute",
6
6
  "license": "0BSD",
7
7
  "repository": {
@@ -13,7 +13,8 @@
13
13
  "src/",
14
14
  "!src/**/*.bench.ts",
15
15
  "!src/**/*.test.ts",
16
- "cli.mjs"
16
+ "cli.mjs",
17
+ "schema/"
17
18
  ],
18
19
  "bin": "./cli.mjs",
19
20
  "exports": {
@@ -21,17 +22,21 @@
21
22
  },
22
23
  "dependencies": {
23
24
  "@badrap/valita": "^0.4.6",
24
- "@externdefs/collider": "^0.3.0",
25
+ "@optique/core": "^0.6.1",
26
+ "@optique/run": "^0.6.1",
25
27
  "picocolors": "^1.1.1",
26
28
  "prettier": "^3.6.2",
27
- "@atcute/lexicon-doc": "^1.1.2"
29
+ "valibot": "^1.0.0",
30
+ "@atcute/lexicon-doc": "^1.1.3"
28
31
  },
29
32
  "devDependencies": {
30
33
  "@types/node": "^22.18.0",
34
+ "@valibot/to-json-schema": "^1.3.0",
31
35
  "@atcute/lexicons": "^1.2.2"
32
36
  },
33
37
  "scripts": {
34
- "build": "tsc",
38
+ "build": "pnpm run generate:schema && tsc",
39
+ "generate:schema": "node scripts/generate-schema.ts",
35
40
  "prepublish": "rm -rf dist; pnpm run build"
36
41
  }
37
42
  }
@@ -0,0 +1,38 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "https://unpkg.com/@atcute/lex-cli/schema/lexicon-package.schema.json",
4
+ "title": "package.json with atcute:lexicons",
5
+ "description": "JSON Schema for package.json with atcute:lexicons field for lexicon import mappings",
6
+ "type": "object",
7
+ "properties": {
8
+ "atcute:lexicons": {
9
+ "type": "object",
10
+ "properties": {
11
+ "mappings": {
12
+ "type": "object",
13
+ "additionalProperties": {
14
+ "type": "object",
15
+ "properties": {
16
+ "type": {
17
+ "enum": [
18
+ "namespace",
19
+ "named"
20
+ ]
21
+ },
22
+ "path": {
23
+ "type": "string",
24
+ "pattern": "^\\.$|^\\.\\/"
25
+ }
26
+ },
27
+ "required": [
28
+ "type",
29
+ "path"
30
+ ]
31
+ }
32
+ }
33
+ },
34
+ "required": []
35
+ }
36
+ },
37
+ "required": []
38
+ }
package/src/cli.ts CHANGED
@@ -2,108 +2,202 @@ import * as fs from 'node:fs/promises';
2
2
  import * as path from 'node:path';
3
3
  import * as url from 'node:url';
4
4
 
5
- import { Builtins, Command, Option, Program } from '@externdefs/collider';
5
+ import { object } from '@optique/core/constructs';
6
+ import { command, constant, option } from '@optique/core/primitives';
7
+ import { run } from '@optique/run';
8
+ import { path as pathParser } from '@optique/run/valueparser';
6
9
  import pc from 'picocolors';
7
10
 
8
11
  import { lexiconDoc, type LexiconDoc } from '@atcute/lexicon-doc';
9
12
 
10
- import { generateLexiconApi } from './codegen.js';
13
+ import { generateLexiconApi, type ImportMapping } from './codegen.js';
11
14
  import type { LexiconConfig } from './index.js';
15
+ import { validatePackageJson } from './lexicon-metadata.js';
16
+
17
+ /**
18
+ * Resolves package imports to ImportMapping[]
19
+ */
20
+ const resolveImportsToMappings = async (
21
+ imports: string[],
22
+ configDirname: string,
23
+ ): Promise<ImportMapping[]> => {
24
+ const mappings: ImportMapping[] = [];
25
+
26
+ for (const packageName of imports) {
27
+ // Walk up from config directory to find package in node_modules
28
+ let packageJson: unknown;
29
+ let currentDir = configDirname;
30
+ let found = false;
31
+
32
+ while (currentDir !== path.dirname(currentDir)) {
33
+ const candidatePath = path.join(currentDir, 'node_modules', packageName, 'package.json');
34
+ try {
35
+ const content = await fs.readFile(candidatePath, 'utf8');
36
+ packageJson = JSON.parse(content);
37
+ found = true;
38
+ break;
39
+ } catch (err: any) {
40
+ // Only continue to parent if file not found
41
+ if (err.code !== 'ENOENT') {
42
+ console.error(pc.bold(pc.red(`failed to read package.json for "${packageName}":`)));
43
+ console.error(err);
44
+ process.exit(1);
45
+ }
12
46
 
13
- const program = new Program({ binaryName: 'lex-cli' });
47
+ // Not found, try parent directory
48
+ currentDir = path.dirname(currentDir);
49
+ }
50
+ }
14
51
 
15
- program.register(Builtins.HelpCommand);
52
+ if (!found) {
53
+ console.error(pc.bold(pc.red(`failed to resolve package "${packageName}"`)));
54
+ console.error(`Could not find package in node_modules starting from ${configDirname}`);
55
+ process.exit(1);
56
+ }
16
57
 
17
- program.register(
18
- class GenerateCommand extends Command {
19
- static override paths = [['generate']];
58
+ // Validate package.json
59
+ const result = validatePackageJson(packageJson);
60
+ if (!result.success) {
61
+ console.error(pc.bold(pc.red(`invalid atcute:lexicons in "${packageName}":`)));
62
+ console.error(result.issues);
63
+ process.exit(1);
64
+ }
20
65
 
21
- static override usage = Command.Usage({
22
- description: `Generates TypeScript schema`,
23
- });
66
+ const lexicons = result.output['atcute:lexicons'];
67
+ if (!lexicons?.mappings) {
68
+ continue;
69
+ }
24
70
 
25
- config = Option.String(['-c', '--config'], {
26
- required: true,
27
- description: `Config file`,
28
- });
71
+ // Convert mapping to ImportMapping[]
72
+ for (const [pattern, entry] of Object.entries(lexicons.mappings)) {
73
+ const isWildcard = pattern.endsWith('.*');
74
+
75
+ mappings.push({
76
+ nsid: [pattern],
77
+ imports: (nsid: string) => {
78
+ // Check if pattern matches
79
+ if (isWildcard) {
80
+ if (!nsid.startsWith(pattern.slice(0, -1))) {
81
+ throw new Error(`NSID ${nsid} does not match pattern ${pattern}`);
82
+ }
83
+ } else {
84
+ if (nsid !== pattern) {
85
+ throw new Error(`NSID ${nsid} does not match pattern ${pattern}`);
86
+ }
87
+ }
29
88
 
30
- async execute(): Promise<number | void> {
31
- const configFilename = path.resolve(this.config);
32
- const configDirname = path.dirname(configFilename);
89
+ const nsidPrefix = isWildcard ? pattern.slice(0, -2) : pattern;
90
+ const nsidRemainder = isWildcard ? nsid.slice(nsidPrefix.length + 1) : '';
33
91
 
34
- let config: LexiconConfig;
35
- try {
36
- const configURL = url.pathToFileURL(configFilename);
37
- const configMod = (await import(configURL.href)) as { default: LexiconConfig };
38
- config = configMod.default;
39
- } catch (err) {
40
- console.error(pc.bold(pc.red(`failed to import config:`)));
41
- console.error(err);
42
-
43
- return 1;
44
- }
92
+ let expandedPath = entry.path
93
+ .replaceAll('{{nsid}}', nsid.replaceAll('.', '/'))
94
+ .replaceAll('{{nsid_remainder}}', nsidRemainder.replaceAll('.', '/'))
95
+ .replaceAll('{{nsid_prefix}}', nsidPrefix.replaceAll('.', '/'));
45
96
 
46
- const documents: LexiconDoc[] = [];
97
+ if (expandedPath === '.') {
98
+ expandedPath = packageName;
99
+ } else if (expandedPath.startsWith('./')) {
100
+ expandedPath = `${packageName}/${expandedPath.slice(2)}`;
101
+ }
47
102
 
48
- for await (const filename of fs.glob(config.files, { cwd: configDirname })) {
49
- let source: string;
50
- try {
51
- source = await fs.readFile(path.join(configDirname, filename), 'utf8');
52
- } catch (err) {
53
- console.error(pc.bold(pc.red(`file read error with "${filename}"`)));
54
- console.error(err);
103
+ return {
104
+ type: entry.type,
105
+ from: expandedPath,
106
+ };
107
+ },
108
+ });
109
+ }
110
+ }
55
111
 
56
- return 1;
57
- }
112
+ return mappings;
113
+ };
58
114
 
59
- let json: unknown;
60
- try {
61
- json = JSON.parse(source);
62
- } catch (err) {
63
- console.error(pc.bold(pc.red(`json parse error in "${filename}"`)));
64
- console.error(err);
115
+ const parser = command(
116
+ 'generate',
117
+ object({
118
+ type: constant('generate'),
119
+ config: option('-c', '--config', pathParser({ metavar: 'CONFIG' })),
120
+ }),
121
+ );
65
122
 
66
- return 1;
67
- }
123
+ const result = run(parser, { programName: 'lex-cli' });
68
124
 
69
- const result = lexiconDoc.try(json, { mode: 'strip' });
70
- if (!result.ok) {
71
- console.error(pc.bold(pc.red(`schema validation failed for "${filename}"`)));
72
- console.error(result.message);
125
+ if (result.type === 'generate') {
126
+ const configFilename = path.resolve(result.config);
127
+ const configDirname = path.dirname(configFilename);
73
128
 
74
- for (const issue of result.issues) {
75
- console.log(`- ${issue.code} at .${issue.path.join('.')}`);
76
- }
129
+ let config: LexiconConfig;
130
+ try {
131
+ const configURL = url.pathToFileURL(configFilename);
132
+ const configMod = (await import(configURL.href)) as { default: LexiconConfig };
133
+ config = configMod.default;
134
+ } catch (err) {
135
+ console.error(pc.bold(pc.red(`failed to import config:`)));
136
+ console.error(err);
77
137
 
78
- return 1;
79
- }
138
+ process.exit(1);
139
+ }
80
140
 
81
- documents.push(result.value);
82
- }
141
+ // Resolve imports to mappings
142
+ const importMappings = config.imports ? await resolveImportsToMappings(config.imports, configDirname) : [];
143
+ const allMappings = [...importMappings, ...(config.mappings ?? [])];
83
144
 
84
- const result = await generateLexiconApi({
85
- documents: documents,
86
- mappings: config.mappings ?? [],
87
- modules: {
88
- importSuffix: config.modules?.importSuffix ?? '.js',
89
- },
90
- prettier: {
91
- cwd: process.cwd(),
92
- },
93
- });
145
+ const documents: LexiconDoc[] = [];
146
+
147
+ for await (const filename of fs.glob(config.files, { cwd: configDirname })) {
148
+ let source: string;
149
+ try {
150
+ source = await fs.readFile(path.join(configDirname, filename), 'utf8');
151
+ } catch (err) {
152
+ console.error(pc.bold(pc.red(`file read error with "${filename}"`)));
153
+ console.error(err);
154
+
155
+ process.exit(1);
156
+ }
94
157
 
95
- const outdir = path.join(configDirname, config.outdir);
158
+ let json: unknown;
159
+ try {
160
+ json = JSON.parse(source);
161
+ } catch (err) {
162
+ console.error(pc.bold(pc.red(`json parse error in "${filename}"`)));
163
+ console.error(err);
96
164
 
97
- for (const file of result.files) {
98
- const filename = path.join(outdir, file.filename);
99
- const dirname = path.dirname(filename);
165
+ process.exit(1);
166
+ }
167
+
168
+ const result = lexiconDoc.try(json, { mode: 'strip' });
169
+ if (!result.ok) {
170
+ console.error(pc.bold(pc.red(`schema validation failed for "${filename}"`)));
171
+ console.error(result.message);
100
172
 
101
- await fs.mkdir(dirname, { recursive: true });
102
- await fs.writeFile(filename, file.code);
173
+ for (const issue of result.issues) {
174
+ console.log(`- ${issue.code} at .${issue.path.join('.')}`);
103
175
  }
176
+
177
+ process.exit(1);
104
178
  }
105
- },
106
- );
107
179
 
108
- const exitCode = await program.run(process.argv.slice(2));
109
- process.exitCode = exitCode;
180
+ documents.push(result.value);
181
+ }
182
+
183
+ const generationResult = await generateLexiconApi({
184
+ documents: documents,
185
+ mappings: allMappings,
186
+ modules: {
187
+ importSuffix: config.modules?.importSuffix ?? '.js',
188
+ },
189
+ prettier: {
190
+ cwd: process.cwd(),
191
+ },
192
+ });
193
+
194
+ const outdir = path.join(configDirname, config.outdir);
195
+
196
+ for (const file of generationResult.files) {
197
+ const filename = path.join(outdir, file.filename);
198
+ const dirname = path.dirname(filename);
199
+
200
+ await fs.mkdir(dirname, { recursive: true });
201
+ await fs.writeFile(filename, file.code);
202
+ }
203
+ }
package/src/codegen.ts CHANGED
@@ -11,6 +11,8 @@ import type {
11
11
  LexPrimitive,
12
12
  LexRecord,
13
13
  LexRefVariant,
14
+ LexUnknown,
15
+ LexUserType,
14
16
  LexXrpcBody,
15
17
  LexXrpcParameters,
16
18
  LexXrpcProcedure,
@@ -564,6 +566,11 @@ const generateObject = (
564
566
  call = `${PURE} v.optional(${call})`;
565
567
  }
566
568
 
569
+ const jsdoc = generateJsdocField(propSpec);
570
+ if (jsdoc.length !== 0) {
571
+ inner += `\n${jsdoc}\n`;
572
+ }
573
+
567
574
  if (lazy) {
568
575
  inner += `get ${lit(prop)} () { return ${call} },`;
569
576
  } else {
@@ -574,6 +581,112 @@ const generateObject = (
574
581
  return `${PURE} v.object({\n${inner}})`;
575
582
  };
576
583
 
584
+ const IS_DEPRECATED_PREFIX_RE = /^\s*(?:\(deprecated\)|deprecated[.:;])/i;
585
+ const IS_DEPRECATED_SUFFIX_RE = /\b(?:deprecated(?::[^]+)?)\s*$/i;
586
+
587
+ const generateJsdocField = (spec: LexUserType | LexRefVariant | LexUnknown) => {
588
+ const lines: string[] = [];
589
+
590
+ if ('description' in spec && spec.description) {
591
+ let desc = spec.description
592
+ .replace(/\*\//g, '*\\/')
593
+ .replace(/@/g, '\\@')
594
+ .replace(/\r?\n/g, ' ')
595
+ .replace(/\s+/g, ' ')
596
+ .trim();
597
+
598
+ if (desc) {
599
+ lines.push(desc);
600
+ }
601
+
602
+ if (IS_DEPRECATED_PREFIX_RE.test(desc) || IS_DEPRECATED_SUFFIX_RE.test(desc)) {
603
+ lines.push(`@deprecated`);
604
+ }
605
+ }
606
+
607
+ // Add annotations based on property spec type
608
+ switch (spec.type) {
609
+ case 'boolean': {
610
+ if (spec.default !== undefined) {
611
+ lines.push(`@default ${lit(spec.default)}`);
612
+ }
613
+ break;
614
+ }
615
+ case 'string': {
616
+ if (spec.minLength !== undefined) {
617
+ lines.push(`@minLength ${spec.minLength}`);
618
+ }
619
+ if (spec.maxLength !== undefined) {
620
+ lines.push(`@maxLength ${spec.maxLength}`);
621
+ }
622
+ if (spec.minGraphemes !== undefined) {
623
+ lines.push(`@minGraphemes ${spec.minGraphemes}`);
624
+ }
625
+ if (spec.maxGraphemes !== undefined) {
626
+ lines.push(`@maxGraphemes ${spec.maxGraphemes}`);
627
+ }
628
+ if (spec.default !== undefined) {
629
+ lines.push(`@default ${lit(spec.default)}`);
630
+ }
631
+ break;
632
+ }
633
+ case 'integer': {
634
+ if (spec.minimum !== undefined) {
635
+ lines.push(`@minimum ${spec.minimum}`);
636
+ }
637
+ if (spec.maximum !== undefined) {
638
+ lines.push(`@maximum ${spec.maximum}`);
639
+ }
640
+ if (spec.default !== undefined) {
641
+ lines.push(`@default ${lit(spec.default)}`);
642
+ }
643
+ break;
644
+ }
645
+ case 'bytes': {
646
+ if (spec.minLength !== undefined) {
647
+ lines.push(`@minLength ${spec.minLength}`);
648
+ }
649
+ if (spec.maxLength !== undefined) {
650
+ lines.push(`@maxLength ${spec.maxLength}`);
651
+ }
652
+ break;
653
+ }
654
+ case 'array': {
655
+ if (spec.minLength !== undefined) {
656
+ lines.push(`@minLength ${spec.minLength}`);
657
+ }
658
+ if (spec.maxLength !== undefined) {
659
+ lines.push(`@maxLength ${spec.maxLength}`);
660
+ }
661
+ break;
662
+ }
663
+ case 'blob': {
664
+ if (spec.accept) {
665
+ const accept = spec.accept.map((mime) => mime.replace(/\*\//g, '*\\/')).join(', ');
666
+ lines.push(`@accept ${accept}`);
667
+ }
668
+ if (spec.maxSize !== undefined) {
669
+ lines.push(`@maxSize ${spec.maxSize}`);
670
+ }
671
+ break;
672
+ }
673
+ }
674
+
675
+ let res = ``;
676
+ if (lines.length > 0) {
677
+ res += `/**\n`;
678
+
679
+ for (let idx = 0, len = lines.length; idx < len; idx++) {
680
+ const line = lines[idx];
681
+ res += ` * ${line}\n`;
682
+ }
683
+
684
+ res += `*/`;
685
+ }
686
+
687
+ return res;
688
+ };
689
+
577
690
  const generateType = (
578
691
  imports: ImportSet,
579
692
  defUri: string,
@@ -678,7 +791,13 @@ const generateType = (
678
791
  }
679
792
 
680
793
  if (spec.enum !== undefined) {
681
- return `${PURE} v.literalEnum(${lit(spec.enum.toSorted())})`;
794
+ let call = `${PURE} v.literalEnum(${lit(spec.enum.toSorted())})`;
795
+
796
+ if (spec.default !== undefined) {
797
+ call = `${PURE} v.optional(${call}, ${lit(spec.default)})`;
798
+ }
799
+
800
+ return call;
682
801
  }
683
802
 
684
803
  let pipe: string[] = [];
@@ -709,7 +828,13 @@ const generateType = (
709
828
  }
710
829
 
711
830
  if (spec.enum !== undefined) {
712
- return `${PURE} v.literalEnum(${lit(spec.enum.toSorted())})`;
831
+ let call = `${PURE} v.literalEnum(${lit(spec.enum.toSorted())})`;
832
+
833
+ if (spec.default !== undefined) {
834
+ call = `${PURE} v.optional(${call}, ${lit(spec.default)})`;
835
+ }
836
+
837
+ return call;
713
838
  }
714
839
 
715
840
  let pipe: string[] = [];
package/src/index.ts CHANGED
@@ -3,6 +3,7 @@ import type { ImportMapping } from './codegen.js';
3
3
  export interface LexiconConfig {
4
4
  outdir: string;
5
5
  files: string[];
6
+ imports?: string[];
6
7
  mappings?: ImportMapping[];
7
8
  modules?: {
8
9
  importSuffix?: string;