-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathresolver.ts
More file actions
1376 lines (1243 loc) · 42.8 KB
/
Copy pathresolver.ts
File metadata and controls
1376 lines (1243 loc) · 42.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { createLogger } from '@sim/logger'
import { toError } from '@sim/utils/errors'
import { isUserFileWithMetadata } from '@/lib/core/utils/user-file'
import { mergeLargeValueKeys } from '@/lib/execution/payloads/access-keys'
import { isLargeArrayManifest } from '@/lib/execution/payloads/large-array-manifest-metadata'
import {
containsLargeValueRef,
formatLargeValueSize,
getLargeValueMaterializationError,
isLargeValueRef,
type LargeValueRef,
} from '@/lib/execution/payloads/large-value-ref'
import { isLikelyReferenceSegment } from '@/lib/workflows/sanitization/references'
import { BlockType, parseReferencePath, REFERENCE } from '@/executor/constants'
import type { ExecutionState, LoopScope } from '@/executor/execution/state'
import type { ExecutionContext } from '@/executor/types'
import { createEnvVarPattern, createReferencePattern } from '@/executor/utils/reference-validation'
import { BlockResolver } from '@/executor/variables/resolvers/block'
import { EnvResolver } from '@/executor/variables/resolvers/env'
import { LoopResolver } from '@/executor/variables/resolvers/loop'
import { ParallelResolver } from '@/executor/variables/resolvers/parallel'
import {
type AsyncPathNavigator,
RESOLVED_EMPTY,
type ResolutionContext,
type Resolver,
} from '@/executor/variables/resolvers/reference'
import { WorkflowResolver } from '@/executor/variables/resolvers/workflow'
import type { SerializedBlock, SerializedWorkflow } from '@/serializer/types'
/** Key used to carry pre-resolved context variables through the inputs map. */
export const FUNCTION_BLOCK_CONTEXT_VARS_KEY = '_runtimeContextVars'
/** Key used to carry display-resolved code through the function execution path. */
export const FUNCTION_BLOCK_DISPLAY_CODE_KEY = '_runtimeDisplayCode'
const logger = createLogger('VariableResolver')
/**
* Combined inline budget (data + display source) for a function block's resolved
* block-output context values. Internal routes cap request bodies at ~10 MB, and a
* resolved block reference is serialized into the function request both as data
* (`contextVariables`) and as a literal in the display source, so it costs roughly
* twice its size. Keeping the inline footprint under this budget leaves headroom for
* the code, params, and environment variables in the same body. Values that would
* overflow the budget are offloaded to durable large-value refs and lazily re-read in
* the sandbox via the `sim.values.read` broker.
*/
const FUNCTION_CONTEXT_INLINE_BUDGET_BYTES = 6 * 1024 * 1024
interface FunctionContextOffloadState {
inlineFootprintRemaining: number
}
function createFunctionContextOffloadState(): FunctionContextOffloadState {
return { inlineFootprintRemaining: FUNCTION_CONTEXT_INLINE_BUDGET_BYTES }
}
function measureJson(value: unknown): { json: string; size: number } | null {
try {
const json = JSON.stringify(value)
if (json === undefined) {
return null
}
return { json, size: Buffer.byteLength(json, 'utf8') }
} catch {
return null
}
}
function getNestedLargeValueMaterializationError(): Error {
return new Error(
'This execution value contains nested large values. Reference the nested field directly so it can be lazy-loaded.'
)
}
async function replaceValidReferencesAsync(
template: string,
replacer: (match: string, index: number, template: string) => Promise<string>
): Promise<string> {
const pattern = createReferencePattern()
let cursor = 0
let result = ''
for (const match of template.matchAll(pattern)) {
const fullMatch = match[0]
const index = match.index ?? 0
result += template.slice(cursor, index)
result += isLikelyReferenceSegment(fullMatch)
? await replacer(fullMatch, index, template)
: fullMatch
cursor = index + fullMatch.length
}
return result + template.slice(cursor)
}
async function replaceEnvVarsAsync(
template: string,
replacer: (match: string) => Promise<string>
): Promise<string> {
const pattern = createEnvVarPattern()
let cursor = 0
let result = ''
for (const match of template.matchAll(pattern)) {
const fullMatch = match[0]
const index = match.index ?? 0
result += template.slice(cursor, index)
result += await replacer(fullMatch)
cursor = index + fullMatch.length
}
return result + template.slice(cursor)
}
type ShellQuoteContext = 'single' | 'double' | null
type CodeStringQuoteContext = ShellQuoteContext | 'triple-single' | 'triple-double' | 'template'
type CodeScanMode =
| { type: 'normal' }
| { type: 'single' }
| { type: 'double' }
| { type: 'triple-single' }
| { type: 'triple-double' }
| { type: 'template' }
| { type: 'template-expression'; depth: number }
| { type: 'line-comment' }
| { type: 'block-comment' }
export class VariableResolver {
private resolvers: Resolver[]
private blockResolver: BlockResolver
constructor(
workflow: SerializedWorkflow,
workflowVariables: Record<string, any>,
private state: ExecutionState,
options: { navigatePathAsync?: AsyncPathNavigator } = {}
) {
this.blockResolver = new BlockResolver(workflow, options.navigatePathAsync)
this.resolvers = [
new LoopResolver(workflow, options.navigatePathAsync),
new ParallelResolver(workflow, options.navigatePathAsync),
new WorkflowResolver(workflowVariables, options.navigatePathAsync),
new EnvResolver(),
this.blockResolver,
]
}
/**
* Resolves inputs for function blocks. Block output references in the `code` field
* are stored as named context variables instead of being embedded as JavaScript
* literals, preventing large values from bloating the code string.
*
* Returns runtime inputs, display inputs, and a `contextVariables` map. Callers
* should inject contextVariables into the function execution request body so the
* isolated VM can access them as global variables.
*/
async resolveInputsForFunctionBlock(
ctx: ExecutionContext,
currentNodeId: string,
params: Record<string, any> | null | undefined,
block: SerializedBlock
): Promise<{
resolvedInputs: Record<string, any>
displayInputs: Record<string, any>
contextVariables: Record<string, unknown>
}> {
const contextVariables: Record<string, unknown> = {}
const resolved: Record<string, any> = {}
const display: Record<string, any> = {}
const offloadState = createFunctionContextOffloadState()
if (!params) {
return { resolvedInputs: resolved, displayInputs: display, contextVariables }
}
for (const [key, value] of Object.entries(params)) {
if (key === 'code') {
if (typeof value === 'string') {
const code = await this.resolveCodeWithContextVars(
ctx,
currentNodeId,
value,
undefined,
block,
contextVariables,
offloadState
)
resolved[key] = code.resolvedCode
display[key] = code.displayCode
} else if (Array.isArray(value)) {
const resolvedItems: any[] = []
const displayItems: any[] = []
for (const item of value) {
if (item && typeof item === 'object' && typeof item.content === 'string') {
const code = await this.resolveCodeWithContextVars(
ctx,
currentNodeId,
item.content,
undefined,
block,
contextVariables,
offloadState
)
resolvedItems.push({
...item,
content: code.resolvedCode,
})
displayItems.push({
...item,
content: code.displayCode,
})
continue
}
resolvedItems.push(item)
displayItems.push(item)
}
resolved[key] = resolvedItems
display[key] = displayItems
} else {
resolved[key] = await this.resolveValue(ctx, currentNodeId, value, undefined, block)
display[key] = resolved[key]
}
} else {
resolved[key] = await this.resolveValue(ctx, currentNodeId, value, undefined, block)
display[key] = resolved[key]
}
}
return { resolvedInputs: resolved, displayInputs: display, contextVariables }
}
async resolveInputs(
ctx: ExecutionContext,
currentNodeId: string,
params: Record<string, any>,
block?: SerializedBlock
): Promise<Record<string, any>> {
if (!params) {
return {}
}
const resolved: Record<string, any> = {}
const isConditionBlock = block?.metadata?.id === BlockType.CONDITION
if (isConditionBlock && typeof params.conditions === 'string') {
try {
const parsed = JSON.parse(params.conditions)
if (Array.isArray(parsed)) {
resolved.conditions = await Promise.all(
parsed.map(async (cond: any) => ({
...cond,
value:
typeof cond.value === 'string'
? await this.resolveTemplateWithoutConditionFormatting(
ctx,
currentNodeId,
cond.value
)
: cond.value,
}))
)
} else {
resolved.conditions = await this.resolveValue(
ctx,
currentNodeId,
params.conditions,
undefined,
block
)
}
} catch (parseError) {
logger.warn('Failed to parse conditions JSON, falling back to normal resolution', {
error: parseError,
conditions: params.conditions,
})
resolved.conditions = await this.resolveValue(
ctx,
currentNodeId,
params.conditions,
undefined,
block
)
}
}
for (const [key, value] of Object.entries(params)) {
if (isConditionBlock && key === 'conditions') {
continue
}
resolved[key] = await this.resolveValue(ctx, currentNodeId, value, undefined, block, {
allowLargeValueRefs: this.canResolveInputToLargeValueRef(block, key),
})
}
return resolved
}
private canResolveInputToLargeValueRef(block: SerializedBlock | undefined, key: string): boolean {
if (block?.metadata?.id === BlockType.VARIABLES) {
return key === 'variables'
}
if (block?.metadata?.id === BlockType.RESPONSE) {
return key === 'data' || key === 'builderData'
}
return false
}
async resolveSingleReference(
ctx: ExecutionContext,
currentNodeId: string,
reference: string,
loopScope?: LoopScope,
options: { allowLargeValueRefs?: boolean } = {}
): Promise<any> {
if (typeof reference === 'string') {
const trimmed = reference.trim()
if (/^<[^<>]+>$/.test(trimmed)) {
const resolutionContext: ResolutionContext = {
executionContext: ctx,
executionState: this.state,
currentNodeId,
loopScope,
allowLargeValueRefs: options.allowLargeValueRefs,
}
const result = await this.resolveReference(trimmed, resolutionContext)
if (result === RESOLVED_EMPTY) {
return null
}
return result
}
}
return this.resolveValue(ctx, currentNodeId, reference, loopScope)
}
private async resolveValue(
ctx: ExecutionContext,
currentNodeId: string,
value: any,
loopScope?: LoopScope,
block?: SerializedBlock,
options: { allowLargeValueRefs?: boolean } = {}
): Promise<any> {
if (value === null || value === undefined) {
return value
}
if (Array.isArray(value)) {
return Promise.all(
value.map((v) => this.resolveValue(ctx, currentNodeId, v, loopScope, block, options))
)
}
if (typeof value === 'object') {
const entries = await Promise.all(
Object.entries(value).map(async ([key, val]) => [
key,
await this.resolveValue(ctx, currentNodeId, val, loopScope, block, options),
])
)
return Object.fromEntries(entries)
}
if (typeof value === 'string') {
return this.resolveTemplate(ctx, currentNodeId, value, loopScope, block, options)
}
return value
}
/**
* Resolves a code template for a function block. Block output references are stored
* in `contextVarAccumulator` as named variables (e.g. `__blockRef_0`) and replaced
* with those variable names in the returned code string. Non-block references (loop
* items, workflow variables, env vars) are still inlined as literals so they remain
* available without any extra passing mechanism.
*/
private async resolveCodeWithContextVars(
ctx: ExecutionContext,
currentNodeId: string,
template: string,
loopScope: LoopScope | undefined,
block: SerializedBlock,
contextVarAccumulator: Record<string, unknown>,
offloadState: FunctionContextOffloadState = createFunctionContextOffloadState()
): Promise<{ resolvedCode: string; displayCode: string }> {
const resolutionContext: ResolutionContext = {
executionContext: ctx,
executionState: this.state,
currentNodeId,
loopScope,
allowLargeValueRefs: true,
}
const language = (block.config?.params as Record<string, unknown> | undefined)?.language as
| string
| undefined
let replacementError: Error | null = null
let displayResult = ''
let displayCursor = 0
let result = await replaceValidReferencesAsync(template, async (match, index) => {
if (replacementError) return match
displayResult += template.slice(displayCursor, index)
displayCursor = index + match.length
try {
const lazyBase64 = await this.resolveLazyFileBase64Reference(
match,
resolutionContext,
language,
template,
index,
contextVarAccumulator
)
if (lazyBase64) {
displayResult += lazyBase64.display
return lazyBase64.replacement
}
if (this.blockResolver.canResolve(match)) {
const resolved = await this.resolveReference(match, resolutionContext)
if (resolved === undefined) {
displayResult += match
return match
}
const effectiveValue = resolved === RESOLVED_EMPTY ? null : resolved
// Block output: store in contextVarAccumulator and replace the reference
// with language-specific runtime access to that stored value.
const varName = `__blockRef_${Object.keys(contextVarAccumulator).length}`
let replacement: string
// `storedValue` is placed in contextVarAccumulator and `displayValue` is
// rendered into the display source. They diverge only when an oversized
// inline value is offloaded to a ref (both then carry the small ref).
let storedValue: unknown = effectiveValue
let displayValue: unknown = effectiveValue
if (isLargeValueRef(effectiveValue)) {
const lazyReplacement = this.formatLazyLargeValueReference(
varName,
language,
template,
index
)
if (!lazyReplacement) {
throw getLargeValueMaterializationError(effectiveValue)
}
replacement = lazyReplacement
} else if (isLargeArrayManifest(effectiveValue)) {
const lazyReplacement = this.formatLazyLargeArrayManifestReference(
varName,
language,
template,
index
)
if (!lazyReplacement) {
throw getNestedLargeValueMaterializationError()
}
replacement = lazyReplacement
} else if (containsLargeValueRef(effectiveValue)) {
throw getNestedLargeValueMaterializationError()
} else {
const offloadedRef = await this.maybeOffloadInlineFunctionContextValue(
ctx,
effectiveValue,
language,
template,
offloadState
)
if (offloadedRef) {
storedValue = offloadedRef
displayValue = offloadedRef
// maybeOffload only returns a ref when the JS runtime helpers are usable —
// the same guard formatLazyLargeValueReference needs — so it is non-null here.
replacement =
this.formatLazyLargeValueReference(varName, language, template, index) ??
this.formatContextVariableReference(
varName,
language,
template,
index,
effectiveValue
)
} else {
replacement = this.formatContextVariableReference(
varName,
language,
template,
index,
effectiveValue
)
}
}
contextVarAccumulator[varName] = storedValue
displayResult += this.formatDisplayValueForCodeContext(
displayValue,
language,
template,
index
)
return replacement
}
const resolved = await this.resolveReference(match, resolutionContext)
if (resolved === undefined) {
displayResult += match
return match
}
const effectiveValue = resolved === RESOLVED_EMPTY ? null : resolved
if (isLargeValueRef(effectiveValue)) {
const varName = `__blockRef_${Object.keys(contextVarAccumulator).length}`
contextVarAccumulator[varName] = effectiveValue
const lazyReplacement = this.formatLazyLargeValueReference(
varName,
language,
template,
index
)
if (lazyReplacement) {
displayResult += this.formatDisplayValueForCodeContext(
effectiveValue,
language,
template,
index
)
return lazyReplacement
}
throw getLargeValueMaterializationError(effectiveValue)
}
if (isLargeArrayManifest(effectiveValue)) {
const varName = `__blockRef_${Object.keys(contextVarAccumulator).length}`
contextVarAccumulator[varName] = effectiveValue
const lazyReplacement = this.formatLazyLargeArrayManifestReference(
varName,
language,
template,
index
)
if (lazyReplacement) {
displayResult += this.formatDisplayValueForCodeContext(
effectiveValue,
language,
template,
index
)
return lazyReplacement
}
throw getNestedLargeValueMaterializationError()
}
if (containsLargeValueRef(effectiveValue)) {
throw getNestedLargeValueMaterializationError()
}
if (
this.isWorkflowVariableReference(match) &&
this.shouldUseContextVariable(effectiveValue)
) {
const varName = `__blockRef_${Object.keys(contextVarAccumulator).length}`
contextVarAccumulator[varName] = effectiveValue
const replacement = this.formatContextVariableReference(
varName,
language,
template,
index,
effectiveValue
)
displayResult += this.formatDisplayValueForCodeContext(
effectiveValue,
language,
template,
index
)
return replacement
}
const replacement = this.blockResolver.formatValueForBlock(
effectiveValue,
BlockType.FUNCTION,
language
)
displayResult += replacement
return replacement
} catch (error) {
replacementError = error instanceof Error ? error : new Error(String(error))
displayResult += match
return match
}
})
displayResult += template.slice(displayCursor)
if (replacementError !== null) {
throw replacementError
}
result = await replaceEnvVarsAsync(result, async (match) => {
const resolved = await this.resolveReference(match, resolutionContext)
return typeof resolved === 'string' ? resolved : match
})
displayResult = await replaceEnvVarsAsync(displayResult, async (match) => {
const resolved = await this.resolveReference(match, resolutionContext)
return typeof resolved === 'string' ? resolved : match
})
return { resolvedCode: result, displayCode: displayResult }
}
private async resolveLazyFileBase64Reference(
reference: string,
context: ResolutionContext,
language: string | undefined,
template: string,
matchIndex: number,
contextVarAccumulator: Record<string, unknown>
): Promise<{ replacement: string; display: string } | null> {
if (!this.canUseJavaScriptRuntimeHelpers(language, template)) {
return null
}
const parts = parseReferencePath(reference)
if (parts.length < 3 || parts.at(-1) !== 'base64') {
return null
}
const fileReference = `${REFERENCE.START}${parts.slice(0, -1).join(REFERENCE.PATH_DELIMITER)}${REFERENCE.END}`
const file = await this.resolveReference(fileReference, context)
if (!isUserFileWithMetadata(file)) {
return null
}
if (!file.key) {
return null
}
const varName = `__blockRef_${Object.keys(contextVarAccumulator).length}`
const { base64: _base64, ...fileMetadata } = file
contextVarAccumulator[varName] = fileMetadata
const fileExpression = `globalThis[${JSON.stringify(varName)}]`
const lazyExpression = `(await sim.files.readBase64(${fileExpression}))`
return {
replacement: this.formatJavaScriptAsyncExpression(lazyExpression, template, matchIndex),
display: reference,
}
}
/**
* Offloads an inline function block-output value to a durable large-value ref when
* keeping it inline would push the function execution request body past its budget.
*
* A few medium values merged in one function block (for example two fetched images)
* can exceed the ~10 MB internal-route body cap even though no single value crosses
* the per-value large-value threshold. Offloading the overflowing values lets the
* function runtime lazily re-read them via the `sim.values.read` broker instead of
* inlining their bytes into the request.
*
* Returns the stored reference when offloaded, or `null` to keep the value inline.
*/
private async maybeOffloadInlineFunctionContextValue(
ctx: ExecutionContext,
value: unknown,
language: string | undefined,
template: string,
offloadState: FunctionContextOffloadState
): Promise<LargeValueRef | null> {
// Lazy re-reading is only available in the JavaScript isolated-vm runtime; other
// runtimes have no broker to materialize a ref, so the value must stay inline.
if (!this.canUseJavaScriptRuntimeHelpers(language, template)) {
return null
}
if (!ctx.workspaceId || !ctx.workflowId || !ctx.executionId) {
return null
}
const measured = measureJson(value)
if (measured === null) {
return null
}
// Inline values are serialized into both the request data and the display source.
const footprint = measured.size * 2
if (footprint <= offloadState.inlineFootprintRemaining) {
offloadState.inlineFootprintRemaining -= footprint
return null
}
try {
const { storeLargeValue } = await import('@/lib/execution/payloads/store')
const ref = await storeLargeValue(value, measured.json, measured.size, {
workspaceId: ctx.workspaceId,
workflowId: ctx.workflowId,
executionId: ctx.executionId,
userId: ctx.userId,
requireDurable: true,
})
// Authorize the function route to materialize the ref it is about to receive.
if (ref.key) {
mergeLargeValueKeys(ctx, [ref.key])
}
return ref
} catch (error) {
logger.warn('Failed to offload oversized function context value; keeping inline', {
error: toError(error).message,
})
return null
}
}
private formatLazyLargeValueReference(
varName: string,
language: string | undefined,
template: string,
matchIndex: number
): string | null {
if (!this.canUseJavaScriptRuntimeHelpers(language, template)) {
return null
}
const expression = `(await sim.values.read(globalThis[${JSON.stringify(varName)}]))`
return this.formatJavaScriptAsyncExpression(expression, template, matchIndex, {
stringifyInStringContext: true,
})
}
private formatLazyLargeArrayManifestReference(
varName: string,
language: string | undefined,
template: string,
matchIndex: number
): string | null {
if (!this.canUseJavaScriptRuntimeHelpers(language, template)) {
return null
}
const expression = `(await sim.values.readArray(globalThis[${JSON.stringify(varName)}]))`
return this.formatJavaScriptAsyncExpression(expression, template, matchIndex, {
stringifyInStringContext: true,
})
}
private isWorkflowVariableReference(reference: string): boolean {
const parts = parseReferencePath(reference)
return parts[0] === REFERENCE.PREFIX.VARIABLE
}
private shouldUseContextVariable(value: unknown): boolean {
return typeof value === 'object' && value !== null
}
private formatJavaScriptAsyncExpression(
expression: string,
template: string,
matchIndex: number,
options: { stringifyInStringContext?: boolean } = {}
): string {
const quoteContext = this.getCodeStringQuoteContext(template, matchIndex, 'javascript')
const stringExpression = options.stringifyInStringContext
? `JSON.stringify(${expression})`
: expression
if (quoteContext === 'template') {
return `\${${stringExpression}}`
}
if (quoteContext === 'single' || quoteContext === 'double') {
const quote = this.getCodeStringQuoteToken(quoteContext)
return `${quote} + ${stringExpression} + ${quote}`
}
return expression
}
private canUseJavaScriptRuntimeHelpers(language: string | undefined, template: string): boolean {
if (language !== 'javascript') {
return false
}
return !this.hasJavaScriptModuleDependencySyntax(template)
}
private hasJavaScriptModuleDependencySyntax(template: string): boolean {
const modes: CodeScanMode[] = [{ type: 'normal' }]
for (let i = 0; i < template.length; i++) {
const char = template[i]
const next = template[i + 1]
const mode = modes[modes.length - 1]
if (mode.type === 'line-comment') {
if (char === '\n') modes.pop()
continue
}
if (mode.type === 'block-comment') {
if (char === '*' && next === '/') {
modes.pop()
i++
}
continue
}
if (mode.type === 'single' || mode.type === 'double') {
const quote = mode.type === 'single' ? "'" : '"'
if (char === '\\') {
i++
continue
}
if (char === quote || char === '\n') modes.pop()
continue
}
if (mode.type === 'template') {
if (char === '\\') {
i++
continue
}
if (char === '`') {
modes.pop()
continue
}
if (char === '$' && next === '{') {
modes.push({ type: 'template-expression', depth: 1 })
i++
}
continue
}
const isCodeMode = mode.type === 'normal' || mode.type === 'template-expression'
if (!isCodeMode) continue
if (char === '/' && next === '/') {
modes.push({ type: 'line-comment' })
i++
continue
}
if (char === '/' && next === '*') {
modes.push({ type: 'block-comment' })
i++
continue
}
if (char === "'") {
modes.push({ type: 'single' })
continue
}
if (char === '"') {
modes.push({ type: 'double' })
continue
}
if (char === '`') {
modes.push({ type: 'template' })
continue
}
if (mode.type === 'template-expression') {
if (char === '{') {
mode.depth += 1
continue
}
if (char === '}') {
mode.depth -= 1
if (mode.depth === 0) modes.pop()
continue
}
}
if (this.startsWithStaticImport(template, i) || this.startsWithRequireCall(template, i)) {
return true
}
}
return false
}
private startsWithStaticImport(template: string, index: number): boolean {
if (!this.matchesKeywordAt(template, index, 'import')) {
return false
}
const nextIndex = this.skipWhitespace(template, index + 'import'.length)
if (nextIndex === index + 'import'.length) {
return false
}
return template[nextIndex] !== '('
}
private startsWithRequireCall(template: string, index: number): boolean {
if (!this.matchesKeywordAt(template, index, 'require')) {
return false
}
const openParenIndex = this.skipWhitespace(template, index + 'require'.length)
if (template[openParenIndex] !== '(') {
return false
}
const argumentIndex = this.skipWhitespace(template, openParenIndex + 1)
return (
template[argumentIndex] === "'" ||
template[argumentIndex] === '"' ||
template[argumentIndex] === '`'
)
}
private matchesKeywordAt(template: string, index: number, keyword: string): boolean {
if (!template.startsWith(keyword, index)) {
return false
}
const before = index > 0 ? template[index - 1] : ''
const after = template[index + keyword.length] ?? ''
return !this.isJavaScriptIdentifierChar(before) && !this.isJavaScriptIdentifierChar(after)
}
private skipWhitespace(template: string, index: number): number {
let cursor = index
while (cursor < template.length && /\s/.test(template[cursor])) {
cursor++
}
return cursor
}
private isJavaScriptIdentifierChar(char: string): boolean {
return /[A-Za-z0-9_$]/.test(char)
}
private formatContextVariableReference(
varName: string,
language: string | undefined,
template: string,
matchIndex: number,
value: unknown
): string {
if (language === 'python') {
const expression = `globals()[${JSON.stringify(varName)}]`
const quoteContext = this.getCodeStringQuoteContext(template, matchIndex, language)
if (this.isPythonStringQuoteContext(quoteContext)) {
const quote = this.getCodeStringQuoteToken(quoteContext)
return `${quote} + json.dumps(${expression}) + ${quote}`
}
return expression
}
if (language === 'shell') {
return this.formatShellContextVariableReference(varName, template, matchIndex, value)
}
const expression = `globalThis[${JSON.stringify(varName)}]`
const quoteContext = this.getCodeStringQuoteContext(template, matchIndex, language)
if (quoteContext === 'template') {
return `\${JSON.stringify(${expression})}`
}
if (quoteContext === 'single' || quoteContext === 'double') {
const quote = this.getCodeStringQuoteToken(quoteContext)
return `${quote} + JSON.stringify(${expression}) + ${quote}`
}
return expression
}
private isPythonStringQuoteContext(
quoteContext: CodeStringQuoteContext
): quoteContext is 'single' | 'double' | 'triple-single' | 'triple-double' {
return (
quoteContext === 'single' ||
quoteContext === 'double' ||
quoteContext === 'triple-single' ||
quoteContext === 'triple-double'
)
}
private getCodeStringQuoteToken(
quoteContext: 'single' | 'double' | 'triple-single' | 'triple-double'
): string {
if (quoteContext === 'single') return "'"
if (quoteContext === 'double') return '"'
if (quoteContext === 'triple-single') return "'''"
return '"""'
}
private formatDisplayValueForCodeContext(
value: unknown,
language: string | undefined,
template: string,
matchIndex: number
): string {
// Offloaded large values carry only a storage ref (or array manifest), never the
// data itself. Render a concise placeholder for the Input view instead of leaking
// the internal ref object, which is unreadable and meaningless to a user.
if (isLargeValueRef(value)) {
return `/* large ${value.kind} · ${formatLargeValueSize(value.size)}, fetched at runtime */`
}
if (isLargeArrayManifest(value)) {
return `/* large array · ${value.totalCount} items · ${formatLargeValueSize(value.byteSize)}, fetched at runtime */`
}
if (language === 'shell') {
return this.formatShellDisplayValue(value, template, matchIndex)
}
return this.blockResolver.formatValueForBlock(value, BlockType.FUNCTION, language)
}
private formatShellDisplayValue(value: unknown, template: string, matchIndex: number): string {
const text = this.stringifyShellDisplayValue(value)
const quoteContext = this.getShellQuoteContext(template, matchIndex)
if (quoteContext === 'double') {
return text.replace(/["\\$`]/g, '\\$&')
}