arri 0.43.2 → 0.45.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,403 @@
1
+ import { existsSync } from 'node:fs';
2
+ import fs from 'node:fs/promises';
3
+ import { removeDisallowedChars, isAppDefinition } from '@arrirpc/codegen-utils';
4
+ import { listenAndWatch } from '@joshmossas/listhen';
5
+ import { loadConfig } from 'c12';
6
+ import { defineCommand } from 'citty';
7
+ import * as esbuild from 'esbuild';
8
+ import { ofetch } from 'ofetch';
9
+ import path from 'pathe';
10
+ import { createConsola } from 'consola';
11
+ import prettier from 'prettier';
12
+ import { camelCase, kebabCase } from 'scule';
13
+
14
+ function isArriConfig(input) {
15
+ if (typeof input !== "object" || input === null) {
16
+ return false;
17
+ }
18
+ if ("generators" in input) {
19
+ if (!Array.isArray(input.generators)) {
20
+ return false;
21
+ }
22
+ }
23
+ if ("port" in input) {
24
+ if (typeof input.port !== "number") {
25
+ return false;
26
+ }
27
+ if (Number.isNaN(input.port)) {
28
+ return false;
29
+ }
30
+ }
31
+ if ("entry" in input && typeof input.entry !== "string") {
32
+ return false;
33
+ }
34
+ return true;
35
+ }
36
+ function isResolvedArriConfig(input) {
37
+ if (!isArriConfig(input)) {
38
+ return false;
39
+ }
40
+ return typeof input.rootDir === "string" && typeof input.srcDir === "string" && (typeof input.procedureDir === "string" || typeof input.procedureDir === "boolean") && Array.isArray(input.procedureGlobPatterns) && Array.isArray(input.generators);
41
+ }
42
+ const defaultConfig = {
43
+ port: 3e3,
44
+ rootDir: ".",
45
+ srcDir: "src",
46
+ entry: "app.ts",
47
+ serverEntry: "",
48
+ procedureDir: "procedures",
49
+ procedureGlobPatterns: ["**/*.rpc.ts"],
50
+ generators: [],
51
+ buildDir: ".arri",
52
+ esbuild: {},
53
+ https: false,
54
+ http2: false,
55
+ devServer: {}
56
+ };
57
+ function defineConfig(config) {
58
+ return {
59
+ port: config.port ?? defaultConfig.port,
60
+ rootDir: config.rootDir ?? defaultConfig.rootDir,
61
+ srcDir: config.srcDir ?? defaultConfig.srcDir,
62
+ entry: config.entry ?? defaultConfig.entry,
63
+ procedureDir: config.procedureDir ?? defaultConfig.procedureDir,
64
+ procedureGlobPatterns: config.procedureGlobPatterns ?? defaultConfig.procedureGlobPatterns,
65
+ generators: config.generators ?? defaultConfig.generators,
66
+ buildDir: config.buildDir ?? defaultConfig.buildDir,
67
+ esbuild: config.esbuild ?? defaultConfig.esbuild,
68
+ serverEntry: config.serverEntry ?? "",
69
+ https: config.https ?? false,
70
+ http2: config.http2 ?? false,
71
+ devServer: config.devServer ?? {}
72
+ };
73
+ }
74
+
75
+ const logger = createConsola().withTag("arri");
76
+ const GEN_APP_FILE = "__arri_app.ts";
77
+ const GEN_SERVER_ENTRY_FILE = "__arri_server.ts";
78
+ const OUT_APP_FILE = "app.mjs";
79
+ const OUT_SERVER_ENTRY = "server.mjs";
80
+ const OUT_CODEGEN = "codegen.mjs";
81
+ async function setupWorkingDir(config) {
82
+ const arriDir = path.resolve(config.rootDir, config.buildDir);
83
+ const outDir = path.resolve(config.rootDir, ".output");
84
+ if (existsSync(arriDir)) {
85
+ await fs.rm(arriDir, { recursive: true, force: true });
86
+ }
87
+ if (existsSync(outDir)) {
88
+ await fs.rm(outDir, { recursive: true, force: true });
89
+ }
90
+ await fs.mkdir(arriDir);
91
+ await fs.mkdir(outDir);
92
+ }
93
+ async function createAppWithRoutesModule(config) {
94
+ const glob = await import('globby');
95
+ const appModule = path.resolve(config.rootDir, config.srcDir, config.entry);
96
+ const appImportParts = path.relative(path.resolve(config.rootDir, config.buildDir), appModule).split(".");
97
+ appImportParts.pop();
98
+ const routes = [];
99
+ const existingRoutes = [];
100
+ await Promise.all(
101
+ config.procedureGlobPatterns.map(async (pattern) => {
102
+ const results = await getFsRouteBatch(glob.globby, pattern, config);
103
+ for (const result of results) {
104
+ if (!existingRoutes.includes(result.name)) {
105
+ routes.push(result);
106
+ existingRoutes.push(result.name);
107
+ }
108
+ }
109
+ })
110
+ );
111
+ routes.sort((a, b) => a.name < b.name ? -1 : 1);
112
+ const module = await prettier.format(
113
+ `import sourceMapSupport from 'source-map-support';
114
+ sourceMapSupport.install();
115
+ import app from '${appImportParts.join(".")}';
116
+ ${routes.map(
117
+ (route) => `import ${route.importName} from '${route.importPath}';`
118
+ ).join("\n")}
119
+ const routes: {id: string; route: any}[] = [${routes.map(
120
+ (route) => `{ id: '${route.name}', route: ${route.importName} }`
121
+ ).join(",\n")}
122
+ ];
123
+ for(const route of routes) {
124
+ if(route.route.transport === 'http') {
125
+ app.rpc({
126
+ name: route.id,
127
+ ...route.route,
128
+ });
129
+ continue;
130
+ }
131
+ if (route.route.transport === 'ws') {
132
+ app.wsRpc({
133
+ name: route.id,
134
+ ...route.route,
135
+ });
136
+ continue;
137
+ }
138
+ }
139
+ export default app`,
140
+ { parser: "typescript", tabWidth: 4 }
141
+ );
142
+ await fs.writeFile(
143
+ path.resolve(config.rootDir, config.buildDir, GEN_APP_FILE),
144
+ module
145
+ );
146
+ }
147
+ async function getFsRouteBatch(glob, globPattern, config) {
148
+ if (!config.procedureDir) {
149
+ return [];
150
+ }
151
+ const target = `${config.rootDir}/${config.srcDir}/${config.procedureDir}/${globPattern}`.split("//").join("/").split("//").join("/");
152
+ const files = await glob(target, {
153
+ onlyFiles: true
154
+ });
155
+ const routes = [];
156
+ for (const file of files) {
157
+ const meta = getRpcMetaFromPath(config, file);
158
+ if (meta) {
159
+ const importParts = path.relative(path.resolve(config.rootDir, config.buildDir), file).split(".");
160
+ importParts.pop();
161
+ importParts.push("js");
162
+ routes.push({
163
+ name: meta.id,
164
+ importName: camelCase(meta.id.split(".").join("_")),
165
+ importPath: `./${importParts.join(".")}`
166
+ });
167
+ }
168
+ }
169
+ return routes;
170
+ }
171
+ const disallowedNameChars = "~`!@#$%^&*()-+=[]{}\\|:;\"'<>,./";
172
+ const getRpcMetaFromPath = (config, filePath) => {
173
+ if (!config.procedureDir) {
174
+ return void 0;
175
+ }
176
+ const resolvedFilePath = filePath.split("./").join("/");
177
+ const parts = resolvedFilePath.split("/");
178
+ const reversedParts = [...parts].reverse();
179
+ const nameParts = [];
180
+ for (const part of reversedParts) {
181
+ if (part === config.procedureDir) {
182
+ break;
183
+ }
184
+ nameParts.push(part);
185
+ }
186
+ const fileName = nameParts.reverse().pop() ?? "";
187
+ const serviceParts = nameParts.filter((part) => part.trim().length > 0).map((part) => removeDisallowedChars(part, disallowedNameChars));
188
+ const fileNameParts = fileName.split(".");
189
+ if (!fileNameParts.length) {
190
+ return void 0;
191
+ }
192
+ const rpcName = removeDisallowedChars(
193
+ fileNameParts[0],
194
+ disallowedNameChars
195
+ );
196
+ const httpParts = [
197
+ ...serviceParts.map((part) => kebabCase(part)),
198
+ kebabCase(rpcName)
199
+ ];
200
+ return {
201
+ id: [...serviceParts, rpcName].join("."),
202
+ httpPath: `/${httpParts.join("/")}`
203
+ };
204
+ };
205
+ function isInsideDir(dir, parentDir) {
206
+ if (path.resolve(dir).startsWith(path.resolve(parentDir))) {
207
+ return true;
208
+ }
209
+ return false;
210
+ }
211
+
212
+ const DEV_ENDPOINT_ROOT = `/__arri_dev__`;
213
+ const DEV_DEFINITION_ENDPOINT = `${DEV_ENDPOINT_ROOT}/__definition`;
214
+ const dev = defineCommand({
215
+ meta: {
216
+ name: "dev",
217
+ description: "Start the arri dev server"
218
+ },
219
+ args: {
220
+ config: {
221
+ type: "string",
222
+ description: "Path to the arri config file",
223
+ alias: "c",
224
+ default: "./arri.config.ts"
225
+ }
226
+ },
227
+ async run({ args }) {
228
+ process.env.ARRI_DEV_MODE = "true";
229
+ const { config } = await loadConfig({
230
+ configFile: path.resolve(args.config)
231
+ });
232
+ if (!isResolvedArriConfig(config)) {
233
+ throw new Error("Unable to find config");
234
+ }
235
+ const appEntry = path.resolve(
236
+ config.rootDir,
237
+ config.srcDir,
238
+ config.entry
239
+ );
240
+ if (!existsSync(appEntry)) {
241
+ throw new Error(`Unable to find entry at ${appEntry}`);
242
+ }
243
+ await startDevServer(config);
244
+ }
245
+ });
246
+ const startListener = (config, showQr = false) => listenAndWatch(path.resolve(config.rootDir, ".output", OUT_SERVER_ENTRY), {
247
+ public: true,
248
+ port: config.port,
249
+ logger,
250
+ qr: showQr,
251
+ https: config.https,
252
+ http2: config.http2,
253
+ ws: true
254
+ });
255
+ async function bundleFilesContext(config) {
256
+ const serverContent = `import app from './${OUT_APP_FILE}';
257
+
258
+ export default app.h3App;`;
259
+ await fs.writeFile(
260
+ path.resolve(config.rootDir, ".output", OUT_SERVER_ENTRY),
261
+ serverContent
262
+ );
263
+ return await esbuild.context({
264
+ ...config.esbuild,
265
+ entryPoints: [
266
+ path.resolve(config.rootDir, config.buildDir, GEN_APP_FILE)
267
+ ],
268
+ outfile: path.resolve(config.rootDir, ".output", OUT_APP_FILE),
269
+ format: "esm",
270
+ bundle: true,
271
+ packages: "external",
272
+ sourcemap: config.esbuild.sourcemap ?? true,
273
+ target: config.esbuild.target ?? "node20",
274
+ platform: config.esbuild.platform ?? "node"
275
+ });
276
+ }
277
+ async function startDevServer(config) {
278
+ await setupWorkingDir(config);
279
+ const watcher = await import('chokidar');
280
+ let fileWatcher;
281
+ await Promise.all([
282
+ createEntryModule(config),
283
+ createAppWithRoutesModule(config)
284
+ ]);
285
+ const context = await bundleFilesContext(config);
286
+ await context.rebuild();
287
+ const listener = await startListener(config, true);
288
+ setTimeout(async () => {
289
+ await generateClients(config);
290
+ }, 1e3);
291
+ const cleanExit = async () => {
292
+ process.exit();
293
+ };
294
+ process.on("exit", async () => {
295
+ await Promise.allSettled([
296
+ listener.close(),
297
+ fileWatcher?.close(),
298
+ context.dispose()
299
+ ]);
300
+ });
301
+ process.on("SIGINT", cleanExit);
302
+ process.on("SIGTERM", cleanExit);
303
+ async function load(isRestart, reason) {
304
+ if (fileWatcher) {
305
+ await fileWatcher.close();
306
+ }
307
+ const srcDir = path.resolve(config.rootDir ?? "", config.srcDir);
308
+ const dirsToWatch = [srcDir];
309
+ if (config.esbuild.alias) {
310
+ for (const key of Object.keys(config.esbuild.alias)) {
311
+ const alias = config.esbuild.alias[key];
312
+ if (alias) {
313
+ if (!isInsideDir(alias, srcDir)) {
314
+ dirsToWatch.push(alias);
315
+ }
316
+ }
317
+ }
318
+ }
319
+ if (config.devServer.additionalWatchDirs?.length) {
320
+ for (const dir of config.devServer.additionalWatchDirs) {
321
+ dirsToWatch.push(dir);
322
+ }
323
+ }
324
+ const buildDir = path.resolve(config.rootDir, config.buildDir);
325
+ const outDir = path.resolve(config.rootDir, ".output");
326
+ fileWatcher = watcher.watch(dirsToWatch, {
327
+ ignoreInitial: true,
328
+ ignored: [
329
+ buildDir,
330
+ outDir,
331
+ "**/.output",
332
+ "**/dist/**",
333
+ "**/node_modules/**",
334
+ "**/.git/**"
335
+ ]
336
+ });
337
+ fileWatcher.on("all", async (eventName, path2) => {
338
+ if (eventName === "addDir" || eventName === "add") {
339
+ return;
340
+ }
341
+ await createAppWithRoutesModule(config);
342
+ let bundleCreated = false;
343
+ try {
344
+ logger.log(
345
+ "Change detected. Bundling files and restarting server...."
346
+ );
347
+ await context.rebuild();
348
+ bundleCreated = true;
349
+ } catch (err) {
350
+ logger.error("ERROR", err);
351
+ bundleCreated = false;
352
+ }
353
+ if (bundleCreated && config.generators.length) {
354
+ setTimeout(async () => {
355
+ await generateClients(config);
356
+ bundleCreated = false;
357
+ }, 1e3);
358
+ }
359
+ });
360
+ }
361
+ await load();
362
+ }
363
+ async function generateClients(config) {
364
+ try {
365
+ const protocol = config.https === true || typeof config.https === "object" ? "https" : "http";
366
+ if (protocol === "https") {
367
+ process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
368
+ }
369
+ const result = await ofetch(
370
+ `${protocol}://127.0.0.1:${config.port}${DEV_DEFINITION_ENDPOINT}`
371
+ );
372
+ if (!isAppDefinition(result)) {
373
+ return;
374
+ }
375
+ logger.log(`Generating client code...`);
376
+ const clientCount = config.generators.length;
377
+ await Promise.allSettled(
378
+ config.generators.map(
379
+ (generator) => generator.generator(result, true)
380
+ )
381
+ );
382
+ logger.success(
383
+ `Generated ${clientCount} client${clientCount === 1 ? "" : "s"}`
384
+ );
385
+ } catch (err) {
386
+ logger.error(err);
387
+ }
388
+ }
389
+ async function createEntryModule(config) {
390
+ const appModule = path.resolve(config.rootDir, config.srcDir, config.entry);
391
+ const appImportParts = path.relative(path.resolve(config.rootDir, config.srcDir), appModule).split(".");
392
+ appImportParts.pop();
393
+ const virtualEntry = `import { toNodeListener } from 'h3';
394
+ import app from './${GEN_APP_FILE}';
395
+
396
+ export default app.h3App;`;
397
+ await fs.writeFile(
398
+ path.resolve(config.rootDir, config.buildDir, GEN_SERVER_ENTRY_FILE),
399
+ virtualEntry
400
+ );
401
+ }
402
+
403
+ export { DEV_DEFINITION_ENDPOINT as D, GEN_APP_FILE as G, OUT_CODEGEN as O, isResolvedArriConfig as a, defineConfig as b, createAppWithRoutesModule as c, defaultConfig as d, OUT_SERVER_ENTRY as e, OUT_APP_FILE as f, dev as g, isArriConfig as i, logger as l, setupWorkingDir as s };
package/package.json CHANGED
@@ -1,59 +1,50 @@
1
1
  {
2
2
  "name": "arri",
3
- "version": "0.43.2",
3
+ "version": "0.45.0",
4
4
  "type": "module",
5
5
  "license": "MIT",
6
6
  "author": {
7
7
  "name": "joshmossas",
8
8
  "url": "https://github.com/joshmossas"
9
9
  },
10
- "main": "./dist/index.cjs",
11
- "module": "./dist/index.mjs",
12
- "types": "./dist/index.d.ts",
13
- "files": [
14
- "dist"
15
- ],
10
+ "bin": {
11
+ "arri": "./dist/cli.mjs"
12
+ },
16
13
  "bugs": {
17
14
  "url": "https://github.com/modiimedia/arri/issues"
18
15
  },
19
16
  "repository": {
20
17
  "type": "git",
21
18
  "url": "https://github.com/modiimedia/arri.git",
22
- "directory": "packages/arri"
23
- },
24
- "bin": {
25
- "arri": "./dist/cli.mjs"
19
+ "directory": "tooling/cli"
26
20
  },
21
+ "main": "./dist/index.cjs",
22
+ "module": "./dist/index.mjs",
23
+ "types": "./dist/index.d.ts",
24
+ "files": [
25
+ "dist"
26
+ ],
27
27
  "dependencies": {
28
- "@joshmossas/listhen": "1.10.1",
29
- "@parcel/watcher": "^2.4.1",
30
- "@types/source-map-support": "^0.5.10",
28
+ "@joshmossas/listhen": "^1.10.1",
31
29
  "c12": "^1.10.0",
32
30
  "chokidar": "^3.6.0",
33
31
  "citty": "^0.1.6",
34
32
  "consola": "^3.2.3",
35
- "crossws": "^0.2.4",
36
33
  "degit": "^2.8.4",
37
34
  "enquirer": "^2.4.1",
38
35
  "esbuild": "^0.21.2",
39
36
  "esbuild-plugin-replace": "^1.4.0",
40
37
  "globby": "^14.0.1",
41
- "h3": "^1.11.1",
42
- "h3-sse": "^0.0.12",
43
- "jiti": "^1.21.0",
44
38
  "ofetch": "^1.3.4",
45
39
  "pathe": "^1.1.2",
46
40
  "prettier": "^3.2.5",
47
41
  "scule": "^1.3.0",
48
- "source-map-support": "^0.5.21",
49
- "uncrypto": "^0.1.3",
50
- "arri-codegen-ts": "0.43.2",
51
- "arri-codegen-dart": "0.43.2",
52
- "arri-codegen-utils": "0.43.2",
53
- "arri-validate": "0.43.2"
42
+ "@arrirpc/codegen-dart": "0.45.0",
43
+ "@arrirpc/codegen-kotlin": "0.45.0",
44
+ "@arrirpc/codegen-ts": "0.45.0",
45
+ "@arrirpc/codegen-utils": "0.45.0"
54
46
  },
55
47
  "devDependencies": {
56
- "@types/degit": "^2.8.6",
57
- "bun-types": "^1.1.8"
48
+ "@types/degit": "^2.8.6"
58
49
  }
59
50
  }
package/dist/codegen.cjs DELETED
@@ -1,11 +0,0 @@
1
- 'use strict';
2
-
3
- const arriCodegenDart = require('arri-codegen-dart');
4
- const arriCodegenTs = require('arri-codegen-ts');
5
- const arriCodegenUtils = require('arri-codegen-utils');
6
-
7
-
8
-
9
- exports.dartClientGenerator = arriCodegenDart.dartClientGenerator;
10
- exports.typescriptClientGenerator = arriCodegenTs.typescriptClientGenerator;
11
- exports.createAppDefinition = arriCodegenUtils.createAppDefinition;
@@ -1,3 +0,0 @@
1
- export { dartClientGenerator } from 'arri-codegen-dart';
2
- export { typescriptClientGenerator } from 'arri-codegen-ts';
3
- export { AppDefinition, createAppDefinition } from 'arri-codegen-utils';
@@ -1,3 +0,0 @@
1
- export { dartClientGenerator } from 'arri-codegen-dart';
2
- export { typescriptClientGenerator } from 'arri-codegen-ts';
3
- export { AppDefinition, createAppDefinition } from 'arri-codegen-utils';
package/dist/codegen.d.ts DELETED
@@ -1,3 +0,0 @@
1
- export { dartClientGenerator } from 'arri-codegen-dart';
2
- export { typescriptClientGenerator } from 'arri-codegen-ts';
3
- export { AppDefinition, createAppDefinition } from 'arri-codegen-utils';
package/dist/codegen.mjs DELETED
@@ -1,3 +0,0 @@
1
- export { dartClientGenerator } from 'arri-codegen-dart';
2
- export { typescriptClientGenerator } from 'arri-codegen-ts';
3
- export { createAppDefinition } from 'arri-codegen-utils';