1
0

worker-json.ts 17 KB

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