worker-json.ts 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  1. /**
  2. * Lossless-JSON snapshots for the dependency-free source worker closure.
  3. * @module @deepseek-ai/dsh-code-runtime-worker-thread/worker-json
  4. */
  5. import type { CodeJsonValue } from '@deepseek-ai/dsh-code-runtime'
  6. /* jscpd:ignore-start -- the source worker mirrors session JSON helpers without workspace runtime imports */
  7. type IntrinsicCallable = (this: unknown, ...args: unknown[]) => unknown
  8. const intrinsicFunctionToString = Reflect.get(Function.prototype, 'toString') as IntrinsicCallable
  9. const intrinsicReflectApply = Reflect.get(Reflect, 'apply') as (
  10. target: IntrinsicCallable,
  11. thisArgument: unknown,
  12. argumentsList: readonly unknown[],
  13. ) => unknown
  14. const IntrinsicError = Error
  15. const IntrinsicSet = Set
  16. const intrinsicArrayIsArray = Array.isArray
  17. const intrinsicArrayPrototype = Array.prototype
  18. const intrinsicNumberIsFinite = Number.isFinite
  19. const intrinsicNumberIsSafeInteger = Number.isSafeInteger
  20. const intrinsicObjectCreate = Object.create
  21. const intrinsicObjectDefineProperty = Object.defineProperty
  22. const intrinsicObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor
  23. const intrinsicObjectGetPrototypeOf = Object.getPrototypeOf
  24. const intrinsicObjectHasOwn = Object.hasOwn
  25. const intrinsicObjectIs = Object.is
  26. const intrinsicObjectKeys = Object.keys
  27. const intrinsicObjectPrototype = Object.prototype
  28. const intrinsicObjectPropertyIsEnumerable = Reflect.get(intrinsicObjectPrototype, 'propertyIsEnumerable') as IntrinsicCallable
  29. const intrinsicReflectOwnKeys = Reflect.ownKeys
  30. const intrinsicSetAdd = Reflect.get(Set.prototype, 'add') as IntrinsicCallable
  31. const intrinsicSetDelete = Reflect.get(Set.prototype, 'delete') as IntrinsicCallable
  32. const intrinsicSetHas = Reflect.get(Set.prototype, 'has') as IntrinsicCallable
  33. /** Build a data descriptor that cannot inherit model-defined accessor fields. */
  34. function dataDescriptor(value: unknown): PropertyDescriptor {
  35. const descriptor = intrinsicObjectCreate(null) as PropertyDescriptor
  36. descriptor.value = value
  37. return descriptor
  38. }
  39. /** Define an ordinary enumerable data slot without a prototype-bearing descriptor. */
  40. function defineEnumerableDataProperty(target: object, key: PropertyKey, value: unknown): void {
  41. const descriptor = dataDescriptor(value)
  42. descriptor.enumerable = true
  43. descriptor.configurable = true
  44. descriptor.writable = true
  45. intrinsicObjectDefineProperty(target, key, descriptor)
  46. }
  47. /** Append without consulting a model-mutated `Array.prototype`. */
  48. function append<T>(target: T[], value: T): void {
  49. defineEnumerableDataProperty(target, target.length, value)
  50. }
  51. /** Pop without consulting a model-mutated `Array.prototype`. */
  52. function takeLast<T>(target: T[]): T | undefined {
  53. if (target.length === 0) return undefined
  54. const index = target.length - 1
  55. const value = target[index]
  56. intrinsicObjectDefineProperty(target, 'length', dataDescriptor(index))
  57. return value
  58. }
  59. /** Whether one captured-intrinsic Set contains a value. */
  60. function setHas<T>(target: Set<T>, value: T): boolean {
  61. return intrinsicReflectApply(intrinsicSetHas, target, [value]) as boolean
  62. }
  63. /** Add to one captured-intrinsic Set. */
  64. function setAdd<T>(target: Set<T>, value: T): void {
  65. intrinsicReflectApply(intrinsicSetAdd, target, [value])
  66. }
  67. /** Delete from one captured-intrinsic Set. */
  68. function setDelete<T>(target: Set<T>, value: T): void {
  69. intrinsicReflectApply(intrinsicSetDelete, target, [value])
  70. }
  71. /** Whether a realm-owned intrinsic prototype is backed by its native constructor. */
  72. function hasIntrinsicConstructor(prototype: object, name: 'Array' | 'Object'): boolean {
  73. const descriptor = intrinsicObjectGetOwnPropertyDescriptor(prototype, 'constructor')
  74. const constructor: unknown = descriptor?.value
  75. if (typeof constructor !== 'function') return false
  76. try {
  77. return constructor.name === name
  78. && constructor.prototype === prototype
  79. && intrinsicReflectApply(intrinsicFunctionToString, constructor, []) === `function ${name}() { [native code] }`
  80. } catch {
  81. return false
  82. }
  83. }
  84. /** Whether a candidate is a foreign realm's intrinsic `Object.prototype`. */
  85. function isForeignIntrinsicObjectPrototype(value: object): boolean {
  86. return intrinsicObjectGetPrototypeOf(value) === null && hasIntrinsicConstructor(value, 'Object')
  87. }
  88. /** Whether an array uses one realm's intrinsic `Array.prototype`, not a subclass or forged prototype. */
  89. function hasPlainArrayPrototype(value: unknown[]): boolean {
  90. const prototype: unknown = intrinsicObjectGetPrototypeOf(value)
  91. if (prototype === intrinsicArrayPrototype) return true
  92. if (!intrinsicArrayIsArray(prototype) || !hasIntrinsicConstructor(prototype, 'Array')) return false
  93. const objectPrototype: unknown = intrinsicObjectGetPrototypeOf(prototype)
  94. return typeof objectPrototype === 'object'
  95. && objectPrototype !== null
  96. && isForeignIntrinsicObjectPrototype(objectPrototype)
  97. }
  98. /** Whether an object is a plain or null-prototype record from any JavaScript realm. */
  99. function hasPlainObjectPrototype(value: object): boolean {
  100. const prototype: unknown = intrinsicObjectGetPrototypeOf(value)
  101. return prototype === null
  102. || prototype === intrinsicObjectPrototype
  103. || typeof prototype === 'object' && isForeignIntrinsicObjectPrototype(prototype)
  104. }
  105. /** Return every JSON-visible object key, or reject own data JSON would discard. */
  106. function enumerableStringKeys(value: object): string[] | undefined {
  107. const keys = intrinsicReflectOwnKeys(value)
  108. for (let index = 0; index < keys.length; index++) {
  109. const key = keys[index]
  110. if (typeof key !== 'string' || !intrinsicReflectApply(intrinsicObjectPropertyIsEnumerable, value, [key])) return undefined
  111. }
  112. return keys as string[]
  113. }
  114. type SnapshotDestination =
  115. | { kind: 'root' }
  116. | { kind: 'array'; target: CodeJsonValue[]; index: number }
  117. | { kind: 'object'; target: Record<string, CodeJsonValue>; key: string }
  118. type SnapshotTask =
  119. | { kind: 'visit'; value: unknown; destination: SnapshotDestination }
  120. | { kind: 'array-item'; source: unknown[]; index: number; target: CodeJsonValue[] }
  121. | { kind: 'object-property'; source: Record<string, unknown>; key: string; target: Record<string, CodeJsonValue> }
  122. | { kind: 'leave'; source: object }
  123. /**
  124. * Validate and detach one worker-boundary value without loading another
  125. * workspace package at runtime. This mirrors the session-owned canonical
  126. * JSON boundary while remaining safe to import from the unbuilt worker.
  127. * Its iterative traversal adds no JavaScript call-stack depth limit.
  128. *
  129. * @param value - the candidate completion value.
  130. * @returns a detached lossless-JSON snapshot, or `undefined` when invalid.
  131. */
  132. export function snapshotCodeJsonValue(value: unknown): CodeJsonValue | undefined {
  133. const active = new IntrinsicSet<object>()
  134. let root: CodeJsonValue | undefined
  135. const assign = (destination: SnapshotDestination, item: CodeJsonValue): void => {
  136. if (destination.kind === 'root') {
  137. root = item
  138. } else if (destination.kind === 'array') {
  139. defineEnumerableDataProperty(destination.target, destination.index, item)
  140. } else {
  141. defineEnumerableDataProperty(destination.target, destination.key, item)
  142. }
  143. }
  144. const tasks: SnapshotTask[] = [{ kind: 'visit', value, destination: { kind: 'root' } }]
  145. for (let task = takeLast(tasks); task !== undefined; task = takeLast(tasks)) {
  146. if (task.kind === 'leave') {
  147. setDelete(active, task.source)
  148. continue
  149. }
  150. if (task.kind === 'array-item') {
  151. if (!intrinsicObjectHasOwn(task.source, task.index)) return undefined
  152. append(tasks, {
  153. kind: 'visit',
  154. value: task.source[task.index],
  155. destination: { kind: 'array', target: task.target, index: task.index },
  156. })
  157. continue
  158. }
  159. if (task.kind === 'object-property') {
  160. append(tasks, {
  161. kind: 'visit',
  162. value: task.source[task.key],
  163. destination: { kind: 'object', target: task.target, key: task.key },
  164. })
  165. continue
  166. }
  167. const candidate = task.value
  168. if (candidate === null) {
  169. assign(task.destination, null)
  170. continue
  171. }
  172. if (typeof candidate === 'boolean' || typeof candidate === 'string') {
  173. assign(task.destination, candidate)
  174. continue
  175. }
  176. if (typeof candidate === 'number') {
  177. if (!intrinsicNumberIsFinite(candidate) || intrinsicObjectIs(candidate, -0)) return undefined
  178. assign(task.destination, candidate)
  179. continue
  180. }
  181. if (typeof candidate !== 'object') return undefined
  182. if (setHas(active, candidate)) return undefined
  183. if (intrinsicArrayIsArray(candidate)) {
  184. if (!hasPlainArrayPrototype(candidate)) return undefined
  185. const length = candidate.length
  186. if (intrinsicReflectOwnKeys(candidate).length !== length + 1) return undefined
  187. const target: CodeJsonValue[] = []
  188. assign(task.destination, target)
  189. setAdd(active, candidate)
  190. append(tasks, { kind: 'leave', source: candidate })
  191. for (let index = length - 1; index >= 0; index--) {
  192. append(tasks, { kind: 'array-item', source: candidate, index, target })
  193. }
  194. continue
  195. }
  196. if (!hasPlainObjectPrototype(candidate)) return undefined
  197. const keys = enumerableStringKeys(candidate)
  198. if (keys === undefined) return undefined
  199. const target: Record<string, CodeJsonValue> = {}
  200. assign(task.destination, target)
  201. setAdd(active, candidate)
  202. append(tasks, { kind: 'leave', source: candidate })
  203. for (let index = keys.length - 1; index >= 0; index--) {
  204. const key = keys[index]
  205. /* v8 ignore next -- the loop is bounded by the captured key count. */
  206. if (key === undefined) return undefined
  207. append(tasks, { kind: 'object-property', source: candidate as Record<string, unknown>, key, target })
  208. }
  209. }
  210. return root
  211. }
  212. interface ArrayWireToken {
  213. kind: 'array'
  214. length: number
  215. }
  216. interface ObjectWireToken {
  217. kind: 'object'
  218. keys: string[]
  219. }
  220. type WorkerJsonToken = null | boolean | number | string | ArrayWireToken | ObjectWireToken
  221. /**
  222. * A pre-order, bounded-depth transport for one lossless JSON value. Container
  223. * markers and scalar leaves share one flat token array, so `worker_threads`
  224. * never has to structured-clone the value's application nesting.
  225. */
  226. export type WorkerJsonWire = WorkerJsonToken[]
  227. /**
  228. * Flatten one validated JSON value for the worker-thread message port.
  229. * @param value - the lossless JSON value to transport.
  230. * @returns a pre-order token stream whose own nesting is bounded.
  231. */
  232. export function encodeWorkerJson(value: CodeJsonValue): WorkerJsonWire {
  233. const wire: WorkerJsonWire = []
  234. const pending: CodeJsonValue[] = [value]
  235. for (let current = takeLast(pending); current !== undefined; current = takeLast(pending)) {
  236. if (current === null || typeof current === 'boolean' || typeof current === 'number' || typeof current === 'string') {
  237. append(wire, current)
  238. continue
  239. }
  240. if (intrinsicArrayIsArray(current)) {
  241. append(wire, { kind: 'array', length: current.length })
  242. for (let index = current.length - 1; index >= 0; index--) {
  243. const item = current[index]
  244. if (item === undefined) throw new IntrinsicError('cannot encode a sparse JSON array')
  245. append(pending, item)
  246. }
  247. continue
  248. }
  249. const keys = intrinsicObjectKeys(current)
  250. append(wire, { kind: 'object', keys })
  251. for (let index = keys.length - 1; index >= 0; index--) {
  252. const key = keys[index]
  253. /* v8 ignore next -- the loop is bounded by the captured key count. */
  254. if (key === undefined) throw new IntrinsicError('cannot encode a missing JSON object key')
  255. const item = current[key]
  256. if (item === undefined) throw new IntrinsicError('cannot encode an undefined JSON object property')
  257. append(pending, item)
  258. }
  259. }
  260. return wire
  261. }
  262. type DecodeFrame =
  263. | { kind: 'array'; target: CodeJsonValue[]; length: number; index: number }
  264. | { kind: 'object'; target: Record<string, CodeJsonValue>; keys: string[]; index: number }
  265. /** Whether an array contains exactly its dense indexed slots and `length`. */
  266. function isDenseArray(value: unknown[]): boolean {
  267. if (!hasPlainArrayPrototype(value) || intrinsicReflectOwnKeys(value).length !== value.length + 1) return false
  268. for (let index = 0; index < value.length; index++) {
  269. if (!intrinsicObjectHasOwn(value, index)) return false
  270. }
  271. return true
  272. }
  273. /** Whether one exact string-key list contains a key, without consulting its prototype. */
  274. function keysContain(keys: string[], expected: string): boolean {
  275. for (let index = 0; index < keys.length; index++) {
  276. if (keys[index] === expected) return true
  277. }
  278. return false
  279. }
  280. /** Return one exact container marker, or reject any extra/missing fields. */
  281. function containerToken(value: object): ArrayWireToken | ObjectWireToken | undefined {
  282. if (intrinsicArrayIsArray(value) || !hasPlainObjectPrototype(value)) return undefined
  283. const keys = enumerableStringKeys(value)
  284. if (keys === undefined) return undefined
  285. const token = value as Record<string, unknown>
  286. if (token.kind === 'array') {
  287. if (keys.length !== 2 || !keysContain(keys, 'kind') || !keysContain(keys, 'length')) return undefined
  288. const length = token.length
  289. return typeof length === 'number' && intrinsicNumberIsSafeInteger(length) && length >= 0
  290. ? { kind: 'array', length }
  291. : undefined
  292. }
  293. if (token.kind === 'object') {
  294. if (keys.length !== 2 || !keysContain(keys, 'kind') || !keysContain(keys, 'keys')) return undefined
  295. const objectKeys = token.keys
  296. if (!intrinsicArrayIsArray(objectKeys) || !isDenseArray(objectKeys)) return undefined
  297. const unique = new IntrinsicSet<string>()
  298. const normalizedKeys: string[] = []
  299. const objectKeyValues = objectKeys as unknown[]
  300. for (let index = 0; index < objectKeyValues.length; index++) {
  301. const key = objectKeyValues[index]
  302. if (typeof key !== 'string' || setHas(unique, key)) return undefined
  303. setAdd(unique, key)
  304. append(normalizedKeys, key)
  305. }
  306. return { kind: 'object', keys: normalizedKeys }
  307. }
  308. return undefined
  309. }
  310. /**
  311. * Rebuild one lossless JSON value from the flat worker-thread wire format.
  312. * Malformed or incomplete traffic returns `undefined`; traversal is iterative
  313. * and therefore independent of the transported value's application depth.
  314. * @param input - untrusted message-port payload.
  315. * @returns the detached JSON value, or `undefined` when the wire is invalid.
  316. */
  317. export function decodeWorkerJson(input: unknown): CodeJsonValue | undefined {
  318. try {
  319. if (!intrinsicArrayIsArray(input) || !isDenseArray(input) || input.length === 0) return undefined
  320. const wire = input as unknown[]
  321. const frames: DecodeFrame[] = []
  322. let root: CodeJsonValue | undefined
  323. let rootAssigned = false
  324. const attach = (value: CodeJsonValue): boolean => {
  325. const parent = frames[frames.length - 1]
  326. if (!parent) {
  327. if (rootAssigned) return false
  328. root = value
  329. rootAssigned = true
  330. return true
  331. }
  332. /* v8 ignore next -- completed frames are popped before another token can attach. */
  333. if (parent.index >= (parent.kind === 'array' ? parent.length : parent.keys.length)) return false
  334. if (parent.kind === 'array') {
  335. append(parent.target, value)
  336. } else {
  337. const key = parent.keys[parent.index]
  338. /* v8 ignore next -- object frames are built from validated keys and their exact length. */
  339. if (key === undefined) return false
  340. defineEnumerableDataProperty(parent.target, key, value)
  341. }
  342. parent.index += 1
  343. return true
  344. }
  345. for (let tokenIndex = 0; tokenIndex < wire.length; tokenIndex++) {
  346. const token = wire[tokenIndex]
  347. let value: CodeJsonValue
  348. let frame: DecodeFrame | undefined
  349. if (token === null || typeof token === 'boolean' || typeof token === 'string') {
  350. value = token
  351. } else if (typeof token === 'number') {
  352. if (!intrinsicNumberIsFinite(token) || intrinsicObjectIs(token, -0)) return undefined
  353. value = token
  354. } else {
  355. if (typeof token !== 'object') return undefined
  356. const marker = containerToken(token)
  357. if (!marker) return undefined
  358. const remainingTokens = wire.length - tokenIndex - 1
  359. if (marker.kind === 'array') {
  360. if (marker.length > remainingTokens) return undefined
  361. const target: CodeJsonValue[] = []
  362. value = target
  363. if (marker.length > 0) frame = { kind: 'array', target, length: marker.length, index: 0 }
  364. } else {
  365. if (marker.keys.length > remainingTokens) return undefined
  366. const target: Record<string, CodeJsonValue> = {}
  367. value = target
  368. if (marker.keys.length > 0) frame = { kind: 'object', target, keys: marker.keys, index: 0 }
  369. }
  370. }
  371. if (!attach(value)) return undefined
  372. if (frame) append(frames, frame)
  373. while (frames.length > 0) {
  374. const current = frames[frames.length - 1]
  375. /* v8 ignore next -- the loop condition guarantees a final frame. */
  376. if (current === undefined) break
  377. if (current.index < (current.kind === 'array' ? current.length : current.keys.length)) break
  378. takeLast(frames)
  379. }
  380. }
  381. return frames.length === 0 ? root : undefined
  382. } catch {
  383. return undefined
  384. }
  385. }
  386. /* jscpd:ignore-end */