@ciderjs/gasnuki 0.2.5 → 0.2.7

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,3 @@
1
+ {
2
+ "cSpell.words": ["gasnuki"]
3
+ }
package/README.ja.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # gasnuki
2
2
 
3
- [![Test Coverage](https://img.shields.io/badge/test%20coverage-83.65%25-green)](https://github.com/luthpg/gasnuki)
3
+ [![Test Coverage](https://img.shields.io/badge/test%20coverage-79.24%25-yellowgreen)](https://github.com/luthpg/gasnuki)
4
4
  [![License](https://img.shields.io/badge/license-ISC-blue.svg)](LICENSE)
5
5
  [![npm version](https://img.shields.io/npm/v/@ciderjs/gasnuki.svg)](https://www.npmjs.com/package/@ciderjs/gasnuki)
6
6
  [![GitHub issues](https://img.shields.io/github/issues/luthpg/gasnuki.svg)](https://github.com/luthpg/gasnuki/issues)
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @ciderjs/gasnuki
2
2
 
3
- [![Test Coverage](https://img.shields.io/badge/test%20coverage-83.65%25-green)](https://github.com/luthpg/gasnuki)
3
+ [![Test Coverage](https://img.shields.io/badge/test%20coverage-79.24%25-yellowgreen)](https://github.com/luthpg/gasnuki)
4
4
  [![License](https://img.shields.io/badge/license-ISC-blue.svg)](LICENSE)
5
5
  [![npm version](https://img.shields.io/npm/v/@ciderjs/gasnuki.svg)](https://www.npmjs.com/package/@ciderjs/gasnuki)
6
6
  [![GitHub issues](https://img.shields.io/github/issues/luthpg/gasnuki.svg)](https://github.com/luthpg/gasnuki/issues)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ciderjs/gasnuki",
3
- "version": "0.2.5",
3
+ "version": "0.2.7",
4
4
  "description": "Type definitions and utilities for Google Apps Script client-side API",
5
5
  "main": "dist/index.mjs",
6
6
  "types": "dist/index.d.ts",
@@ -29,11 +29,16 @@
29
29
  "test:coverage": "vitest run --coverage",
30
30
  "update-coverage-badge": "jiti scripts/update-coverage-badge.ts README.md README.ja.md",
31
31
  "test:coverage:update": "pnpm test:coverage && pnpm update-coverage-badge",
32
- "prepare": "pnpm run generate && pnpm run check && pnpm run test:coverage:update && pnpm run build",
32
+ "postinstall": "pnpm run generate",
33
+ "prepublish": "pnpm run generate && pnpm run check && pnpm run test:coverage:update && pnpm run build",
33
34
  "pg:react": "pnpm -C playground/react",
34
35
  "pg:vue": "pnpm -C playground/vue3"
35
36
  },
36
- "keywords": ["google-apps-script", "typescript", "@google/clasp"],
37
+ "keywords": [
38
+ "google-apps-script",
39
+ "typescript",
40
+ "@google/clasp"
41
+ ],
37
42
  "author": "ciderjs/luth",
38
43
  "license": "ISC",
39
44
  "repository": {
@@ -45,19 +50,18 @@
45
50
  },
46
51
  "packageManager": "pnpm@10.11.1",
47
52
  "dependencies": {
48
- "@inquirer/prompts": "^7.5.3",
49
53
  "chokidar": "^4.0.3",
50
54
  "commander": "^14.0.0",
51
55
  "consola": "^3.4.2",
52
- "jiti": "^2.4.2",
56
+ "jiti": "^2.5.1",
53
57
  "ts-morph": "^26.0.0"
54
58
  },
55
59
  "devDependencies": {
56
- "@biomejs/biome": "^1.9.4",
57
- "@types/node": "^22.15.29",
58
- "@vitest/coverage-v8": "3.2.1",
59
- "typescript": "^5.8.3",
60
- "unbuild": "^3.5.0",
61
- "vitest": "^3.2.1"
60
+ "@biomejs/biome": "^2.1.4",
61
+ "@types/node": "^24.2.1",
62
+ "@vitest/coverage-v8": "3.2.4",
63
+ "typescript": "^5.9.2",
64
+ "unbuild": "^3.6.0",
65
+ "vitest": "3.2.4"
62
66
  }
63
67
  }
package/dist/cli.cjs DELETED
@@ -1,77 +0,0 @@
1
- #! /usr/bin/env node
2
- 'use strict';
3
-
4
- const path = require('node:path');
5
- const commander = require('commander');
6
- const index = require('./shared/gasnuki.Ce9vzQ2b.cjs');
7
- require('chokidar');
8
- require('consola');
9
- require('node:fs');
10
- require('ts-morph');
11
- require('jiti');
12
-
13
- function _interopNamespaceCompat(e) {
14
- if (e && typeof e === 'object' && 'default' in e) return e;
15
- const n = Object.create(null);
16
- if (e) {
17
- for (const k in e) {
18
- n[k] = e[k];
19
- }
20
- }
21
- n.default = e;
22
- return n;
23
- }
24
-
25
- const path__namespace = /*#__PURE__*/_interopNamespaceCompat(path);
26
-
27
- const version = "0.2.5";
28
-
29
- const parseArgs = async (command) => {
30
- const cliOpts = command.opts();
31
- const fileConfig = await index.loadConfig(path__namespace.resolve(cliOpts.project));
32
- const defaultOpts = {};
33
- for (const option of command.options) {
34
- const key = option.attributeName();
35
- defaultOpts[key] = option.defaultValue;
36
- }
37
- const explicitCliOpts = {};
38
- for (const option of command.options) {
39
- const key = option.attributeName();
40
- if (command.getOptionValueSource(key) === "cli") {
41
- explicitCliOpts[key] = cliOpts[key];
42
- }
43
- }
44
- const finalOptions = {
45
- ...defaultOpts,
46
- ...fileConfig,
47
- ...explicitCliOpts,
48
- project: cliOpts.project,
49
- watch: cliOpts.watch
50
- };
51
- await index.generateTypes(finalOptions);
52
- };
53
- const cli = async () => {
54
- const program = new commander.Command();
55
- program.name("gasnuki").description(
56
- "Generate type definitions and utilities for Google Apps Script client-side API"
57
- );
58
- program.version(version, "-v, --version");
59
- program.action(async (_param, command) => await parseArgs(command)).option(
60
- "-p, --project <project>",
61
- "Project root directory path",
62
- process.cwd().replace(/\\/g, "/")
63
- ).option(
64
- "-s, --srcDir <dir>",
65
- "Source directory name (relative to project root)",
66
- "server"
67
- ).option(
68
- "-o, --outDir <dir>",
69
- "Output directory name (relative to project root)",
70
- "types"
71
- ).option("-f, --outputFile <file>", "Output file name", "appsscript.ts").option("-w, --watch", "Watch for changes and re-generate types", false);
72
- await program.parseAsync(process.argv);
73
- };
74
- cli();
75
-
76
- exports.cli = cli;
77
- exports.parseArgs = parseArgs;
package/dist/cli.d.cts DELETED
@@ -1,7 +0,0 @@
1
-
2
- import { Command } from 'commander';
3
-
4
- declare const parseArgs: (command: Command) => Promise<void>;
5
- declare const cli: () => Promise<void>;
6
-
7
- export { cli, parseArgs };
package/dist/cli.d.mts DELETED
@@ -1,7 +0,0 @@
1
-
2
- import { Command } from 'commander';
3
-
4
- declare const parseArgs: (command: Command) => Promise<void>;
5
- declare const cli: () => Promise<void>;
6
-
7
- export { cli, parseArgs };
package/dist/cli.d.ts DELETED
@@ -1,7 +0,0 @@
1
-
2
- import { Command } from 'commander';
3
-
4
- declare const parseArgs: (command: Command) => Promise<void>;
5
- declare const cli: () => Promise<void>;
6
-
7
- export { cli, parseArgs };
package/dist/cli.mjs DELETED
@@ -1,60 +0,0 @@
1
- #! /usr/bin/env node
2
- import * as path from 'node:path';
3
- import { Command } from 'commander';
4
- import { l as loadConfig, g as generateTypes } from './shared/gasnuki.DJCCMztm.mjs';
5
- import 'chokidar';
6
- import 'consola';
7
- import 'node:fs';
8
- import 'ts-morph';
9
- import 'jiti';
10
-
11
- const version = "0.2.5";
12
-
13
- const parseArgs = async (command) => {
14
- const cliOpts = command.opts();
15
- const fileConfig = await loadConfig(path.resolve(cliOpts.project));
16
- const defaultOpts = {};
17
- for (const option of command.options) {
18
- const key = option.attributeName();
19
- defaultOpts[key] = option.defaultValue;
20
- }
21
- const explicitCliOpts = {};
22
- for (const option of command.options) {
23
- const key = option.attributeName();
24
- if (command.getOptionValueSource(key) === "cli") {
25
- explicitCliOpts[key] = cliOpts[key];
26
- }
27
- }
28
- const finalOptions = {
29
- ...defaultOpts,
30
- ...fileConfig,
31
- ...explicitCliOpts,
32
- project: cliOpts.project,
33
- watch: cliOpts.watch
34
- };
35
- await generateTypes(finalOptions);
36
- };
37
- const cli = async () => {
38
- const program = new Command();
39
- program.name("gasnuki").description(
40
- "Generate type definitions and utilities for Google Apps Script client-side API"
41
- );
42
- program.version(version, "-v, --version");
43
- program.action(async (_param, command) => await parseArgs(command)).option(
44
- "-p, --project <project>",
45
- "Project root directory path",
46
- process.cwd().replace(/\\/g, "/")
47
- ).option(
48
- "-s, --srcDir <dir>",
49
- "Source directory name (relative to project root)",
50
- "server"
51
- ).option(
52
- "-o, --outDir <dir>",
53
- "Output directory name (relative to project root)",
54
- "types"
55
- ).option("-f, --outputFile <file>", "Output file name", "appsscript.ts").option("-w, --watch", "Watch for changes and re-generate types", false);
56
- await program.parseAsync(process.argv);
57
- };
58
- cli();
59
-
60
- export { cli, parseArgs };
package/dist/index.cjs DELETED
@@ -1,14 +0,0 @@
1
- 'use strict';
2
-
3
- require('node:path');
4
- require('chokidar');
5
- require('consola');
6
- const index = require('./shared/gasnuki.Ce9vzQ2b.cjs');
7
- require('node:fs');
8
- require('ts-morph');
9
- require('jiti');
10
-
11
-
12
-
13
- exports.defineConfig = index.defineConfig;
14
- exports.generateTypes = index.generateTypes;
package/dist/index.d.cts DELETED
@@ -1,23 +0,0 @@
1
- /**
2
- * User-defined configuration for gasnuki.
3
- * `project` and `watch` options are excluded as they are runtime flags.
4
- */
5
- type UserConfig = Partial<Omit<GenerateOptions, 'watch' | 'project'>>;
6
- /**
7
- * A helper function to define the gasnuki configuration with type safety.
8
- * @param config The configuration object.
9
- * @returns The configuration object.
10
- */
11
- declare function defineConfig(config: UserConfig): UserConfig;
12
-
13
- interface GenerateOptions {
14
- project: string;
15
- srcDir: string;
16
- outDir: string;
17
- outputFile: string;
18
- watch: boolean;
19
- }
20
- declare const generateTypes: ({ project, srcDir, outDir, outputFile, watch, }: GenerateOptions) => Promise<void>;
21
-
22
- export { defineConfig, generateTypes };
23
- export type { GenerateOptions, UserConfig };
package/dist/index.d.mts DELETED
@@ -1,23 +0,0 @@
1
- /**
2
- * User-defined configuration for gasnuki.
3
- * `project` and `watch` options are excluded as they are runtime flags.
4
- */
5
- type UserConfig = Partial<Omit<GenerateOptions, 'watch' | 'project'>>;
6
- /**
7
- * A helper function to define the gasnuki configuration with type safety.
8
- * @param config The configuration object.
9
- * @returns The configuration object.
10
- */
11
- declare function defineConfig(config: UserConfig): UserConfig;
12
-
13
- interface GenerateOptions {
14
- project: string;
15
- srcDir: string;
16
- outDir: string;
17
- outputFile: string;
18
- watch: boolean;
19
- }
20
- declare const generateTypes: ({ project, srcDir, outDir, outputFile, watch, }: GenerateOptions) => Promise<void>;
21
-
22
- export { defineConfig, generateTypes };
23
- export type { GenerateOptions, UserConfig };
package/dist/index.d.ts DELETED
@@ -1,23 +0,0 @@
1
- /**
2
- * User-defined configuration for gasnuki.
3
- * `project` and `watch` options are excluded as they are runtime flags.
4
- */
5
- type UserConfig = Partial<Omit<GenerateOptions, 'watch' | 'project'>>;
6
- /**
7
- * A helper function to define the gasnuki configuration with type safety.
8
- * @param config The configuration object.
9
- * @returns The configuration object.
10
- */
11
- declare function defineConfig(config: UserConfig): UserConfig;
12
-
13
- interface GenerateOptions {
14
- project: string;
15
- srcDir: string;
16
- outDir: string;
17
- outputFile: string;
18
- watch: boolean;
19
- }
20
- declare const generateTypes: ({ project, srcDir, outDir, outputFile, watch, }: GenerateOptions) => Promise<void>;
21
-
22
- export { defineConfig, generateTypes };
23
- export type { GenerateOptions, UserConfig };
package/dist/index.mjs DELETED
@@ -1,7 +0,0 @@
1
- import 'node:path';
2
- import 'chokidar';
3
- import 'consola';
4
- export { d as defineConfig, g as generateTypes } from './shared/gasnuki.DJCCMztm.mjs';
5
- import 'node:fs';
6
- import 'ts-morph';
7
- import 'jiti';
package/dist/promise.cjs DELETED
@@ -1,19 +0,0 @@
1
- 'use strict';
2
-
3
- const getPromisedServerScripts = (mockupFunctions = {}) => {
4
- return new Proxy(mockupFunctions, {
5
- get(target, method) {
6
- if (!("google" in globalThis) || !google?.script?.run) {
7
- return target[method];
8
- }
9
- if (!(method in google.script.run)) {
10
- throw Error(`Method ${method} not found in AppsScript.`);
11
- }
12
- return (...args) => new Promise((resolve, reject) => {
13
- google.script.run.withSuccessHandler(resolve).withFailureHandler(reject)[method](...args);
14
- });
15
- }
16
- });
17
- };
18
-
19
- exports.getPromisedServerScripts = getPromisedServerScripts;
@@ -1,8 +0,0 @@
1
- type Promised<T> = {
2
- [K in keyof T]: T[K] extends (...args: infer A) => infer R ? (...args: A) => Promise<R> : T[K];
3
- };
4
- type PartialScriptType<T> = Partial<Promised<T>>;
5
- declare const getPromisedServerScripts: <T extends Record<string, (...args: any[]) => any> = Omit<typeof google.script.run, "withSuccessHandler" | "withFailureHandler" | "withUserObject">>(mockupFunctions?: PartialScriptType<T>) => Promised<T>;
6
-
7
- export { getPromisedServerScripts };
8
- export type { PartialScriptType, Promised };
@@ -1,8 +0,0 @@
1
- type Promised<T> = {
2
- [K in keyof T]: T[K] extends (...args: infer A) => infer R ? (...args: A) => Promise<R> : T[K];
3
- };
4
- type PartialScriptType<T> = Partial<Promised<T>>;
5
- declare const getPromisedServerScripts: <T extends Record<string, (...args: any[]) => any> = Omit<typeof google.script.run, "withSuccessHandler" | "withFailureHandler" | "withUserObject">>(mockupFunctions?: PartialScriptType<T>) => Promised<T>;
6
-
7
- export { getPromisedServerScripts };
8
- export type { PartialScriptType, Promised };
package/dist/promise.d.ts DELETED
@@ -1,8 +0,0 @@
1
- type Promised<T> = {
2
- [K in keyof T]: T[K] extends (...args: infer A) => infer R ? (...args: A) => Promise<R> : T[K];
3
- };
4
- type PartialScriptType<T> = Partial<Promised<T>>;
5
- declare const getPromisedServerScripts: <T extends Record<string, (...args: any[]) => any> = Omit<typeof google.script.run, "withSuccessHandler" | "withFailureHandler" | "withUserObject">>(mockupFunctions?: PartialScriptType<T>) => Promised<T>;
6
-
7
- export { getPromisedServerScripts };
8
- export type { PartialScriptType, Promised };
package/dist/promise.mjs DELETED
@@ -1,17 +0,0 @@
1
- const getPromisedServerScripts = (mockupFunctions = {}) => {
2
- return new Proxy(mockupFunctions, {
3
- get(target, method) {
4
- if (!("google" in globalThis) || !google?.script?.run) {
5
- return target[method];
6
- }
7
- if (!(method in google.script.run)) {
8
- throw Error(`Method ${method} not found in AppsScript.`);
9
- }
10
- return (...args) => new Promise((resolve, reject) => {
11
- google.script.run.withSuccessHandler(resolve).withFailureHandler(reject)[method](...args);
12
- });
13
- }
14
- });
15
- };
16
-
17
- export { getPromisedServerScripts };
@@ -1,324 +0,0 @@
1
- 'use strict';
2
-
3
- const path = require('node:path');
4
- const chokidar = require('chokidar');
5
- const consola = require('consola');
6
- const fs = require('node:fs');
7
- const tsMorph = require('ts-morph');
8
- const jiti = require('jiti');
9
-
10
- function _interopNamespaceCompat(e) {
11
- if (e && typeof e === 'object' && 'default' in e) return e;
12
- const n = Object.create(null);
13
- if (e) {
14
- for (const k in e) {
15
- n[k] = e[k];
16
- }
17
- }
18
- n.default = e;
19
- return n;
20
- }
21
-
22
- const path__namespace = /*#__PURE__*/_interopNamespaceCompat(path);
23
- const chokidar__namespace = /*#__PURE__*/_interopNamespaceCompat(chokidar);
24
- const fs__namespace = /*#__PURE__*/_interopNamespaceCompat(fs);
25
-
26
- const text = "export type RemoveReturnType<T> = {\n [P in keyof T]: T[P] extends (...args: infer A) => any\n ? (...args: A) => void\n : T[P];\n};\n\ntype _AppsScriptRun = RemoveReturnType<ServerScripts> & {\n [key: string]: (...args: any[]) => any;\n withSuccessHandler: <T = string | number | boolean | undefined, U = any>(\n callback: (returnValues: T, userObject?: U) => void,\n ) => _AppsScriptRun;\n withFailureHandler: <U = any>(\n callback: (error: Error, userObject?: U) => void,\n ) => _AppsScriptRun;\n withUserObject: <U = any>(userObject: U) => _AppsScriptRun;\n};\n\ntype _AppsScriptHistoryFunction = (\n stateObject: object,\n params: object,\n hash: string,\n) => void;\n\ninterface _WebAppLovacationType {\n hash: string;\n parameter: Record<string, string>;\n parameters: Record<string, string[]>;\n}\n\nexport declare interface GoogleClientSideApi {\n script: {\n run: _AppsScriptRun;\n url: {\n getLocation: (\n callback: (location: _WebAppLovacationType) => void,\n ) => void;\n };\n history: {\n push: _AppsScriptHistoryFunction;\n replace: _AppsScriptHistoryFunction;\n setChangeHandler: (\n callback: (e: {\n state: object;\n location: _WebAppLovacationType;\n }) => void,\n ) => void;\n };\n };\n}\n\ndeclare global {\n const google: GoogleClientSideApi;\n}\n";
27
-
28
- const getInterfaceMethodDefinition_ = (name, node) => {
29
- const typeParameters = node.getTypeParameters?.() ?? [];
30
- const typeParamsString = typeParameters.length > 0 ? `<${typeParameters.map((tp) => tp.getText()).join(", ")}>` : "";
31
- const parameters = node.getParameters().map((param) => {
32
- const paramName = param.getName();
33
- const type = param.getTypeNode()?.getText() ?? param.getType().getText(node) ?? "any";
34
- const questionToken = param.hasQuestionToken() ? "?" : "";
35
- return `${paramName}${questionToken}: ${type}`;
36
- }).join(", ");
37
- const returnTypeNode = node.getReturnTypeNode();
38
- let returnType;
39
- if (returnTypeNode != null) {
40
- returnType = returnTypeNode.getText();
41
- } else {
42
- const inferredReturnType = node.getReturnType();
43
- if (inferredReturnType.isVoid()) {
44
- returnType = "void";
45
- } else {
46
- returnType = inferredReturnType.getText(node);
47
- }
48
- }
49
- let jsDocString = "";
50
- const jsDocOwner = "getJsDocs" in node ? node : "getParentOrThrow" in node && // @ts-expect-error variable declaration
51
- node.getParentOrThrow().getKind() === tsMorph.SyntaxKind.VariableDeclaration ? (
52
- // @ts-expect-error variable declaration
53
- node.getParentOrThrow()
54
- ) : null;
55
- if (jsDocOwner != null) {
56
- const jsDocs = "getJsDocs" in jsDocOwner ? jsDocOwner.getJsDocs() : [];
57
- if (jsDocs.length > 0) {
58
- const firstDoc = jsDocs[0];
59
- jsDocString = `${firstDoc.getFullText().trim()}
60
- `;
61
- }
62
- }
63
- return `${jsDocString}${name}${typeParamsString}(${parameters}): ${returnType};`;
64
- };
65
- const SIMPLE_TRIGGER_FUNCTION_NAMES = [
66
- "onOpen",
67
- "onEdit",
68
- "onInstall",
69
- "onSelectionChange",
70
- "doGet",
71
- "doPost"
72
- ];
73
- const generateAppsScriptTypes = async ({
74
- project: projectPath,
75
- srcDir,
76
- outDir,
77
- outputFile
78
- }) => {
79
- const absoluteSrcDir = path__namespace.resolve(projectPath, srcDir);
80
- const absoluteOutDir = path__namespace.resolve(projectPath, outDir);
81
- const absoluteOutputFile = path__namespace.resolve(absoluteOutDir, outputFile);
82
- consola.consola.info("Starting AppsScript type generation with gasnuki...");
83
- consola.consola.info(` AppsScript Source Directory: ${absoluteSrcDir}`);
84
- consola.consola.info(` Output File: ${absoluteOutputFile}`);
85
- const project = new tsMorph.Project({
86
- tsConfigFilePath: path__namespace.resolve(projectPath, "tsconfig.json"),
87
- skipAddingFilesFromTsConfig: true
88
- });
89
- const sourceFilesPattern = path__namespace.join(absoluteSrcDir, "**/*.ts").replace(/\\/g, "/");
90
- const testFilesPattern = `!${path__namespace.join(absoluteSrcDir, "**/*.{test,spec}.ts").replace(/\\/g, "/")}`;
91
- project.addSourceFilesAtPaths([sourceFilesPattern, testFilesPattern]);
92
- const sourceFiles = project.getSourceFiles();
93
- consola.consola.info(`Found ${sourceFiles.length} source file(s).`);
94
- const methodDefinitions = [];
95
- const localDeclarations = [];
96
- const localDeclarationNames = /* @__PURE__ */ new Set();
97
- for (const sourceFile of sourceFiles) {
98
- for (const iface of sourceFile.getInterfaces()) {
99
- const name = iface.getName?.();
100
- if (name && !name.endsWith("_")) {
101
- localDeclarations.push(iface);
102
- localDeclarationNames.add(name);
103
- }
104
- }
105
- for (const typeAlias of sourceFile.getTypeAliases()) {
106
- const name = typeAlias.getName();
107
- if (name && !name.endsWith("_")) {
108
- localDeclarations.push(typeAlias);
109
- localDeclarationNames.add(name);
110
- }
111
- }
112
- for (const func of sourceFile.getFunctions()) {
113
- const name = func.getName();
114
- if (name && !func.isAmbient() && !name.endsWith("_") && !SIMPLE_TRIGGER_FUNCTION_NAMES.includes(name)) {
115
- localDeclarations.push(func);
116
- localDeclarationNames.add(name);
117
- methodDefinitions.push(getInterfaceMethodDefinition_(name, func));
118
- }
119
- }
120
- for (const varStmt of sourceFile.getVariableStatements()) {
121
- if (varStmt.isAmbient()) continue;
122
- for (const varDecl of varStmt.getDeclarations()) {
123
- const name = varDecl.getName();
124
- const initializer = varDecl.getInitializer();
125
- if (!name.endsWith("_") && !SIMPLE_TRIGGER_FUNCTION_NAMES.includes(name) && initializer && (initializer.getKind() === tsMorph.SyntaxKind.ArrowFunction || initializer.getKind() === tsMorph.SyntaxKind.FunctionExpression)) {
126
- localDeclarations.push(varDecl);
127
- localDeclarationNames.add(name);
128
- methodDefinitions.push(
129
- getInterfaceMethodDefinition_(
130
- name,
131
- initializer
132
- )
133
- );
134
- }
135
- }
136
- }
137
- }
138
- const importsMap = /* @__PURE__ */ new Map();
139
- for (const decl of localDeclarations) {
140
- const descendants = decl.getDescendantsOfKind?.(tsMorph.SyntaxKind.TypeReference) ?? [];
141
- for (const descendant of descendants) {
142
- const symbol = descendant.getType().getAliasSymbol() ?? descendant.getType().getSymbol();
143
- if (symbol) {
144
- const symbolFlags = symbol.getFlags();
145
- if (symbolFlags & tsMorph.SymbolFlags.TypeParameter) {
146
- continue;
147
- }
148
- const symbolName = symbol.getName();
149
- if (localDeclarationNames.has(symbolName) || symbolName === "__type") {
150
- continue;
151
- }
152
- const declaration = symbol.getDeclarations()[0];
153
- if (declaration) {
154
- const declarationSourceFile = declaration.getSourceFile();
155
- if (declarationSourceFile.getFilePath().includes("node_modules")) {
156
- continue;
157
- }
158
- let modulePath = path__namespace.relative(absoluteOutDir, declarationSourceFile.getFilePath()).replace(/\\/g, "/");
159
- modulePath = modulePath.replace(/\.(d\.)?ts$/, "");
160
- if (modulePath.endsWith("/index")) {
161
- modulePath = modulePath.slice(0, -6);
162
- }
163
- if (modulePath === "index" || modulePath === "") {
164
- modulePath = ".";
165
- }
166
- if (!modulePath.startsWith(".")) {
167
- modulePath = `./${modulePath}`;
168
- }
169
- if (!importsMap.has(modulePath)) {
170
- importsMap.set(modulePath, /* @__PURE__ */ new Set());
171
- }
172
- importsMap.get(modulePath)?.add(symbolName);
173
- }
174
- }
175
- }
176
- }
177
- if (!fs__namespace.existsSync(absoluteOutDir)) {
178
- fs__namespace.mkdirSync(absoluteOutDir, { recursive: true });
179
- consola.consola.info(`Created output directory: ${absoluteOutDir}`);
180
- }
181
- const generatorName = "gasnuki";
182
- let outputContent = `// Auto-generated by ${generatorName}
183
- // Do NOT edit this file manually.
184
-
185
- `;
186
- const sortedModulePaths = [...importsMap.keys()].sort((a, b) => {
187
- const aIsRelative = a.startsWith(".");
188
- const bIsRelative = b.startsWith(".");
189
- if (aIsRelative !== bIsRelative) return aIsRelative ? 1 : -1;
190
- return a.localeCompare(b);
191
- });
192
- if (sortedModulePaths.length > 0) {
193
- const importStatements = sortedModulePaths.map((modulePath) => {
194
- const imports = [...importsMap.get(modulePath) ?? []].sort();
195
- const finalModulePath = modulePath === "." ? "./index" : modulePath;
196
- return `import type { ${imports.join(", ")} } from '${finalModulePath}';`;
197
- });
198
- outputContent += `${importStatements.join("\n")}
199
-
200
- `;
201
- }
202
- const globalTypeDefinitions = localDeclarations.filter(
203
- (d) => d.getKind?.() === tsMorph.SyntaxKind.InterfaceDeclaration || d.getKind?.() === tsMorph.SyntaxKind.TypeAliasDeclaration
204
- ).map((decl) => decl.getText?.());
205
- if (globalTypeDefinitions.length > 0) {
206
- outputContent += `${globalTypeDefinitions.join("\n\n")}
207
-
208
- `;
209
- }
210
- if (methodDefinitions.length > 0) {
211
- const formattedMethods = methodDefinitions.map(
212
- (method) => method.split("\n").map((line) => ` ${line}`).join("\n")
213
- ).join("\n\n");
214
- outputContent += `export type ServerScripts = {
215
- ${formattedMethods}
216
- }
217
- `;
218
- consola.consola.info(
219
- `Interface 'ServerScript' type definitions written to ${absoluteOutputFile} (${methodDefinitions.length} function(s), ${globalTypeDefinitions.length} type(s)).`
220
- );
221
- } else {
222
- outputContent += "export type ServerScripts = {}\n";
223
- consola.consola.info(
224
- `Interface 'ServerScript' type definitions written to ${absoluteOutputFile} (no functions found).`
225
- );
226
- }
227
- outputContent += `
228
- // Auto-generated Types for GoogleAppsScript in client-side code
229
-
230
- ${text}`;
231
- fs__namespace.writeFileSync(absoluteOutputFile, outputContent);
232
- };
233
-
234
- function defineConfig(config) {
235
- return config;
236
- }
237
- async function loadConfig(projectRoot) {
238
- const configFileExtensions = [".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"];
239
- let foundConfigPath;
240
- let foundConfigFileName;
241
- for (const configFileExtension of configFileExtensions) {
242
- const configFile = `gasnuki.config${configFileExtension}`;
243
- const fullPath = path__namespace.resolve(projectRoot, configFile);
244
- if (fs__namespace.existsSync(fullPath)) {
245
- foundConfigPath = fullPath;
246
- foundConfigFileName = configFile;
247
- break;
248
- }
249
- }
250
- if (!foundConfigPath || !foundConfigFileName) {
251
- return {};
252
- }
253
- try {
254
- const jiti$1 = jiti.createJiti(projectRoot, {
255
- fsCache: false,
256
- moduleCache: false,
257
- interopDefault: true
258
- });
259
- const configModule = await jiti$1.import(foundConfigPath, {
260
- default: true
261
- });
262
- consola.consola.success(`Loaded configuration from ${foundConfigFileName}`);
263
- return configModule;
264
- } catch (error) {
265
- consola.consola.error(`Error loading ${foundConfigFileName}:`, error);
266
- return {};
267
- }
268
- }
269
-
270
- const generateTypes = async ({
271
- project,
272
- srcDir,
273
- outDir,
274
- outputFile,
275
- watch
276
- }) => {
277
- const runGeneration = async (triggeredBy) => {
278
- const reason = triggeredBy ? ` (${triggeredBy})` : "";
279
- consola.consola.info(`Generating AppsScript types${reason}...`);
280
- try {
281
- await generateAppsScriptTypes({ project, srcDir, outDir, outputFile });
282
- consola.consola.info("Type generation complete.");
283
- } catch (e) {
284
- consola.consola.error(`Type generation failed: ${e.message}`, e);
285
- }
286
- };
287
- await runGeneration();
288
- if (watch) {
289
- const sourcePathToWatch = path__namespace.resolve(project, srcDir).replace(/\\/g, "/");
290
- consola.consola.info(
291
- `Watching for changes in ${sourcePathToWatch}... (Press Ctrl+C to stop)`
292
- );
293
- const watcher = chokidar__namespace.watch(sourcePathToWatch, {
294
- ignored: ["node_modules", "dist"],
295
- persistent: true,
296
- ignoreInitial: true
297
- });
298
- const eventHandler = async (filePath, eventName) => {
299
- consola.consola.info(`Watcher is called triggered on ${eventName}`);
300
- const relativePath = path__namespace.relative(project, filePath);
301
- await runGeneration(relativePath);
302
- };
303
- watcher.on("ready", async () => {
304
- console.log("...waiting...");
305
- watcher.on("all", async (event, path2) => {
306
- consola.consola.info(`Watcher is called triggered on ${event}: ${path2}`);
307
- await eventHandler(path2, event);
308
- });
309
- });
310
- for (const signal of ["SIGINT", "SIGTERM"]) {
311
- process.on(signal, async () => {
312
- await watcher.close();
313
- consola.consola.info("Watcher is closed.");
314
- process.exit(0);
315
- });
316
- }
317
- } else {
318
- process.exit(0);
319
- }
320
- };
321
-
322
- exports.defineConfig = defineConfig;
323
- exports.generateTypes = generateTypes;
324
- exports.loadConfig = loadConfig;
@@ -1,304 +0,0 @@
1
- import * as path from 'node:path';
2
- import * as chokidar from 'chokidar';
3
- import { consola } from 'consola';
4
- import * as fs from 'node:fs';
5
- import { Project, SyntaxKind, SymbolFlags } from 'ts-morph';
6
- import { createJiti } from 'jiti';
7
-
8
- const text = "export type RemoveReturnType<T> = {\n [P in keyof T]: T[P] extends (...args: infer A) => any\n ? (...args: A) => void\n : T[P];\n};\n\ntype _AppsScriptRun = RemoveReturnType<ServerScripts> & {\n [key: string]: (...args: any[]) => any;\n withSuccessHandler: <T = string | number | boolean | undefined, U = any>(\n callback: (returnValues: T, userObject?: U) => void,\n ) => _AppsScriptRun;\n withFailureHandler: <U = any>(\n callback: (error: Error, userObject?: U) => void,\n ) => _AppsScriptRun;\n withUserObject: <U = any>(userObject: U) => _AppsScriptRun;\n};\n\ntype _AppsScriptHistoryFunction = (\n stateObject: object,\n params: object,\n hash: string,\n) => void;\n\ninterface _WebAppLovacationType {\n hash: string;\n parameter: Record<string, string>;\n parameters: Record<string, string[]>;\n}\n\nexport declare interface GoogleClientSideApi {\n script: {\n run: _AppsScriptRun;\n url: {\n getLocation: (\n callback: (location: _WebAppLovacationType) => void,\n ) => void;\n };\n history: {\n push: _AppsScriptHistoryFunction;\n replace: _AppsScriptHistoryFunction;\n setChangeHandler: (\n callback: (e: {\n state: object;\n location: _WebAppLovacationType;\n }) => void,\n ) => void;\n };\n };\n}\n\ndeclare global {\n const google: GoogleClientSideApi;\n}\n";
9
-
10
- const getInterfaceMethodDefinition_ = (name, node) => {
11
- const typeParameters = node.getTypeParameters?.() ?? [];
12
- const typeParamsString = typeParameters.length > 0 ? `<${typeParameters.map((tp) => tp.getText()).join(", ")}>` : "";
13
- const parameters = node.getParameters().map((param) => {
14
- const paramName = param.getName();
15
- const type = param.getTypeNode()?.getText() ?? param.getType().getText(node) ?? "any";
16
- const questionToken = param.hasQuestionToken() ? "?" : "";
17
- return `${paramName}${questionToken}: ${type}`;
18
- }).join(", ");
19
- const returnTypeNode = node.getReturnTypeNode();
20
- let returnType;
21
- if (returnTypeNode != null) {
22
- returnType = returnTypeNode.getText();
23
- } else {
24
- const inferredReturnType = node.getReturnType();
25
- if (inferredReturnType.isVoid()) {
26
- returnType = "void";
27
- } else {
28
- returnType = inferredReturnType.getText(node);
29
- }
30
- }
31
- let jsDocString = "";
32
- const jsDocOwner = "getJsDocs" in node ? node : "getParentOrThrow" in node && // @ts-expect-error variable declaration
33
- node.getParentOrThrow().getKind() === SyntaxKind.VariableDeclaration ? (
34
- // @ts-expect-error variable declaration
35
- node.getParentOrThrow()
36
- ) : null;
37
- if (jsDocOwner != null) {
38
- const jsDocs = "getJsDocs" in jsDocOwner ? jsDocOwner.getJsDocs() : [];
39
- if (jsDocs.length > 0) {
40
- const firstDoc = jsDocs[0];
41
- jsDocString = `${firstDoc.getFullText().trim()}
42
- `;
43
- }
44
- }
45
- return `${jsDocString}${name}${typeParamsString}(${parameters}): ${returnType};`;
46
- };
47
- const SIMPLE_TRIGGER_FUNCTION_NAMES = [
48
- "onOpen",
49
- "onEdit",
50
- "onInstall",
51
- "onSelectionChange",
52
- "doGet",
53
- "doPost"
54
- ];
55
- const generateAppsScriptTypes = async ({
56
- project: projectPath,
57
- srcDir,
58
- outDir,
59
- outputFile
60
- }) => {
61
- const absoluteSrcDir = path.resolve(projectPath, srcDir);
62
- const absoluteOutDir = path.resolve(projectPath, outDir);
63
- const absoluteOutputFile = path.resolve(absoluteOutDir, outputFile);
64
- consola.info("Starting AppsScript type generation with gasnuki...");
65
- consola.info(` AppsScript Source Directory: ${absoluteSrcDir}`);
66
- consola.info(` Output File: ${absoluteOutputFile}`);
67
- const project = new Project({
68
- tsConfigFilePath: path.resolve(projectPath, "tsconfig.json"),
69
- skipAddingFilesFromTsConfig: true
70
- });
71
- const sourceFilesPattern = path.join(absoluteSrcDir, "**/*.ts").replace(/\\/g, "/");
72
- const testFilesPattern = `!${path.join(absoluteSrcDir, "**/*.{test,spec}.ts").replace(/\\/g, "/")}`;
73
- project.addSourceFilesAtPaths([sourceFilesPattern, testFilesPattern]);
74
- const sourceFiles = project.getSourceFiles();
75
- consola.info(`Found ${sourceFiles.length} source file(s).`);
76
- const methodDefinitions = [];
77
- const localDeclarations = [];
78
- const localDeclarationNames = /* @__PURE__ */ new Set();
79
- for (const sourceFile of sourceFiles) {
80
- for (const iface of sourceFile.getInterfaces()) {
81
- const name = iface.getName?.();
82
- if (name && !name.endsWith("_")) {
83
- localDeclarations.push(iface);
84
- localDeclarationNames.add(name);
85
- }
86
- }
87
- for (const typeAlias of sourceFile.getTypeAliases()) {
88
- const name = typeAlias.getName();
89
- if (name && !name.endsWith("_")) {
90
- localDeclarations.push(typeAlias);
91
- localDeclarationNames.add(name);
92
- }
93
- }
94
- for (const func of sourceFile.getFunctions()) {
95
- const name = func.getName();
96
- if (name && !func.isAmbient() && !name.endsWith("_") && !SIMPLE_TRIGGER_FUNCTION_NAMES.includes(name)) {
97
- localDeclarations.push(func);
98
- localDeclarationNames.add(name);
99
- methodDefinitions.push(getInterfaceMethodDefinition_(name, func));
100
- }
101
- }
102
- for (const varStmt of sourceFile.getVariableStatements()) {
103
- if (varStmt.isAmbient()) continue;
104
- for (const varDecl of varStmt.getDeclarations()) {
105
- const name = varDecl.getName();
106
- const initializer = varDecl.getInitializer();
107
- if (!name.endsWith("_") && !SIMPLE_TRIGGER_FUNCTION_NAMES.includes(name) && initializer && (initializer.getKind() === SyntaxKind.ArrowFunction || initializer.getKind() === SyntaxKind.FunctionExpression)) {
108
- localDeclarations.push(varDecl);
109
- localDeclarationNames.add(name);
110
- methodDefinitions.push(
111
- getInterfaceMethodDefinition_(
112
- name,
113
- initializer
114
- )
115
- );
116
- }
117
- }
118
- }
119
- }
120
- const importsMap = /* @__PURE__ */ new Map();
121
- for (const decl of localDeclarations) {
122
- const descendants = decl.getDescendantsOfKind?.(SyntaxKind.TypeReference) ?? [];
123
- for (const descendant of descendants) {
124
- const symbol = descendant.getType().getAliasSymbol() ?? descendant.getType().getSymbol();
125
- if (symbol) {
126
- const symbolFlags = symbol.getFlags();
127
- if (symbolFlags & SymbolFlags.TypeParameter) {
128
- continue;
129
- }
130
- const symbolName = symbol.getName();
131
- if (localDeclarationNames.has(symbolName) || symbolName === "__type") {
132
- continue;
133
- }
134
- const declaration = symbol.getDeclarations()[0];
135
- if (declaration) {
136
- const declarationSourceFile = declaration.getSourceFile();
137
- if (declarationSourceFile.getFilePath().includes("node_modules")) {
138
- continue;
139
- }
140
- let modulePath = path.relative(absoluteOutDir, declarationSourceFile.getFilePath()).replace(/\\/g, "/");
141
- modulePath = modulePath.replace(/\.(d\.)?ts$/, "");
142
- if (modulePath.endsWith("/index")) {
143
- modulePath = modulePath.slice(0, -6);
144
- }
145
- if (modulePath === "index" || modulePath === "") {
146
- modulePath = ".";
147
- }
148
- if (!modulePath.startsWith(".")) {
149
- modulePath = `./${modulePath}`;
150
- }
151
- if (!importsMap.has(modulePath)) {
152
- importsMap.set(modulePath, /* @__PURE__ */ new Set());
153
- }
154
- importsMap.get(modulePath)?.add(symbolName);
155
- }
156
- }
157
- }
158
- }
159
- if (!fs.existsSync(absoluteOutDir)) {
160
- fs.mkdirSync(absoluteOutDir, { recursive: true });
161
- consola.info(`Created output directory: ${absoluteOutDir}`);
162
- }
163
- const generatorName = "gasnuki";
164
- let outputContent = `// Auto-generated by ${generatorName}
165
- // Do NOT edit this file manually.
166
-
167
- `;
168
- const sortedModulePaths = [...importsMap.keys()].sort((a, b) => {
169
- const aIsRelative = a.startsWith(".");
170
- const bIsRelative = b.startsWith(".");
171
- if (aIsRelative !== bIsRelative) return aIsRelative ? 1 : -1;
172
- return a.localeCompare(b);
173
- });
174
- if (sortedModulePaths.length > 0) {
175
- const importStatements = sortedModulePaths.map((modulePath) => {
176
- const imports = [...importsMap.get(modulePath) ?? []].sort();
177
- const finalModulePath = modulePath === "." ? "./index" : modulePath;
178
- return `import type { ${imports.join(", ")} } from '${finalModulePath}';`;
179
- });
180
- outputContent += `${importStatements.join("\n")}
181
-
182
- `;
183
- }
184
- const globalTypeDefinitions = localDeclarations.filter(
185
- (d) => d.getKind?.() === SyntaxKind.InterfaceDeclaration || d.getKind?.() === SyntaxKind.TypeAliasDeclaration
186
- ).map((decl) => decl.getText?.());
187
- if (globalTypeDefinitions.length > 0) {
188
- outputContent += `${globalTypeDefinitions.join("\n\n")}
189
-
190
- `;
191
- }
192
- if (methodDefinitions.length > 0) {
193
- const formattedMethods = methodDefinitions.map(
194
- (method) => method.split("\n").map((line) => ` ${line}`).join("\n")
195
- ).join("\n\n");
196
- outputContent += `export type ServerScripts = {
197
- ${formattedMethods}
198
- }
199
- `;
200
- consola.info(
201
- `Interface 'ServerScript' type definitions written to ${absoluteOutputFile} (${methodDefinitions.length} function(s), ${globalTypeDefinitions.length} type(s)).`
202
- );
203
- } else {
204
- outputContent += "export type ServerScripts = {}\n";
205
- consola.info(
206
- `Interface 'ServerScript' type definitions written to ${absoluteOutputFile} (no functions found).`
207
- );
208
- }
209
- outputContent += `
210
- // Auto-generated Types for GoogleAppsScript in client-side code
211
-
212
- ${text}`;
213
- fs.writeFileSync(absoluteOutputFile, outputContent);
214
- };
215
-
216
- function defineConfig(config) {
217
- return config;
218
- }
219
- async function loadConfig(projectRoot) {
220
- const configFileExtensions = [".ts", ".mts", ".cts", ".js", ".mjs", ".cjs"];
221
- let foundConfigPath;
222
- let foundConfigFileName;
223
- for (const configFileExtension of configFileExtensions) {
224
- const configFile = `gasnuki.config${configFileExtension}`;
225
- const fullPath = path.resolve(projectRoot, configFile);
226
- if (fs.existsSync(fullPath)) {
227
- foundConfigPath = fullPath;
228
- foundConfigFileName = configFile;
229
- break;
230
- }
231
- }
232
- if (!foundConfigPath || !foundConfigFileName) {
233
- return {};
234
- }
235
- try {
236
- const jiti = createJiti(projectRoot, {
237
- fsCache: false,
238
- moduleCache: false,
239
- interopDefault: true
240
- });
241
- const configModule = await jiti.import(foundConfigPath, {
242
- default: true
243
- });
244
- consola.success(`Loaded configuration from ${foundConfigFileName}`);
245
- return configModule;
246
- } catch (error) {
247
- consola.error(`Error loading ${foundConfigFileName}:`, error);
248
- return {};
249
- }
250
- }
251
-
252
- const generateTypes = async ({
253
- project,
254
- srcDir,
255
- outDir,
256
- outputFile,
257
- watch
258
- }) => {
259
- const runGeneration = async (triggeredBy) => {
260
- const reason = triggeredBy ? ` (${triggeredBy})` : "";
261
- consola.info(`Generating AppsScript types${reason}...`);
262
- try {
263
- await generateAppsScriptTypes({ project, srcDir, outDir, outputFile });
264
- consola.info("Type generation complete.");
265
- } catch (e) {
266
- consola.error(`Type generation failed: ${e.message}`, e);
267
- }
268
- };
269
- await runGeneration();
270
- if (watch) {
271
- const sourcePathToWatch = path.resolve(project, srcDir).replace(/\\/g, "/");
272
- consola.info(
273
- `Watching for changes in ${sourcePathToWatch}... (Press Ctrl+C to stop)`
274
- );
275
- const watcher = chokidar.watch(sourcePathToWatch, {
276
- ignored: ["node_modules", "dist"],
277
- persistent: true,
278
- ignoreInitial: true
279
- });
280
- const eventHandler = async (filePath, eventName) => {
281
- consola.info(`Watcher is called triggered on ${eventName}`);
282
- const relativePath = path.relative(project, filePath);
283
- await runGeneration(relativePath);
284
- };
285
- watcher.on("ready", async () => {
286
- console.log("...waiting...");
287
- watcher.on("all", async (event, path2) => {
288
- consola.info(`Watcher is called triggered on ${event}: ${path2}`);
289
- await eventHandler(path2, event);
290
- });
291
- });
292
- for (const signal of ["SIGINT", "SIGTERM"]) {
293
- process.on(signal, async () => {
294
- await watcher.close();
295
- consola.info("Watcher is closed.");
296
- process.exit(0);
297
- });
298
- }
299
- } else {
300
- process.exit(0);
301
- }
302
- };
303
-
304
- export { defineConfig as d, generateTypes as g, loadConfig as l };