@xrystal/core 3.51.5 → 3.52.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +35 -1
- package/package.json +1 -1
- package/x/bin/commands/create.mjs +44 -0
- package/x/bin/commands/projects.mjs +53 -0
- package/x/bin/commands/sync.mjs +49 -1
- package/x/bin/commands/tmp.mjs +1 -1
- package/x/bin/helpers/.generated/.generated-from +2 -0
- package/x/bin/helpers/.generated/seed-from-tmp.mjs +25 -31
- package/x/bin/helpers/.generated/tmp-schema.mjs +156 -96
- package/x/bin/helpers/.generated/workspace.mjs +402 -0
- package/x/bin/helpers/.generated/xrystal-home-registry.mjs +310 -0
- package/x/bin/helpers/build-config.mjs +3 -2
- package/x/bin/helpers/cli-help.mjs +3 -1
- package/x/bin/helpers/project-artifacts.mjs +9 -0
- package/x/bin/helpers/tmp-config.mjs +13 -12
- package/x/bin/helpers/tmp-layout.mjs +28 -52
- package/x/bin/helpers/tmp-schema.mjs +9 -3
- package/x/bin/helpers/workspace-resolve.mjs +11 -0
- package/x/bin/helpers/workspace-scaffold.mjs +23 -0
- package/x/bin/helpers/xrystal-registry.mjs +13 -0
- package/x/bin/main-cli.js +2 -0
- package/x/dist/index.js +5 -1
- package/x/dist/loader/clients/index.js +22 -1
- package/x/dist/loader/configs/index.js +97 -1
- package/x/dist/loader/controller/index.js +267 -1
- package/x/dist/loader/dto/index.js +92 -1
- package/x/dist/loader/events/index.js +39 -1
- package/x/dist/loader/index.js +13 -1
- package/x/dist/loader/kafka/index.js +142 -1
- package/x/dist/loader/kafka/resolve-ssl.js +23 -1
- package/x/dist/loader/localizations/index.js +46 -1
- package/x/dist/loader/logger/index.js +229 -2
- package/x/dist/loader/mongo/index.js +52 -1
- package/x/dist/loader/mongo/resolve-connect.js +16 -1
- package/x/dist/loader/redis/index.js +57 -1
- package/x/dist/loader/redis/resolve-socket.js +31 -1
- package/x/dist/loader/registry/index.js +1 -1
- package/x/dist/loader/service/index.js +7 -1
- package/x/dist/loader/system/index.js +26 -1
- package/x/dist/project/index.js +51 -1
- package/x/dist/utils/constants/defaults.json +3 -1
- package/x/dist/utils/constants/index.d.ts +1 -0
- package/x/dist/utils/constants/index.js +42 -1
- package/x/dist/utils/constants/package-root.js +6 -1
- package/x/dist/utils/helpers/configs/index.js +1 -1
- package/x/dist/utils/helpers/context/controller-store.js +12 -1
- package/x/dist/utils/helpers/context/index.js +24 -1
- package/x/dist/utils/helpers/core/handlebars-resolve.js +15 -1
- package/x/dist/utils/helpers/core/index.js +46 -1
- package/x/dist/utils/helpers/core/paths.js +78 -1
- package/x/dist/utils/helpers/core/tmp-layout.d.ts +4 -4
- package/x/dist/utils/helpers/core/tmp-layout.js +229 -1
- package/x/dist/utils/helpers/date/index.js +48 -1
- package/x/dist/utils/helpers/dispatch/index.js +53 -1
- package/x/dist/utils/helpers/dto/index.js +10 -1
- package/x/dist/utils/helpers/filters/index.js +44 -1
- package/x/dist/utils/helpers/framework/index.js +18 -1
- package/x/dist/utils/helpers/handlers/adapters.js +41 -1
- package/x/dist/utils/helpers/handlers/execute.js +82 -1
- package/x/dist/utils/helpers/handlers/index.js +31 -1
- package/x/dist/utils/helpers/hash/crypto.js +22 -1
- package/x/dist/utils/helpers/id/index.js +24 -1
- package/x/dist/utils/helpers/index.d.ts +1 -0
- package/x/dist/utils/helpers/index.js +28 -1
- package/x/dist/utils/helpers/ip/index.js +21 -1
- package/x/dist/utils/helpers/is/index.js +35 -1
- package/x/dist/utils/helpers/kafka-loader-options/index.js +14 -1
- package/x/dist/utils/helpers/locales/index.js +82 -1
- package/x/dist/utils/helpers/logger-layer/index.js +33 -1
- package/x/dist/utils/helpers/math/index.js +14 -1
- package/x/dist/utils/helpers/middleware/index.js +36 -1
- package/x/dist/utils/helpers/node-env/index.js +20 -1
- package/x/dist/utils/helpers/objects/index.js +55 -1
- package/x/dist/utils/helpers/path/index.js +5 -1
- package/x/dist/utils/helpers/path/resolve-alias-path.d.ts +1 -1
- package/x/dist/utils/helpers/path/resolve-alias-path.js +62 -1
- package/x/dist/utils/helpers/protocol/index.d.ts +1 -1
- package/x/dist/utils/helpers/protocol/index.js +100 -1
- package/x/dist/utils/helpers/protocol/options.js +13 -1
- package/x/dist/utils/helpers/regex/checkSpecialRegexControl.js +3 -1
- package/x/dist/utils/helpers/registry/index.d.ts +6 -0
- package/x/dist/utils/helpers/registry/index.js +103 -1
- package/x/dist/utils/helpers/runtime/dto-access.js +5 -1
- package/x/dist/utils/helpers/runtime/dto-types.js +1 -1
- package/x/dist/utils/helpers/runtime/index.js +2 -1
- package/x/dist/utils/helpers/runtime/shutdown.js +36 -1
- package/x/dist/utils/helpers/state/index.js +185 -1
- package/x/dist/utils/helpers/state/props-from-tmp.js +46 -1
- package/x/dist/utils/helpers/state/request-key-guard.js +43 -1
- package/x/dist/utils/helpers/state/scopes.js +69 -1
- package/x/dist/utils/helpers/string/index.js +9 -1
- package/x/dist/utils/helpers/timer/index.js +5 -1
- package/x/dist/utils/helpers/tmp/index.d.ts +2 -2
- package/x/dist/utils/helpers/tmp/index.js +8 -1
- package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +14 -1
- package/x/dist/utils/helpers/tmp/path-normalize.js +27 -1
- package/x/dist/utils/helpers/tmp/runtime-tmp.js +42 -1
- package/x/dist/utils/helpers/tmp/seed-from-tmp.d.ts +2 -2
- package/x/dist/utils/helpers/tmp/seed-from-tmp.js +62 -1
- package/x/dist/utils/helpers/tmp/tmp-interpolate.js +22 -1
- package/x/dist/utils/helpers/tmp/tmp-loader.js +56 -1
- package/x/dist/utils/helpers/tmp/tmp-schema.d.ts +35 -23
- package/x/dist/utils/helpers/tmp/tmp-schema.js +211 -1
- package/x/dist/utils/helpers/tmp/tmp-watch.js +23 -1
- package/x/dist/utils/helpers/tmp/toolchain-heal.js +157 -2
- package/x/dist/utils/helpers/validates/index.js +20 -1
- package/x/dist/utils/helpers/workspace/index.d.ts +42 -0
- package/x/dist/utils/helpers/workspace/index.js +222 -0
- package/x/dist/utils/helpers/xrystal-home/registry.d.ts +32 -0
- package/x/dist/utils/helpers/xrystal-home/registry.js +92 -0
- package/x/dist/utils/index.js +3 -1
- package/x/dist/utils/models/classes/class.clients.js +142 -1
- package/x/dist/utils/models/classes/class.interfaces.js +10 -1
- package/x/dist/utils/models/classes/class.service-locator.js +16 -1
- package/x/dist/utils/models/classes/class.tmp-file-loader.js +61 -1
- package/x/dist/utils/models/classes/class.x.js +181 -1
- package/x/dist/utils/models/enums/index.d.ts +9 -1
- package/x/dist/utils/models/enums/index.js +169 -1
- package/x/dist/utils/models/index.js +9 -1
- package/x/dist/utils/models/types/index.js +2 -1
- package/x/tmp.yml +7 -50
|
@@ -0,0 +1,222 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { GlobalTypeEnum } from '../../../utils/models/enums/index.js';
|
|
4
|
+
import { normalizeGlobalType } from '../../../utils/helpers/tmp/tmp-schema.js';
|
|
5
|
+
export const TMP_FILE = 'tmp.yml';
|
|
6
|
+
export const SKIP_DIRS = new Set(['node_modules', '.git', 'dist', '.turbo', 'coverage']);
|
|
7
|
+
export const DEFAULT_FOLDER_STRUCTURE = {
|
|
8
|
+
api: 'api',
|
|
9
|
+
admin: 'admin',
|
|
10
|
+
web: 'web',
|
|
11
|
+
};
|
|
12
|
+
function parseScalar(raw) {
|
|
13
|
+
const trimmed = raw.trim();
|
|
14
|
+
if ((trimmed.startsWith('"') && trimmed.endsWith('"'))
|
|
15
|
+
|| (trimmed.startsWith("'") && trimmed.endsWith("'"))) {
|
|
16
|
+
return trimmed.slice(1, -1);
|
|
17
|
+
}
|
|
18
|
+
return trimmed;
|
|
19
|
+
}
|
|
20
|
+
export function readTmpFile(filePath) {
|
|
21
|
+
const text = fs.readFileSync(filePath, 'utf8');
|
|
22
|
+
const out = { path: filePath, folderStructure: { ...DEFAULT_FOLDER_STRUCTURE } };
|
|
23
|
+
const projectMatch = text.match(/^project:\s*\n(?:[ \t]+[^\n]+\n)*?[ \t]+name:\s*(.+?)\s*(?:#.*)?$/m)
|
|
24
|
+
?? text.match(/^project:\s*\n[ \t]+name:\s*(.+?)\s*(?:#.*)?$/m);
|
|
25
|
+
if (projectMatch)
|
|
26
|
+
out.projectName = parseScalar(projectMatch[1]);
|
|
27
|
+
const typeMatch = text.match(/global:\s*\n(?:[ \t]+[^\n]+\n)*?[ \t]+type:\s*(.+?)\s*(?:#.*)?$/m);
|
|
28
|
+
if (typeMatch)
|
|
29
|
+
out.globalType = parseScalar(typeMatch[1]);
|
|
30
|
+
const kubeMatch = text.match(/^kubeconfig:\s*(.+?)\s*(?:#.*)?$/m);
|
|
31
|
+
if (kubeMatch)
|
|
32
|
+
out.kubeconfig = parseScalar(kubeMatch[1]).replace(/^~/, process.env.HOME ?? '');
|
|
33
|
+
const rootBlock = text.match(/paths:\s*\n(?:[ \t]+[^\n]+\n)*?[ \t]+root:\s*(.+?)\s*(?:#.*)?$/m);
|
|
34
|
+
if (rootBlock)
|
|
35
|
+
out.pathsRoot = parseScalar(rootBlock[1]);
|
|
36
|
+
const tmpBlock = text.match(/paths:\s*\n(?:[ \t]+[^\n]+\n)*?[ \t]+tmp:\s*(.+?)\s*(?:#.*)?$/m);
|
|
37
|
+
if (tmpBlock)
|
|
38
|
+
out.pathsTmp = parseScalar(tmpBlock[1]);
|
|
39
|
+
if (out.projectName)
|
|
40
|
+
out.clusterDeployment = out.projectName;
|
|
41
|
+
out.folderStructure = parseFolderStructure(text);
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
export function parseFolderStructure(text) {
|
|
45
|
+
const fsBlock = text.match(/folder-structure:\s*\n((?:[ \t]+[^\n]+\n?)*)/)?.[1] ?? '';
|
|
46
|
+
const readSlot = (key) => {
|
|
47
|
+
const scalar = fsBlock.match(new RegExp(`^[ \t]+${key}:\s*(.+?)(?:\s+#.*)?$`, 'm'));
|
|
48
|
+
if (scalar)
|
|
49
|
+
return parseScalar(scalar[1]);
|
|
50
|
+
return DEFAULT_FOLDER_STRUCTURE[key];
|
|
51
|
+
};
|
|
52
|
+
return {
|
|
53
|
+
api: readSlot('api'),
|
|
54
|
+
admin: readSlot('admin'),
|
|
55
|
+
web: readSlot('web'),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export { normalizeGlobalType } from '../../../utils/helpers/tmp/tmp-schema.js';
|
|
59
|
+
export function entryName(meta) {
|
|
60
|
+
const project = (meta.projectName ?? '').trim();
|
|
61
|
+
return project || null;
|
|
62
|
+
}
|
|
63
|
+
export function entryType(meta, slot) {
|
|
64
|
+
const explicit = (meta.globalType ?? '').trim();
|
|
65
|
+
if (explicit) {
|
|
66
|
+
try {
|
|
67
|
+
return normalizeGlobalType(explicit) ?? null;
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return null;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
if (slot === 'api')
|
|
74
|
+
return GlobalTypeEnum.API_SERVICE;
|
|
75
|
+
return null;
|
|
76
|
+
}
|
|
77
|
+
export function findWorkspaceRoot(startDir = process.cwd()) {
|
|
78
|
+
let cur = path.resolve(startDir);
|
|
79
|
+
for (;;) {
|
|
80
|
+
const candidate = path.join(cur, TMP_FILE);
|
|
81
|
+
if (fs.existsSync(candidate)) {
|
|
82
|
+
const meta = readTmpFile(candidate);
|
|
83
|
+
if (meta.globalType === GlobalTypeEnum.WORKSPACE)
|
|
84
|
+
return cur;
|
|
85
|
+
}
|
|
86
|
+
const parent = path.dirname(cur);
|
|
87
|
+
if (parent === cur)
|
|
88
|
+
break;
|
|
89
|
+
cur = parent;
|
|
90
|
+
}
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
function isTraversableDir(entry, fullPath) {
|
|
94
|
+
if (entry.isDirectory())
|
|
95
|
+
return true;
|
|
96
|
+
if (entry.isSymbolicLink()) {
|
|
97
|
+
try {
|
|
98
|
+
return fs.statSync(fullPath).isDirectory();
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
function walkTmpUnder(rootDir) {
|
|
107
|
+
const found = [];
|
|
108
|
+
if (!fs.existsSync(rootDir))
|
|
109
|
+
return found;
|
|
110
|
+
const stack = [rootDir];
|
|
111
|
+
while (stack.length) {
|
|
112
|
+
const dir = stack.pop();
|
|
113
|
+
let entries;
|
|
114
|
+
try {
|
|
115
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
116
|
+
}
|
|
117
|
+
catch {
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
for (const entry of entries) {
|
|
121
|
+
const full = path.join(dir, entry.name);
|
|
122
|
+
if (isTraversableDir(entry, full)) {
|
|
123
|
+
if (SKIP_DIRS.has(entry.name) || entry.name.startsWith('.'))
|
|
124
|
+
continue;
|
|
125
|
+
stack.push(full);
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
if (entry.isFile() && entry.name === TMP_FILE)
|
|
129
|
+
found.push(full);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return found;
|
|
133
|
+
}
|
|
134
|
+
function stripDotSlash(value) {
|
|
135
|
+
return value.replace(/^\.\//, '');
|
|
136
|
+
}
|
|
137
|
+
function repoRootFromTmp(tmpPath, meta) {
|
|
138
|
+
const abs = tmpPath.replace(/\\/g, '/');
|
|
139
|
+
const rootFolder = stripDotSlash(meta.pathsRoot ?? './x');
|
|
140
|
+
const tmpName = stripDotSlash(meta.pathsTmp ?? 'tmp.yml');
|
|
141
|
+
const rel = `${rootFolder}/${tmpName}`.replace(/\/+/g, '/');
|
|
142
|
+
if (abs.endsWith(`/${rel}`)) {
|
|
143
|
+
return abs.slice(0, -(rel.length + 1));
|
|
144
|
+
}
|
|
145
|
+
throw new Error(`tmp path mismatch: expected */${rel}, got ${abs}`);
|
|
146
|
+
}
|
|
147
|
+
export function findEntries(workspaceRoot) {
|
|
148
|
+
const wsMeta = readTmpFile(path.join(workspaceRoot, TMP_FILE));
|
|
149
|
+
const fsMap = wsMeta.folderStructure;
|
|
150
|
+
const entries = [];
|
|
151
|
+
const seen = new Set();
|
|
152
|
+
const slots = ['api', 'admin', 'web'];
|
|
153
|
+
for (const slot of slots) {
|
|
154
|
+
const folder = path.join(workspaceRoot, fsMap[slot]);
|
|
155
|
+
for (const tmpPath of walkTmpUnder(folder)) {
|
|
156
|
+
if (path.resolve(tmpPath) === path.join(workspaceRoot, TMP_FILE))
|
|
157
|
+
continue;
|
|
158
|
+
const meta = readTmpFile(tmpPath);
|
|
159
|
+
const kind = entryType(meta, slot);
|
|
160
|
+
if (kind === GlobalTypeEnum.WORKSPACE)
|
|
161
|
+
continue;
|
|
162
|
+
if (slot !== 'api' && kind !== GlobalTypeEnum.FRONTEND)
|
|
163
|
+
continue;
|
|
164
|
+
if (kind !== GlobalTypeEnum.API_SERVICE && kind !== GlobalTypeEnum.FRONTEND)
|
|
165
|
+
continue;
|
|
166
|
+
const name = entryName(meta);
|
|
167
|
+
if (!name)
|
|
168
|
+
continue;
|
|
169
|
+
const key = `${kind}:${name}`;
|
|
170
|
+
if (seen.has(key))
|
|
171
|
+
continue;
|
|
172
|
+
seen.add(key);
|
|
173
|
+
entries.push({
|
|
174
|
+
name,
|
|
175
|
+
type: kind,
|
|
176
|
+
path: repoRootFromTmp(tmpPath, meta),
|
|
177
|
+
tmp: tmpPath,
|
|
178
|
+
slot,
|
|
179
|
+
cluster: meta.clusterDeployment ?? meta.projectName,
|
|
180
|
+
});
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return entries.sort((a, b) => (a.type === b.type ? a.name.localeCompare(b.name) : a.type.localeCompare(b.type)));
|
|
184
|
+
}
|
|
185
|
+
export function findApiServices(workspaceRoot) {
|
|
186
|
+
return findEntries(workspaceRoot).filter((e) => e.type === GlobalTypeEnum.API_SERVICE);
|
|
187
|
+
}
|
|
188
|
+
export function resolveEntryPath(workspaceRoot, name) {
|
|
189
|
+
const hit = findEntries(workspaceRoot).find((e) => e.name === name);
|
|
190
|
+
return hit?.path ?? null;
|
|
191
|
+
}
|
|
192
|
+
export function workspaceProjectName(workspaceRoot) {
|
|
193
|
+
const meta = readTmpFile(path.join(workspaceRoot, TMP_FILE));
|
|
194
|
+
return meta.projectName?.trim() || path.basename(workspaceRoot);
|
|
195
|
+
}
|
|
196
|
+
export function readWorkspaceGlobalTmp(workspaceRoot) {
|
|
197
|
+
const text = fs.readFileSync(path.join(workspaceRoot, TMP_FILE), 'utf8');
|
|
198
|
+
const match = text.match(/options:\s*\n(?:[ \t]+[^\n]+\n)*?[ \t]+fileWatchIntervalMs:\s*(\d+)/m)
|
|
199
|
+
?? text.match(/fileWatchIntervalMs:\s*(\d+)/);
|
|
200
|
+
return match ? { fileWatchIntervalMs: Number(match[1]) } : {};
|
|
201
|
+
}
|
|
202
|
+
/** @deprecated */ export const readWorkspaceCoreTmp = readWorkspaceGlobalTmp;
|
|
203
|
+
export function workspaceTmpTemplate(projectName) {
|
|
204
|
+
return `project:
|
|
205
|
+
name: ${projectName}
|
|
206
|
+
|
|
207
|
+
configs:
|
|
208
|
+
global:
|
|
209
|
+
type: workspace
|
|
210
|
+
runtime: bun
|
|
211
|
+
framework: bun
|
|
212
|
+
paths:
|
|
213
|
+
root: .
|
|
214
|
+
tmp: tmp.yml
|
|
215
|
+
options:
|
|
216
|
+
fileWatchIntervalMs: 500
|
|
217
|
+
folder-structure:
|
|
218
|
+
api: api
|
|
219
|
+
admin: admin
|
|
220
|
+
web: web
|
|
221
|
+
`;
|
|
222
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { type WorkspaceEntry } from '../../../utils/helpers/workspace';
|
|
2
|
+
export declare const XRYSTAL_HOME_DIR = ".xrystal";
|
|
3
|
+
export type RegistryProject = {
|
|
4
|
+
name: string;
|
|
5
|
+
type: string;
|
|
6
|
+
path: string;
|
|
7
|
+
slot: string;
|
|
8
|
+
cluster?: string;
|
|
9
|
+
};
|
|
10
|
+
export type RegistryWorkspace = {
|
|
11
|
+
name: string;
|
|
12
|
+
path: string;
|
|
13
|
+
projects: RegistryProject[];
|
|
14
|
+
updatedAt: string;
|
|
15
|
+
};
|
|
16
|
+
export type XrystalRegistry = {
|
|
17
|
+
version: 1;
|
|
18
|
+
updatedAt: string;
|
|
19
|
+
workspaces: RegistryWorkspace[];
|
|
20
|
+
};
|
|
21
|
+
export declare function resolveXrystalHome(): string;
|
|
22
|
+
export declare function registryFilePath(): string;
|
|
23
|
+
export declare function ensureXrystalHome(): string;
|
|
24
|
+
export declare function entryToRegistryProject(entry: WorkspaceEntry): RegistryProject;
|
|
25
|
+
export declare function scanWorkspace(workspacePath: string, workspaceName?: string): RegistryWorkspace;
|
|
26
|
+
export declare function readRegistry(): XrystalRegistry;
|
|
27
|
+
export declare function writeRegistry(registry: XrystalRegistry): void;
|
|
28
|
+
export declare function upsertWorkspace(registry: XrystalRegistry, workspace: RegistryWorkspace): XrystalRegistry;
|
|
29
|
+
export declare function syncRegistryFromPath(startDir?: string): XrystalRegistry;
|
|
30
|
+
export declare function listRegistryProjects(registry?: XrystalRegistry): Array<RegistryProject & {
|
|
31
|
+
workspace: string;
|
|
32
|
+
}>;
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { findEntries, findWorkspaceRoot } from '../../../utils/helpers/workspace/index.js';
|
|
5
|
+
export const XRYSTAL_HOME_DIR = '.xrystal';
|
|
6
|
+
export function resolveXrystalHome() {
|
|
7
|
+
return path.join(os.homedir(), XRYSTAL_HOME_DIR);
|
|
8
|
+
}
|
|
9
|
+
export function registryFilePath() {
|
|
10
|
+
return path.join(resolveXrystalHome(), 'registry.json');
|
|
11
|
+
}
|
|
12
|
+
export function ensureXrystalHome() {
|
|
13
|
+
const home = resolveXrystalHome();
|
|
14
|
+
fs.mkdirSync(path.join(home, 'workspaces'), { recursive: true });
|
|
15
|
+
return home;
|
|
16
|
+
}
|
|
17
|
+
export function entryToRegistryProject(entry) {
|
|
18
|
+
return {
|
|
19
|
+
name: entry.name,
|
|
20
|
+
type: entry.type,
|
|
21
|
+
path: entry.path,
|
|
22
|
+
slot: entry.slot,
|
|
23
|
+
cluster: entry.cluster ?? entry.name,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
26
|
+
function normalizeRegistryPath(input) {
|
|
27
|
+
const resolved = path.resolve(input);
|
|
28
|
+
try {
|
|
29
|
+
return fs.realpathSync.native(resolved);
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
return resolved;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
export function scanWorkspace(workspacePath, workspaceName) {
|
|
36
|
+
const root = normalizeRegistryPath(workspacePath);
|
|
37
|
+
const entries = findEntries(root);
|
|
38
|
+
const name = workspaceName ?? path.basename(root);
|
|
39
|
+
return {
|
|
40
|
+
name,
|
|
41
|
+
path: root,
|
|
42
|
+
projects: entries.map(entryToRegistryProject),
|
|
43
|
+
updatedAt: new Date().toISOString(),
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export function readRegistry() {
|
|
47
|
+
ensureXrystalHome();
|
|
48
|
+
const file = registryFilePath();
|
|
49
|
+
if (!fs.existsSync(file)) {
|
|
50
|
+
return { version: 1, updatedAt: new Date().toISOString(), workspaces: [] };
|
|
51
|
+
}
|
|
52
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
53
|
+
}
|
|
54
|
+
export function writeRegistry(registry) {
|
|
55
|
+
ensureXrystalHome();
|
|
56
|
+
registry.updatedAt = new Date().toISOString();
|
|
57
|
+
fs.writeFileSync(registryFilePath(), `${JSON.stringify(registry, null, 2)}\n`);
|
|
58
|
+
for (const ws of registry.workspaces) {
|
|
59
|
+
const wsDir = path.join(resolveXrystalHome(), 'workspaces', ws.name);
|
|
60
|
+
fs.mkdirSync(wsDir, { recursive: true });
|
|
61
|
+
fs.writeFileSync(path.join(wsDir, 'workspace.json'), `${JSON.stringify(ws, null, 2)}\n`);
|
|
62
|
+
for (const project of ws.projects) {
|
|
63
|
+
fs.writeFileSync(path.join(wsDir, `${project.name}.json`), `${JSON.stringify(project, null, 2)}\n`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
export function upsertWorkspace(registry, workspace) {
|
|
68
|
+
const workspacePath = normalizeRegistryPath(workspace.path);
|
|
69
|
+
const normalized = { ...workspace, path: workspacePath };
|
|
70
|
+
const next = registry.workspaces.filter((item) => normalizeRegistryPath(item.path) !== workspacePath);
|
|
71
|
+
next.push(normalized);
|
|
72
|
+
return { ...registry, workspaces: next.sort((a, b) => a.name.localeCompare(b.name)) };
|
|
73
|
+
}
|
|
74
|
+
export function syncRegistryFromPath(startDir = process.cwd()) {
|
|
75
|
+
const workspaceRoot = findWorkspaceRoot(startDir);
|
|
76
|
+
if (!workspaceRoot) {
|
|
77
|
+
throw new Error('No workspace tmp.yml found — run xry create demo --workspace first');
|
|
78
|
+
}
|
|
79
|
+
const scanned = scanWorkspace(workspaceRoot);
|
|
80
|
+
const registry = upsertWorkspace(readRegistry(), scanned);
|
|
81
|
+
writeRegistry(registry);
|
|
82
|
+
return registry;
|
|
83
|
+
}
|
|
84
|
+
export function listRegistryProjects(registry = readRegistry()) {
|
|
85
|
+
const rows = [];
|
|
86
|
+
for (const ws of registry.workspaces) {
|
|
87
|
+
for (const project of ws.projects) {
|
|
88
|
+
rows.push({ ...project, workspace: ws.name });
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return rows.sort((a, b) => a.workspace.localeCompare(b.workspace) || a.name.localeCompare(b.name));
|
|
92
|
+
}
|
package/x/dist/utils/index.js
CHANGED
|
@@ -1 +1,142 @@
|
|
|
1
|
-
import
|
|
1
|
+
import { createHash, createHmac } from 'node:crypto';
|
|
2
|
+
import { Configs, Logger } from '../../../loader/index.js';
|
|
3
|
+
import { LoggerLayerEnum, x } from '../../../utils/index.js';
|
|
4
|
+
import { getRequestId } from '../../../utils/helpers/context/index.js';
|
|
5
|
+
export class ClientStore {
|
|
6
|
+
static _store = {};
|
|
7
|
+
static get(clientName) { return this._store[clientName] || {}; }
|
|
8
|
+
static set(clientName, data) {
|
|
9
|
+
this._store[clientName] = { ...this._store[clientName], ...data };
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
export class Client {
|
|
13
|
+
logger = x.get(Logger);
|
|
14
|
+
configs = x.get(Configs);
|
|
15
|
+
clientName;
|
|
16
|
+
baseURL;
|
|
17
|
+
version = null;
|
|
18
|
+
timeout = 15000;
|
|
19
|
+
debug;
|
|
20
|
+
authConfigs;
|
|
21
|
+
breaker = {
|
|
22
|
+
failures: 0,
|
|
23
|
+
lastFailure: 0,
|
|
24
|
+
state: 'CLOSED',
|
|
25
|
+
threshold: 5,
|
|
26
|
+
cooldown: 30000
|
|
27
|
+
};
|
|
28
|
+
constructor({ clientName, baseURL, version, timeout, auth, debug }) {
|
|
29
|
+
this.clientName = clientName;
|
|
30
|
+
this.baseURL = baseURL;
|
|
31
|
+
this.version = version || null;
|
|
32
|
+
this.authConfigs = auth;
|
|
33
|
+
this.timeout = timeout || 15000;
|
|
34
|
+
const configDebug = Number(this.configs.all.debug) >= LoggerLayerEnum.DEBUG;
|
|
35
|
+
this.debug = debug ?? configDebug;
|
|
36
|
+
if (auth?.token)
|
|
37
|
+
ClientStore.set(clientName, { accessToken: auth.token });
|
|
38
|
+
}
|
|
39
|
+
resolvePath(obj, path) {
|
|
40
|
+
return path.split('.').reduce((prev, curr) => prev ? prev[curr] : undefined, obj);
|
|
41
|
+
}
|
|
42
|
+
static cryptoHashGenerate = ({ algorithm, input, digest = 'hex' }) => {
|
|
43
|
+
return createHash(algorithm).update(input).digest(digest);
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export class BaseApiClient extends Client {
|
|
47
|
+
constructor(config) { super(config); }
|
|
48
|
+
async request(path, options = {}) {
|
|
49
|
+
if (this.breaker.state === 'OPEN') {
|
|
50
|
+
if (Date.now() - this.breaker.lastFailure > this.breaker.cooldown) {
|
|
51
|
+
this.breaker.state = 'HALF_OPEN';
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
throw new Error(`[CircuitBreaker] ${this.clientName} is OPEN`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
const maxRetries = options.retries ?? 3;
|
|
58
|
+
let attempt = 0;
|
|
59
|
+
while (attempt < maxRetries) {
|
|
60
|
+
try {
|
|
61
|
+
const response = await this._execute(path, { ...options });
|
|
62
|
+
if (response.ok || response.status === 401) {
|
|
63
|
+
this.breaker.failures = 0;
|
|
64
|
+
this.breaker.state = 'CLOSED';
|
|
65
|
+
return response;
|
|
66
|
+
}
|
|
67
|
+
if ([502, 503, 504].includes(response.status)) {
|
|
68
|
+
throw new Error(`Server Error: ${response.status}`);
|
|
69
|
+
}
|
|
70
|
+
return response;
|
|
71
|
+
}
|
|
72
|
+
catch (error) {
|
|
73
|
+
attempt++;
|
|
74
|
+
this.breaker.failures++;
|
|
75
|
+
this.breaker.lastFailure = Date.now();
|
|
76
|
+
if (this.breaker.failures >= this.breaker.threshold)
|
|
77
|
+
this.breaker.state = 'OPEN';
|
|
78
|
+
if (attempt >= maxRetries)
|
|
79
|
+
throw error;
|
|
80
|
+
const backoff = Math.pow(2, attempt) * 500;
|
|
81
|
+
await new Promise(res => setTimeout(res, backoff));
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
throw new Error(`${this.clientName} failed after ${maxRetries} attempts`);
|
|
85
|
+
}
|
|
86
|
+
async _execute(path, options) {
|
|
87
|
+
const base = this.baseURL.replace(/\/$/, '');
|
|
88
|
+
const activeVersion = options.version !== undefined ? options.version : this.version;
|
|
89
|
+
const ver = activeVersion ? `/${activeVersion.replace(/^\//, '')}` : '';
|
|
90
|
+
const url = `${base}${ver}${path}`;
|
|
91
|
+
const correlationId = getRequestId();
|
|
92
|
+
const headers = new Headers(options.headers || {});
|
|
93
|
+
const isUrlEncoded = options.body instanceof URLSearchParams;
|
|
94
|
+
const isFormData = options.body instanceof FormData;
|
|
95
|
+
if (!isUrlEncoded && !isFormData) {
|
|
96
|
+
headers.set('Content-Type', 'application/json');
|
|
97
|
+
}
|
|
98
|
+
if (correlationId)
|
|
99
|
+
headers.set('x-correlation-id', correlationId);
|
|
100
|
+
const systemSecret = this.configs.all.internalSecret || process.env.INTERNAL_SECRET;
|
|
101
|
+
if (systemSecret) {
|
|
102
|
+
const timestamp = Date.now().toString();
|
|
103
|
+
const signature = createHmac('sha256', systemSecret)
|
|
104
|
+
.update(timestamp + this.clientName)
|
|
105
|
+
.digest('hex');
|
|
106
|
+
headers.set('x-internal-signature', signature);
|
|
107
|
+
headers.set('x-internal-timestamp', timestamp);
|
|
108
|
+
headers.set('x-internal-client', this.clientName);
|
|
109
|
+
}
|
|
110
|
+
const isDebugMode = options.debug ?? this.debug;
|
|
111
|
+
const { version, retries, debug, ...fetchOptions } = options;
|
|
112
|
+
let processedBody = fetchOptions.body;
|
|
113
|
+
if (processedBody && typeof processedBody === 'object' && !isUrlEncoded && !isFormData) {
|
|
114
|
+
processedBody = JSON.stringify(processedBody);
|
|
115
|
+
}
|
|
116
|
+
if (isDebugMode) {
|
|
117
|
+
const logData = {
|
|
118
|
+
method: fetchOptions.method || 'GET',
|
|
119
|
+
url,
|
|
120
|
+
body: processedBody && typeof processedBody === 'string' ? JSON.parse(processedBody) : processedBody
|
|
121
|
+
};
|
|
122
|
+
console.log(`[DEBUG] ${this.clientName}`, logData);
|
|
123
|
+
this.logger.winston.info(`${this.clientName} Request`, logData);
|
|
124
|
+
}
|
|
125
|
+
const controller = new AbortController();
|
|
126
|
+
const timeoutId = setTimeout(() => controller.abort(), this.timeout);
|
|
127
|
+
try {
|
|
128
|
+
const response = await fetch(url, {
|
|
129
|
+
...fetchOptions,
|
|
130
|
+
body: processedBody,
|
|
131
|
+
headers,
|
|
132
|
+
signal: controller.signal
|
|
133
|
+
});
|
|
134
|
+
clearTimeout(timeoutId);
|
|
135
|
+
return response;
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
clearTimeout(timeoutId);
|
|
139
|
+
throw error;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
}
|
|
@@ -1 +1,10 @@
|
|
|
1
|
-
export class ILifeCycle
|
|
1
|
+
export class ILifeCycle {
|
|
2
|
+
async onInit(props = {}) {
|
|
3
|
+
}
|
|
4
|
+
onAfterInit(_context) {
|
|
5
|
+
}
|
|
6
|
+
onDispose(_context) {
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
export class IProvide extends ILifeCycle {
|
|
10
|
+
}
|
|
@@ -1 +1,16 @@
|
|
|
1
|
-
|
|
1
|
+
// => // X Service Locator
|
|
2
|
+
export class Locator {
|
|
3
|
+
_context = new Map();
|
|
4
|
+
constructor({}) {
|
|
5
|
+
}
|
|
6
|
+
set = ({ service, reference, args }) => {
|
|
7
|
+
this._context.set(service, new reference(...(args || [])));
|
|
8
|
+
};
|
|
9
|
+
get = (service) => {
|
|
10
|
+
if (!this._context.has(service)) {
|
|
11
|
+
throw new Error(`${service} not found in context.`);
|
|
12
|
+
}
|
|
13
|
+
return this._context.get(service);
|
|
14
|
+
};
|
|
15
|
+
}
|
|
16
|
+
export default new Locator({});
|
|
@@ -1 +1,61 @@
|
|
|
1
|
-
import{EventEmitter
|
|
1
|
+
import { EventEmitter } from 'node:events';
|
|
2
|
+
import { readFileSync, unwatchFile, watchFile } from 'node:fs';
|
|
3
|
+
import { resolve } from 'node:path';
|
|
4
|
+
import { parse } from 'yaml';
|
|
5
|
+
import { resolveObjWithHandlebars } from '../../../utils/helpers/core/handlebars-resolve.js';
|
|
6
|
+
import { normalizeTmpDocument } from '../../../utils/helpers/tmp/tmp-schema.js';
|
|
7
|
+
import { resolveTmpWatchIntervalMs } from '../../../utils/helpers/tmp/tmp-watch.js';
|
|
8
|
+
export class TmpFileLoader extends EventEmitter {
|
|
9
|
+
#tmpFileJson = {};
|
|
10
|
+
#filePath;
|
|
11
|
+
#watchIntervalMs = resolveTmpWatchIntervalMs(null);
|
|
12
|
+
#watching = false;
|
|
13
|
+
constructor({ filePath }) {
|
|
14
|
+
super();
|
|
15
|
+
this.#filePath = resolve(filePath);
|
|
16
|
+
this.#loadSync();
|
|
17
|
+
this.#restartWatcher();
|
|
18
|
+
}
|
|
19
|
+
#loadSync() {
|
|
20
|
+
try {
|
|
21
|
+
const content = readFileSync(this.#filePath, 'utf8');
|
|
22
|
+
const parsed = parse(content);
|
|
23
|
+
const nextInterval = resolveTmpWatchIntervalMs(parsed);
|
|
24
|
+
const intervalChanged = this.#watching && nextInterval !== this.#watchIntervalMs;
|
|
25
|
+
this.#tmpFileJson = parsed;
|
|
26
|
+
this.#watchIntervalMs = nextInterval;
|
|
27
|
+
this.emit('reload', this.#tmpFileJson);
|
|
28
|
+
if (intervalChanged) {
|
|
29
|
+
this.#restartWatcher();
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
catch (err) {
|
|
33
|
+
console.error(`[TmpFileLoader] Error: ${err}`);
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
#restartWatcher() {
|
|
37
|
+
if (this.#watching) {
|
|
38
|
+
unwatchFile(this.#filePath);
|
|
39
|
+
}
|
|
40
|
+
this.#watchIntervalMs = resolveTmpWatchIntervalMs(this.#tmpFileJson);
|
|
41
|
+
watchFile(this.#filePath, { interval: this.#watchIntervalMs }, (curr, prev) => {
|
|
42
|
+
if (curr.mtimeMs !== prev.mtimeMs) {
|
|
43
|
+
this.#loadSync();
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
this.#watching = true;
|
|
47
|
+
}
|
|
48
|
+
stop() {
|
|
49
|
+
if (this.#watching) {
|
|
50
|
+
unwatchFile(this.#filePath);
|
|
51
|
+
this.#watching = false;
|
|
52
|
+
}
|
|
53
|
+
this.removeAllListeners();
|
|
54
|
+
}
|
|
55
|
+
getResolvedTmpFile() {
|
|
56
|
+
const data = Object.keys(this.#tmpFileJson).length > 0
|
|
57
|
+
? this.#tmpFileJson
|
|
58
|
+
: (this.#loadSync(), this.#tmpFileJson);
|
|
59
|
+
return normalizeTmpDocument(resolveObjWithHandlebars(data, data));
|
|
60
|
+
}
|
|
61
|
+
}
|