@mearie/codegen 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,20 @@
1
+ MIT License
2
+
3
+ Copyright 2025 Bae Junehyeon
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
6
+ this software and associated documentation files (the "Software"), to deal in
7
+ the Software without restriction, including without limitation the rights to
8
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9
+ the Software, and to permit persons to whom the Software is furnished to do so,
10
+ subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,55 @@
1
+ # @mearie/codegen
2
+
3
+ Code generation utilities for Mearie GraphQL client.
4
+
5
+ This package provides the core code generation logic that can be reused across different build tool integrations (Vite, Webpack, Rollup, etc.).
6
+
7
+ ## Features
8
+
9
+ - **Scanner**: Scans files for GraphQL operations
10
+ - **Generator**: Generates TypeScript types from GraphQL operations and schema
11
+ - **Writer**: Writes generated types to the filesystem
12
+
13
+ ## Usage
14
+
15
+ ```typescript
16
+ import { runCodegen, scanDocuments, generateTypes, writeTypes } from '@mearie/codegen';
17
+
18
+ // High-level API
19
+ await runCodegen({
20
+ schema: 'schema.graphql',
21
+ documents: 'src/**/*.ts',
22
+ cwd: process.cwd(),
23
+ });
24
+
25
+ // Low-level API for custom workflows
26
+ const operations = await scanDocuments(
27
+ {
28
+ include: 'src/**/*.ts',
29
+ exclude: 'node_modules/**',
30
+ },
31
+ process.cwd(),
32
+ );
33
+
34
+ const { types, augmentation } = await generateTypes(operations, schemaContent);
35
+
36
+ await writeTypes({ types, augmentation });
37
+ ```
38
+
39
+ ## API
40
+
41
+ ### `runCodegen(config: CodegenConfig): Promise<void>`
42
+
43
+ Runs the complete code generation pipeline.
44
+
45
+ ### `scanDocuments(patterns: ScanPatterns, cwd: string): Promise<ExtractedDocument[]>`
46
+
47
+ Scans files for GraphQL operations.
48
+
49
+ ### `generateTypes(operations: ExtractedDocument[], schema: string): Promise<GeneratedCode>`
50
+
51
+ Generates TypeScript types from operations and schema.
52
+
53
+ ### `writeTypes(code: GeneratedCode, outputDir?: string): Promise<WrittenFiles>`
54
+
55
+ Writes generated types to the filesystem.
package/dist/index.cjs ADDED
@@ -0,0 +1,166 @@
1
+ //#region rolldown:runtime
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __copyProps = (to, from, except, desc) => {
9
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
10
+ key = keys[i];
11
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
12
+ get: ((k) => from[k]).bind(null, key),
13
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
14
+ });
15
+ }
16
+ return to;
17
+ };
18
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
19
+ value: mod,
20
+ enumerable: true
21
+ }) : target, mod));
22
+
23
+ //#endregion
24
+ let tinyglobby = require("tinyglobby");
25
+ tinyglobby = __toESM(tinyglobby);
26
+ let picomatch = require("picomatch");
27
+ picomatch = __toESM(picomatch);
28
+ let __mearie_native = require("@mearie/native");
29
+ __mearie_native = __toESM(__mearie_native);
30
+ let __mearie_core = require("@mearie/core");
31
+ __mearie_core = __toESM(__mearie_core);
32
+ let node_fs_promises = require("node:fs/promises");
33
+ node_fs_promises = __toESM(node_fs_promises);
34
+ let __mearie_extractor = require("@mearie/extractor");
35
+ __mearie_extractor = __toESM(__mearie_extractor);
36
+ let node_module = require("node:module");
37
+ node_module = __toESM(node_module);
38
+ let node_path = require("node:path");
39
+ node_path = __toESM(node_path);
40
+
41
+ //#region src/glob.ts
42
+ /**
43
+ * Finds files matching the given patterns.
44
+ * @param cwd - Current working directory.
45
+ * @param patterns - File patterns to match.
46
+ * @returns Array of absolute file paths.
47
+ */
48
+ const findFiles = async (cwd, patterns) => {
49
+ const includePatterns = Array.isArray(patterns.include) ? patterns.include : [patterns.include];
50
+ const negatedExcludes = (patterns.exclude ? Array.isArray(patterns.exclude) ? patterns.exclude : [patterns.exclude] : []).map((pattern) => `!${pattern}`);
51
+ return await (0, tinyglobby.glob)([...includePatterns, ...negatedExcludes], {
52
+ cwd,
53
+ absolute: true
54
+ });
55
+ };
56
+ /**
57
+ * Creates a matcher function.
58
+ * @internal
59
+ * @param patterns - File patterns to match.
60
+ * @returns A function that checks if a file path matches the patterns.
61
+ */
62
+ const createMatcher = (patterns) => {
63
+ const includePatterns = Array.isArray(patterns.include) ? patterns.include : [patterns.include];
64
+ const excludePatterns = patterns.exclude ? Array.isArray(patterns.exclude) ? patterns.exclude : [patterns.exclude] : [];
65
+ const isMatch = (0, picomatch.default)(includePatterns);
66
+ const isExcluded = excludePatterns.length > 0 ? (0, picomatch.default)(excludePatterns) : () => false;
67
+ return (filePath) => {
68
+ return isMatch(filePath) && !isExcluded(filePath);
69
+ };
70
+ };
71
+
72
+ //#endregion
73
+ //#region src/generator.ts
74
+ /**
75
+ * Generates code from GraphQL documents and schemas.
76
+ * @param options - Generation options.
77
+ * @returns Generated code.
78
+ * @throws {Error} If code generation fails.
79
+ */
80
+ const generate = (options) => {
81
+ const { schemas, documents } = options;
82
+ const { sources, errors } = (0, __mearie_native.generateCode)(schemas, documents);
83
+ return {
84
+ sources,
85
+ errors: errors.map((error) => __mearie_core.MearieError.fromNative(error))
86
+ };
87
+ };
88
+
89
+ //#endregion
90
+ //#region src/writer.ts
91
+ const writeFiles = async (sources) => {
92
+ const clientPackageJsonPath = (0, node_module.createRequire)(node_path.default.resolve(process.cwd(), "package.json")).resolve("@mearie/client/package.json");
93
+ const meariePackagePath = node_path.default.dirname(clientPackageJsonPath);
94
+ const clientDir = node_path.default.resolve(meariePackagePath, ".mearie", "client");
95
+ await (0, node_fs_promises.mkdir)(clientDir, { recursive: true });
96
+ await Promise.all(sources.map((source) => (0, node_fs_promises.writeFile)(node_path.default.join(clientDir, source.filePath), source.code, "utf8")));
97
+ };
98
+
99
+ //#endregion
100
+ //#region src/context.ts
101
+ /**
102
+ * Stateful context for incremental code generation.
103
+ * Reads and caches file contents when files are added/updated.
104
+ */
105
+ var CodegenContext = class {
106
+ schemas = /* @__PURE__ */ new Map();
107
+ documents = /* @__PURE__ */ new Map();
108
+ /**
109
+ * Adds a schema file by reading it.
110
+ * @param filePath - Schema file path.
111
+ */
112
+ async addSchema(filePath) {
113
+ const code = await (0, node_fs_promises.readFile)(filePath, "utf8");
114
+ this.schemas.set(filePath, {
115
+ code,
116
+ filePath,
117
+ startLine: 1
118
+ });
119
+ }
120
+ /**
121
+ * Removes a schema file.
122
+ * @param filePath - Schema file path.
123
+ */
124
+ removeSchema(filePath) {
125
+ this.schemas.delete(filePath);
126
+ }
127
+ /**
128
+ * Adds a document file by reading and extracting operations.
129
+ * @param filePath - Document file path.
130
+ */
131
+ async addDocument(filePath) {
132
+ const { sources, errors } = await (0, __mearie_extractor.extractGraphQLSources)({
133
+ code: await (0, node_fs_promises.readFile)(filePath, "utf8"),
134
+ filePath,
135
+ startLine: 1
136
+ });
137
+ this.documents.set(filePath, sources);
138
+ if (errors.length > 0) throw new __mearie_core.MearieAggregateError(errors);
139
+ }
140
+ /**
141
+ * Removes a document file.
142
+ * @param filePath - Document file path.
143
+ */
144
+ removeDocument(filePath) {
145
+ this.documents.delete(filePath);
146
+ }
147
+ /**
148
+ * Generates code from cached schemas and documents and writes to files.
149
+ * @returns Written file paths.
150
+ * @throws {Error} If generation or writing fails.
151
+ */
152
+ async generate() {
153
+ const { sources, errors } = generate({
154
+ schemas: [...this.schemas.values()],
155
+ documents: [...this.documents.values()].flat()
156
+ });
157
+ await writeFiles(sources);
158
+ if (errors.length > 0) throw new __mearie_core.MearieAggregateError(errors);
159
+ }
160
+ };
161
+
162
+ //#endregion
163
+ exports.CodegenContext = CodegenContext;
164
+ exports.createMatcher = createMatcher;
165
+ exports.findFiles = findFiles;
166
+ exports.generate = generate;
@@ -0,0 +1,87 @@
1
+ import { MearieError, Source } from "@mearie/core";
2
+
3
+ //#region src/glob.d.ts
4
+ type GlobPatterns = {
5
+ include: string | string[];
6
+ exclude?: string | string[];
7
+ };
8
+ /**
9
+ * Finds files matching the given patterns.
10
+ * @param cwd - Current working directory.
11
+ * @param patterns - File patterns to match.
12
+ * @returns Array of absolute file paths.
13
+ */
14
+ declare const findFiles: (cwd: string, patterns: GlobPatterns) => Promise<string[]>;
15
+ /**
16
+ * Creates a matcher function.
17
+ * @internal
18
+ * @param patterns - File patterns to match.
19
+ * @returns A function that checks if a file path matches the patterns.
20
+ */
21
+ declare const createMatcher: (patterns: GlobPatterns) => ((filePath: string) => boolean);
22
+ //#endregion
23
+ //#region src/generator.d.ts
24
+ type GenerateOptions = {
25
+ schemas: Source[];
26
+ documents: Source[];
27
+ };
28
+ type GenerateResult = {
29
+ sources: Source[];
30
+ errors: MearieError[];
31
+ };
32
+ /**
33
+ * Generates code from GraphQL documents and schemas.
34
+ * @param options - Generation options.
35
+ * @returns Generated code.
36
+ * @throws {Error} If code generation fails.
37
+ */
38
+ declare const generate: (options: GenerateOptions) => GenerateResult;
39
+ //#endregion
40
+ //#region src/context.d.ts
41
+ /**
42
+ * Stateful context for incremental code generation.
43
+ * Reads and caches file contents when files are added/updated.
44
+ */
45
+ declare class CodegenContext {
46
+ private schemas;
47
+ private documents;
48
+ /**
49
+ * Adds a schema file by reading it.
50
+ * @param filePath - Schema file path.
51
+ */
52
+ addSchema(filePath: string): Promise<void>;
53
+ /**
54
+ * Removes a schema file.
55
+ * @param filePath - Schema file path.
56
+ */
57
+ removeSchema(filePath: string): void;
58
+ /**
59
+ * Adds a document file by reading and extracting operations.
60
+ * @param filePath - Document file path.
61
+ */
62
+ addDocument(filePath: string): Promise<void>;
63
+ /**
64
+ * Removes a document file.
65
+ * @param filePath - Document file path.
66
+ */
67
+ removeDocument(filePath: string): void;
68
+ /**
69
+ * Generates code from cached schemas and documents and writes to files.
70
+ * @returns Written file paths.
71
+ * @throws {Error} If generation or writing fails.
72
+ */
73
+ generate(): Promise<void>;
74
+ }
75
+ //#endregion
76
+ //#region src/types.d.ts
77
+ /**
78
+ * Configuration for the code generator.
79
+ */
80
+ type CodegenConfig = {
81
+ schemas: string;
82
+ documents: string | string[];
83
+ exclude?: string | string[];
84
+ cwd: string;
85
+ };
86
+ //#endregion
87
+ export { type CodegenConfig, CodegenContext, type GenerateOptions, type GlobPatterns, createMatcher, findFiles, generate };
@@ -0,0 +1,87 @@
1
+ import { MearieError, Source } from "@mearie/core";
2
+
3
+ //#region src/glob.d.ts
4
+ type GlobPatterns = {
5
+ include: string | string[];
6
+ exclude?: string | string[];
7
+ };
8
+ /**
9
+ * Finds files matching the given patterns.
10
+ * @param cwd - Current working directory.
11
+ * @param patterns - File patterns to match.
12
+ * @returns Array of absolute file paths.
13
+ */
14
+ declare const findFiles: (cwd: string, patterns: GlobPatterns) => Promise<string[]>;
15
+ /**
16
+ * Creates a matcher function.
17
+ * @internal
18
+ * @param patterns - File patterns to match.
19
+ * @returns A function that checks if a file path matches the patterns.
20
+ */
21
+ declare const createMatcher: (patterns: GlobPatterns) => ((filePath: string) => boolean);
22
+ //#endregion
23
+ //#region src/generator.d.ts
24
+ type GenerateOptions = {
25
+ schemas: Source[];
26
+ documents: Source[];
27
+ };
28
+ type GenerateResult = {
29
+ sources: Source[];
30
+ errors: MearieError[];
31
+ };
32
+ /**
33
+ * Generates code from GraphQL documents and schemas.
34
+ * @param options - Generation options.
35
+ * @returns Generated code.
36
+ * @throws {Error} If code generation fails.
37
+ */
38
+ declare const generate: (options: GenerateOptions) => GenerateResult;
39
+ //#endregion
40
+ //#region src/context.d.ts
41
+ /**
42
+ * Stateful context for incremental code generation.
43
+ * Reads and caches file contents when files are added/updated.
44
+ */
45
+ declare class CodegenContext {
46
+ private schemas;
47
+ private documents;
48
+ /**
49
+ * Adds a schema file by reading it.
50
+ * @param filePath - Schema file path.
51
+ */
52
+ addSchema(filePath: string): Promise<void>;
53
+ /**
54
+ * Removes a schema file.
55
+ * @param filePath - Schema file path.
56
+ */
57
+ removeSchema(filePath: string): void;
58
+ /**
59
+ * Adds a document file by reading and extracting operations.
60
+ * @param filePath - Document file path.
61
+ */
62
+ addDocument(filePath: string): Promise<void>;
63
+ /**
64
+ * Removes a document file.
65
+ * @param filePath - Document file path.
66
+ */
67
+ removeDocument(filePath: string): void;
68
+ /**
69
+ * Generates code from cached schemas and documents and writes to files.
70
+ * @returns Written file paths.
71
+ * @throws {Error} If generation or writing fails.
72
+ */
73
+ generate(): Promise<void>;
74
+ }
75
+ //#endregion
76
+ //#region src/types.d.ts
77
+ /**
78
+ * Configuration for the code generator.
79
+ */
80
+ type CodegenConfig = {
81
+ schemas: string;
82
+ documents: string | string[];
83
+ exclude?: string | string[];
84
+ cwd: string;
85
+ };
86
+ //#endregion
87
+ export { type CodegenConfig, CodegenContext, type GenerateOptions, type GlobPatterns, createMatcher, findFiles, generate };
package/dist/index.js ADDED
@@ -0,0 +1,132 @@
1
+ import { createRequire } from "node:module";
2
+ import { glob } from "tinyglobby";
3
+ import picomatch from "picomatch";
4
+ import { generateCode } from "@mearie/native";
5
+ import { MearieAggregateError, MearieError } from "@mearie/core";
6
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
7
+ import { extractGraphQLSources } from "@mearie/extractor";
8
+ import path from "node:path";
9
+
10
+ //#region src/glob.ts
11
+ /**
12
+ * Finds files matching the given patterns.
13
+ * @param cwd - Current working directory.
14
+ * @param patterns - File patterns to match.
15
+ * @returns Array of absolute file paths.
16
+ */
17
+ const findFiles = async (cwd, patterns) => {
18
+ const includePatterns = Array.isArray(patterns.include) ? patterns.include : [patterns.include];
19
+ const negatedExcludes = (patterns.exclude ? Array.isArray(patterns.exclude) ? patterns.exclude : [patterns.exclude] : []).map((pattern) => `!${pattern}`);
20
+ return await glob([...includePatterns, ...negatedExcludes], {
21
+ cwd,
22
+ absolute: true
23
+ });
24
+ };
25
+ /**
26
+ * Creates a matcher function.
27
+ * @internal
28
+ * @param patterns - File patterns to match.
29
+ * @returns A function that checks if a file path matches the patterns.
30
+ */
31
+ const createMatcher = (patterns) => {
32
+ const includePatterns = Array.isArray(patterns.include) ? patterns.include : [patterns.include];
33
+ const excludePatterns = patterns.exclude ? Array.isArray(patterns.exclude) ? patterns.exclude : [patterns.exclude] : [];
34
+ const isMatch = picomatch(includePatterns);
35
+ const isExcluded = excludePatterns.length > 0 ? picomatch(excludePatterns) : () => false;
36
+ return (filePath) => {
37
+ return isMatch(filePath) && !isExcluded(filePath);
38
+ };
39
+ };
40
+
41
+ //#endregion
42
+ //#region src/generator.ts
43
+ /**
44
+ * Generates code from GraphQL documents and schemas.
45
+ * @param options - Generation options.
46
+ * @returns Generated code.
47
+ * @throws {Error} If code generation fails.
48
+ */
49
+ const generate = (options) => {
50
+ const { schemas, documents } = options;
51
+ const { sources, errors } = generateCode(schemas, documents);
52
+ return {
53
+ sources,
54
+ errors: errors.map((error) => MearieError.fromNative(error))
55
+ };
56
+ };
57
+
58
+ //#endregion
59
+ //#region src/writer.ts
60
+ const writeFiles = async (sources) => {
61
+ const clientPackageJsonPath = createRequire(path.resolve(process.cwd(), "package.json")).resolve("@mearie/client/package.json");
62
+ const meariePackagePath = path.dirname(clientPackageJsonPath);
63
+ const clientDir = path.resolve(meariePackagePath, ".mearie", "client");
64
+ await mkdir(clientDir, { recursive: true });
65
+ await Promise.all(sources.map((source) => writeFile(path.join(clientDir, source.filePath), source.code, "utf8")));
66
+ };
67
+
68
+ //#endregion
69
+ //#region src/context.ts
70
+ /**
71
+ * Stateful context for incremental code generation.
72
+ * Reads and caches file contents when files are added/updated.
73
+ */
74
+ var CodegenContext = class {
75
+ schemas = /* @__PURE__ */ new Map();
76
+ documents = /* @__PURE__ */ new Map();
77
+ /**
78
+ * Adds a schema file by reading it.
79
+ * @param filePath - Schema file path.
80
+ */
81
+ async addSchema(filePath) {
82
+ const code = await readFile(filePath, "utf8");
83
+ this.schemas.set(filePath, {
84
+ code,
85
+ filePath,
86
+ startLine: 1
87
+ });
88
+ }
89
+ /**
90
+ * Removes a schema file.
91
+ * @param filePath - Schema file path.
92
+ */
93
+ removeSchema(filePath) {
94
+ this.schemas.delete(filePath);
95
+ }
96
+ /**
97
+ * Adds a document file by reading and extracting operations.
98
+ * @param filePath - Document file path.
99
+ */
100
+ async addDocument(filePath) {
101
+ const { sources, errors } = await extractGraphQLSources({
102
+ code: await readFile(filePath, "utf8"),
103
+ filePath,
104
+ startLine: 1
105
+ });
106
+ this.documents.set(filePath, sources);
107
+ if (errors.length > 0) throw new MearieAggregateError(errors);
108
+ }
109
+ /**
110
+ * Removes a document file.
111
+ * @param filePath - Document file path.
112
+ */
113
+ removeDocument(filePath) {
114
+ this.documents.delete(filePath);
115
+ }
116
+ /**
117
+ * Generates code from cached schemas and documents and writes to files.
118
+ * @returns Written file paths.
119
+ * @throws {Error} If generation or writing fails.
120
+ */
121
+ async generate() {
122
+ const { sources, errors } = generate({
123
+ schemas: [...this.schemas.values()],
124
+ documents: [...this.documents.values()].flat()
125
+ });
126
+ await writeFiles(sources);
127
+ if (errors.length > 0) throw new MearieAggregateError(errors);
128
+ }
129
+ };
130
+
131
+ //#endregion
132
+ export { CodegenContext, createMatcher, findFiles, generate };
package/package.json ADDED
@@ -0,0 +1,39 @@
1
+ {
2
+ "name": "@mearie/codegen",
3
+ "version": "0.0.0",
4
+ "description": "Code generation utilities for Mearie",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "./src/index.ts",
8
+ "files": [
9
+ "dist"
10
+ ],
11
+ "dependencies": {
12
+ "picomatch": "^4.0.3",
13
+ "tinyglobby": "^0.2.15",
14
+ "@mearie/core": "0.0.0",
15
+ "@mearie/config": "0.0.0",
16
+ "@mearie/extractor": "0.0.0",
17
+ "@mearie/native": "0.0.0"
18
+ },
19
+ "devDependencies": {
20
+ "@types/picomatch": "^4.0.2",
21
+ "tsdown": "^0.15.7",
22
+ "vitest": "^3.2.4"
23
+ },
24
+ "publishConfig": {
25
+ "access": "public"
26
+ },
27
+ "scripts": {
28
+ "build": "tsdown",
29
+ "test": "vitest run",
30
+ "test:watch": "vitest"
31
+ },
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.js",
36
+ "require": "./dist/index.cjs"
37
+ }
38
+ }
39
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export { findFiles, createMatcher, type GlobPatterns } from './glob.ts';
2
+ export { generate, type GenerateOptions } from './generator.ts';
3
+ export { CodegenContext } from './context.ts';
4
+ export type { CodegenConfig } from './types.ts';