@akanjs/devkit 0.0.40 → 0.0.41

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/index.d.ts +1 -24
  2. package/index.js +1950 -21
  3. package/package.json +20 -2
  4. package/src/auth.d.ts +6 -9
  5. package/src/baseDevEnv.d.ts +4 -6
  6. package/src/capacitorApp.d.ts +5 -11
  7. package/src/commandDecorators/argMeta.d.ts +55 -0
  8. package/src/commandDecorators/command.d.ts +2 -0
  9. package/src/commandDecorators/commandMeta.d.ts +2 -0
  10. package/src/commandDecorators/index.d.ts +5 -0
  11. package/src/commandDecorators/targetMeta.d.ts +18 -0
  12. package/src/commandDecorators/types.d.ts +1 -0
  13. package/src/constants.d.ts +9 -11
  14. package/src/createTunnel.d.ts +2 -3
  15. package/src/dependencyScanner.d.ts +1 -3
  16. package/src/executors.d.ts +14 -157
  17. package/src/extractDeps.d.ts +2 -5
  18. package/src/getCredentials.d.ts +3 -9
  19. package/src/getDependencies.d.ts +1 -3
  20. package/src/getModelFileData.d.ts +2 -3
  21. package/src/getRelatedCnsts.d.ts +1 -3
  22. package/src/index.d.ts +18 -101
  23. package/src/installExternalLib.d.ts +2 -8
  24. package/src/selectModel.d.ts +1 -3
  25. package/src/streamAi.d.ts +2 -3
  26. package/src/types.d.ts +2 -4
  27. package/src/uploadRelease.d.ts +1 -3
  28. package/src/aiEditor.d.ts +0 -10
  29. package/src/aiEditor.js +0 -61
  30. package/src/auth.js +0 -79
  31. package/src/baseDevEnv.js +0 -50
  32. package/src/capacitorApp.js +0 -186
  33. package/src/constants.js +0 -47
  34. package/src/createTunnel.js +0 -47
  35. package/src/dependencyScanner.js +0 -171
  36. package/src/executors.js +0 -715
  37. package/src/extractDeps.js +0 -114
  38. package/src/getCredentials.js +0 -43
  39. package/src/getDependencies.js +0 -67
  40. package/src/getModelFileData.js +0 -67
  41. package/src/getRelatedCnsts.js +0 -145
  42. package/src/index.js +0 -55
  43. package/src/installExternalLib.js +0 -34
  44. package/src/selectModel.js +0 -50
  45. package/src/streamAi.js +0 -69
  46. package/src/types.js +0 -15
  47. package/src/uploadRelease.js +0 -82
package/index.js CHANGED
@@ -1,21 +1,1950 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
- var __getOwnPropNames = Object.getOwnPropertyNames;
4
- var __hasOwnProp = Object.prototype.hasOwnProperty;
5
- var __copyProps = (to, from, except, desc) => {
6
- if (from && typeof from === "object" || typeof from === "function") {
7
- for (let key of __getOwnPropNames(from))
8
- if (!__hasOwnProp.call(to, key) && key !== except)
9
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
10
- }
11
- return to;
12
- };
13
- var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
14
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
15
- var index_exports = {};
16
- module.exports = __toCommonJS(index_exports);
17
- __reExport(index_exports, require("./src"), module.exports);
18
- // Annotate the CommonJS export names for ESM import in node:
19
- 0 && (module.exports = {
20
- ...require("./src")
21
- });
1
+ (() => {
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 __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
9
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
10
+ }) : x)(function(x) {
11
+ if (typeof require !== "undefined")
12
+ return require.apply(this, arguments);
13
+ throw Error('Dynamic require of "' + x + '" is not supported');
14
+ });
15
+ var __copyProps = (to, from, except, desc) => {
16
+ if (from && typeof from === "object" || typeof from === "function") {
17
+ for (let key of __getOwnPropNames(from))
18
+ if (!__hasOwnProp.call(to, key) && key !== except)
19
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
20
+ }
21
+ return to;
22
+ };
23
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
24
+ // If the importer is in node compatibility mode or this is not an ESM
25
+ // file that has been converted to a CommonJS file using a Babel-
26
+ // compatible transform (i.e. "__esModule" has not been set), then set
27
+ // "default" to the CommonJS "module.exports" for node compatibility.
28
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
29
+ mod
30
+ ));
31
+
32
+ // pkgs/@akanjs/devkit/src/baseDevEnv.ts
33
+ var appName = process.env.NEXT_PUBLIC_APP_NAME;
34
+ var repoName = process.env.NEXT_PUBLIC_REPO_NAME;
35
+ if (!repoName)
36
+ throw new Error("NEXT_PUBLIC_REPO_NAME is not set");
37
+ var serveDomain = process.env.NEXT_PUBLIC_SERVE_DOMAIN;
38
+ if (!serveDomain)
39
+ throw new Error("NEXT_PUBLIC_SERVE_DOMAIN is not set");
40
+ var env = process.env.NEXT_PUBLIC_ENV ?? "debug";
41
+ if (!env)
42
+ throw new Error("NEXT_PUBLIC_ENV is not set");
43
+ var baseDevEnv = { ...appName ? { appName } : {}, repoName, serveDomain, env };
44
+ var getSshTunnelOptions = (appName2, environment) => ({
45
+ host: `${appName2}-${environment}.${serveDomain}`,
46
+ port: process.env.SSU_TUNNEL_PORT ? parseInt(process.env.SSU_TUNNEL_PORT) : 32767,
47
+ username: process.env.SSU_TUNNEL_USERNAME ?? "root",
48
+ password: process.env.SSU_TUNNEL_PASSWORD ?? repoName
49
+ });
50
+
51
+ // pkgs/@akanjs/devkit/src/createTunnel.ts
52
+ var import_tunnel_ssh = __require("tunnel-ssh");
53
+ var createTunnel = async ({ appName: appName2, environment, port = 27017 }) => {
54
+ const tunnelOptions = { autoClose: true, reconnectOnError: true };
55
+ const sshOptions = getSshTunnelOptions(appName2, environment);
56
+ const serverOptions = { port };
57
+ const forwardOptions = {
58
+ srcAddr: "0.0.0.0",
59
+ srcPort: port,
60
+ dstAddr: `mongo-0.mongo-svc.${appName2}-${environment}`,
61
+ dstPort: 27017
62
+ };
63
+ const [server, client] = await (0, import_tunnel_ssh.createTunnel)(tunnelOptions, serverOptions, sshOptions, forwardOptions);
64
+ return `localhost:${port}`;
65
+ };
66
+
67
+ // pkgs/@akanjs/devkit/src/getCredentials.ts
68
+ var import_fs = __toESM(__require("fs"));
69
+ var import_js_yaml = __toESM(__require("js-yaml"));
70
+ var getCredentials = (app, environment) => {
71
+ const secret = import_js_yaml.default.load(
72
+ import_fs.default.readFileSync(`${app.workspace.workspaceRoot}/infra/app/values/${app.name}-secret.yaml`, "utf-8")
73
+ );
74
+ return secret[environment];
75
+ };
76
+
77
+ // pkgs/@akanjs/devkit/src/getDependencies.ts
78
+ var import_devkit = __require("@nx/devkit");
79
+ var addLibDepSet = (depName, { libDepSet, npmDepSet, dependencies }) => {
80
+ const deps = dependencies[depName];
81
+ if (!deps)
82
+ throw new Error(`No dependencies found for project or library ${depName}`);
83
+ for (const dep of deps) {
84
+ if (dep.target.startsWith("npm:"))
85
+ npmDepSet.add(dep.target);
86
+ else if (libDepSet.has(dep.target))
87
+ continue;
88
+ else {
89
+ libDepSet.add(dep.target);
90
+ addLibDepSet(dep.target, { libDepSet, npmDepSet, dependencies });
91
+ }
92
+ }
93
+ };
94
+ var getDependencies = async (projectName) => {
95
+ const graph = await (0, import_devkit.createProjectGraphAsync)();
96
+ const [libDepSet, npmDepSet] = [/* @__PURE__ */ new Set(), /* @__PURE__ */ new Set()];
97
+ const dependencies = graph.dependencies;
98
+ const projectDeps = dependencies[projectName];
99
+ if (!projectDeps)
100
+ throw new Error(`No dependencies found for project ${projectName}`);
101
+ addLibDepSet(projectName, { libDepSet, npmDepSet, dependencies });
102
+ return {
103
+ libDeps: [...libDepSet.values()],
104
+ npmDeps: [...npmDepSet.values()].map((depName) => depName.replace("npm:", ""))
105
+ };
106
+ };
107
+
108
+ // pkgs/@akanjs/devkit/src/uploadRelease.ts
109
+ var import_axios = __toESM(__require("axios"));
110
+ var import_form_data = __toESM(__require("form-data"));
111
+ var import_fs2 = __toESM(__require("fs"));
112
+ var uploadRelease = async (projectName, {
113
+ workspaceRoot,
114
+ environment,
115
+ buildNum,
116
+ platformVersion,
117
+ local
118
+ }) => {
119
+ const basePath2 = local ? "http://localhost:8080/backend" : "https://akasys.akamir.com/backend";
120
+ const buildPath = `${workspaceRoot}/releases/builds/${projectName}-release.tar.gz`;
121
+ const appBuildPath = `${workspaceRoot}/releases/builds/${projectName}-appBuild.zip`;
122
+ const sourcePath = `${workspaceRoot}/releases/sources/${projectName}-source.tar.gz`;
123
+ const formData = new import_form_data.default();
124
+ const build = import_fs2.default.readFileSync(buildPath);
125
+ const source = import_fs2.default.readFileSync(sourcePath);
126
+ const appBuild = import_fs2.default.readFileSync(appBuildPath);
127
+ const buildStat = import_fs2.default.statSync(buildPath);
128
+ const sourceStat = import_fs2.default.statSync(sourcePath);
129
+ const appBuildStat = import_fs2.default.statSync(appBuildPath);
130
+ formData.append("files", build, `${projectName}-release.tar.gz`);
131
+ formData.append("files", source, `${projectName}-source.tar.gz`);
132
+ formData.append("files", appBuild, `${projectName}-appBuild.zip`);
133
+ formData.append(
134
+ "metas",
135
+ JSON.stringify([
136
+ { lastModifiedAt: buildStat.mtime, size: buildStat.size },
137
+ { lastModifiedAt: sourceStat.mtime, size: sourceStat.size },
138
+ { lastModifiedAt: appBuildStat.mtime, size: appBuildStat.size }
139
+ ])
140
+ );
141
+ formData.append("type", "release");
142
+ try {
143
+ const [buildFile, sourceFile, appBuildFile] = (await import_axios.default.post(`${basePath2}/file/addFilesRestApi`, formData)).data;
144
+ const major = platformVersion ? parseInt(platformVersion.split(".")[0]) : 1;
145
+ const minor = platformVersion ? parseInt(platformVersion.split(".")[1]) : 0;
146
+ const patch = platformVersion ? parseInt(platformVersion.split(".")[2]) : 0;
147
+ const latestRelease = await import_axios.default.get(
148
+ `${basePath2}/release/findVersionRelease?appName=${projectName}&branch=${environment}&major=${major}&minor=${minor}`
149
+ );
150
+ const release = (await import_axios.default.post(
151
+ `${basePath2}/release/pushRelease/${projectName}/${environment}/${major}/${minor}/${sourceFile.id}/${buildFile.id}/${appBuildFile.id}`
152
+ )).data;
153
+ return release;
154
+ } catch (e) {
155
+ return null;
156
+ }
157
+ };
158
+
159
+ // pkgs/@akanjs/devkit/src/getModelFileData.ts
160
+ var import_fs3 = __toESM(__require("fs"));
161
+ var getModelFileData = (modulePath, modelName) => {
162
+ const moduleType = modulePath.startsWith("apps") ? "app" : "lib";
163
+ const moduleName = modulePath.split("/")[1];
164
+ const constantFilePath = `${modulePath}/lib/${modelName}/${modelName}.constant.ts`;
165
+ const unitFilePath = `${modulePath}/lib/${modelName}/${modelName}.Unit.tsx`;
166
+ const viewFilePath = `${modulePath}/lib/${modelName}/${modelName}.View.tsx`;
167
+ const constantFileStr = import_fs3.default.readFileSync(constantFilePath, "utf8");
168
+ const unitFileStr = import_fs3.default.readFileSync(unitFilePath, "utf8");
169
+ const viewFileStr = import_fs3.default.readFileSync(viewFilePath, "utf8");
170
+ const constantFileLines = constantFileStr.split("\n");
171
+ const importLibNames = constantFileLines.filter((line) => line.startsWith("import { cnst as ")).map((line) => line.split("cnst as ")[1].split(" ")[0]);
172
+ const importLocalPaths = constantFileLines.filter((line) => line.startsWith("import { ") && line.includes('from "../')).map((line) => line.split("from ")[1].split('"')[1]);
173
+ const importModelNames = importLocalPaths.map((path5) => path5.split("/")[1]).filter((name) => !name.startsWith("_"));
174
+ const hasImportScalar = !!importLocalPaths.map((path5) => path5.split("/")[1]).filter((name) => name.startsWith("_")).length;
175
+ return {
176
+ moduleType,
177
+ moduleName,
178
+ modelName,
179
+ constantFilePath,
180
+ unitFilePath,
181
+ viewFilePath,
182
+ importModelNames,
183
+ hasImportScalar,
184
+ importLibNames,
185
+ constantFileStr,
186
+ unitFileStr,
187
+ viewFileStr
188
+ };
189
+ };
190
+
191
+ // pkgs/@akanjs/devkit/src/getRelatedCnsts.ts
192
+ var import_fs4 = __toESM(__require("fs"));
193
+ var import_ora = __toESM(__require("ora"));
194
+ var ts = __toESM(__require("typescript"));
195
+ var getRelatedCnsts = (constantFilePath) => {
196
+ const tsConfigPath = `./tsconfig.json`;
197
+ const configFile = ts.readConfigFile(tsConfigPath, (path5) => {
198
+ return ts.sys.readFile(path5);
199
+ });
200
+ const parsedConfig = ts.parseJsonConfigFileContent(
201
+ configFile.config,
202
+ ts.sys,
203
+ import_fs4.default.realpathSync(tsConfigPath).replace(/[^/\\]+$/, "")
204
+ );
205
+ const propertyMap = /* @__PURE__ */ new Map();
206
+ function findPropertyOriginAll(filePath) {
207
+ const program2 = ts.createProgram([filePath], parsedConfig.options);
208
+ const checker = program2.getTypeChecker();
209
+ const source = program2.getSourceFile(filePath);
210
+ if (!source)
211
+ return null;
212
+ function visit(node) {
213
+ if (!source)
214
+ return;
215
+ if (ts.isPropertyAccessExpression(node)) {
216
+ const left = node.expression;
217
+ const right = node.name;
218
+ const { line } = ts.getLineAndCharacterOfPosition(source, node.getStart());
219
+ const sourceLines = source.getFullText().split("\n");
220
+ if (ts.isIdentifier(left) && sourceLines.length && (sourceLines[line].includes(`@Field.Prop(() => ${left.text}.${right.text}`) || sourceLines[line].includes(`base.Filter(${left.text}.${right.text},`))) {
221
+ const symbol = checker.getSymbolAtLocation(right);
222
+ if (symbol?.declarations && symbol.declarations.length > 0) {
223
+ const key = symbol.declarations[0].getSourceFile().fileName.split("/").pop()?.split(".")[0] ?? "";
224
+ const property = propertyMap.get(key);
225
+ const isScalar = symbol.declarations[0].getSourceFile().fileName.includes("_");
226
+ const filePath2 = symbol.declarations[0].getSourceFile().fileName.replace(`${ts.sys.getCurrentDirectory()}/`, "");
227
+ if (property) {
228
+ propertyMap.set(`${left.text}.${right.text}`, {
229
+ filePath: filePath2,
230
+ isLibModule: true,
231
+ isImport: false,
232
+ libName: left.text,
233
+ isScalar
234
+ });
235
+ } else
236
+ propertyMap.set(key, {
237
+ filePath: filePath2,
238
+ isLibModule: true,
239
+ isImport: false,
240
+ libName: left.text,
241
+ isScalar
242
+ });
243
+ findPropertyOriginAll(filePath2);
244
+ }
245
+ }
246
+ } else if (ts.isImportDeclaration(node)) {
247
+ const importPath = node.moduleSpecifier.getText().slice(1, -1);
248
+ if (importPath.startsWith(".")) {
249
+ const resolved = ts.resolveModuleName(importPath, filePath, parsedConfig.options, ts.sys).resolvedModule?.resolvedFileName;
250
+ const moduleName = importPath.split("/").pop()?.split(".")[0] ?? "";
251
+ const property = propertyMap.get(moduleName);
252
+ const isScalar = importPath.includes("_");
253
+ if (moduleName && resolved && (!property || property.filePath !== resolved)) {
254
+ propertyMap.set(moduleName, {
255
+ filePath: resolved,
256
+ isLibModule: false,
257
+ isImport: true,
258
+ isScalar
259
+ });
260
+ findPropertyOriginAll(resolved);
261
+ }
262
+ }
263
+ }
264
+ ts.forEachChild(node, visit);
265
+ }
266
+ visit(source);
267
+ return propertyMap;
268
+ }
269
+ function findPropertyOrigin(filePath, aliasName, libName) {
270
+ const program2 = ts.createProgram([filePath], parsedConfig.options);
271
+ const checker = program2.getTypeChecker();
272
+ const source = program2.getSourceFile(filePath);
273
+ const propertyMap2 = /* @__PURE__ */ new Map();
274
+ if (!source)
275
+ return null;
276
+ function visit(node) {
277
+ if (ts.isPropertyAccessExpression(node)) {
278
+ const left = node.expression;
279
+ const right = node.name;
280
+ if (ts.isIdentifier(left) && left.text === aliasName && right.text === libName) {
281
+ const symbol = checker.getSymbolAtLocation(right);
282
+ if (symbol?.declarations && symbol.declarations.length > 0) {
283
+ return symbol.declarations[0].getSourceFile().fileName;
284
+ }
285
+ }
286
+ }
287
+ return ts.forEachChild(node, visit) || null;
288
+ }
289
+ return visit(source);
290
+ }
291
+ const spinner = (0, import_ora.default)("Finding property origin...");
292
+ spinner.start();
293
+ const paths = findPropertyOriginAll(constantFilePath);
294
+ spinner.succeed("property origin found.");
295
+ return { paths };
296
+ };
297
+
298
+ // pkgs/@akanjs/devkit/src/selectModel.ts
299
+ var import_prompts = __require("@inquirer/prompts");
300
+ var import_fs5 = __toESM(__require("fs"));
301
+ var selectModel = async (modulePath) => {
302
+ const modelNames = import_fs5.default.readdirSync(`${modulePath}/lib`).filter((dir) => !dir.includes(".") && !dir.startsWith("_"));
303
+ const modelName = await (0, import_prompts.select)({
304
+ message: "Select the model to create the unit for",
305
+ choices: modelNames.map((name) => ({ name, value: name }))
306
+ });
307
+ return modelName;
308
+ };
309
+
310
+ // pkgs/@akanjs/devkit/src/streamAi.ts
311
+ var import_prompts2 = __require("@langchain/core/prompts");
312
+ var import_runnables = __require("@langchain/core/runnables");
313
+ var import_openai = __require("@langchain/openai");
314
+ var streamAi = async (question, callback) => {
315
+ const createStreamingModel = (apiKey = process.env.DEEPSEEK_API_KEY) => {
316
+ if (!apiKey)
317
+ throw new Error(`process.env.DEEPSEEK_API_KEY is not set`);
318
+ return new import_openai.ChatOpenAI({
319
+ modelName: "deepseek-reasoner",
320
+ temperature: 0.7,
321
+ streaming: true,
322
+ // Enable streaming
323
+ configuration: { baseURL: "https://api.deepseek.com/v1", apiKey }
324
+ });
325
+ };
326
+ const createProcessingChain = () => {
327
+ return import_runnables.RunnableSequence.from([import_prompts2.PromptTemplate.fromTemplate(`Answer concisely: {question}`), createStreamingModel()]);
328
+ };
329
+ try {
330
+ const chain = createProcessingChain();
331
+ const stream = await chain.stream({ question });
332
+ let fullResponse = "";
333
+ for await (const chunk of stream) {
334
+ const content = chunk.content;
335
+ if (typeof content === "string") {
336
+ fullResponse += content;
337
+ callback(content);
338
+ }
339
+ }
340
+ return { content: fullResponse };
341
+ } catch (error) {
342
+ throw new Error("Failed to stream response");
343
+ }
344
+ };
345
+
346
+ // pkgs/@akanjs/common/src/isDayjs.ts
347
+ var import_dayjs = __require("dayjs");
348
+
349
+ // pkgs/@akanjs/common/src/isQueryEqual.ts
350
+ var import_dayjs2 = __toESM(__require("dayjs"));
351
+
352
+ // pkgs/@akanjs/common/src/isValidDate.ts
353
+ var import_dayjs3 = __toESM(__require("dayjs"));
354
+ var import_customParseFormat = __toESM(__require("dayjs/plugin/customParseFormat"));
355
+ import_dayjs3.default.extend(import_customParseFormat.default);
356
+
357
+ // pkgs/@akanjs/common/src/pluralize.ts
358
+ var import_pluralize = __toESM(__require("pluralize"));
359
+
360
+ // pkgs/@akanjs/common/src/capitalize.ts
361
+ var capitalize = (str) => {
362
+ return str.charAt(0).toUpperCase() + str.slice(1);
363
+ };
364
+
365
+ // pkgs/@akanjs/common/src/Logger.ts
366
+ var import_dayjs4 = __toESM(__require("dayjs"));
367
+ var logLevels = ["trace", "verbose", "debug", "log", "info", "warn", "error"];
368
+ var clc = {
369
+ bold: (text) => `\x1B[1m${text}\x1B[0m`,
370
+ green: (text) => `\x1B[32m${text}\x1B[39m`,
371
+ yellow: (text) => `\x1B[33m${text}\x1B[39m`,
372
+ red: (text) => `\x1B[31m${text}\x1B[39m`,
373
+ magentaBright: (text) => `\x1B[95m${text}\x1B[39m`,
374
+ cyanBright: (text) => `\x1B[96m${text}\x1B[39m`
375
+ };
376
+ var colorizeMap = {
377
+ trace: clc.bold,
378
+ verbose: clc.cyanBright,
379
+ debug: clc.magentaBright,
380
+ log: clc.green,
381
+ info: clc.green,
382
+ warn: clc.yellow,
383
+ error: clc.red
384
+ };
385
+ var Logger = class _Logger {
386
+ static #ignoreCtxSet = /* @__PURE__ */ new Set([
387
+ "InstanceLoader",
388
+ "RoutesResolver",
389
+ "RouterExplorer",
390
+ "NestFactory",
391
+ "WebSocketsController",
392
+ "GraphQLModule",
393
+ "NestApplication"
394
+ ]);
395
+ static level = process.env.NEXT_PUBLIC_LOG_LEVEL ?? "log";
396
+ static #levelIdx = logLevels.findIndex((l) => l === process.env.NEXT_PUBLIC_LOG_LEVEL);
397
+ static #startAt = (0, import_dayjs4.default)();
398
+ static setLevel(level) {
399
+ this.level = level;
400
+ this.#levelIdx = logLevels.findIndex((l) => l === level);
401
+ }
402
+ name;
403
+ constructor(name) {
404
+ this.name = name;
405
+ }
406
+ trace(msg, context = "") {
407
+ if (_Logger.#levelIdx <= 0)
408
+ _Logger.#printMessages(this.name ?? "App", msg, context, "trace");
409
+ }
410
+ verbose(msg, context = "") {
411
+ if (_Logger.#levelIdx <= 1)
412
+ _Logger.#printMessages(this.name ?? "App", msg, context, "verbose");
413
+ }
414
+ debug(msg, context = "") {
415
+ if (_Logger.#levelIdx <= 2)
416
+ _Logger.#printMessages(this.name ?? "App", msg, context, "debug");
417
+ }
418
+ log(msg, context = "") {
419
+ if (_Logger.#levelIdx <= 3)
420
+ _Logger.#printMessages(this.name ?? "App", msg, context, "log");
421
+ }
422
+ info(msg, context = "") {
423
+ if (_Logger.#levelIdx <= 4)
424
+ _Logger.#printMessages(this.name ?? "App", msg, context, "info");
425
+ }
426
+ warn(msg, context = "") {
427
+ if (_Logger.#levelIdx <= 5)
428
+ _Logger.#printMessages(this.name ?? "App", msg, context, "warn");
429
+ }
430
+ error(msg, context = "") {
431
+ if (_Logger.#levelIdx <= 6)
432
+ _Logger.#printMessages(this.name ?? "App", msg, context, "error");
433
+ }
434
+ raw(msg, method) {
435
+ _Logger.rawLog(msg, method);
436
+ }
437
+ rawLog(msg, method) {
438
+ _Logger.rawLog(msg, method);
439
+ }
440
+ static trace(msg, context = "") {
441
+ if (_Logger.#levelIdx <= 0)
442
+ _Logger.#printMessages("App", msg, context, "trace");
443
+ }
444
+ static verbose(msg, context = "") {
445
+ if (_Logger.#levelIdx <= 1)
446
+ _Logger.#printMessages("App", msg, context, "verbose");
447
+ }
448
+ static debug(msg, context = "") {
449
+ if (_Logger.#levelIdx <= 2)
450
+ _Logger.#printMessages("App", msg, context, "debug");
451
+ }
452
+ static log(msg, context = "") {
453
+ if (_Logger.#levelIdx <= 3)
454
+ _Logger.#printMessages("App", msg, context, "log");
455
+ }
456
+ static info(msg, context = "") {
457
+ if (_Logger.#levelIdx <= 4)
458
+ _Logger.#printMessages("App", msg, context, "info");
459
+ }
460
+ static warn(msg, context = "") {
461
+ if (_Logger.#levelIdx <= 5)
462
+ _Logger.#printMessages("App", msg, context, "warn");
463
+ }
464
+ static error(msg, context = "") {
465
+ if (_Logger.#levelIdx <= 6)
466
+ _Logger.#printMessages("App", msg, context, "error");
467
+ }
468
+ static #colorize(msg, logLevel) {
469
+ return colorizeMap[logLevel](msg);
470
+ }
471
+ static #printMessages(name, content, context, logLevel, writeStreamType = logLevel === "error" ? "stderr" : "stdout") {
472
+ if (this.#ignoreCtxSet.has(context))
473
+ return;
474
+ const now = (0, import_dayjs4.default)();
475
+ const processMsg = this.#colorize(
476
+ `[${name ?? "App"}] ${global.process?.pid ?? "window"} -`,
477
+ logLevel
478
+ );
479
+ const timestampMsg = now.format("MM/DD/YYYY, HH:mm:ss A");
480
+ const logLevelMsg = this.#colorize(logLevel.toUpperCase().padStart(7, " "), logLevel);
481
+ const contextMsg = context ? clc.yellow(`[${context}] `) : "";
482
+ const contentMsg = this.#colorize(content, logLevel);
483
+ const timeDiffMsg = clc.yellow(`+${now.diff(_Logger.#startAt, "ms")}ms`);
484
+ if (typeof window === "undefined")
485
+ process[writeStreamType].write(
486
+ `${processMsg} ${timestampMsg} ${logLevelMsg} ${contextMsg} ${contentMsg} ${timeDiffMsg}
487
+ `
488
+ );
489
+ else
490
+ console.log(`${processMsg} ${timestampMsg} ${logLevelMsg} ${contextMsg} ${contentMsg} ${timeDiffMsg}
491
+ `);
492
+ }
493
+ static rawLog(msg, method) {
494
+ this.raw(`${msg}
495
+ `, method);
496
+ }
497
+ static raw(msg, method) {
498
+ if (typeof window === "undefined" && method !== "console" && global.process)
499
+ global.process.stdout.write(msg);
500
+ else
501
+ console.log(msg);
502
+ }
503
+ };
504
+
505
+ // pkgs/@akanjs/config/src/akanConfig.ts
506
+ var import_fs6 = __toESM(__require("fs"));
507
+ var import_path2 = __toESM(__require("path"));
508
+
509
+ // pkgs/@akanjs/config/src/baseConfigEnv.ts
510
+ var getBaseConfigEnv = (appName2 = process.env.NEXT_PUBLIC_APP_NAME) => {
511
+ if (!appName2)
512
+ throw new Error("NEXT_PUBLIC_APP_NAME is not set");
513
+ const repoName2 = process.env.NEXT_PUBLIC_REPO_NAME;
514
+ if (!repoName2)
515
+ throw new Error("NEXT_PUBLIC_REPO_NAME is not set");
516
+ const serveDomain2 = process.env.NEXT_PUBLIC_SERVE_DOMAIN;
517
+ if (!serveDomain2)
518
+ throw new Error("NEXT_PUBLIC_SERVE_DOMAIN is not set");
519
+ const env2 = process.env.NEXT_PUBLIC_ENV ?? "debug";
520
+ if (!env2)
521
+ throw new Error("NEXT_PUBLIC_ENV is not set");
522
+ return { appName: appName2, repoName: repoName2, serveDomain: serveDomain2, env: env2 };
523
+ };
524
+
525
+ // pkgs/@akanjs/config/src/nextConfig.ts
526
+ var import_bundle_analyzer = __toESM(__require("@next/bundle-analyzer"));
527
+ var import_next_pwa = __toESM(__require("next-pwa"));
528
+ var import_cache = __toESM(__require("next-pwa/cache"));
529
+ var import_path = __toESM(__require("path"));
530
+ var composePlugins = (...plugins) => {
531
+ return function(baseConfig) {
532
+ return async function combined(phase, context) {
533
+ let config = baseConfig;
534
+ for (const plugin of plugins) {
535
+ const fn = plugin;
536
+ const configOrFn = fn(config);
537
+ if (typeof configOrFn === "function")
538
+ config = await configOrFn(phase, context);
539
+ else
540
+ config = configOrFn;
541
+ }
542
+ return config;
543
+ };
544
+ };
545
+ };
546
+ var commandType = process.env.AKAN_COMMAND_TYPE?.includes("serve") ? "serve" : process.env.AKAN_COMMAND_TYPE?.includes("build") ? "build" : "deploy";
547
+ var withPWA = (0, import_next_pwa.default)({
548
+ dest: "public",
549
+ register: true,
550
+ skipWaiting: true,
551
+ // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
552
+ runtimeCaching: import_cache.default,
553
+ disable: commandType === "serve"
554
+ });
555
+ var devDomain = process.env.NEXT_PUBLIC_SERVE_DOMAIN ?? "akanjs.com";
556
+ var withBase = (appName2, config, libs, routes = []) => {
557
+ return composePlugins(
558
+ (0, import_bundle_analyzer.default)({ enabled: process.env.ANALYZE === "true" }),
559
+ ...commandType !== "serve" || process.env.USE_PWA === "true" ? [withPWA] : []
560
+ )({
561
+ ...config,
562
+ eslint: { ...config.eslint, ignoreDuringBuilds: true },
563
+ env: {
564
+ ...config.env,
565
+ basePaths: routes.map(({ basePath: basePath2 }) => basePath2).join(",")
566
+ },
567
+ transpilePackages: [
568
+ "swiper",
569
+ "ssr-window",
570
+ "dom7",
571
+ ...libs.map((lib) => `@${lib}`),
572
+ "@akanjs/base",
573
+ "@akanjs/common",
574
+ "@akanjs/next",
575
+ "@akanjs/ui",
576
+ "@akanjs/client",
577
+ "@akanjs/server",
578
+ "@akanjs/service",
579
+ "@akanjs/signal",
580
+ "@akanjs/store",
581
+ "@akanjs/dictionary",
582
+ "@akanjs/constant",
583
+ "@akanjs/config",
584
+ "@akanjs/document"
585
+ ],
586
+ reactStrictMode: commandType === "serve" ? false : true,
587
+ experimental: {
588
+ ...config.experimental ?? {},
589
+ optimizePackageImports: [
590
+ ...[appName2, ...libs].map((lib) => [`@${lib}/ui`, `@${lib}/next`, `@${lib}/common`, `@${lib}/client`]).flat(),
591
+ "@contract",
592
+ "@akanjs/next",
593
+ "@akanjs/common"
594
+ ]
595
+ },
596
+ // modularizeImports: {
597
+ // "react-icons/?(((\\w*)?/?)*)": {
598
+ // transform: "@react-icons/all-files/{{ matches.[1] }}/{{member}}",
599
+ // skipDefaultConversion: true,
600
+ // },
601
+ // lodash: { transform: "lodash/{{member}}", preventFullImport: true },
602
+ // ...Object.fromEntries(
603
+ // [appName, ...libs].reduce(
604
+ // (acc, lib) => [
605
+ // ...acc,
606
+ // [`@${lib}/ui`, { transform: `@${lib}/ui/{{member}}`, skipDefaultConversion: true }],
607
+ // [`@${lib}/next`, { transform: `@${lib}/next/{{member}}`, skipDefaultConversion: true }],
608
+ // [`@${lib}/common`, { transform: `@${lib}/common/{{member}}`, skipDefaultConversion: true }],
609
+ // [`@${lib}/client`, { transform: `@${lib}/lib/{{ camelCase member }}`, skipDefaultConversion: true }],
610
+ // ],
611
+ // [
612
+ // ["@contract", { transform: `@contract/src/{{member}}`, skipDefaultConversion: true }],
613
+ // [`@akanjs/next`, { transform: `@akanjs/next/src/{{member}}`, skipDefaultConversion: true }],
614
+ // [`@akanjs/common`, { transform: `@akanjs/common/src/{{member}}`, skipDefaultConversion: true }],
615
+ // ]
616
+ // )
617
+ // ),
618
+ // ...(config.modularizeImports ?? {}),
619
+ // },
620
+ images: {
621
+ formats: ["image/avif", "image/webp"],
622
+ ...config.images ?? {},
623
+ remotePatterns: [
624
+ ...config.images?.remotePatterns ?? [],
625
+ ...routes.map(({ domains }) => [
626
+ ...domains.main?.map((domain) => ({ protocol: "https", hostname: `**.${domain}` })) ?? [],
627
+ ...domains.develop?.map((domain) => ({ protocol: "https", hostname: `**.${domain}` })) ?? [],
628
+ ...domains.debug?.map((domain) => ({ protocol: "https", hostname: `**.${domain}` })) ?? []
629
+ ]).flat(),
630
+ { protocol: "https", hostname: `**.${devDomain}` }
631
+ ]
632
+ },
633
+ webpack: (config2) => {
634
+ config2.resolve.alias.canvas = false;
635
+ config2.resolve.alias.encoding = false;
636
+ if (process.env.USE_AKANJS_PKGS === "true")
637
+ config2.resolve.alias["@akanjs/config"] = import_path.default.resolve(__dirname, "../../../../pkgs/@akanjs/config");
638
+ return config2;
639
+ },
640
+ redirects() {
641
+ return routes.map(({ basePath: basePath2, domains }) => [
642
+ { basePath: basePath2, domain: `${basePath2}-debug.${devDomain}` },
643
+ { basePath: basePath2, domain: `${basePath2}-develop.${devDomain}` },
644
+ { basePath: basePath2, domain: `${basePath2}-main.${devDomain}` },
645
+ ...domains.main?.map((domain) => ({ basePath: basePath2, domain })) ?? [],
646
+ ...domains.develop?.map((domain) => ({ basePath: basePath2, domain })) ?? [],
647
+ ...domains.debug?.map((domain) => ({ basePath: basePath2, domain })) ?? []
648
+ ]).flat().map(({ basePath: basePath2, domain }) => ({
649
+ source: `/:locale/${basePath2}/:path*`,
650
+ has: [{ type: "host", value: domain }],
651
+ permanent: true,
652
+ destination: "/:locale/:path*"
653
+ }));
654
+ },
655
+ rewrites() {
656
+ return routes.map(({ basePath: basePath2, domains }) => [
657
+ { basePath: basePath2, domain: `${basePath2}-debug.${devDomain}` },
658
+ { basePath: basePath2, domain: `${basePath2}-develop.${devDomain}` },
659
+ { basePath: basePath2, domain: `${basePath2}-main.${devDomain}` },
660
+ ...domains.main?.map((domain) => ({ basePath: basePath2, domain })) ?? [],
661
+ ...domains.develop?.map((domain) => ({ basePath: basePath2, domain })) ?? [],
662
+ ...domains.debug?.map((domain) => ({ basePath: basePath2, domain })) ?? []
663
+ ]).flat().map(({ basePath: basePath2, domain }) => [
664
+ {
665
+ source: "/:locale",
666
+ has: [{ type: "host", value: domain }],
667
+ destination: `/:locale/${basePath2}`
668
+ },
669
+ {
670
+ source: `/:locale/:path((?!${basePath2}$)(?!admin(?:/|$)).*)`,
671
+ has: [{ type: "host", value: domain }],
672
+ destination: `/:locale/${basePath2}/:path*`
673
+ }
674
+ ]).flat();
675
+ }
676
+ });
677
+ };
678
+
679
+ // pkgs/@akanjs/config/src/akanConfig.ts
680
+ var makeAppConfig = (config, props = {}) => {
681
+ const baseConfigEnv = getBaseConfigEnv(props.appName);
682
+ const {
683
+ appName: appName2 = baseConfigEnv.appName,
684
+ repoName: repoName2 = baseConfigEnv.repoName,
685
+ serveDomain: serveDomain2 = baseConfigEnv.serveDomain,
686
+ env: env2 = baseConfigEnv.env,
687
+ command = "build"
688
+ } = props;
689
+ return {
690
+ rootLib: config.rootLib,
691
+ libs: config.libs ?? [],
692
+ backend: {
693
+ dockerfile: config.backend?.dockerfile ?? `FROM node:22-slim
694
+ RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
695
+ RUN apt-get update && apt-get upgrade -y
696
+ RUN apt-get install -y ca-certificates fonts-liberation libappindicator3-1 libasound2 libatk-bridge2.0-0 libatk1.0-0 libc6 libcairo2 libcups2 libdbus-1-3 libexpat1 libfontconfig1 libgbm1 libgcc1 libglib2.0-0 libgtk-3-0 libnspr4 libnss3 libpango-1.0-0 libpangocairo-1.0-0 libstdc++6 libx11-6 libx11-xcb1 libxcb1 libxcomposite1 libxcursor1 libxdamage1 libxext6 libxfixes3 libxi6 libxrandr2 libxrender1 libxss1 libxtst6 lsb-release wget xdg-utils udev
697
+ ARG TARGETARCH
698
+ RUN if [ "$TARGETARCH" = "amd64" ]; then wget https://fastdl.mongodb.org/tools/db/mongodb-database-tools-debian92-x86_64-100.3.1.deb && apt-get install -y ./mongodb-database-tools-*.deb && rm -f mongodb-database-tools-*.deb; fi
699
+ RUN apt-get install -y git redis build-essential python3
700
+ RUN rm -rf /var/lib/apt/lists/*
701
+ RUN mkdir -p /workspace
702
+ WORKDIR /workspace
703
+ COPY ./package.json ./package.json
704
+ RUN npx pnpm i --prod
705
+ COPY . .
706
+ ENV PORT 8080
707
+ ENV NODE_OPTIONS=--max_old_space_size=8192
708
+ ENV NEXT_PUBLIC_REPO_NAME=${repoName2}
709
+ ENV NEXT_PUBLIC_SERVE_DOMAIN=${serveDomain2}
710
+ ENV NEXT_PUBLIC_APP_NAME=${appName2}
711
+ ENV NEXT_PUBLIC_ENV=${env2}
712
+ ENV NEXT_PUBLIC_OPERATION_MODE=cloud
713
+ CMD ["node", "main.js"]`,
714
+ explicitDependencies: config.backend?.explicitDependencies ?? []
715
+ },
716
+ frontend: {
717
+ dockerfile: config.frontend?.dockerfile ?? `FROM node:22-alpine
718
+ RUN ln -sf /usr/share/zoneinfo/Asia/Seoul /etc/localtime
719
+ RUN apk --no-cache add git
720
+ RUN mkdir -p /workspace
721
+ WORKDIR /workspace
722
+ COPY ./package.json ./package.json
723
+ RUN npx pnpm i --prod
724
+ COPY . .
725
+ ENV PORT 4200
726
+ ENV NODE_OPTIONS=--max_old_space_size=8192
727
+ ENV NEXT_PUBLIC_REPO_NAME=${repoName2}
728
+ ENV NEXT_PUBLIC_SERVE_DOMAIN=${serveDomain2}
729
+ ENV NEXT_PUBLIC_APP_NAME=${appName2}
730
+ ENV NEXT_PUBLIC_ENV=${env2}
731
+ ENV NEXT_PUBLIC_OPERATION_MODE=cloud
732
+ CMD ["npm", "start"]`,
733
+ nextConfig: withBase(
734
+ appName2,
735
+ config.frontend?.nextConfig ? typeof config.frontend.nextConfig === "function" ? config.frontend.nextConfig() : config.frontend.nextConfig : {},
736
+ config.libs ?? [],
737
+ config.frontend?.routes
738
+ ),
739
+ explicitDependencies: config.frontend?.explicitDependencies ?? []
740
+ }
741
+ };
742
+ };
743
+ var getAppConfig = async (appRoot, props) => {
744
+ const akanConfigPath = import_path2.default.join(appRoot, "akan.config.ts");
745
+ if (!import_fs6.default.existsSync(akanConfigPath))
746
+ throw new Error(`application akan.config.ts is not found ${appRoot}`);
747
+ const configImp = (await import(`${appRoot}/akan.config.ts`)).default;
748
+ const config = typeof configImp === "function" ? configImp(props) : configImp;
749
+ return makeAppConfig(config, props);
750
+ };
751
+ var makeLibConfig = (config, props = {}) => {
752
+ return {
753
+ rootLib: config.rootLib,
754
+ libs: config.libs ?? [],
755
+ backend: {
756
+ explicitDependencies: config.backend?.explicitDependencies ?? []
757
+ },
758
+ frontend: {
759
+ explicitDependencies: config.frontend?.explicitDependencies ?? []
760
+ }
761
+ };
762
+ };
763
+ var getLibConfig = async (libRoot, props) => {
764
+ const akanConfigPath = import_path2.default.join(libRoot, "akan.config.ts");
765
+ if (!import_fs6.default.existsSync(akanConfigPath))
766
+ throw new Error(`library akan.config.ts is not found ${libRoot}`);
767
+ const configImp = (await import(`${libRoot}/akan.config.ts`)).default;
768
+ const config = typeof configImp === "function" ? configImp(props) : configImp;
769
+ return makeLibConfig(config, props);
770
+ };
771
+
772
+ // pkgs/@akanjs/config/index.ts
773
+ var getDefaultFileScan = () => ({
774
+ constants: {
775
+ databases: [],
776
+ scalars: []
777
+ },
778
+ dictionary: {
779
+ databases: [],
780
+ services: [],
781
+ scalars: []
782
+ },
783
+ documents: {
784
+ databases: [],
785
+ scalars: []
786
+ },
787
+ services: {
788
+ databases: [],
789
+ services: [],
790
+ scalars: []
791
+ },
792
+ signal: {
793
+ databases: [],
794
+ services: [],
795
+ scalars: []
796
+ },
797
+ store: {
798
+ databases: [],
799
+ services: [],
800
+ scalars: []
801
+ },
802
+ components: {
803
+ databases: [],
804
+ services: [],
805
+ scalars: []
806
+ }
807
+ });
808
+
809
+ // pkgs/@akanjs/devkit/src/executors.ts
810
+ var import_child_process = __require("child_process");
811
+ var import_fs7 = __toESM(__require("fs"));
812
+ var import_promises = __toESM(__require("fs/promises"));
813
+ var import_path3 = __toESM(__require("path"));
814
+
815
+ // pkgs/@akanjs/devkit/src/dependencyScanner.ts
816
+ var fs7 = __toESM(__require("fs"));
817
+ var path3 = __toESM(__require("path"));
818
+ var ts2 = __toESM(__require("typescript"));
819
+ var TypeScriptDependencyScanner = class {
820
+ constructor(directory) {
821
+ this.directory = directory;
822
+ }
823
+ #fileDependencies = /* @__PURE__ */ new Map();
824
+ #visitedFiles = /* @__PURE__ */ new Set();
825
+ async getImportSets(depSets) {
826
+ const fileDependencies = await this.getDependencies();
827
+ const importedDepSets = new Array(depSets.length);
828
+ for (let i = 0; i < depSets.length; i++)
829
+ importedDepSets[i] = /* @__PURE__ */ new Set();
830
+ fileDependencies.forEach((imps) => {
831
+ imps.forEach((imp) => {
832
+ if (imp.startsWith("."))
833
+ return;
834
+ const moduleName = imp;
835
+ const moduleNameParts = moduleName.split("/");
836
+ const subModuleLength = moduleNameParts.length;
837
+ for (let i = 0; i < subModuleLength; i++) {
838
+ const importName = moduleNameParts.slice(0, i + 1).join("/");
839
+ for (let j = 0; j < depSets.length; j++) {
840
+ if (depSets[j].has(importName)) {
841
+ importedDepSets[j].add(importName);
842
+ return;
843
+ }
844
+ }
845
+ }
846
+ });
847
+ });
848
+ return importedDepSets;
849
+ }
850
+ async getDependencies() {
851
+ this.#fileDependencies.clear();
852
+ this.#visitedFiles.clear();
853
+ const files = await this.#findTypeScriptFiles(this.directory);
854
+ for (const file of files)
855
+ await this.#analyzeFile(file, this.directory);
856
+ return this.#fileDependencies;
857
+ }
858
+ async #findTypeScriptFiles(directory) {
859
+ const files = [];
860
+ const processDirectory = async (dir) => {
861
+ const entries = await fs7.promises.readdir(dir, { withFileTypes: true });
862
+ for (const entry of entries) {
863
+ const fullPath = path3.join(dir, entry.name);
864
+ if (entry.isDirectory()) {
865
+ if (!["node_modules", "dist", "build", ".git", ".next", "public", "ios", "android"].includes(entry.name))
866
+ await processDirectory(fullPath);
867
+ } else if (entry.isFile() && (entry.name.endsWith(".ts") || entry.name.endsWith(".tsx")))
868
+ files.push(fullPath);
869
+ }
870
+ };
871
+ await processDirectory(directory);
872
+ return files;
873
+ }
874
+ async #analyzeFile(filePath, baseDir) {
875
+ if (this.#visitedFiles.has(filePath))
876
+ return;
877
+ this.#visitedFiles.add(filePath);
878
+ try {
879
+ const fileContent = await fs7.promises.readFile(filePath, "utf-8");
880
+ const imports = this.#extractImports(fileContent, filePath);
881
+ const resolvedImports = imports.map((importPath) => {
882
+ if (importPath.startsWith(".")) {
883
+ const resolvedPath = "./" + path3.join(path3.relative(baseDir, filePath), importPath);
884
+ return this.#ensureExtension(resolvedPath);
885
+ }
886
+ return importPath;
887
+ });
888
+ const relativePath = path3.relative(baseDir, filePath);
889
+ this.#fileDependencies.set(relativePath, resolvedImports);
890
+ } catch (error) {
891
+ }
892
+ }
893
+ #ensureExtension(filePath) {
894
+ if (fs7.existsSync(`${filePath}.ts`))
895
+ return `${filePath}.ts`;
896
+ else if (fs7.existsSync(`${filePath}.tsx`))
897
+ return `${filePath}.tsx`;
898
+ else if (fs7.existsSync(filePath))
899
+ return filePath;
900
+ return `${filePath}.ts`;
901
+ }
902
+ #extractImports(source, filePath) {
903
+ const imports = [];
904
+ const sourceFile = ts2.createSourceFile(filePath, source, ts2.ScriptTarget.Latest, true);
905
+ const visit = (node) => {
906
+ if (ts2.isImportDeclaration(node)) {
907
+ const moduleSpecifier = node.moduleSpecifier;
908
+ if (ts2.isStringLiteral(moduleSpecifier))
909
+ imports.push(moduleSpecifier.text);
910
+ }
911
+ ts2.forEachChild(node, visit);
912
+ };
913
+ visit(sourceFile);
914
+ return imports;
915
+ }
916
+ generateDependencyGraph() {
917
+ let graph = "Dependency Graph:\n\n";
918
+ for (const [file, imports] of this.#fileDependencies.entries()) {
919
+ graph += `${file}:
920
+ `;
921
+ const projectImports = imports.filter((i) => !i.startsWith("react") && !i.startsWith("@"));
922
+ const externalImports = imports.filter((i) => i.startsWith("react") || i.startsWith("@"));
923
+ if (projectImports.length > 0) {
924
+ graph += " Project dependencies:\n";
925
+ projectImports.forEach((imp) => {
926
+ graph += ` \u2192 ${imp}
927
+ `;
928
+ });
929
+ }
930
+ if (externalImports.length > 0) {
931
+ graph += " External dependencies:\n";
932
+ externalImports.forEach((imp) => {
933
+ graph += ` \u2192 ${imp}
934
+ `;
935
+ });
936
+ }
937
+ graph += "\n";
938
+ }
939
+ return graph;
940
+ }
941
+ };
942
+
943
+ // pkgs/@akanjs/devkit/src/executors.ts
944
+ var Executor = class {
945
+ logger;
946
+ cwdPath;
947
+ constructor(name, cwdPath) {
948
+ this.logger = new Logger(name);
949
+ this.cwdPath = cwdPath;
950
+ if (!import_fs7.default.existsSync(cwdPath))
951
+ import_fs7.default.mkdirSync(cwdPath, { recursive: true });
952
+ }
953
+ exec(command, options = {}) {
954
+ const proc = (0, import_child_process.exec)(command, { cwd: this.cwdPath, ...options });
955
+ proc.stdout?.on("data", (data) => {
956
+ Logger.raw(data.toString());
957
+ });
958
+ proc.stderr?.on("data", (data) => {
959
+ Logger.raw(data.toString());
960
+ });
961
+ return new Promise((resolve, reject) => {
962
+ proc.on("exit", (code, signal) => {
963
+ if (!!code || signal)
964
+ reject({ code, signal });
965
+ else
966
+ resolve({ code, signal });
967
+ });
968
+ });
969
+ }
970
+ spawn(command, args = [], options = {}) {
971
+ const proc = (0, import_child_process.spawn)(command, args, { cwd: this.cwdPath, stdio: "inherit", ...options });
972
+ proc.stderr?.on("data", (data) => {
973
+ Logger.raw(data.toString());
974
+ });
975
+ return new Promise((resolve, reject) => {
976
+ proc.on("exit", (code, signal) => {
977
+ if (!!code || signal)
978
+ reject({ code, signal });
979
+ else
980
+ resolve({ code, signal });
981
+ });
982
+ });
983
+ }
984
+ fork(modulePath, args = [], options = {}) {
985
+ const proc = (0, import_child_process.fork)(modulePath, args, {
986
+ cwd: this.cwdPath,
987
+ stdio: ["ignore", "inherit", "inherit", "ipc"],
988
+ ...options
989
+ });
990
+ proc.stdout?.on("data", (data) => {
991
+ Logger.raw(data.toString());
992
+ });
993
+ proc.stderr?.on("data", (data) => {
994
+ Logger.raw(data.toString());
995
+ });
996
+ return new Promise((resolve, reject) => {
997
+ proc.on("exit", (code, signal) => {
998
+ if (!!code || signal)
999
+ reject({ code, signal });
1000
+ else
1001
+ resolve({ code, signal });
1002
+ });
1003
+ });
1004
+ }
1005
+ mkdir(dirPath) {
1006
+ const writePath = import_path3.default.isAbsolute(dirPath) ? dirPath : `${this.cwdPath}/${dirPath}`;
1007
+ if (!import_fs7.default.existsSync(writePath))
1008
+ import_fs7.default.mkdirSync(writePath, { recursive: true });
1009
+ this.logger.verbose(`Make directory ${writePath}`);
1010
+ return this;
1011
+ }
1012
+ writeFile(filePath, content) {
1013
+ const writePath = import_path3.default.isAbsolute(filePath) ? filePath : `${this.cwdPath}/${filePath}`;
1014
+ const dir = import_path3.default.dirname(writePath);
1015
+ if (!import_fs7.default.existsSync(dir))
1016
+ import_fs7.default.mkdirSync(dir, { recursive: true });
1017
+ const contentStr = typeof content === "string" ? content : JSON.stringify(content, null, 2);
1018
+ if (import_fs7.default.existsSync(writePath)) {
1019
+ const currentContent = import_fs7.default.readFileSync(writePath, "utf8");
1020
+ if (currentContent === contentStr)
1021
+ this.logger.verbose(`File ${writePath} is unchanged`);
1022
+ else {
1023
+ import_fs7.default.writeFileSync(writePath, contentStr, "utf8");
1024
+ this.logger.debug(`File ${writePath} is changed`);
1025
+ }
1026
+ } else {
1027
+ import_fs7.default.writeFileSync(writePath, contentStr, "utf8");
1028
+ this.logger.debug(`File ${writePath} is created`);
1029
+ }
1030
+ return this;
1031
+ }
1032
+ writeJson(filePath, content) {
1033
+ this.writeFile(filePath, JSON.stringify(content, null, 2));
1034
+ return this;
1035
+ }
1036
+ readFile(filePath) {
1037
+ const readPath = import_path3.default.isAbsolute(filePath) ? filePath : `${this.cwdPath}/${filePath}`;
1038
+ return import_fs7.default.readFileSync(readPath, "utf8");
1039
+ }
1040
+ readJson(filePath) {
1041
+ const readPath = import_path3.default.isAbsolute(filePath) ? filePath : `${this.cwdPath}/${filePath}`;
1042
+ return JSON.parse(import_fs7.default.readFileSync(readPath, "utf8"));
1043
+ }
1044
+ async cp(srcPath, destPath) {
1045
+ const src = import_path3.default.isAbsolute(srcPath) ? srcPath : `${this.cwdPath}/${srcPath}`;
1046
+ const dest = import_path3.default.isAbsolute(destPath) ? destPath : `${this.cwdPath}/${destPath}`;
1047
+ await import_promises.default.cp(src, dest, { recursive: true });
1048
+ }
1049
+ log(msg) {
1050
+ this.logger.info(msg);
1051
+ return this;
1052
+ }
1053
+ verbose(msg) {
1054
+ this.logger.verbose(msg);
1055
+ return this;
1056
+ }
1057
+ getTsConfig(pathname) {
1058
+ const tsconfig = this.readJson(pathname);
1059
+ if (tsconfig.extends) {
1060
+ const extendsTsconfig = this.getTsConfig(tsconfig.extends);
1061
+ return {
1062
+ ...extendsTsconfig,
1063
+ ...tsconfig,
1064
+ compilerOptions: { ...extendsTsconfig.compilerOptions, ...tsconfig.compilerOptions }
1065
+ };
1066
+ }
1067
+ return tsconfig;
1068
+ }
1069
+ async #applyTemplateFile({
1070
+ templatePath,
1071
+ targetPath,
1072
+ scanResult
1073
+ }, dict = {}) {
1074
+ if (targetPath.endsWith(".js")) {
1075
+ const getContent = await import(templatePath);
1076
+ const content = getContent.default(scanResult ?? null, dict);
1077
+ const convertedTargetPath = Object.entries(dict).reduce(
1078
+ (path5, [key, value]) => path5.replace(new RegExp(`__${key}__`, "g"), value),
1079
+ targetPath.replace(".js", ".ts")
1080
+ );
1081
+ if (content === null)
1082
+ return;
1083
+ this.logger.verbose(`Apply template ${templatePath} to ${convertedTargetPath}`);
1084
+ this.writeFile(convertedTargetPath, content);
1085
+ } else if (targetPath.endsWith(".template")) {
1086
+ const content = await import_promises.default.readFile(templatePath, "utf8");
1087
+ const convertedTargetPath = Object.entries(dict).reduce(
1088
+ (path5, [key, value]) => path5.replace(new RegExp(`__${key}__`, "g"), value),
1089
+ targetPath.slice(0, -9)
1090
+ );
1091
+ const convertedContent = Object.entries(dict).reduce(
1092
+ (content2, [key, value]) => content2.replace(new RegExp(`<%= ${key} %>`, "g"), value),
1093
+ content
1094
+ );
1095
+ this.logger.verbose(`Apply template ${templatePath} to ${convertedTargetPath}`);
1096
+ this.writeFile(convertedTargetPath, convertedContent);
1097
+ }
1098
+ }
1099
+ async applyTemplate({
1100
+ basePath: basePath2,
1101
+ template,
1102
+ scanResult,
1103
+ dict = {}
1104
+ }) {
1105
+ const templatePath = `${__dirname}/src/templates${template ? `/${template}` : ""}`.replace(".ts", ".js");
1106
+ if (import_fs7.default.statSync(templatePath).isFile()) {
1107
+ const filename = import_path3.default.basename(templatePath);
1108
+ await this.#applyTemplateFile({ templatePath, targetPath: import_path3.default.join(basePath2, filename), scanResult }, dict);
1109
+ } else {
1110
+ if (!import_fs7.default.existsSync(basePath2))
1111
+ await import_promises.default.mkdir(basePath2, { recursive: true });
1112
+ const subdirs = await import_promises.default.readdir(templatePath);
1113
+ await Promise.all(
1114
+ subdirs.map(async (subdir) => {
1115
+ const subpath = import_path3.default.join(templatePath, subdir);
1116
+ if (import_fs7.default.statSync(subpath).isFile())
1117
+ await this.#applyTemplateFile(
1118
+ { templatePath: subpath, targetPath: import_path3.default.join(basePath2, subdir), scanResult },
1119
+ dict
1120
+ );
1121
+ else
1122
+ await this.applyTemplate({
1123
+ basePath: import_path3.default.join(basePath2, subdir),
1124
+ template: import_path3.default.join(template, subdir),
1125
+ scanResult,
1126
+ dict
1127
+ });
1128
+ })
1129
+ );
1130
+ }
1131
+ }
1132
+ };
1133
+ var WorkspaceExecutor = class _WorkspaceExecutor extends Executor {
1134
+ workspaceRoot;
1135
+ repoName;
1136
+ constructor({ workspaceRoot, repoName: repoName2 }) {
1137
+ super(`${repoName2} Executor`, workspaceRoot);
1138
+ this.workspaceRoot = workspaceRoot;
1139
+ this.repoName = repoName2;
1140
+ }
1141
+ static fromRoot() {
1142
+ const repoName2 = import_path3.default.basename(process.cwd());
1143
+ return new _WorkspaceExecutor({ workspaceRoot: process.cwd(), repoName: repoName2 });
1144
+ }
1145
+ async scan() {
1146
+ const [appNames, libNames, pkgNames] = await Promise.all([this.getApps(), this.getLibs(), this.getPkgs()]);
1147
+ const [appScanResults, libScanResults, pkgScanResults] = await Promise.all([
1148
+ Promise.all(
1149
+ appNames.map(async (appName2) => {
1150
+ const app = AppExecutor.from(this, appName2);
1151
+ const akanConfig = await app.getConfig("scan");
1152
+ return await app.scan({ akanConfig });
1153
+ })
1154
+ ),
1155
+ Promise.all(
1156
+ libNames.map(async (libName) => {
1157
+ const lib = LibExecutor.from(this, libName);
1158
+ const akanConfig = await lib.getConfig("scan");
1159
+ return await lib.scan({ akanConfig });
1160
+ })
1161
+ ),
1162
+ Promise.all(
1163
+ pkgNames.map(async (pkgName) => {
1164
+ return await PkgExecutor.from(this, pkgName).scan();
1165
+ })
1166
+ )
1167
+ ]);
1168
+ return {
1169
+ appNames,
1170
+ libNames,
1171
+ pkgNames,
1172
+ apps: Object.fromEntries(appScanResults.map((app) => [app.name, app])),
1173
+ libs: Object.fromEntries(libScanResults.map((lib) => [lib.name, lib])),
1174
+ pkgs: Object.fromEntries(pkgScanResults.map((pkg) => [pkg.name, pkg]))
1175
+ };
1176
+ }
1177
+ async getApps() {
1178
+ return await this.#getDirHasFile(`${this.workspaceRoot}/apps`, "akan.config.ts");
1179
+ }
1180
+ async getLibs() {
1181
+ return await this.#getDirHasFile(`${this.workspaceRoot}/libs`, "akan.config.ts");
1182
+ }
1183
+ async getSyss() {
1184
+ const [appNames, libNames] = await Promise.all([this.getApps(), this.getLibs()]);
1185
+ return [appNames, libNames];
1186
+ }
1187
+ async getPkgs() {
1188
+ return await this.#getDirHasFile(`${this.workspaceRoot}/pkgs`, "package.json");
1189
+ }
1190
+ async #getDirHasFile(basePath2, targetFilename) {
1191
+ const AVOID_DIRS = ["node_modules", "dist", "public", "./next"];
1192
+ const getDirs = async (dirname, maxDepth = 3, results = [], prefix = "") => {
1193
+ const dirs = await import_promises.default.readdir(dirname);
1194
+ await Promise.all(
1195
+ dirs.map(async (dir) => {
1196
+ if (AVOID_DIRS.includes(dir))
1197
+ return;
1198
+ const dirPath = import_path3.default.join(dirname, dir);
1199
+ if (import_fs7.default.lstatSync(dirPath).isDirectory()) {
1200
+ const hasTargetFile = import_fs7.default.existsSync(import_path3.default.join(dirPath, targetFilename));
1201
+ if (hasTargetFile)
1202
+ results.push(`${prefix}${dir}`);
1203
+ if (maxDepth > 0)
1204
+ await getDirs(dirPath, maxDepth - 1, results, `${prefix}${dir}/`);
1205
+ }
1206
+ })
1207
+ );
1208
+ return results;
1209
+ };
1210
+ return await getDirs(basePath2);
1211
+ }
1212
+ };
1213
+ var SysExecutor = class extends Executor {
1214
+ workspace;
1215
+ name;
1216
+ type;
1217
+ constructor({ workspace = WorkspaceExecutor.fromRoot(), name, type }) {
1218
+ super(`${name} Sys Executor`, `${workspace.workspaceRoot}/${type}s/${name}`);
1219
+ this.workspace = workspace;
1220
+ this.name = name;
1221
+ this.type = type;
1222
+ }
1223
+ async getConfig(command) {
1224
+ return this.type === "app" ? await getAppConfig(this.cwdPath, { ...baseDevEnv, appName: this.name, command }) : await getLibConfig(this.cwdPath, { ...baseDevEnv, appName: this.name, command });
1225
+ }
1226
+ async scan({
1227
+ tsconfig = this.getTsConfig(`${this.cwdPath}/tsconfig.json`),
1228
+ akanConfig
1229
+ }, libScanResults = {}) {
1230
+ if (libScanResults[this.name])
1231
+ return libScanResults[this.name];
1232
+ const rootPackageJson = this.readJson(`${this.workspace.workspaceRoot}/package.json`);
1233
+ const scanner = new TypeScriptDependencyScanner(this.cwdPath);
1234
+ const npmSet = new Set(Object.keys({ ...rootPackageJson.dependencies, ...rootPackageJson.devDependencies }));
1235
+ const pkgPathSet = new Set(
1236
+ Object.keys(tsconfig.compilerOptions.paths).filter((path5) => tsconfig.compilerOptions.paths[path5].some((resolve) => resolve.startsWith("pkgs/"))).map((path5) => path5.replace("/*", ""))
1237
+ );
1238
+ const libPathSet = new Set(
1239
+ Object.keys(tsconfig.compilerOptions.paths).filter((path5) => tsconfig.compilerOptions.paths[path5].some((resolve) => resolve.startsWith("libs/"))).map((path5) => path5.replace("/*", ""))
1240
+ );
1241
+ const [npmDepSet, pkgPathDepSet, libPathDepSet] = await scanner.getImportSets([npmSet, pkgPathSet, libPathSet]);
1242
+ const pkgDeps = [...pkgPathDepSet].map((path5) => {
1243
+ const pathSplitLength = path5.split("/").length;
1244
+ return tsconfig.compilerOptions.paths[path5][0].split("/").slice(1, 1 + pathSplitLength).join("/");
1245
+ });
1246
+ const libDeps = [...libPathDepSet].map((path5) => {
1247
+ const pathSplitLength = path5.split("/").length;
1248
+ return tsconfig.compilerOptions.paths[path5][0].split("/").slice(1, 1 + pathSplitLength).join("/");
1249
+ }).filter((libName) => libName !== this.name);
1250
+ if (!import_fs7.default.existsSync(`${this.cwdPath}/lib/__scalar`))
1251
+ import_fs7.default.mkdirSync(`${this.cwdPath}/lib/__scalar`, { recursive: true });
1252
+ const files = getDefaultFileScan();
1253
+ const dirnames = (await import_promises.default.readdir(`${this.cwdPath}/lib`)).filter(
1254
+ (name) => import_fs7.default.lstatSync(`${this.cwdPath}/lib/${name}`).isDirectory()
1255
+ );
1256
+ const databaseDirs = dirnames.filter((name) => !name.startsWith("_"));
1257
+ const serviceDirs = dirnames.filter((name) => name.startsWith("_") && !name.startsWith("__"));
1258
+ await Promise.all(
1259
+ databaseDirs.map(async (name) => {
1260
+ const filenames = await import_promises.default.readdir(import_path3.default.join(this.cwdPath, "lib", name));
1261
+ filenames.forEach((filename) => {
1262
+ if (filename.endsWith(".constant.ts"))
1263
+ files.constants.databases.push(name);
1264
+ else if (filename.endsWith(".dictionary.ts"))
1265
+ files.dictionary.databases.push(name);
1266
+ else if (filename.endsWith(".document.ts"))
1267
+ files.documents.databases.push(name);
1268
+ else if (filename.endsWith(".service.ts"))
1269
+ files.services.databases.push(name);
1270
+ else if (filename.endsWith(".signal.ts"))
1271
+ files.signal.databases.push(name);
1272
+ else if (filename.endsWith(".store.ts"))
1273
+ files.store.databases.push(name);
1274
+ else if (filename === "index.tsx")
1275
+ files.components.databases.push(name);
1276
+ });
1277
+ })
1278
+ );
1279
+ await Promise.all(
1280
+ serviceDirs.map(async (dirname) => {
1281
+ const name = dirname.slice(1);
1282
+ const filenames = await import_promises.default.readdir(import_path3.default.join(this.cwdPath, "lib", dirname));
1283
+ filenames.forEach((filename) => {
1284
+ if (filename.endsWith(".dictionary.ts"))
1285
+ files.dictionary.services.push(name);
1286
+ else if (filename.endsWith(".service.ts"))
1287
+ files.services.services.push(name);
1288
+ else if (filename.endsWith(".signal.ts"))
1289
+ files.signal.services.push(name);
1290
+ else if (filename.endsWith(".store.ts"))
1291
+ files.store.services.push(name);
1292
+ else if (filename === "index.tsx")
1293
+ files.components.services.push(name);
1294
+ });
1295
+ })
1296
+ );
1297
+ const scalarDirs = (await import_promises.default.readdir(`${this.cwdPath}/lib/__scalar`)).filter(
1298
+ (name) => !name.startsWith("_")
1299
+ );
1300
+ await Promise.all(
1301
+ scalarDirs.map(async (name) => {
1302
+ const filenames = await import_promises.default.readdir(import_path3.default.join(this.cwdPath, "lib/__scalar", name));
1303
+ filenames.forEach((filename) => {
1304
+ if (filename.endsWith(".constant.ts"))
1305
+ files.constants.scalars.push(name);
1306
+ else if (filename.endsWith(".dictionary.ts"))
1307
+ files.dictionary.scalars.push(name);
1308
+ else if (filename.endsWith(".document.ts"))
1309
+ files.documents.scalars.push(name);
1310
+ else if (filename.endsWith(".service.ts"))
1311
+ files.services.scalars.push(name);
1312
+ else if (filename.endsWith(".signal.ts"))
1313
+ files.signal.scalars.push(name);
1314
+ else if (filename.endsWith(".store.ts"))
1315
+ files.store.scalars.push(name);
1316
+ else if (filename === "index.ts")
1317
+ files.components.scalars.push(name);
1318
+ });
1319
+ })
1320
+ );
1321
+ const missingLibDeps = [];
1322
+ libDeps.forEach((libName) => {
1323
+ if (!akanConfig.libs.includes(libName))
1324
+ missingLibDeps.push(libName);
1325
+ });
1326
+ if (missingLibDeps.length)
1327
+ throw new Error(
1328
+ `Missing libs: ${missingLibDeps.join(", ")}, add these dependencies in akan.config.ts as { libs: [...other deps, ${missingLibDeps.join(", ")}] }`
1329
+ );
1330
+ for (const libName of libDeps) {
1331
+ if (libScanResults[libName])
1332
+ continue;
1333
+ const lib = new LibExecutor({ workspace: this.workspace, name: libName });
1334
+ const akanConfig2 = await lib.getConfig();
1335
+ libScanResults[libName] = await lib.scan({ akanConfig: akanConfig2 }, libScanResults);
1336
+ }
1337
+ const scanResult = {
1338
+ name: this.name,
1339
+ type: this.type,
1340
+ akanConfig,
1341
+ files,
1342
+ libDeps,
1343
+ pkgDeps,
1344
+ dependencies: [...npmDepSet],
1345
+ libs: Object.fromEntries(libDeps.map((libName) => [libName, libScanResults[libName]]))
1346
+ };
1347
+ await this.applyTemplate({ basePath: "lib", template: "lib", scanResult });
1348
+ await this.applyTemplate({ basePath: ".", template: "server.ts", scanResult });
1349
+ await this.applyTemplate({ basePath: ".", template: "client.ts", scanResult });
1350
+ if (this.type === "lib")
1351
+ await this.applyTemplate({ basePath: ".", template: "index.ts", scanResult });
1352
+ this.writeJson(`akan.${this.type}.json`, scanResult);
1353
+ return scanResult;
1354
+ }
1355
+ async getDatabaseModules() {
1356
+ const databaseModules = (await import_promises.default.readdir(`${this.cwdPath}/lib`)).filter((name) => !name.startsWith("_")).filter((name) => import_fs7.default.existsSync(`${this.cwdPath}/lib/${name}/${name}.constant.ts`));
1357
+ return databaseModules;
1358
+ }
1359
+ async getServiceModules() {
1360
+ const serviceModules = (await import_promises.default.readdir(`${this.cwdPath}/lib`)).filter((name) => name.startsWith("_") && !name.startsWith("__")).filter((name) => import_fs7.default.existsSync(`${this.cwdPath}/lib/${name}/${name}.service.ts`));
1361
+ return serviceModules;
1362
+ }
1363
+ async getScalarModules() {
1364
+ const scalarModules = (await import_promises.default.readdir(`${this.cwdPath}/lib/__scalar`)).filter((name) => !name.startsWith("_")).filter((name) => import_fs7.default.existsSync(`${this.cwdPath}/lib/__scalar/${name}/${name}.constant.ts`));
1365
+ return scalarModules;
1366
+ }
1367
+ };
1368
+ var AppExecutor = class _AppExecutor extends SysExecutor {
1369
+ constructor({ workspace, name }) {
1370
+ super({ workspace, name, type: "app" });
1371
+ }
1372
+ static from(executor, name) {
1373
+ if (executor instanceof WorkspaceExecutor)
1374
+ return new _AppExecutor({ workspace: executor, name });
1375
+ return new _AppExecutor({ workspace: executor.workspace, name });
1376
+ }
1377
+ async getConfig(command) {
1378
+ return await getAppConfig(this.cwdPath, { ...baseDevEnv, appName: this.name, command });
1379
+ }
1380
+ async syncAssets(libDeps) {
1381
+ const projectPublicLibPath = `${this.cwdPath}/public/libs`;
1382
+ if (import_fs7.default.existsSync(projectPublicLibPath))
1383
+ await import_promises.default.rm(projectPublicLibPath, { recursive: true });
1384
+ const targetDeps = libDeps.filter((dep) => import_fs7.default.existsSync(`${this.workspace.workspaceRoot}/libs/${dep}/public`));
1385
+ await Promise.all(targetDeps.map((dep) => import_promises.default.mkdir(`${projectPublicLibPath}/${dep}`, { recursive: true })));
1386
+ await Promise.all(
1387
+ targetDeps.map(
1388
+ (dep) => import_promises.default.cp(`${this.workspace.workspaceRoot}/libs/${dep}/public`, `${projectPublicLibPath}/${dep}`, {
1389
+ recursive: true
1390
+ })
1391
+ )
1392
+ );
1393
+ }
1394
+ };
1395
+ var DistAppExecutor = class _DistAppExecutor extends Executor {
1396
+ name;
1397
+ constructor({ workspace, name }) {
1398
+ super(`${name} Dist App Executor`, `${workspace.workspaceRoot}/dist/apps/${name}`);
1399
+ this.name = name;
1400
+ }
1401
+ static from(executor, name) {
1402
+ if (executor instanceof WorkspaceExecutor)
1403
+ return new _DistAppExecutor({ workspace: executor, name });
1404
+ return new _DistAppExecutor({ workspace: executor.workspace, name });
1405
+ }
1406
+ };
1407
+ var LibExecutor = class _LibExecutor extends SysExecutor {
1408
+ workspaceRoot;
1409
+ repoName;
1410
+ constructor({ workspace, name }) {
1411
+ super({ workspace, name, type: "lib" });
1412
+ }
1413
+ static from(executor, name) {
1414
+ if (executor instanceof WorkspaceExecutor)
1415
+ return new _LibExecutor({ workspace: executor, name });
1416
+ return new _LibExecutor({ workspace: executor.workspace, name });
1417
+ }
1418
+ async getConfig(command) {
1419
+ return await getLibConfig(this.cwdPath, { ...baseDevEnv, appName: this.name, command });
1420
+ }
1421
+ };
1422
+ var DistLibExecutor = class _DistLibExecutor extends Executor {
1423
+ name;
1424
+ constructor({ workspace, name }) {
1425
+ super(`${name} Dist Lib Executor`, `${workspace.workspaceRoot}/dist/libs/${name}`);
1426
+ this.name = name;
1427
+ }
1428
+ static from(executor, name) {
1429
+ if (executor instanceof WorkspaceExecutor)
1430
+ return new DistAppExecutor({ workspace: executor, name });
1431
+ return new _DistLibExecutor({ workspace: executor.workspace, name });
1432
+ }
1433
+ };
1434
+ var PkgExecutor = class _PkgExecutor extends Executor {
1435
+ workspace;
1436
+ name;
1437
+ constructor({ workspace = WorkspaceExecutor.fromRoot(), name }) {
1438
+ super(`${name} Pkg Executor`, `${workspace.workspaceRoot}/pkgs/${name}`);
1439
+ this.workspace = workspace;
1440
+ this.name = name;
1441
+ }
1442
+ static from(executor, name) {
1443
+ if (executor instanceof WorkspaceExecutor)
1444
+ return new _PkgExecutor({ workspace: executor, name });
1445
+ return new _PkgExecutor({ workspace: executor.workspace, name });
1446
+ }
1447
+ async scan({
1448
+ packageJson = this.readJson(`${this.cwdPath}/package.json`),
1449
+ tsconfig = this.getTsConfig(`${this.cwdPath}/tsconfig.json`)
1450
+ } = {}) {
1451
+ const rootPackageJson = this.readJson(`${this.workspace.workspaceRoot}/package.json`);
1452
+ const scanner = new TypeScriptDependencyScanner(this.cwdPath);
1453
+ const npmSet = new Set(Object.keys({ ...rootPackageJson.dependencies, ...rootPackageJson.devDependencies }));
1454
+ const pkgPathSet = new Set(
1455
+ Object.keys(tsconfig.compilerOptions.paths).filter((path5) => tsconfig.compilerOptions.paths[path5].some((resolve) => resolve.startsWith("pkgs/"))).map((path5) => path5.replace("/*", ""))
1456
+ );
1457
+ const [npmDepSet, pkgPathDepSet] = await scanner.getImportSets([npmSet, pkgPathSet]);
1458
+ const pkgDeps = [...pkgPathDepSet].map((path5) => {
1459
+ const pathSplitLength = path5.split("/").length;
1460
+ return tsconfig.compilerOptions.paths[path5][0].split("/").slice(1, 1 + pathSplitLength).join("/");
1461
+ }).filter((pkg) => pkg !== this.name);
1462
+ const pkgScanResult = {
1463
+ name: this.name,
1464
+ pkgDeps,
1465
+ dependencies: [...npmDepSet]
1466
+ };
1467
+ return pkgScanResult;
1468
+ }
1469
+ };
1470
+ var DistPkgExecutor = class _DistPkgExecutor extends Executor {
1471
+ workspaceRoot;
1472
+ repoName;
1473
+ name;
1474
+ constructor({ workspaceRoot, repoName: repoName2, name }) {
1475
+ super(`${name} Dist Pkg Executor`, `${workspaceRoot}/dist/pkgs/${name}`);
1476
+ this.workspaceRoot = workspaceRoot;
1477
+ this.repoName = repoName2;
1478
+ this.name = name;
1479
+ }
1480
+ static from(workspaceExecutor, name) {
1481
+ return new _DistPkgExecutor({
1482
+ workspaceRoot: workspaceExecutor.workspaceRoot,
1483
+ repoName: workspaceExecutor.repoName,
1484
+ name
1485
+ });
1486
+ }
1487
+ };
1488
+
1489
+ // pkgs/@akanjs/devkit/src/constants.ts
1490
+ var import_os = __require("os");
1491
+ var basePath = `${(0, import_os.homedir)()}/.akan`;
1492
+ var configPath = `${basePath}/config.json`;
1493
+ var akanCloudHost = process.env.NEXT_PUBLIC_OPERATION_MODE === "local" ? "http://localhost" : "https://akasys-debug.akamir.com";
1494
+ var akanCloudBackendUrl = `${akanCloudHost}${process.env.NEXT_PUBLIC_OPERATION_MODE === "local" ? ":8080" : ""}/backend`;
1495
+ var akanCloudClientUrl = `${akanCloudHost}${process.env.NEXT_PUBLIC_OPERATION_MODE === "local" ? ":4200" : ""}`;
1496
+ var defaultHostConfig = {};
1497
+ var defaultAkanGlobalConfig = {};
1498
+
1499
+ // pkgs/@akanjs/devkit/src/auth.ts
1500
+ var import_fs8 = __toESM(__require("fs"));
1501
+ var getAkanGlobalConfig = () => {
1502
+ const akanConfig = import_fs8.default.existsSync(configPath) ? JSON.parse(import_fs8.default.readFileSync(configPath, "utf8")) : defaultAkanGlobalConfig;
1503
+ return akanConfig;
1504
+ };
1505
+ var setAkanGlobalConfig = (akanConfig) => {
1506
+ import_fs8.default.mkdirSync(basePath, { recursive: true });
1507
+ import_fs8.default.writeFileSync(configPath, JSON.stringify(akanConfig, null, 2));
1508
+ };
1509
+ var getHostConfig = (host = akanCloudHost) => {
1510
+ const akanConfig = getAkanGlobalConfig();
1511
+ return akanConfig[host] ?? defaultHostConfig;
1512
+ };
1513
+ var setHostConfig = (host = akanCloudHost, config = {}) => {
1514
+ const akanConfig = getAkanGlobalConfig();
1515
+ akanConfig[host] = config;
1516
+ setAkanGlobalConfig(akanConfig);
1517
+ };
1518
+ var getSelf = async (token) => {
1519
+ try {
1520
+ const res = await fetch(`${akanCloudBackendUrl}/user/getSelf`, { headers: { Authorization: `Bearer ${token}` } });
1521
+ const user = await res.json();
1522
+ return user;
1523
+ } catch (e) {
1524
+ return null;
1525
+ }
1526
+ };
1527
+
1528
+ // pkgs/@akanjs/devkit/src/capacitorApp.ts
1529
+ var import_project = __require("@trapezedev/project");
1530
+ var import_fs9 = __toESM(__require("fs"));
1531
+ var CapacitorApp = class {
1532
+ constructor(app) {
1533
+ this.app = app;
1534
+ }
1535
+ project;
1536
+ iosTargetName = "App";
1537
+ async init() {
1538
+ const project = new import_project.MobileProject(this.app.cwdPath, {
1539
+ android: { path: "android" },
1540
+ ios: { path: "ios/App" }
1541
+ });
1542
+ await project.load();
1543
+ if (!project.android)
1544
+ throw new Error(`Android is not added, Please add platform first
1545
+ akan serve-android ${this.app.name}`);
1546
+ if (!project.ios)
1547
+ throw new Error(`iOS is not added, Please add platform first
1548
+ akan serve-ios ${this.app.name}`);
1549
+ this.project = project;
1550
+ return this;
1551
+ }
1552
+ async save() {
1553
+ await this.project.commit();
1554
+ }
1555
+ async releaseIos() {
1556
+ const isAdded = import_fs9.default.existsSync(`${this.app.cwdPath}/ios/App/Podfile`);
1557
+ if (!isAdded) {
1558
+ await this.app.spawn("npx cap add ios");
1559
+ await this.app.spawn("npx @capacitor/assets generate");
1560
+ } else
1561
+ this.app.log(`iOS already added, skip adding process`);
1562
+ await this.app.spawn("cross-env", ["APP_OPERATION_MODE=release", "npx", "cap", "sync", "ios"]);
1563
+ }
1564
+ async releaseAndroid() {
1565
+ const isAdded = import_fs9.default.existsSync(`${this.app.cwdPath}/android/app/build.gradle`);
1566
+ if (!isAdded) {
1567
+ await this.app.spawn("npx cap add android");
1568
+ await this.app.spawn("npx @capacitor/assets generate");
1569
+ } else
1570
+ this.app.log(`android already added, skip adding process`);
1571
+ await this.app.spawn("cross-env", ["APP_OPERATION_MODE=release", "npx", "cap", "sync", "android"]);
1572
+ }
1573
+ async addCamera() {
1574
+ await this.#setPermissionInIos({
1575
+ cameraUsageDescription: "$(PRODUCT_NAME) requires access to the camera to take photos.",
1576
+ photoAddUsageDescription: "$(PRODUCT_NAME) requires access to the photo library to take photos.",
1577
+ photoUsageDescription: "$(PRODUCT_NAME) requires access to the photo library to take photos."
1578
+ });
1579
+ this.#setPermissionsInAndroid(["READ_MEDIA_IMAGES", "READ_EXTERNAL_STORAGE", "WRITE_EXTERNAL_STORAGE"]);
1580
+ }
1581
+ async addContact() {
1582
+ await this.#setPermissionInIos({
1583
+ contactsUsageDescription: "$(PRODUCT_NAME) requires access to the contacts to add new contacts."
1584
+ });
1585
+ this.#setPermissionsInAndroid(["READ_CONTACTS", "WRITE_CONTACTS"]);
1586
+ }
1587
+ async addLocation() {
1588
+ await this.#setPermissionInIos({
1589
+ locationAlwaysUsageDescription: "$(PRODUCT_NAME) requires access to the location to get the user's location.",
1590
+ locationWhenInUseUsageDescription: "$(PRODUCT_NAME) requires access to the location to get the user's location."
1591
+ });
1592
+ this.#setPermissionsInAndroid(["ACCESS_COARSE_LOCATION", "ACCESS_FINE_LOCATION"]);
1593
+ this.#setFeaturesInAndroid(["android.hardware.location.gps"]);
1594
+ }
1595
+ async #setPermissionInIos(permissions) {
1596
+ const updateNs = Object.fromEntries(
1597
+ Object.entries(permissions).map(([key, value]) => [`NS${capitalize(key)}`, value])
1598
+ );
1599
+ await Promise.all([
1600
+ this.project.ios.updateInfoPlist(this.iosTargetName, "Debug", updateNs),
1601
+ this.project.ios.updateInfoPlist(this.iosTargetName, "Release", updateNs)
1602
+ ]);
1603
+ }
1604
+ #setFeaturesInAndroid(features) {
1605
+ for (const feature of features) {
1606
+ if (this.#hasFeatureInAndroid(feature)) {
1607
+ this.app.logger.info(`${feature} already exists in android`);
1608
+ return this;
1609
+ }
1610
+ this.app.logger.info(`Adding ${feature} to android`);
1611
+ this.project.android.getAndroidManifest().injectFragment("manifest", `<uses-feature android:name="${feature}" />`);
1612
+ }
1613
+ return this;
1614
+ }
1615
+ #getFeaturesInAndroid() {
1616
+ const androidManifest = this.project.android.getAndroidManifest();
1617
+ const element = androidManifest.getDocumentElement();
1618
+ if (!element)
1619
+ throw new Error("manifest not found");
1620
+ const usesFeature = element.getElementsByTagName("uses-feature");
1621
+ return Array.from(usesFeature).map((feature) => feature.getAttribute("android:name"));
1622
+ }
1623
+ #hasFeatureInAndroid(feature) {
1624
+ return this.#getFeaturesInAndroid().includes(feature);
1625
+ }
1626
+ #setPermissionsInAndroid(permissions) {
1627
+ for (const permission of permissions) {
1628
+ if (this.#hasPermissionInAndroid(permission)) {
1629
+ this.app.logger.info(`${permission} already exists in android`);
1630
+ return this;
1631
+ }
1632
+ this.app.logger.info(`Adding ${permission} to android`);
1633
+ this.project.android.getAndroidManifest().injectFragment("manifest", `<uses-permission android:name="android.permission.${permission}" />`);
1634
+ }
1635
+ return this;
1636
+ }
1637
+ #getPermissionsInAndroid() {
1638
+ const androidManifest = this.project.android.getAndroidManifest();
1639
+ const element = androidManifest.getDocumentElement();
1640
+ if (!element)
1641
+ throw new Error("manifest not found");
1642
+ const usesPermission = element.getElementsByTagName("uses-permission");
1643
+ return Array.from(usesPermission).map((permission) => permission.getAttribute("android:name"));
1644
+ }
1645
+ #hasPermissionInAndroid(permission) {
1646
+ return this.#getPermissionsInAndroid().includes(permission);
1647
+ }
1648
+ };
1649
+
1650
+ // pkgs/@akanjs/devkit/src/extractDeps.ts
1651
+ var fs11 = __toESM(__require("fs"));
1652
+ var NODE_NATIVE_MODULE_SET = /* @__PURE__ */ new Set([
1653
+ "assert",
1654
+ "async_hooks",
1655
+ "buffer",
1656
+ "child_process",
1657
+ "cluster",
1658
+ "console",
1659
+ "constants",
1660
+ "crypto",
1661
+ "dgram",
1662
+ "dns",
1663
+ "domain",
1664
+ "events",
1665
+ "fs",
1666
+ "http",
1667
+ "http2",
1668
+ "https",
1669
+ "inspector",
1670
+ "module",
1671
+ "net",
1672
+ "os",
1673
+ "path",
1674
+ "perf_hooks",
1675
+ "process",
1676
+ "punycode",
1677
+ "querystring",
1678
+ "readline",
1679
+ "repl",
1680
+ "stream",
1681
+ "string_decoder",
1682
+ "timers",
1683
+ "tls",
1684
+ "trace_events",
1685
+ "tty",
1686
+ "url",
1687
+ "util",
1688
+ "v8",
1689
+ "vm",
1690
+ "wasi",
1691
+ "worker_threads",
1692
+ "zlib"
1693
+ ]);
1694
+ var extractDependencies = (bundlePath, pacakgeJson, defaultDependencies = []) => {
1695
+ if (!pacakgeJson.dependencies)
1696
+ throw new Error("No dependencies found in package.json");
1697
+ const code = fs11.readFileSync(bundlePath, "utf8");
1698
+ const dependencies = new Set(defaultDependencies);
1699
+ const existingDependencies = /* @__PURE__ */ new Set([
1700
+ ...Object.keys(pacakgeJson.dependencies ?? {}),
1701
+ ...Object.keys(pacakgeJson.devDependencies ?? {})
1702
+ ]);
1703
+ const versionObj = {
1704
+ ...pacakgeJson.dependencies ?? {},
1705
+ ...pacakgeJson.devDependencies ?? {}
1706
+ };
1707
+ const requireRegex = /require\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/g;
1708
+ let requireMatch;
1709
+ while ((requireMatch = requireRegex.exec(code)) !== null) {
1710
+ const moduleName = requireMatch[1];
1711
+ const moduleNameParts = moduleName.split("/");
1712
+ const subModuleLength = moduleNameParts.length;
1713
+ for (let i = 0; i < subModuleLength; i++) {
1714
+ const libName = moduleNameParts.slice(0, i + 1).join("/");
1715
+ if (!NODE_NATIVE_MODULE_SET.has(libName) && existingDependencies.has(libName))
1716
+ dependencies.add(libName);
1717
+ }
1718
+ }
1719
+ return Object.fromEntries(
1720
+ [...dependencies].sort().map((dep) => {
1721
+ const version = versionObj[dep];
1722
+ if (!version)
1723
+ throw new Error(`No version found for ${dep}`);
1724
+ return [dep, version];
1725
+ })
1726
+ );
1727
+ };
1728
+
1729
+ // pkgs/@akanjs/devkit/src/commandDecorators/argMeta.ts
1730
+ var import_reflect_metadata = __require("reflect-metadata");
1731
+ var argTypes = ["Option"];
1732
+ var internalArgTypes = ["Workspace", "App", "Lib", "Sys", "Pkg"];
1733
+ var getArgMetas = (command, key) => {
1734
+ const allArgMetas = getArgMetasOnPrototype(command.prototype, key);
1735
+ const argMetas = allArgMetas.filter((argMeta) => argMeta.type === "Option");
1736
+ const internalArgMetas = allArgMetas.filter((argMeta) => argMeta.type !== "Option");
1737
+ return [allArgMetas, argMetas, internalArgMetas];
1738
+ };
1739
+ var getArgMetasOnPrototype = (prototype, key) => {
1740
+ return Reflect.getMetadata("args", prototype, key) ?? [];
1741
+ };
1742
+ var setArgMetasOnPrototype = (prototype, key, argMetas) => {
1743
+ Reflect.defineMetadata("args", argMetas, prototype, key);
1744
+ };
1745
+ var getArg = (type) => function(name, argsOption = {}) {
1746
+ return function(prototype, key, idx) {
1747
+ const argMetas = getArgMetasOnPrototype(prototype, key);
1748
+ argMetas[idx] = { name, argsOption, key, idx, type };
1749
+ setArgMetasOnPrototype(prototype, key, argMetas);
1750
+ };
1751
+ };
1752
+ var Option = getArg("Option");
1753
+ var createArgMetaDecorator = (type) => {
1754
+ return function(option = {}) {
1755
+ return function(prototype, key, idx) {
1756
+ const argMetas = getArgMetasOnPrototype(prototype, key);
1757
+ argMetas[idx] = { key, idx, type, option };
1758
+ setArgMetasOnPrototype(prototype, key, argMetas);
1759
+ };
1760
+ };
1761
+ };
1762
+ var App = createArgMetaDecorator("App");
1763
+ var Lib = createArgMetaDecorator("Lib");
1764
+ var Sys = createArgMetaDecorator("Sys");
1765
+ var Pkg = createArgMetaDecorator("Pkg");
1766
+ var Workspace = createArgMetaDecorator("Workspace");
1767
+
1768
+ // pkgs/@akanjs/devkit/src/commandDecorators/commandMeta.ts
1769
+ var Commands = () => {
1770
+ return function(target) {
1771
+ };
1772
+ };
1773
+
1774
+ // pkgs/@akanjs/devkit/src/commandDecorators/targetMeta.ts
1775
+ var getTargetMetas = (command) => {
1776
+ const targetMetaMap = Reflect.getMetadata("target", command.prototype);
1777
+ if (!targetMetaMap)
1778
+ throw new Error(`TargetMeta is not defined for ${command.name}`);
1779
+ return [...targetMetaMap.values()];
1780
+ };
1781
+ var getTargetMetaMapOnPrototype = (prototype) => {
1782
+ const targetMetaMap = Reflect.getMetadata("target", prototype);
1783
+ return targetMetaMap ?? /* @__PURE__ */ new Map();
1784
+ };
1785
+ var setTargetMetaMapOnPrototype = (prototype, targetMetaMap) => {
1786
+ Reflect.defineMetadata("target", targetMetaMap, prototype);
1787
+ };
1788
+ var getTarget = (type) => (targetOption = {}) => {
1789
+ return (prototype, key, descriptor) => {
1790
+ const metadataMap = getTargetMetaMapOnPrototype(prototype);
1791
+ metadataMap.set(key, {
1792
+ key,
1793
+ descriptor,
1794
+ targetOption: { ...targetOption, type }
1795
+ });
1796
+ setTargetMetaMapOnPrototype(prototype, metadataMap);
1797
+ };
1798
+ };
1799
+ var Target = {
1800
+ Public: getTarget("public"),
1801
+ Cloud: getTarget("cloud"),
1802
+ Dev: getTarget("dev")
1803
+ };
1804
+
1805
+ // pkgs/@akanjs/devkit/src/commandDecorators/command.ts
1806
+ var import_prompts3 = __require("@inquirer/prompts");
1807
+ var import_commander = __require("commander");
1808
+ var camelToKebabCase = (str) => str.replace(/([A-Z])/g, "-$1").toLowerCase();
1809
+ var handleOption = (programCommand, argMeta) => {
1810
+ const {
1811
+ type,
1812
+ flag = argMeta.name.slice(0, 1).toLowerCase(),
1813
+ desc = argMeta.name,
1814
+ example,
1815
+ enum: choices,
1816
+ ask
1817
+ } = argMeta.argsOption;
1818
+ const kebabName = camelToKebabCase(argMeta.name);
1819
+ programCommand.option(
1820
+ `-${flag}, --${kebabName} <${kebabName}>`,
1821
+ `${desc}${ask ? ` (${ask})` : ""}${example ? ` (example: ${example})` : ""}${choices ? ` (choices: ${choices.join(", ")})` : ""}`
1822
+ );
1823
+ return programCommand;
1824
+ };
1825
+ var convertOptionValue = (value, type) => {
1826
+ if (type === "string")
1827
+ return value;
1828
+ else if (type === "number")
1829
+ return Number(value);
1830
+ else
1831
+ return value === "true";
1832
+ };
1833
+ var getOptionValue = async (argMeta, opt) => {
1834
+ const {
1835
+ name,
1836
+ argsOption: { enum: choices, default: defaultValue, type, desc, nullable, example, ask }
1837
+ } = argMeta;
1838
+ if (opt[argMeta.name] !== void 0)
1839
+ return convertOptionValue(opt[argMeta.name], type ?? "string");
1840
+ else if (defaultValue !== void 0)
1841
+ return defaultValue;
1842
+ else if (nullable)
1843
+ return null;
1844
+ if (choices) {
1845
+ const choice = await (0, import_prompts3.select)({
1846
+ message: ask ?? `Select the ${name} value`,
1847
+ choices: choices.map((choice2) => choice2.toString())
1848
+ });
1849
+ return choice;
1850
+ } else if (type === "boolean") {
1851
+ const message = ask ?? `Do you want to set ${name}? ${desc ? ` (${desc})` : ""}: `;
1852
+ return await (0, import_prompts3.confirm)({ message });
1853
+ } else {
1854
+ const message = ask ?? `Enter the ${name} value${example ? ` (example: ${example})` : ""}: `;
1855
+ if (argMeta.argsOption.nullable)
1856
+ return await (0, import_prompts3.input)({ message });
1857
+ else
1858
+ return convertOptionValue(await (0, import_prompts3.input)({ message }), type ?? "string");
1859
+ }
1860
+ };
1861
+ var getArgumentValue = async (argMeta, value, workspace) => {
1862
+ if (argMeta.type === "Workspace")
1863
+ return workspace;
1864
+ const sysType = argMeta.type.toLowerCase();
1865
+ if (sysType === "sys") {
1866
+ const [appNames, libNames] = await workspace.getSyss();
1867
+ const sysName = await (0, import_prompts3.select)({
1868
+ message: `Select the App or Lib name`,
1869
+ choices: [...appNames, ...libNames]
1870
+ });
1871
+ if (appNames.includes(sysName))
1872
+ return AppExecutor.from(workspace, sysName);
1873
+ else
1874
+ return LibExecutor.from(workspace, sysName);
1875
+ } else if (sysType === "app") {
1876
+ if (value)
1877
+ return AppExecutor.from(workspace, value);
1878
+ const apps = await workspace.getApps();
1879
+ const appName2 = await (0, import_prompts3.select)({ message: `Select the ${sysType} name`, choices: apps });
1880
+ return AppExecutor.from(workspace, appName2);
1881
+ } else if (sysType === "lib") {
1882
+ if (value)
1883
+ return LibExecutor.from(workspace, value);
1884
+ const libs = await workspace.getLibs();
1885
+ const libName = await (0, import_prompts3.select)({ message: `Select the ${sysType} name`, choices: libs });
1886
+ return LibExecutor.from(workspace, libName);
1887
+ } else if (sysType === "pkg") {
1888
+ if (value)
1889
+ return PkgExecutor.from(workspace, value);
1890
+ const pkgs = await workspace.getPkgs();
1891
+ const pkgName = await (0, import_prompts3.select)({ message: `Select the ${sysType} name`, choices: pkgs });
1892
+ return PkgExecutor.from(workspace, pkgName);
1893
+ } else
1894
+ throw new Error(`Invalid system type: ${argMeta.type}`);
1895
+ };
1896
+ var runCommands = async (...commands) => {
1897
+ import_commander.program.version("0.0.1").description("An example CLI for managing a directory");
1898
+ for (const command of commands) {
1899
+ const targetMetas = getTargetMetas(command);
1900
+ for (const targetMeta of targetMetas) {
1901
+ const kebabKey = camelToKebabCase(targetMeta.key);
1902
+ const commandNames = targetMeta.targetOption.short === true ? [
1903
+ kebabKey,
1904
+ typeof targetMeta.targetOption.short === "string" ? targetMeta.targetOption.short : kebabKey.split("-").map((s) => s.slice(0, 1)).join("")
1905
+ ] : [kebabKey];
1906
+ for (const commandName of commandNames) {
1907
+ let programCommand = import_commander.program.command(commandName, {
1908
+ hidden: targetMeta.targetOption.devOnly
1909
+ });
1910
+ const [allArgMetas] = getArgMetas(command, targetMeta.key);
1911
+ for (const argMeta of allArgMetas) {
1912
+ if (argMeta.type === "Option")
1913
+ programCommand = handleOption(programCommand, argMeta);
1914
+ else if (argMeta.type === "Workspace")
1915
+ continue;
1916
+ const sysType = argMeta.type.toLowerCase();
1917
+ programCommand = programCommand.argument(
1918
+ `[${sysType}]`,
1919
+ `${sysType} in this workspace ${sysType}s/<${sysType}Name>`
1920
+ );
1921
+ }
1922
+ programCommand.action(async (...args) => {
1923
+ const cmdArgs = args.slice(0, args.length - 2);
1924
+ const opt = args[args.length - 2];
1925
+ const commandArgs = [];
1926
+ const workspace = WorkspaceExecutor.fromRoot();
1927
+ for (const argMeta of allArgMetas) {
1928
+ if (argMeta.type === "Option")
1929
+ commandArgs[argMeta.idx] = await getOptionValue(argMeta, opt);
1930
+ else
1931
+ commandArgs[argMeta.idx] = await getArgumentValue(argMeta, cmdArgs[argMeta.idx], workspace);
1932
+ }
1933
+ const cmd = new command();
1934
+ await cmd[targetMeta.key](...commandArgs);
1935
+ });
1936
+ }
1937
+ }
1938
+ }
1939
+ await import_commander.program.parseAsync(process.argv);
1940
+ };
1941
+
1942
+ // pkgs/@akanjs/devkit/src/installExternalLib.ts
1943
+ var installExternalLib = async (libName, workspace) => {
1944
+ workspace.log(`Installing ${libName} library as git subtree...`);
1945
+ await workspace.exec(`git remote add ${libName} git@github.com:akan-team/${libName}.git`);
1946
+ await workspace.exec(`git subtree add --prefix=libs/${libName} ${libName} main`);
1947
+ };
1948
+ })();
1949
+ //!Field.Prop 거르기가 빡세네.
1950
+ //! Temp