gen-session-format-catalog.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. /** Generate the build-static Session format catalog from edge package metadata. */
  2. import { globSync, readFileSync, writeFileSync } from 'node:fs'
  3. import { resolve } from 'node:path'
  4. import { pathToFileURL } from 'node:url'
  5. import type { DshSessionFormatMigrationManifest } from '@deepseek-ai/dsh-package-manifest'
  6. const root = resolve(import.meta.dirname, '..')
  7. const OUT = 'packages/session/session-format-catalog/src/generated.ts'
  8. /** Validated adjacent migration metadata with its resolved package import path. */
  9. export interface SessionFormatMigrationManifest extends Readonly<Omit<DshSessionFormatMigrationManifest, 'export'>> {
  10. readonly packageName: string
  11. readonly importPath: string
  12. }
  13. interface RawManifest {
  14. readonly name?: unknown
  15. readonly dependencies?: Readonly<Record<string, unknown>>
  16. readonly peerDependencies?: Readonly<Record<string, unknown>>
  17. readonly devDependencies?: Readonly<Record<string, unknown>>
  18. readonly dsh?: {
  19. readonly sessionFormatMigration?: Readonly<Record<string, unknown>>
  20. }
  21. }
  22. function readJson(path: string): RawManifest {
  23. return JSON.parse(readFileSync(path, 'utf8')) as RawManifest
  24. }
  25. function safeVersion(value: unknown, label: string): number {
  26. if (!Number.isSafeInteger(value) || (value as number) < 0 || Object.is(value, -0)) {
  27. throw new Error(`gen-session-format-catalog: ${label} must be a non-negative safe integer`)
  28. }
  29. return value as number
  30. }
  31. function nonempty(value: unknown, label: string): string {
  32. if (typeof value !== 'string' || value.length === 0) {
  33. throw new Error(`gen-session-format-catalog: ${label} must be a non-empty string`)
  34. }
  35. return value
  36. }
  37. /**
  38. * Read the current writer version from the core Session source of truth.
  39. * @param scanRoot - repository root whose Session source is authoritative.
  40. * @returns the current non-negative Session format version.
  41. */
  42. export function readCurrentSessionFormatVersion(scanRoot: string = root): number {
  43. const source = readFileSync(resolve(scanRoot, 'packages/core/session/src/types.ts'), 'utf8')
  44. const match = source.match(/export const SESSION_FORMAT_VERSION = (\d+)\b/)
  45. if (match === null) throw new Error('gen-session-format-catalog: cannot read SESSION_FORMAT_VERSION')
  46. return safeVersion(Number(match[1]), 'SESSION_FORMAT_VERSION')
  47. }
  48. /**
  49. * Collect and validate the unique complete adjacent migration inventory.
  50. * @param scanRoot - repository root containing migration package manifests.
  51. * @param currentVersion - writer version the inventory must reach exactly.
  52. * @returns ordered adjacent migration declarations from v0 to the current writer.
  53. */
  54. export function collectSessionFormatMigrations(
  55. scanRoot: string = root,
  56. currentVersion: number = readCurrentSessionFormatVersion(scanRoot),
  57. ): SessionFormatMigrationManifest[] {
  58. const declarations: SessionFormatMigrationManifest[] = []
  59. for (const discovered of globSync('packages/session/session-format-v*-to-v*/package.json', { cwd: scanRoot }).sort()) {
  60. const rel = discovered.replaceAll('\\', '/')
  61. const manifest = readJson(resolve(scanRoot, rel))
  62. const metadata = manifest.dsh?.sessionFormatMigration
  63. if (metadata === undefined) {
  64. throw new Error(`gen-session-format-catalog: ${rel} lacks dsh.sessionFormatMigration`)
  65. }
  66. const allowed: ReadonlySet<string> = new Set<keyof DshSessionFormatMigrationManifest>([
  67. 'from', 'to', 'export', 'migration', 'sourceCodec', 'targetCodec',
  68. 'targetHeaderValidator', 'targetRestorer',
  69. ])
  70. const extra = Object.keys(metadata).find(key => !allowed.has(key))
  71. if (extra !== undefined) throw new Error(`gen-session-format-catalog: ${rel} has unknown metadata member ${extra}`)
  72. const packageName = nonempty(manifest.name, `${rel} name`)
  73. const from = safeVersion(metadata['from'], `${rel} from`)
  74. const to = safeVersion(metadata['to'], `${rel} to`)
  75. if (to !== from + 1) throw new Error(`gen-session-format-catalog: ${rel} must declare adjacent v${from}->v${from + 1}`)
  76. const expectedPackageName = `@deepseek-ai/dsh-session-format-v${from}-to-v${to}`
  77. if (packageName !== expectedPackageName) {
  78. throw new Error(`gen-session-format-catalog: ${rel} name must be ${expectedPackageName}`)
  79. }
  80. const directoryMatch = rel.match(/session-format-v(\d+)-to-v(\d+)\/package\.json$/)
  81. if (directoryMatch === null || Number(directoryMatch[1]) !== from || Number(directoryMatch[2]) !== to) {
  82. throw new Error(`gen-session-format-catalog: ${rel} directory does not match v${from}->v${to}`)
  83. }
  84. const exportPath = nonempty(metadata['export'], `${rel} export`)
  85. declarations.push({
  86. packageName,
  87. importPath: exportPath === '.' ? packageName : `${packageName}/${exportPath.replace(/^\.\//, '')}`,
  88. from,
  89. to,
  90. migration: nonempty(metadata['migration'], `${rel} migration`),
  91. sourceCodec: nonempty(metadata['sourceCodec'], `${rel} sourceCodec`),
  92. targetCodec: nonempty(metadata['targetCodec'], `${rel} targetCodec`),
  93. targetHeaderValidator: nonempty(metadata['targetHeaderValidator'], `${rel} targetHeaderValidator`),
  94. targetRestorer: nonempty(metadata['targetRestorer'], `${rel} targetRestorer`),
  95. })
  96. }
  97. declarations.sort((left, right) => left.from - right.from)
  98. for (let version = 0; version < currentVersion; version += 1) {
  99. const matches = declarations.filter(item => item.from === version)
  100. if (matches.length !== 1) {
  101. throw new Error(`gen-session-format-catalog: expected exactly one v${version}->v${version + 1} package, found ${matches.length}`)
  102. }
  103. }
  104. const extra = declarations.find(item => item.from >= currentVersion)
  105. if (extra !== undefined || declarations.length !== currentVersion) {
  106. throw new Error(`gen-session-format-catalog: migration inventory does not end exactly at current v${currentVersion}`)
  107. }
  108. const catalog = readJson(resolve(scanRoot, 'packages/session/session-format-catalog/package.json'))
  109. if (catalog.dependencies?.['@deepseek-ai/dsh-session'] !== undefined
  110. || catalog.peerDependencies?.['@deepseek-ai/dsh-session'] === undefined
  111. || catalog.devDependencies?.['@deepseek-ai/dsh-session'] === undefined) {
  112. throw new Error(
  113. 'gen-session-format-catalog: catalog must share @deepseek-ai/dsh-session through peer + dev dependencies',
  114. )
  115. }
  116. for (const [index, declaration] of declarations.entries()) {
  117. if (catalog.dependencies?.[declaration.packageName] === undefined) {
  118. throw new Error(`gen-session-format-catalog: catalog package lacks dependency ${declaration.packageName}`)
  119. }
  120. const previous = declarations[index - 1]
  121. if (previous === undefined) continue
  122. if (declaration.sourceCodec !== previous.targetCodec) {
  123. throw new Error(
  124. `gen-session-format-catalog: v${declaration.from} source codec ${declaration.sourceCodec} `
  125. + `does not continue ${previous.targetCodec}`,
  126. )
  127. }
  128. const manifest = readJson(resolve(
  129. scanRoot,
  130. `packages/session/session-format-v${declaration.from}-to-v${declaration.to}/package.json`,
  131. ))
  132. if (manifest.dependencies?.[previous.packageName] === undefined) {
  133. throw new Error(
  134. `gen-session-format-catalog: ${declaration.packageName} must depend on ${previous.packageName} `
  135. + 'to share the adjacent source codec',
  136. )
  137. }
  138. }
  139. return declarations
  140. }
  141. /**
  142. * Render the deterministic direct-import catalog source.
  143. * @param declarations - validated adjacent migrations in version order.
  144. * @param currentVersion - writer version reached by the final declaration.
  145. * @returns complete generated TypeScript source.
  146. */
  147. export function renderSessionFormatCatalog(
  148. declarations: readonly SessionFormatMigrationManifest[],
  149. currentVersion: number,
  150. ): string {
  151. const imports = declarations.map((item) => {
  152. const names = [item.targetCodec, item.migration]
  153. if (item.from === 0) names.push(item.sourceCodec)
  154. if (item.to === currentVersion) names.push(item.targetRestorer, item.targetHeaderValidator)
  155. return `import { ${[...new Set(names)].sort().join(', ')} } from '${item.importPath}'`
  156. })
  157. const first = declarations[0]
  158. const codecs = first === undefined
  159. ? []
  160. : [first.sourceCodec, ...declarations.map(item => item.targetCodec)]
  161. const restorer = declarations.at(-1)?.targetRestorer
  162. const headerValidator = declarations.at(-1)?.targetHeaderValidator
  163. const currentCodec = declarations.at(-1)?.targetCodec
  164. if (restorer === undefined) throw new Error('gen-session-format-catalog: current format has no target restorer')
  165. if (headerValidator === undefined) {
  166. throw new Error('gen-session-format-catalog: current format has no target header validator')
  167. }
  168. if (currentCodec === undefined) throw new Error('gen-session-format-catalog: current format has no target codec')
  169. return [
  170. '/**',
  171. ' * GENERATED by `scripts/gen-session-format-catalog.ts` — do not edit by hand.',
  172. ' * The direct imports make historical readability independent of mounted plugins.',
  173. ' */',
  174. '',
  175. "import { KNOWN_SESSION_EVENT_TYPES } from '@deepseek-ai/dsh-session'",
  176. "import { createSessionFormatCatalog } from '@deepseek-ai/dsh-session-format'",
  177. "import { validateInstalledCurrentSessionArtifact, validateInstalledCurrentSessionHeader } from './current.ts'",
  178. ...imports,
  179. '',
  180. '/** Physical codec dispatch and complete adjacent chain, independent of mounted plugins. */',
  181. 'export const sessionFormatCatalog = createSessionFormatCatalog({',
  182. ` currentVersion: ${currentVersion},`,
  183. ` codecs: [${codecs.join(', ')}],`,
  184. ` currentEncoder: ${currentCodec},`,
  185. ` migrations: [${declarations.map(item => item.migration).join(', ')}],`,
  186. ' restoreCurrent(artifact) {',
  187. ` const restored = ${restorer}(artifact, KNOWN_SESSION_EVENT_TYPES)`,
  188. ' validateInstalledCurrentSessionArtifact(restored)',
  189. ' return restored',
  190. ' },',
  191. ' restoreTransformedCurrent(artifact) {',
  192. ` return ${restorer}(artifact, KNOWN_SESSION_EVENT_TYPES)`,
  193. ' },',
  194. ' restoreCurrentHeader(header) {',
  195. ` ${headerValidator}(header)`,
  196. ' validateInstalledCurrentSessionHeader(header)',
  197. ' return header',
  198. ' },',
  199. '})',
  200. '',
  201. ].join('\n')
  202. }
  203. function main(): void {
  204. const currentVersion = readCurrentSessionFormatVersion(root)
  205. const declarations = collectSessionFormatMigrations(root, currentVersion)
  206. const output = renderSessionFormatCatalog(declarations, currentVersion)
  207. const target = resolve(root, OUT)
  208. if (process.argv.includes('--check')) {
  209. let current = ''
  210. try { current = readFileSync(target, 'utf8') } catch { /* missing is stale */ }
  211. if (current !== output) {
  212. console.error(`gen-session-format-catalog: ${OUT} is stale; run pnpm run gen-session-format-catalog`)
  213. process.exitCode = 1
  214. return
  215. }
  216. console.log(`gen-session-format-catalog: ${OUT} is up to date.`)
  217. return
  218. }
  219. writeFileSync(target, output)
  220. console.log(`gen-session-format-catalog: wrote ${OUT}.`)
  221. }
  222. if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) main()