gen-session-format-catalog.ts 11 KB

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