@xrystal/core 3.42.0 → 3.45.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +27 -24
- package/package.json +2 -2
- package/x/bin/commands/project.mjs +24 -11
- package/x/bin/commands/release.mjs +2 -2
- package/x/bin/commands/sync.mjs +1 -1
- package/x/bin/helpers/.generated/seed-from-tmp.mjs +1 -0
- package/x/bin/helpers/.generated/tmp-schema.mjs +93 -14
- package/x/bin/helpers/banner.mjs +7 -7
- package/x/bin/helpers/build-config.mjs +71 -17
- package/x/bin/helpers/cli-help.mjs +5 -4
- package/x/bin/helpers/cli-identity.mjs +6 -0
- package/x/bin/helpers/package-defaults.mjs +27 -1
- package/x/bin/helpers/project-artifacts.mjs +16 -7
- package/x/bin/helpers/tmp-schema.mjs +5 -0
- package/x/bin/helpers/toolchain-config.mjs +1 -1
- package/x/bin/main-cli.js +8 -4
- package/x/bin/scripts/clean-source-types.mjs +5 -2
- package/x/bin/scripts/prepare-npm-publish.mjs +9 -7
- package/x/bin/scripts/publish-guard.mjs +7 -5
- package/x/dist/loader/controller/index.js +1 -1
- package/x/dist/utils/constants/defaults.json +1 -0
- package/x/dist/utils/constants/index.d.ts +3 -0
- package/x/dist/utils/constants/index.js +1 -1
- package/x/dist/utils/helpers/handlers/adapters.js +1 -1
- package/x/dist/utils/helpers/protocol/index.d.ts +1 -1
- package/x/dist/utils/helpers/protocol/index.js +1 -1
- package/x/dist/utils/helpers/state/props-from-tmp.d.ts +1 -1
- package/x/dist/utils/helpers/state/props-from-tmp.js +1 -1
- package/x/dist/utils/helpers/state/request-key-guard.d.ts +1 -1
- package/x/dist/utils/helpers/state/request-key-guard.js +1 -1
- package/x/dist/utils/helpers/tmp/index.d.ts +2 -1
- package/x/dist/utils/helpers/tmp/index.js +1 -1
- package/x/dist/utils/helpers/tmp/loader-tmp-sync.js +1 -1
- package/x/dist/utils/helpers/tmp/runtime-tmp.js +1 -1
- package/x/dist/utils/helpers/tmp/tmp-interpolate.d.ts +1 -0
- package/x/dist/utils/helpers/tmp/tmp-interpolate.js +1 -0
- package/x/dist/utils/helpers/tmp/tmp-schema.d.ts +12 -0
- package/x/dist/utils/helpers/tmp/tmp-schema.js +1 -1
- package/x/dist/utils/helpers/tmp/toolchain-heal.d.ts +46 -0
- package/x/dist/utils/helpers/tmp/toolchain-heal.js +2 -0
- package/x/dist/utils/models/enums/index.d.ts +10 -0
- package/x/dist/utils/models/enums/index.js +1 -1
- package/x/tmp.yml +7 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import chalk from 'chalk'
|
|
2
2
|
|
|
3
|
-
import { CLI_BIN_NAMES, CLI_PRIMARY_NAME } from './cli-identity.mjs'
|
|
3
|
+
import { CLI_BIN_NAMES, CLI_PRIMARY_NAME, PACKAGE_NAME } from './cli-identity.mjs'
|
|
4
4
|
|
|
5
5
|
export const LIST_BULLET = chalk.cyan('◆')
|
|
6
6
|
import { brandTitle } from './banner.mjs'
|
|
@@ -8,7 +8,7 @@ import { packageDefaults } from './package-defaults.mjs'
|
|
|
8
8
|
|
|
9
9
|
const QUICK_COMMANDS = [
|
|
10
10
|
{ cmd: 'create', hint: '<name> [path]', desc: 'Scaffold service · path defaults to cwd' },
|
|
11
|
-
{ cmd: 'dev', desc: 'Watch
|
|
11
|
+
{ cmd: 'dev', desc: 'Watch TypeScript entry + dev env' },
|
|
12
12
|
{ cmd: 'build', desc: 'Bundle to dist/ (tmp.yml layout)' },
|
|
13
13
|
{ cmd: 'start', desc: 'Run production dist/index.js' },
|
|
14
14
|
{ cmd: 'test', desc: 'Run tests folder from tmp.yml' },
|
|
@@ -31,7 +31,7 @@ const COMMAND_GROUPS = [
|
|
|
31
31
|
{ cmd: 'tmp', desc: 'Ensure tmp.yml exists (runtime config seed)' },
|
|
32
32
|
{ cmd: 'hooks install', desc: 'Install .git/hooks pre-commit version check' },
|
|
33
33
|
{ cmd: 'hooks status', desc: 'Show whether pre-commit hook is installed' },
|
|
34
|
-
{ cmd: 'sync', desc: '
|
|
34
|
+
{ cmd: 'sync', desc: 'Force-sync tsconfig from tmp.yml (auto-heals otherwise)' },
|
|
35
35
|
],
|
|
36
36
|
},
|
|
37
37
|
{
|
|
@@ -112,7 +112,8 @@ export function formatRootHelp({ cliName = CLI_PRIMARY_NAME } = {}) {
|
|
|
112
112
|
|
|
113
113
|
return [
|
|
114
114
|
chalk.bold.white(`\n Usage`),
|
|
115
|
-
chalk.gray(` ${
|
|
115
|
+
chalk.gray(` ${PACKAGE_NAME} [options] [command]`),
|
|
116
|
+
chalk.dim(` invoke: ${cliName}`),
|
|
116
117
|
...sections,
|
|
117
118
|
formatOptionsSection(cliName),
|
|
118
119
|
].join('\n')
|
|
@@ -43,12 +43,38 @@ export const packageDefaults = Object.freeze({
|
|
|
43
43
|
export const coreVersionPattern = /^\d{2}\.\d{2}\.\d{2}-v\d+$/
|
|
44
44
|
export const semverVersionPattern = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$/
|
|
45
45
|
|
|
46
|
+
export const PACKAGE_NAME = packageDefaults.packageName
|
|
46
47
|
export const CLI_PRIMARY_NAME = packageDefaults.cliName
|
|
47
48
|
export const CLI_BIN_NAMES = packageDefaults.cliBinNames
|
|
49
|
+
export const CLI_BIN_FILE = packageDefaults.cliBinFile ?? 'main-cli.js'
|
|
50
|
+
|
|
51
|
+
/** Commander / banner description from brand SSOT. */
|
|
52
|
+
export function packageCliDescription() {
|
|
53
|
+
const brand = packageDefaults.brand ?? {}
|
|
54
|
+
const title = [brand.primary, brand.secondary].filter(Boolean).join(' ')
|
|
55
|
+
const tagline = brand.tagline ? String(brand.tagline) : ''
|
|
56
|
+
if (title && tagline) return `${title} — ${tagline}`
|
|
57
|
+
return tagline || PACKAGE_NAME
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** Log / error prefix: always the npm package name. */
|
|
61
|
+
export function packageLogTag() {
|
|
62
|
+
return PACKAGE_NAME
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Relative bin entry for package.json / manifests. */
|
|
66
|
+
export function resolveCliBinEntry() {
|
|
67
|
+
return `./${packageDefaults.packageRootFolder}/bin/${CLI_BIN_FILE}`
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Authored main source folder segment without ./ */
|
|
71
|
+
export function resolveMainSourceRel() {
|
|
72
|
+
return String(packageDefaults.mainSourceFolder ?? 'source').replace(/^\.\//, '')
|
|
73
|
+
}
|
|
48
74
|
|
|
49
75
|
export function resolveInvokedAs(argv = process.argv) {
|
|
50
76
|
const base = path.basename(argv[1] || CLI_PRIMARY_NAME)
|
|
51
|
-
if (base ===
|
|
77
|
+
if (base === CLI_BIN_FILE) return CLI_PRIMARY_NAME
|
|
52
78
|
if (CLI_BIN_NAMES.includes(base)) return base
|
|
53
79
|
return CLI_PRIMARY_NAME
|
|
54
80
|
}
|
|
@@ -4,9 +4,9 @@ import path from 'node:path'
|
|
|
4
4
|
import { fileURLToPath } from 'node:url'
|
|
5
5
|
|
|
6
6
|
import { isCorePackageName } from './build-config.mjs'
|
|
7
|
-
import { syncProjectToolchain } from './toolchain-config.mjs'
|
|
7
|
+
import { auditTsconfigAlignment, syncProjectToolchain } from './toolchain-config.mjs'
|
|
8
8
|
import { ensureTmpFile, relativeFromRoot } from './tmp-layout.mjs'
|
|
9
|
-
import { packageDefaults } from './package-defaults.mjs'
|
|
9
|
+
import { packageDefaults, resolveCliBinEntry } from './package-defaults.mjs'
|
|
10
10
|
|
|
11
11
|
const CLI_BIN_DIR = path.dirname(fileURLToPath(import.meta.url))
|
|
12
12
|
const CLI_GENERATED_DIR = path.join(CLI_BIN_DIR, '.generated')
|
|
@@ -142,7 +142,7 @@ export function syncCliGeneratedModules(root = process.cwd(), { force = false }
|
|
|
142
142
|
}
|
|
143
143
|
|
|
144
144
|
execSync(
|
|
145
|
-
`bun build "${srcAbs}" --outfile "${mod.outfile}" --target node --format esm --external yaml`,
|
|
145
|
+
`bun build "${srcAbs}" --outfile "${mod.outfile}" --target node --format esm --external yaml --external handlebars`,
|
|
146
146
|
{ cwd: root, stdio: 'pipe' },
|
|
147
147
|
)
|
|
148
148
|
results.push({ source: mod.source, synced: true, out: mod.outfile })
|
|
@@ -175,7 +175,7 @@ export function syncPackageManifest(root = process.cwd(), { write = true } = {})
|
|
|
175
175
|
}
|
|
176
176
|
|
|
177
177
|
const { distPrefix, distRel } = resolveDistLayout(root)
|
|
178
|
-
const binEntry =
|
|
178
|
+
const binEntry = resolveCliBinEntry()
|
|
179
179
|
const bin = Object.fromEntries(packageDefaults.cliBinNames.map((name) => [name, binEntry]))
|
|
180
180
|
|
|
181
181
|
const next = {
|
|
@@ -195,7 +195,7 @@ export function syncPackageManifest(root = process.cwd(), { write = true } = {})
|
|
|
195
195
|
return { synced: true, wrote: write && changed, distPrefix, distRel, changed }
|
|
196
196
|
}
|
|
197
197
|
|
|
198
|
-
/** tmp.yml → toolchain + CLI schema
|
|
198
|
+
/** tmp.yml → toolchain (+ CLI schema / package exports). Heals tsconfig when layout drifts. */
|
|
199
199
|
export function ensureProjectArtifacts(root = process.cwd(), options = {}) {
|
|
200
200
|
const {
|
|
201
201
|
writeToolchain = false,
|
|
@@ -204,7 +204,16 @@ export function ensureProjectArtifacts(root = process.cwd(), options = {}) {
|
|
|
204
204
|
} = options
|
|
205
205
|
|
|
206
206
|
const { generated, defaults } = syncCliRuntime(root, { force: forceSchema })
|
|
207
|
-
const
|
|
207
|
+
const audit = auditTsconfigAlignment(root)
|
|
208
|
+
const shouldWriteToolchain = writeToolchain || !audit.ok
|
|
209
|
+
const toolchain = syncProjectToolchain(root, { write: shouldWriteToolchain })
|
|
210
|
+
if (shouldWriteToolchain && !writeToolchain && !audit.ok) {
|
|
211
|
+
toolchain.healed = true
|
|
212
|
+
toolchain.healNotes = audit.notes
|
|
213
|
+
if (process.env.XRY_QUIET !== '1') {
|
|
214
|
+
console.info(`[${packageDefaults.packageName}] toolchain auto-synced (tsconfig) — layout drift`)
|
|
215
|
+
}
|
|
216
|
+
}
|
|
208
217
|
let manifest = { synced: false, reason: 'skipped' }
|
|
209
218
|
|
|
210
219
|
const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
|
|
@@ -212,5 +221,5 @@ export function ensureProjectArtifacts(root = process.cwd(), options = {}) {
|
|
|
212
221
|
manifest = syncPackageManifest(root, { write: true })
|
|
213
222
|
}
|
|
214
223
|
|
|
215
|
-
return { generated, defaults, toolchain, manifest }
|
|
224
|
+
return { generated, defaults, toolchain, manifest, audit }
|
|
216
225
|
}
|
|
@@ -2,8 +2,13 @@ export {
|
|
|
2
2
|
normalizeRootFolder,
|
|
3
3
|
normalizeSourceFolder,
|
|
4
4
|
normalizeTmpDocument,
|
|
5
|
+
normalizeRuntime,
|
|
6
|
+
normalizeBundler,
|
|
7
|
+
resolveEffectiveBundler,
|
|
5
8
|
readTmpCoreBlock,
|
|
6
9
|
readTmpServiceBlock,
|
|
10
|
+
readTmpGlobalBlock,
|
|
11
|
+
applyTmpGlobalVars,
|
|
7
12
|
resolveServiceLayoutPaths,
|
|
8
13
|
resolveTmpRuntimeConfigs,
|
|
9
14
|
} from './.generated/tmp-schema.mjs'
|
|
@@ -142,7 +142,7 @@ export function auditTsconfigAlignment(root, options = null) {
|
|
|
142
142
|
const recommended = resolveRecommendedTsconfig(resolvedOptions)
|
|
143
143
|
const onDisk = readProjectTsconfig(root)
|
|
144
144
|
if (!onDisk) {
|
|
145
|
-
return { ok: false, missing: true, notes: [`tsconfig.json not found —
|
|
145
|
+
return { ok: false, missing: true, notes: [`tsconfig.json not found — auto-healed on layout change, next ${CLI_PRIMARY_NAME} command, or ${CLI_PRIMARY_NAME} sync`] }
|
|
146
146
|
}
|
|
147
147
|
|
|
148
148
|
const notes = []
|
package/x/bin/main-cli.js
CHANGED
|
@@ -12,7 +12,11 @@ import { registerTagCommand, registerVersionCommand } from './commands/release.m
|
|
|
12
12
|
import { registerHooksCommand } from './commands/hooks.mjs'
|
|
13
13
|
import { printBanner, shouldShowBanner } from './helpers/banner.mjs'
|
|
14
14
|
import { formatRootHelp, formatCreateCommandHelp, isCreateHelpRequest, isRootHelpRequest, printQuickStartGuide } from './helpers/cli-help.mjs'
|
|
15
|
-
import {
|
|
15
|
+
import {
|
|
16
|
+
PACKAGE_NAME,
|
|
17
|
+
packageCliDescription,
|
|
18
|
+
resolveInvokedAs,
|
|
19
|
+
} from './helpers/cli-identity.mjs'
|
|
16
20
|
import { readCliPackageJson, getProjectRoot } from './helpers/project-root.mjs'
|
|
17
21
|
import { ensureProjectArtifacts } from './helpers/project-artifacts.mjs'
|
|
18
22
|
|
|
@@ -49,9 +53,9 @@ if (isCreateHelpRequest()) {
|
|
|
49
53
|
const cli = new Command()
|
|
50
54
|
|
|
51
55
|
cli
|
|
52
|
-
.name(
|
|
53
|
-
.description(
|
|
54
|
-
.version(pkg.version, '-V, --version', `Show ${
|
|
56
|
+
.name(PACKAGE_NAME)
|
|
57
|
+
.description(packageCliDescription())
|
|
58
|
+
.version(pkg.version, '-V, --version', `Show ${PACKAGE_NAME} version`)
|
|
55
59
|
.configureHelp({
|
|
56
60
|
helpWidth: () => Math.min(100, Math.max(56, process.stdout.columns || 80)),
|
|
57
61
|
sortSubcommands: true,
|
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import fs from 'node:fs'
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
|
|
4
|
+
import { resolveMainSourceRel } from '../helpers/package-defaults.mjs'
|
|
5
|
+
|
|
4
6
|
const root = process.cwd()
|
|
5
|
-
const
|
|
6
|
-
const
|
|
7
|
+
const sourceRel = resolveMainSourceRel()
|
|
8
|
+
const sourceRoot = path.join(root, sourceRel)
|
|
9
|
+
const keepRel = path.join(sourceRel, 'utils', 'models', 'types', 'shims.d.ts')
|
|
7
10
|
|
|
8
11
|
function walk(dir) {
|
|
9
12
|
for (const name of fs.readdirSync(dir)) {
|
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import fs from 'node:fs'
|
|
3
3
|
import path from 'node:path'
|
|
4
|
+
import { packageDefaults, resolveMainSourceRel } from '../helpers/package-defaults.mjs'
|
|
4
5
|
import { PublishGuardError, runPublishGuards } from './publish-guard.mjs'
|
|
5
6
|
|
|
6
7
|
const root = process.cwd()
|
|
7
8
|
|
|
8
9
|
const pathsToRemove = [
|
|
9
|
-
|
|
10
|
-
|
|
10
|
+
resolveMainSourceRel(),
|
|
11
|
+
`${packageDefaults.packageRootFolder}/tests`,
|
|
11
12
|
'.github',
|
|
12
13
|
'.vscode',
|
|
13
|
-
|
|
14
|
-
|
|
14
|
+
`${packageDefaults.packageRootFolder}/logs`,
|
|
15
|
+
`${packageDefaults.packageRootFolder}/docker`,
|
|
15
16
|
'tsconfig.json',
|
|
16
17
|
'eslint.config.js',
|
|
17
18
|
'.gitignore',
|
|
@@ -25,14 +26,15 @@ for (const rel of pathsToRemove) {
|
|
|
25
26
|
console.log(`prepare-npm-publish: removed ${rel}`)
|
|
26
27
|
}
|
|
27
28
|
|
|
28
|
-
|
|
29
|
-
|
|
29
|
+
const distRel = path.join(packageDefaults.packageRootFolder, packageDefaults.layoutPaths.dist)
|
|
30
|
+
if (!fs.existsSync(path.join(root, distRel))) {
|
|
31
|
+
console.error(`prepare-npm-publish: ${distRel} missing — run build first`)
|
|
30
32
|
process.exit(1)
|
|
31
33
|
}
|
|
32
34
|
|
|
33
35
|
try {
|
|
34
36
|
const { jsCount } = runPublishGuards(root, { strictDisk: true })
|
|
35
|
-
console.log(`prepare-npm-publish: ready (${jsCount} .js in
|
|
37
|
+
console.log(`prepare-npm-publish: ready (${jsCount} .js in ${distRel}, verified)`)
|
|
36
38
|
} catch (error) {
|
|
37
39
|
console.error(`prepare-npm-publish: ✗ ${error instanceof PublishGuardError ? error.message : error.message}`)
|
|
38
40
|
process.exit(1)
|
|
@@ -2,7 +2,7 @@ import { execSync } from 'node:child_process'
|
|
|
2
2
|
import fs from 'node:fs'
|
|
3
3
|
import path from 'node:path'
|
|
4
4
|
|
|
5
|
-
import { packageDefaults } from '../helpers/package-defaults.mjs'
|
|
5
|
+
import { packageDefaults, resolveMainSourceRel } from '../helpers/package-defaults.mjs'
|
|
6
6
|
|
|
7
7
|
export class PublishGuardError extends Error {
|
|
8
8
|
constructor(message) {
|
|
@@ -34,10 +34,11 @@ export function assertFilesListNoSource(pkg) {
|
|
|
34
34
|
const files = Array.isArray(pkg.files) ? pkg.files : []
|
|
35
35
|
const bad = files.filter((entry) => {
|
|
36
36
|
const normalized = String(entry).replace(/^\.\//, '').replace(/\\/g, '/')
|
|
37
|
-
|
|
37
|
+
const sourceRel = resolveMainSourceRel()
|
|
38
|
+
return normalized === sourceRel || normalized.startsWith(`${sourceRel}/`)
|
|
38
39
|
})
|
|
39
40
|
if (bad.length > 0) {
|
|
40
|
-
throw new PublishGuardError(`package.json files must not include
|
|
41
|
+
throw new PublishGuardError(`package.json files must not include ${resolveMainSourceRel()}/ (found: ${bad.join(', ')})`)
|
|
41
42
|
}
|
|
42
43
|
}
|
|
43
44
|
|
|
@@ -65,8 +66,9 @@ export function assertMainExportsPointToDist(pkg) {
|
|
|
65
66
|
}
|
|
66
67
|
|
|
67
68
|
export function assertSourceAbsentOnDisk(root = process.cwd()) {
|
|
68
|
-
|
|
69
|
-
|
|
69
|
+
const sourceRel = resolveMainSourceRel()
|
|
70
|
+
if (fs.existsSync(path.join(root, sourceRel))) {
|
|
71
|
+
throw new PublishGuardError(`${sourceRel}/ must not exist on disk at publish time`)
|
|
70
72
|
}
|
|
71
73
|
}
|
|
72
74
|
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import{Constants as h}from"../../utils/constants";import g from"qs";import S from"../../loader/logger";import T from"../../loader/system";import{bindLoaderTmpSync as E,getClientIp as D,getConfiguredProtocols as O,isRealtimeProtocol as q,LoggerLayerEnum as j,parseResponseMessage as P,ProtocolEnum as y,x,controllerContextStorage,getControllerCtx,runControllerStore as B,adapterBagFromRequest as I,isFetchRequest as M,toHandler as H,toRealtimeHandler as N,resolveCtrOptions as A}from"../../utils";export{controllerContextStorage,getControllerCtx};export const runController=B;function b(t){return t instanceof Response||t instanceof Blob||t instanceof Uint8Array||t instanceof ArrayBuffer}function l(t){if(!t||typeof t!=="object")return null;return t}function w(t,e){const r=l(e);if(!r)return;if(r.statusCode!==void 0)return void t.httpStatus(Number(r.statusCode));if(r.code!==void 0){const a=Number(r.code);if(a>=100)t.httpStatus(a);else t.code(a)}}function R(t){const e=l(t);if(!e)return{data:void 0,extraData:void 0,message:void 0};const r=l(e.payload);if(r)return{data:r.data!==void 0?r.data:r,extraData:r.extraData,message:e.message};if(e.data!==void 0||e.extraData!==void 0)return{data:e.data,extraData:e.extraData,message:e.message};if(!(e.status!==void 0||e.message!==void 0||e.code!==void 0||e.statusCode!==void 0)&&Object.keys(e).length>0)return{data:e,extraData:void 0,message:e.message};return{data:void 0,extraData:void 0,message:e.message}}function F(t){return t instanceof ReadableStream||typeof t==="object"&&t!==null&&typeof t.getReader==="function"}function k(t){if(Array.isArray(t))return t[0]??"";return t??""}export function resolveBuilder(t){const e=t.ctx?.builder??t.res?.builder??t.socket?.builder;if(e)return e;throw Error(`[${h.packageName}] use dtoMiddleware() — builder attaches at request start via @xrystal/dto adapter`)}export class BaseController{system=x.get(T);logger=x.get(S);supportedProtocols=[y.HTTP,y.WEBSOCKET];get store(){return getControllerCtx()}get protocol(){return this.store?.protocol||y.HTTP}get req(){const t=this.store,e=t?.ctx||{},r=t?.req||{},a=M(e.request)?e.request:void 0,o=I(e.request),n=e.headers??r.headers??a?.headers??o?.headers,s=n instanceof Headers?Object.fromEntries(n.entries()):n??{},i=a?.url??o?.url??r.url??e.url??"";let c=t?.metadata?.parsedQuery||e.query||r.query||o?.query||{};if(!Object.keys(c).length&&i.includes("?"))c=g.parse(i.split("?")[1]);let u=e.cookies||r.cookies||o?.cookies||{};const d=s.cookie;if(!Object.keys(u).length&&typeof d==="string")u=Object.fromEntries(d.split(";").map((f)=>{const[m,p]=f.trim().split("=");return[decodeURIComponent(m),decodeURIComponent(p||"")]}));return{url:i,method:(e.method||r.method||a?.method||o?.method||"").toUpperCase(),headers:s,body:t?.metadata?.parsedBody||e.body||r.body||o?.body||{},query:c,params:{...r.params,...e.params,...o?.params,...o?.routeParams},cookies:u,ip:D(r,e),lang:e.lang||r.lang||"en",requestId:t?.requestId??e.requestId??r.ctx?.requestId??String(s["x-request-id"]??s["x-correlation-id"]??""),startTime:e.startTime??r.ctx?.startTime??Date.now(),t:e.t||r.t||((f)=>f),accounts:e.accounts||r.accounts||e.user}}get res(){const t=this.store;if(!t)throw Error(`[${h.packageName}] controller context missing`);const e=t.metadata?.locals??{};return{builder:resolveBuilder(t),locals:e}}async parseRequestBody(){const t=this.store;if(!t)return;const e=t.ctx?.request,r=t.req||e||t.ctx?.req,a=this.req,o=k(a.headers["content-type"]).toLowerCase(),n=parseInt(k(a.headers["content-length"])||"-1",10);let s=a.body;const i=(d)=>{if(!d)return{};if(o.includes("application/json"))try{return JSON.parse(d)}catch{return d}if(o.includes("application/x-www-form-urlencoded"))return g.parse(d);try{return JSON.parse(d)}catch{try{return g.parse(d)}catch{return d}}},c=F,u=s&&typeof s==="object"&&!c(s)&&Object.keys(s).length>0;if(!q(this.protocol)&&!["GET","HEAD","OPTIONS"].includes(a.method)&&!u){if(r instanceof Request&&(c(s)||n>0))try{s=i(await r.clone().text())}catch{if(typeof s==="string")s=i(s)}else if(r&&typeof r==="object"&&"on"in r&&typeof r.on==="function"&&n!==0){const d=r;s=await new Promise((f)=>{let m="";const p=setTimeout(()=>f({}),200);d.on("data",(C)=>{m+=String(C)});d.on("end",()=>{clearTimeout(p);f(i(m))});d.on("error",()=>{clearTimeout(p);f({})})})}else if(typeof s==="string"&&s.length)s=i(s)}if(typeof FormData<"u"&&s instanceof FormData)s=Object.fromEntries(s.entries());if(!t.metadata)t.metadata={locals:{}};t.metadata.parsedBody=s||{};t.metadata.parsedQuery=a.query}}export default class Controller extends BaseController{async onInit(){await this.syncFromTmp();E(this)}syncFromTmp=()=>{this.supportedProtocols=O()};parseMessage(t,e,r=!1){return P(t,e,r)}args(t){const e=this.req,r=this.store.metadata?.locals??{};return{req:e,res:{builder:t,locals:r},builder:t,body:e.body,query:e.query,queries:e.query,params:e.params,cookies:e.cookies,locals:r,t:e.t}}fail(t,e,r){w(t,e);const{data:a,extraData:o}=R(e),n=l(e),s=this.parseMessage(n?.message??e,r,!0),i=a!==void 0||o!==void 0?{data:a,extraData:o}:void 0;return(a!==void 0?t.as.fail(a,s,i):t.as.fail(s,i)).build()}ok(t,e,r,a){let o="success_process",n=e!==void 0?e:r;if(typeof e==="string"){o=e;n=r}const{data:s,extraData:i,message:c}=R(n);if(typeof c==="string")o=c;w(t,n);return t.as.ok(s,this.parseMessage(o,a,!1),i!==void 0?{extraData:i}:void 0).build()}async schema({checks:t,logic:e,response:r}){const a=resolveBuilder(this.store);try{await this.parseRequestBody();const n=this.args(a);if(t){const u=await t(n);if(u!==!0)return this.fail(a,u,n.req.t)}let s=e?await e(n):{};const i=l(s);if(i&&typeof i.response==="function")s=await i.response();if(b(s))return s;if(i?.status===!1)return this.fail(a,s,n.req.t);const c=r?await r({...n,logicResult:s}):s;if(b(c))return c;return this.ok(a,c,s,n.req.t)}catch(o){const n=o instanceof Error?o.message:String(o);this.logger?.log(j.ERROR,`Controller Error: ${n}`);return a.as.internalServerError(this.parseMessage(n,this.req.t,!0)).build()}}ctr(t,e){const{framework:r,protocol:a}=A(e),o=()=>this.schema(t);if(q(a))return N(o,a);return H(o,r)}}
|
|
@@ -36,6 +36,9 @@ export declare class Constants {
|
|
|
36
36
|
environments: string;
|
|
37
37
|
dist: string;
|
|
38
38
|
};
|
|
39
|
+
static readonly cliBinFile: string;
|
|
40
|
+
/** Prefer package name in logs/errors (not a short brand alias). */
|
|
41
|
+
static readonly logTag: string;
|
|
39
42
|
static readonly bundledCoreTmpPath: string;
|
|
40
43
|
}
|
|
41
44
|
export { seedFromTmp, loadSeedFromBundledTmp } from '../../utils/helpers/tmp/seed-from-tmp';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import n from"node:path";import{packageRootDir as q}from"../../utils/package-root";import b from"./defaults.json" with { type: 'json' };import{seedFromTmp as j}from"../../utils/helpers/tmp/seed-from-tmp";export const packageDefaults=Object.freeze({...b,mainSourceFolder:j.sourceFolder,framework:j.framework,layoutPaths:Object.freeze({...j.layout}),brand:Object.freeze({...b.brand}),buildDefaults:Object.freeze({...b.buildDefaults}),tmpWatchDefaults:Object.freeze({...b.tmpWatchDefaults}),cliBinNames:Object.freeze([...b.cliBinNames??[b.cliName]])}),coreVersionPattern=/^\d{2}\.\d{2}\.\d{2}-v\d+$/,semverVersionPattern=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$/;const v=`${packageDefaults.tmpBaseName}${packageDefaults.tmpExtension}`;export class Constants{static packageName=packageDefaults.packageName;static packageRootFolder=packageDefaults.packageRootFolder;static tmpBaseName=packageDefaults.tmpBaseName;static tmpExtension=packageDefaults.tmpExtension;static publicFolderName=packageDefaults.publicFolderName;static kafkaLogsTopic=packageDefaults.kafkaLogsTopic;static templateRepoUri=packageDefaults.templateRepoUri;static cliName=packageDefaults.cliName;static cliBinNames=packageDefaults.cliBinNames;static pathAliasKey=packageDefaults.pathAliasKey;static brand=packageDefaults.brand;static mainSourceFolder=packageDefaults.mainSourceFolder;static framework=packageDefaults.framework;static layoutPaths=packageDefaults.layoutPaths;static bundledCoreTmpPath=n.join(q,packageDefaults.packageRootFolder,v)}export{seedFromTmp,loadSeedFromBundledTmp}from"../../utils/helpers/tmp/seed-from-tmp";
|
|
1
|
+
import n from"node:path";import{packageRootDir as q}from"../../utils/package-root";import b from"./defaults.json" with { type: 'json' };import{seedFromTmp as j}from"../../utils/helpers/tmp/seed-from-tmp";export const packageDefaults=Object.freeze({...b,mainSourceFolder:j.sourceFolder,framework:j.framework,layoutPaths:Object.freeze({...j.layout}),brand:Object.freeze({...b.brand}),buildDefaults:Object.freeze({...b.buildDefaults}),tmpWatchDefaults:Object.freeze({...b.tmpWatchDefaults}),cliBinNames:Object.freeze([...b.cliBinNames??[b.cliName]])}),coreVersionPattern=/^\d{2}\.\d{2}\.\d{2}-v\d+$/,semverVersionPattern=/^\d+\.\d+\.\d+(?:-[0-9A-Za-z-.]+)?(?:\+[0-9A-Za-z-.]+)?$/;const v=`${packageDefaults.tmpBaseName}${packageDefaults.tmpExtension}`;export class Constants{static packageName=packageDefaults.packageName;static packageRootFolder=packageDefaults.packageRootFolder;static tmpBaseName=packageDefaults.tmpBaseName;static tmpExtension=packageDefaults.tmpExtension;static publicFolderName=packageDefaults.publicFolderName;static kafkaLogsTopic=packageDefaults.kafkaLogsTopic;static templateRepoUri=packageDefaults.templateRepoUri;static cliName=packageDefaults.cliName;static cliBinNames=packageDefaults.cliBinNames;static pathAliasKey=packageDefaults.pathAliasKey;static brand=packageDefaults.brand;static mainSourceFolder=packageDefaults.mainSourceFolder;static framework=packageDefaults.framework;static layoutPaths=packageDefaults.layoutPaths;static cliBinFile=packageDefaults.cliBinFile??"main-cli.js";static logTag=packageDefaults.packageName;static bundledCoreTmpPath=n.join(q,packageDefaults.packageRootFolder,v)}export{seedFromTmp,loadSeedFromBundledTmp}from"../../utils/helpers/tmp/seed-from-tmp";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{FrameworkEnum as G,ProtocolEnum as K}from"../../../utils/models";import{detectSocketProtocol as L}from"../../../utils/helpers/protocol";import{getFramework as M}from"../../../utils/helpers/framework";import{runAction as I}from"../../../utils/helpers/handlers/execute";export function toRealtimeHandler(z,D){const B=(b)=>{const J=L(b,D);return I({socket:b,ctx:{ws:b},protocol:J},z)},j=(b)=>B(b);j.with=(b)=>()=>B(b);return j}export const toHandler=(z,D)=>{const B=D??M();switch(B){case G.ELYSIA:return(j)=>I({framework:B,ctx:j},z);case G.FETCH:return(j,b)=>I({framework:B,ctx:{request:j,...b}},z);case G.NODE:return(j,b)=>I({framework:B,req:j,res:b},z,b);case G.EXPRESS:return(j,b,J)=>{I({framework:B,req:j,res:b,metadata:{locals:b.locals||{}}},z,b).catch(J)};case G.WEBSOCKET:case G.SOCKETIO:throw Error(
|
|
1
|
+
import{FrameworkEnum as G,ProtocolEnum as K}from"../../../utils/models";import{detectSocketProtocol as L}from"../../../utils/helpers/protocol";import{getFramework as M}from"../../../utils/helpers/framework";import{runAction as I}from"../../../utils/helpers/handlers/execute";import{Constants as N}from"../../../utils/constants";export function toRealtimeHandler(z,D){const B=(b)=>{const J=L(b,D);return I({socket:b,ctx:{ws:b},protocol:J},z)},j=(b)=>B(b);j.with=(b)=>()=>B(b);return j}export const toHandler=(z,D)=>{const B=D??M();switch(B){case G.ELYSIA:return(j)=>I({framework:B,ctx:j},z);case G.FETCH:return(j,b)=>I({framework:B,ctx:{request:j,...b}},z);case G.NODE:return(j,b)=>I({framework:B,req:j,res:b},z,b);case G.EXPRESS:return(j,b,J)=>{I({framework:B,req:j,res:b,metadata:{locals:b.locals||{}}},z,b).catch(J)};case G.WEBSOCKET:case G.SOCKETIO:throw Error(`[${N.packageName}] realtime: ctr({ ... }, { protocol: "ws" | "socketio" })`);default:return(j)=>I({framework:G.ELYSIA,ctx:j},z)}},toWebSocket=(z,D)=>toRealtimeHandler(D,K.WEBSOCKET)(z),toSocketIo=(z,D)=>toRealtimeHandler(D,K.SOCKETIO)(z);
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { ProtocolEnum } from '../../../utils/models/enums';
|
|
2
2
|
import { getRuntimeTmpConfigs } from '../../../utils/helpers/tmp/runtime-tmp';
|
|
3
|
-
declare const REALTIME_MIDDLEWARE_HINT
|
|
3
|
+
declare const REALTIME_MIDDLEWARE_HINT: string;
|
|
4
4
|
export declare function parseProtocol(value: unknown): ProtocolEnum;
|
|
5
5
|
export declare function isRealtimeProtocol(protocol?: ProtocolEnum): boolean;
|
|
6
6
|
export declare function isHttpProtocol(protocol?: ProtocolEnum): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ProtocolEnum as h}from"../../../utils/models/enums";import{getRuntimeTmpConfigs as
|
|
1
|
+
import{Constants as J}from"../../../utils/constants";import{ProtocolEnum as h}from"../../../utils/models/enums";import{getRuntimeTmpConfigs as K}from"../../../utils/helpers/tmp/runtime-tmp";const G={http:h.HTTP,https:h.HTTPS,ws:h.WEBSOCKET,websocket:h.WEBSOCKET,socketio:h.SOCKETIO,socket:h.SOCKETIO},REALTIME_MIDDLEWARE_HINT=`[${J.packageName}] tmp.yml lists both ws and socketio — use realtimeMiddleware("ws") or realtimeMiddleware("socketio")`;export function parseProtocol(b){if(!b)return h.HTTP;const j=String(b).toLowerCase().replace(/[-_\s.]/g,"");if(G[j])return G[j];return Object.values(h).includes(String(b))?b:h.HTTP}export function isRealtimeProtocol(b){return b===h.WEBSOCKET||b===h.SOCKETIO}export function isHttpProtocol(b){return!b||b===h.HTTP||b===h.HTTPS}function B(){return K()?.service}export function resolveProtocolsFromConfig(b){const j=b?.protocols;if(!j)return[h.HTTP];return(Array.isArray(j)?j:[j]).map(parseProtocol)}export function getConfiguredProtocols(){try{return resolveProtocolsFromConfig(B())}catch{return[h.HTTP,h.WEBSOCKET]}}export function getConfiguredRealtimeProtocols(b){return resolveProtocolsFromConfig(b).filter(isRealtimeProtocol)}export function defaultRealtimeProtocolFromConfig(b){const j=getConfiguredRealtimeProtocols(b);if(j.length===1)return j[0];if(j.length>1)return;return h.WEBSOCKET}export function getDefaultRealtimeProtocol(){try{return defaultRealtimeProtocolFromConfig(B())}catch{return h.WEBSOCKET}}export function resolveRealtimeMiddlewareProtocol(b,j){if(b!==void 0&&b!==null&&b!=="")return parseProtocol(b);let q=j;if(!q)try{q=B()}catch{return h.WEBSOCKET}const z=getConfiguredRealtimeProtocols(q);if(z.length===1)return z[0];if(z.length>1)throw Error(REALTIME_MIDDLEWARE_HINT);return h.WEBSOCKET}export function detectSocketProtocol(b,j){if(j)return j;const q=b;if(q?.__xrystalProtocol)return q.__xrystalProtocol;return h.WEBSOCKET}export function attachSocketTransport(b,j,q){const z=b;if(j===h.SOCKETIO)q.attachSocketIo(b);else q.attachWebSocket(b);z.__xrystalProtocol=j}export{REALTIME_MIDDLEWARE_HINT};
|
|
@@ -4,6 +4,6 @@ export type GStoreBoot = {
|
|
|
4
4
|
warnOnRequestKeys: boolean;
|
|
5
5
|
vars: Record<string, unknown>;
|
|
6
6
|
};
|
|
7
|
-
export declare const G_PROP_NOT_ALLOWED
|
|
7
|
+
export declare const G_PROP_NOT_ALLOWED: string;
|
|
8
8
|
export declare function resolveGStoreBoot(tmp?: Record<string, unknown>): GStoreBoot;
|
|
9
9
|
export declare function propsFromTmp(tmp?: Record<string, unknown>): Record<string, unknown>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Constants as I}from"../../../utils/constants";import{readTmpServiceBlock as J}from"../../../utils/helpers/tmp/tmp-schema";export const G_PROP_NOT_ALLOWED=`[${I.packageName}] G prop not declared in tmp.yml vars — set autoCreateProps: true to allow runtime keys`;const F=()=>({});function L(j){return J(j).loaders?.system?.gStore}function M(j){if(typeof j.bootstrap==="boolean")return j.bootstrap;return!0}function Q(j){if(typeof j.autoCreateProps==="boolean")return j.autoCreateProps;return!0}function U(j){if(typeof j.warnOnRequestKeys==="boolean")return j.warnOnRequestKeys;return!0}export function resolveGStoreBoot(j={}){const x=j.configs??j,z=L(x);if(!z)return{bootstrap:!0,allowAutoCreateProps:!0,warnOnRequestKeys:!0,vars:F()};const E=z.options??{},D=z.vars,H=D&&typeof D==="object"&&!Array.isArray(D)?{...D}:F();return{bootstrap:M(E),allowAutoCreateProps:Q(E),warnOnRequestKeys:U(E),vars:H}}export function propsFromTmp(j={}){const x=resolveGStoreBoot(j);return x.bootstrap?x.vars:F()}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export declare const G_REQUEST_KEY_WARN
|
|
1
|
+
export declare const G_REQUEST_KEY_WARN: string;
|
|
2
2
|
export declare function looksLikeRequestScopedKey(key: string): boolean;
|
|
3
3
|
export declare function warnIfRequestScopedKey(key: string, enabled: boolean): void;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
import{Constants as B}from"../../../utils/constants";import{getRunContext as D}from"../../../utils/helpers/context";import{getControllerCtx as F}from"../../../utils/helpers/context/controller-store";export const G_REQUEST_KEY_WARN=`[${B.packageName}] G: key looks request-scoped — use run/controller context, not global G`;const H=new Set(["requestid","reqid","correlationid","cookies","cookie","headers","header","body","query","queries","params","locals","session","sessionid"]);export function looksLikeRequestScopedKey(j){const z=j.trim();if(!z)return!1;const f=z.toLowerCase();if(H.has(f))return!0;if(f.endsWith("requestid")||f.endsWith("correlationid"))return!0;if(f==="req"||f==="res")return!0;return!1}export function warnIfRequestScopedKey(j,z){if(!z||!looksLikeRequestScopedKey(j))return;const f=D()?"run":F()?"controller":"outside-request";console.warn(`${G_REQUEST_KEY_WARN} (key: ${j}, scope: ${f})`)}
|
|
@@ -2,6 +2,7 @@ export { setRuntimeTmpConfigs, getRuntimeTmpConfigs, onRuntimeTmpChange, notifyR
|
|
|
2
2
|
export { getTmpLoader, getTmpLoaderPath, getTmpSnapshot, onTmpReload, resetTmpLoaderForTests, stopTmpLoader, } from '../../../utils/helpers/tmp/tmp-loader';
|
|
3
3
|
export { bindLoaderTmpSync, type ITmpSyncLoader, } from '../../../utils/helpers/tmp/loader-tmp-sync';
|
|
4
4
|
export { resolveTmpWatchIntervalMs } from '../../../utils/helpers/tmp/tmp-watch';
|
|
5
|
-
export { normalizeTmpDocument, normalizeRootFolder, normalizeSourceFolder, readTmpCoreBlock, readTmpServiceBlock, resolveServiceLayoutPaths, resolveTmpRuntimeConfigs, } from '../../../utils/helpers/tmp/tmp-schema';
|
|
5
|
+
export { normalizeTmpDocument, normalizeRootFolder, normalizeSourceFolder, normalizeRuntime, normalizeBundler, resolveEffectiveBundler, readTmpCoreBlock, readTmpServiceBlock, readTmpGlobalBlock, applyTmpGlobalVars, resolveServiceLayoutPaths, resolveTmpRuntimeConfigs, } from '../../../utils/helpers/tmp/tmp-schema';
|
|
6
6
|
export { loadSeedFromBundledTmp, seedFromTmp, type SeedFromTmp, type SeedLayoutPaths, } from '../../../utils/helpers/tmp/seed-from-tmp';
|
|
7
7
|
export { normalizeLayoutPaths, type LayoutPaths, } from '../../../utils/helpers/tmp/path-normalize';
|
|
8
|
+
export { healToolchainIfLayoutNeedsSync, layoutFingerprint, layoutOptionsFromRuntimeConfigs, resetToolchainHealState, writeTsconfigFromLayout, auditTsconfigAgainstLayout, type ToolchainHealResult, type ToolchainLayoutOptions, } from '../../../utils/helpers/tmp/toolchain-heal';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export{setRuntimeTmpConfigs,getRuntimeTmpConfigs,onRuntimeTmpChange,notifyRuntimeTmpChange,clearRuntimeTmpConfigs}from"../../../utils/helpers/tmp/runtime-tmp";export{getTmpLoader,getTmpLoaderPath,getTmpSnapshot,onTmpReload,resetTmpLoaderForTests,stopTmpLoader}from"../../../utils/helpers/tmp/tmp-loader";export{bindLoaderTmpSync}from"../../../utils/helpers/tmp/loader-tmp-sync";export{resolveTmpWatchIntervalMs}from"../../../utils/helpers/tmp/tmp-watch";export{normalizeTmpDocument,normalizeRootFolder,normalizeSourceFolder,readTmpCoreBlock,readTmpServiceBlock,resolveServiceLayoutPaths,resolveTmpRuntimeConfigs}from"../../../utils/helpers/tmp/tmp-schema";export{loadSeedFromBundledTmp,seedFromTmp}from"../../../utils/helpers/tmp/seed-from-tmp";export{normalizeLayoutPaths}from"../../../utils/helpers/tmp/path-normalize";
|
|
1
|
+
export{setRuntimeTmpConfigs,getRuntimeTmpConfigs,onRuntimeTmpChange,notifyRuntimeTmpChange,clearRuntimeTmpConfigs}from"../../../utils/helpers/tmp/runtime-tmp";export{getTmpLoader,getTmpLoaderPath,getTmpSnapshot,onTmpReload,resetTmpLoaderForTests,stopTmpLoader}from"../../../utils/helpers/tmp/tmp-loader";export{bindLoaderTmpSync}from"../../../utils/helpers/tmp/loader-tmp-sync";export{resolveTmpWatchIntervalMs}from"../../../utils/helpers/tmp/tmp-watch";export{normalizeTmpDocument,normalizeRootFolder,normalizeSourceFolder,normalizeRuntime,normalizeBundler,resolveEffectiveBundler,readTmpCoreBlock,readTmpServiceBlock,readTmpGlobalBlock,applyTmpGlobalVars,resolveServiceLayoutPaths,resolveTmpRuntimeConfigs}from"../../../utils/helpers/tmp/tmp-schema";export{loadSeedFromBundledTmp,seedFromTmp}from"../../../utils/helpers/tmp/seed-from-tmp";export{normalizeLayoutPaths}from"../../../utils/helpers/tmp/path-normalize";export{healToolchainIfLayoutNeedsSync,layoutFingerprint,layoutOptionsFromRuntimeConfigs,resetToolchainHealState,writeTsconfigFromLayout,auditTsconfigAgainstLayout}from"../../../utils/helpers/tmp/toolchain-heal";
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{onRuntimeTmpChange as
|
|
1
|
+
import{packageDefaults as w}from"../../../utils/constants";import{onRuntimeTmpChange as x}from"../../../utils/helpers/tmp/runtime-tmp";export function bindLoaderTmpSync(j){const q=j.constructor.name;x(async()=>{try{await j.syncFromTmp()}catch(b){const v=b instanceof Error?b.message:String(b);console.warn(`[${w.packageName}] ${q} tmp reload failed: ${v}`)}})}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
let
|
|
1
|
+
import{packageDefaults as A}from"../../../utils/constants";import{healToolchainIfLayoutNeedsSync as B,resetToolchainHealState as E}from"../../../utils/helpers/tmp/toolchain-heal";let v;const w=[];export function setRuntimeTmpConfigs(j){v=j}export function getRuntimeTmpConfigs(){return v}export function onRuntimeTmpChange(j){w.push(j);return()=>{const b=w.indexOf(j);if(b>=0)w.splice(b,1)}}export async function notifyRuntimeTmpChange(j){if(j)v=j;const b=v;if(!b)return;if(b.rootFolderPath&&b.service?.paths)try{B(process.cwd(),b)}catch(q){const z=q instanceof Error?q.message:String(q);console.warn(`[${A.packageName}] toolchain auto-sync skipped: ${z}`)}for(const q of w)await q(b)}export function clearRuntimeTmpConfigs(){v=void 0;w.length=0;E()}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export declare function interpolateWithContext<T>(value: T, context: Record<string, unknown>): T;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import f from"handlebars";function e(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)}export function interpolateWithContext(r,n){if(typeof r==="string"){if(!r.includes("{{"))return r;return f.compile(r)(n)}if(Array.isArray(r))return r.map((t)=>interpolateWithContext(t,n));if(e(r)){const t={};for(const[i,o]of Object.entries(r))t[i]=interpolateWithContext(o,n);return t}return r}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { BundlerEnum, RuntimeEnum } from '../../../utils/models/enums';
|
|
1
2
|
export type TmpServiceSpecialPaths = {
|
|
2
3
|
tests?: string;
|
|
3
4
|
environments?: string;
|
|
@@ -21,12 +22,17 @@ export type TmpCoreBlock = {
|
|
|
21
22
|
fileWatchIntervalMs?: number | string;
|
|
22
23
|
};
|
|
23
24
|
};
|
|
25
|
+
export type TmpGlobalBlock = {
|
|
26
|
+
runtime: RuntimeEnum;
|
|
27
|
+
vars: Record<string, unknown>;
|
|
28
|
+
};
|
|
24
29
|
export type TmpLayoutPathsFlat = {
|
|
25
30
|
tests: string;
|
|
26
31
|
environments: string;
|
|
27
32
|
dist: string;
|
|
28
33
|
};
|
|
29
34
|
export type TmpRuntimeConfigs = {
|
|
35
|
+
global: TmpGlobalBlock;
|
|
30
36
|
service: TmpServiceBlock & {
|
|
31
37
|
paths: Required<Pick<TmpServicePathsBlock, 'root' | 'source'>> & {
|
|
32
38
|
special: TmpLayoutPathsFlat;
|
|
@@ -35,10 +41,16 @@ export type TmpRuntimeConfigs = {
|
|
|
35
41
|
core: TmpCoreBlock;
|
|
36
42
|
rootFolderPath: string;
|
|
37
43
|
};
|
|
44
|
+
export declare function normalizeRuntime(value: unknown): RuntimeEnum;
|
|
45
|
+
export declare function normalizeBundler(value: unknown): BundlerEnum;
|
|
46
|
+
export declare function resolveEffectiveBundler(bundler: BundlerEnum, runtime: RuntimeEnum): Exclude<BundlerEnum, BundlerEnum.AUTO>;
|
|
38
47
|
export declare function normalizeRootFolder(value?: string): string;
|
|
39
48
|
export declare function normalizeSourceFolder(value?: string): string;
|
|
49
|
+
export declare function readTmpGlobalBlock(configs?: Record<string, unknown>): TmpGlobalBlock;
|
|
40
50
|
export declare function readTmpCoreBlock(configs?: Record<string, unknown>): TmpCoreBlock;
|
|
41
51
|
export declare function readTmpServiceBlock(configs?: Record<string, unknown>): TmpServiceBlock;
|
|
42
52
|
export declare function resolveServiceLayoutPaths(service: TmpServiceBlock): TmpLayoutPathsFlat;
|
|
53
|
+
export declare function buildTmpVarContext(global: TmpGlobalBlock): Record<string, unknown>;
|
|
54
|
+
export declare function applyTmpGlobalVars(tmp: Record<string, unknown>): Record<string, unknown>;
|
|
43
55
|
export declare function resolveTmpRuntimeConfigs(tmp?: Record<string, unknown> | null): TmpRuntimeConfigs;
|
|
44
56
|
export declare function normalizeTmpDocument(tmp: Record<string, unknown>): Record<string, unknown>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import
|
|
1
|
+
import X from"../../../utils/constants/defaults.json" with { type: 'json' };import{BundlerEnum as H,RuntimeEnum as O}from"../../../utils/models/enums";import{seedFromTmp as Q}from"../../../utils/helpers/tmp/seed-from-tmp";import{interpolateWithContext as Z}from"../../../utils/helpers/tmp/tmp-interpolate";import{normalizeLayoutPaths as _,normalizeRootFolder as $,normalizeSourceFolder as I}from"../../../utils/helpers/tmp/path-normalize";function D(j){return typeof j==="object"&&j!==null&&!Array.isArray(j)}function x(j){if(typeof j==="number"||typeof j==="string")return j;return}export function normalizeRuntime(j){const q=typeof j==="string"?j.trim().toLowerCase():"";if(q===O.NODE)return O.NODE;if(q===O.BUN)return O.BUN;return O.BUN}export function normalizeBundler(j){const q=typeof j==="string"?j.trim().toLowerCase():"";if(q===H.TSC)return H.TSC;if(q===H.ESBUILD)return H.ESBUILD;if(q===H.BUN)return H.BUN;if(q===H.AUTO)return H.AUTO;return H.AUTO}export function resolveEffectiveBundler(j,q){if(j!==H.AUTO)return j;return q===O.NODE?H.TSC:H.BUN}export function normalizeRootFolder(j){return $(j,X.packageRootFolder)}export function normalizeSourceFolder(j){return I(j,Q.sourceFolder)}export function readTmpGlobalBlock(j){const q=D(j?.global)?j.global:{},A=D(q.vars)?q.vars:{};return{runtime:normalizeRuntime(q.runtime),vars:{...A}}}export function readTmpCoreBlock(j){const q=D(j?.core)?j.core:{},A=D(q.tmp)?q.tmp:{};return{tmp:{fileWatchIntervalMs:x(A.fileWatchIntervalMs)}}}export function readTmpServiceBlock(j){const q=D(j?.service)?j.service:{},A=D(q.paths)?q.paths:{},J=D(A.special)?A.special:{};let K=D(q.loaders)?{...q.loaders}:void 0,M=D(q.build)?q.build:void 0;if(K&&D(K.build)){const{build:U,...Y}=K;K=Y;if(!M&&D(U))M=U}return{name:typeof q.name==="string"?q.name:void 0,framework:typeof q.framework==="string"?q.framework:void 0,paths:{root:typeof A.root==="string"?A.root:void 0,source:typeof A.source==="string"?A.source:void 0,special:{tests:typeof J.tests==="string"?J.tests:void 0,environments:typeof J.environments==="string"?J.environments:void 0,dist:typeof J.dist==="string"?J.dist:void 0}},protocols:q.protocols,loaders:K,build:M}}export function resolveServiceLayoutPaths(j){return _(j.paths?.special,Q.layout)}function L(j){const q=resolveServiceLayoutPaths(j);return{name:j.name,framework:j.framework??Q.framework,paths:{root:j.paths?.root??X.packageRootFolder,source:j.paths?.source??Q.sourceFolder,special:q},protocols:j.protocols,loaders:j.loaders,build:j.build}}function N(j){return{tmp:{fileWatchIntervalMs:j.tmp?.fileWatchIntervalMs}}}export function buildTmpVarContext(j){return{...j.vars,runtime:j.runtime,global:j}}export function applyTmpGlobalVars(j){const q=D(j.configs)?j.configs:{},A=readTmpGlobalBlock(q);return Z(j,buildTmpVarContext(A))}export function resolveTmpRuntimeConfigs(j){const q=D(j?.configs)?j.configs:{},A=readTmpGlobalBlock(q),J=readTmpServiceBlock(q),K=readTmpCoreBlock(q),M=L(J);return{global:A,service:M,core:N(K),rootFolderPath:normalizeRootFolder(M.paths.root)}}export function normalizeTmpDocument(j){const q=applyTmpGlobalVars(j);return{...q,configs:resolveTmpRuntimeConfigs(q)}}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import type { TmpRuntimeConfigs } from '../../../utils/helpers/tmp/tmp-schema';
|
|
2
|
+
export type ToolchainLayoutOptions = {
|
|
3
|
+
rootFolderPath: string;
|
|
4
|
+
mainFolderPath: string;
|
|
5
|
+
pathsDist: string;
|
|
6
|
+
pathsTests: string;
|
|
7
|
+
};
|
|
8
|
+
export type ToolchainHealResult = {
|
|
9
|
+
healed: boolean;
|
|
10
|
+
reason?: 'bootstrap' | 'layout-changed';
|
|
11
|
+
tsconfigRel: string;
|
|
12
|
+
fingerprint: string;
|
|
13
|
+
};
|
|
14
|
+
export declare function layoutOptionsFromRuntimeConfigs(configs: TmpRuntimeConfigs): ToolchainLayoutOptions;
|
|
15
|
+
export declare function layoutFingerprint(options: ToolchainLayoutOptions): string;
|
|
16
|
+
export declare function resolveRecommendedTsconfig(options: ToolchainLayoutOptions): {
|
|
17
|
+
include: string[];
|
|
18
|
+
exclude: string[];
|
|
19
|
+
compilerOptions: {
|
|
20
|
+
baseUrl: string;
|
|
21
|
+
paths: {
|
|
22
|
+
[x: string]: string[];
|
|
23
|
+
};
|
|
24
|
+
rootDir: string;
|
|
25
|
+
outDir: string;
|
|
26
|
+
};
|
|
27
|
+
};
|
|
28
|
+
export declare function auditTsconfigAgainstLayout(root: string, options: ToolchainLayoutOptions, tsconfigRel?: string): {
|
|
29
|
+
ok: boolean;
|
|
30
|
+
missing: boolean;
|
|
31
|
+
notes: string[];
|
|
32
|
+
};
|
|
33
|
+
export declare function writeTsconfigFromLayout(root: string, options: ToolchainLayoutOptions, tsconfigRel?: string): {
|
|
34
|
+
wrote: boolean;
|
|
35
|
+
created: boolean;
|
|
36
|
+
abs: string;
|
|
37
|
+
};
|
|
38
|
+
/** Test/reset helper — clears in-memory layout fingerprint. */
|
|
39
|
+
export declare function resetToolchainHealState(): void;
|
|
40
|
+
/**
|
|
41
|
+
* Live pulse: sync tsconfig only when layout paths change, or once on bootstrap if already drifted.
|
|
42
|
+
* Non-path tmp edits do not rewrite toolchain files.
|
|
43
|
+
*/
|
|
44
|
+
export declare function healToolchainIfLayoutNeedsSync(root: string, configs: TmpRuntimeConfigs, options?: {
|
|
45
|
+
quiet?: boolean;
|
|
46
|
+
}): ToolchainHealResult;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import N from"node:fs";import X from"node:path";import{packageDefaults as J}from"../../../utils/constants";import{normalizeSourceFolder as $}from"../../../utils/helpers/tmp/path-normalize";function Y(j){return String(j).replace(/^\.\//,"")}export function layoutOptionsFromRuntimeConfigs(j){const q=j.service?.paths,B=q?.special;return{rootFolderPath:j.rootFolderPath||J.packageRootFolder,mainFolderPath:$(q?.source,J.mainSourceFolder),pathsDist:B?.dist||J.layoutPaths.dist,pathsTests:B?.tests||J.layoutPaths.tests}}export function layoutFingerprint(j){return[j.rootFolderPath,Y(j.mainFolderPath),j.pathsDist,j.pathsTests].join("\x00")}export function resolveRecommendedTsconfig(j){const q=Y(j.mainFolderPath),B=j.rootFolderPath,H=J.pathAliasKey;return{include:[q],exclude:[`${B}/${j.pathsTests}`],compilerOptions:{baseUrl:".",paths:{[H]:[`${q}/*`]},rootDir:`./${q}`,outDir:`./${B}/${j.pathsDist}`}}}function A(j){const q=X.join(j,"package.json");if(!N.existsSync(q))return`${J.packageName}/tsconfig.base.json`;try{if(JSON.parse(N.readFileSync(q,"utf8")).name===J.packageName)return"./tsconfig.base.json"}catch{}return`${J.packageName}/tsconfig.base.json`}function C(j,q,B){const H=q.compilerOptions??{};return{...q,extends:q.extends??B,include:j.include,exclude:j.exclude,compilerOptions:{...H,baseUrl:j.compilerOptions.baseUrl,paths:j.compilerOptions.paths,rootDir:j.compilerOptions.rootDir,outDir:j.compilerOptions.outDir}}}export function auditTsconfigAgainstLayout(j,q,B=J.buildDefaults?.tsconfig??"tsconfig.json"){const H=X.join(j,B);if(!N.existsSync(H))return{ok:!1,missing:!0,notes:[`${B} missing`]};let I;try{I=JSON.parse(N.readFileSync(H,"utf8"))}catch{return{ok:!1,missing:!1,notes:[`${B} unreadable`]}}const G=resolveRecommendedTsconfig(q),M=[],U=I.compilerOptions??{},V=J.pathAliasKey;if(U.outDir!==G.compilerOptions.outDir)M.push("outDir drift");if(!(Array.isArray(I.include)?I.include.map(String):[]).some((_)=>Y(_)===G.include[0]))M.push("include drift");const Z=U.paths?.[V];if(JSON.stringify(Z)!==JSON.stringify(G.compilerOptions.paths[V]))M.push(`paths ${V} drift`);return{ok:M.length===0,missing:!1,notes:M}}export function writeTsconfigFromLayout(j,q,B=J.buildDefaults?.tsconfig??"tsconfig.json"){const H=X.join(j,B),I=!N.existsSync(H);let G={};if(!I)try{G=JSON.parse(N.readFileSync(H,"utf8"))}catch{G={}}const M=resolveRecommendedTsconfig(q),U=C(M,G,A(j));N.writeFileSync(H,`${JSON.stringify(U,null,2)}
|
|
2
|
+
`,"utf8");return{wrote:!0,created:I,abs:H}}let Q=null;export function resetToolchainHealState(){Q=null}export function healToolchainIfLayoutNeedsSync(j,q,B={}){const H=layoutOptionsFromRuntimeConfigs(q),I=layoutFingerprint(H),G=J.buildDefaults?.tsconfig??"tsconfig.json",M=auditTsconfigAgainstLayout(j,H,G);if(Q===null){Q=I;if(M.ok)return{healed:!1,tsconfigRel:G,fingerprint:I};writeTsconfigFromLayout(j,H,G);if(!B.quiet)console.info(`[${J.packageName}] toolchain auto-synced (${G}) — bootstrap layout drift`);return{healed:!0,reason:"bootstrap",tsconfigRel:G,fingerprint:I}}if(I===Q)return{healed:!1,tsconfigRel:G,fingerprint:I};Q=I;writeTsconfigFromLayout(j,H,G);if(!B.quiet)console.info(`[${J.packageName}] toolchain auto-synced (${G}) — tmp layout paths changed`);return{healed:!0,reason:"layout-changed",tsconfigRel:G,fingerprint:I}}
|
|
@@ -18,6 +18,16 @@ export declare enum FrameworkEnum {
|
|
|
18
18
|
WEBSOCKET = "websocket",
|
|
19
19
|
SOCKETIO = "socketio"
|
|
20
20
|
}
|
|
21
|
+
export declare enum RuntimeEnum {
|
|
22
|
+
BUN = "bun",
|
|
23
|
+
NODE = "node"
|
|
24
|
+
}
|
|
25
|
+
export declare enum BundlerEnum {
|
|
26
|
+
AUTO = "auto",
|
|
27
|
+
BUN = "bun",
|
|
28
|
+
TSC = "tsc",
|
|
29
|
+
ESBUILD = "esbuild"
|
|
30
|
+
}
|
|
21
31
|
export declare enum PolarityTypeEnum {
|
|
22
32
|
NOTR = 0,
|
|
23
33
|
POSITIVE = 1,
|