diff --git a/apps/docs/content/docs/cli/reference.mdx b/apps/docs/content/docs/cli/reference.mdx index 80202cd3497..367a8af5f8d 100644 --- a/apps/docs/content/docs/cli/reference.mdx +++ b/apps/docs/content/docs/cli/reference.mdx @@ -8865,7 +8865,7 @@ sim workflows source find [options] -Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. <block> is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir. +Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. <block> is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir. When the source does not compile, readers are left out (JSON output carries compiles: false). Exit codes: 0 printed; 1 no block matches (the closest name is suggested), or the directory is not a workflow source directory. diff --git a/apps/docs/content/docs/cli/workflows.mdx b/apps/docs/content/docs/cli/workflows.mdx index a3271b8e013..ec7e3e97bde 100644 --- a/apps/docs/content/docs/cli/workflows.mdx +++ b/apps/docs/content/docs/cli/workflows.mdx @@ -1597,7 +1597,7 @@ sim workflows source find [options] -Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. <block> is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir. +Prints each block the name matches, read from the directory alone (no request is made): its declaration in workflow.ts with line numbers, its function file, the wiring statements of its incoming and outgoing edges, and every block that reads its outputs (a param, a branch, or a function file's $ref), each as file:line. <block> is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most 20). Run it from a workflow source directory, or pass --dir. When the source does not compile, readers are left out (JSON output carries compiles: false). Exit codes: 0 printed; 1 no block matches (the closest name is suggested), or the directory is not a workflow source directory. diff --git a/apps/sim/executor/variables/resolver.test.ts b/apps/sim/executor/variables/resolver.test.ts index 5f08c6b1712..25142569776 100644 --- a/apps/sim/executor/variables/resolver.test.ts +++ b/apps/sim/executor/variables/resolver.test.ts @@ -19,6 +19,7 @@ import { StartBlockPath } from '@/lib/workflows/triggers/triggers' import { AgentBlock } from '@/blocks/blocks/agent' import { ResponseBlock } from '@/blocks/blocks/response' import { TableV2Block } from '@/blocks/blocks/table_v2' +import { WorkflowInputBlock } from '@/blocks/blocks/workflow_input' import { getBlock } from '@/blocks/registry' import type { BlockConfig } from '@/blocks/types' import { BlockType } from '@/executor/constants' @@ -1296,6 +1297,7 @@ describe('VariableResolver JSON text inputs', () => { [BlockType.AGENT]: AgentBlock, [BlockType.RESPONSE]: ResponseBlock, table_v2: TableV2Block, + [BlockType.WORKFLOW_INPUT]: WorkflowInputBlock, } beforeEach(() => { @@ -1452,6 +1454,18 @@ describe('VariableResolver JSON text inputs', () => { expect(JSON.parse(resolved.data)).toEqual({ body: awkwardText }) }) + it('escapes references in a child workflow input mapping stored as JSON text', async () => { + const { resolve } = createJsonResolver(BlockType.WORKFLOW_INPUT, { + workflowId: 'child', + inputMapping: '{"summary": "", "record": ""}', + }) + const resolved = await resolve() + expect(JSON.parse(resolved.inputMapping)).toEqual({ + summary: awkwardText, + record: JSON.stringify({ name: 'Ada "the first"', tags: ['x', 'y'] }), + }) + }) + it('leaves quoted references in non-JSON fields raw', async () => { const { resolve } = createJsonResolver(BlockType.AGENT, { userPrompt: '{"note": ""}', diff --git a/apps/sim/executor/variables/resolver.ts b/apps/sim/executor/variables/resolver.ts index a73b3d20028..c54a58557be 100644 --- a/apps/sim/executor/variables/resolver.ts +++ b/apps/sim/executor/variables/resolver.ts @@ -1,5 +1,6 @@ import { createLogger } from '@sim/logger' import { toError } from '@sim/utils/errors' +import { JSON_TEXT_CONTAINER_TYPES } from '@sim/workflow-code/json-text' 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' @@ -322,16 +323,19 @@ interface TemplateResolutionOptions { jsonText?: boolean } -/** Whether `key` is a block input the editor stores as JSON text (a JSON code field). */ -function isJsonCodeInput(block: SerializedBlock | undefined, key: string): boolean { +/** + * Whether `key` is a block input that may hold JSON text: a JSON code field, or a container field + * (`JSON_TEXT_CONTAINER_TYPES`) whose runtime parses text and objects alike. + */ +function isJsonTextInput(block: SerializedBlock | undefined, key: string): boolean { const blockType = block?.metadata?.id if (!blockType) return false return ( getBlock(blockType)?.subBlocks.some( (subBlock) => - subBlock.type === 'code' && - subBlock.language === 'json' && - (subBlock.id === key || subBlock.canonicalParamId === key) + (subBlock.id === key || subBlock.canonicalParamId === key) && + ((subBlock.type === 'code' && subBlock.language === 'json') || + JSON_TEXT_CONTAINER_TYPES.has(subBlock.type)) ) ?? false ) } @@ -516,7 +520,7 @@ export class VariableResolver { resolved[key] = await this.resolveValue(ctx, currentNodeId, value, undefined, block, { allowLargeValueRefs: this.canResolveInputToLargeValueRef(block, key), inputPath: [key], - jsonText: typeof value === 'string' && isJSONString(value) && isJsonCodeInput(block, key), + jsonText: typeof value === 'string' && isJSONString(value) && isJsonTextInput(block, key), }) } return resolved diff --git a/apps/sim/lib/workflows/canonical/subblock-value.ts b/apps/sim/lib/workflows/canonical/subblock-value.ts index 20fb417931a..d3e01b4cd29 100644 --- a/apps/sim/lib/workflows/canonical/subblock-value.ts +++ b/apps/sim/lib/workflows/canonical/subblock-value.ts @@ -1,4 +1,4 @@ -import { JSON_TEXT_CONTAINER_TYPES, parseJsonContainer } from '@sim/workflow-code' +import { JSON_TEXT_CONTAINER_TYPES, parseJsonContainer } from '@sim/workflow-code/json-text' import { normalizedStringify, sanitizeInputFormat, diff --git a/apps/sim/lib/workflows/code/api-built-source.test.ts b/apps/sim/lib/workflows/code/api-built-source.test.ts index 05b78a84aa8..838d3b8d173 100644 --- a/apps/sim/lib/workflows/code/api-built-source.test.ts +++ b/apps/sim/lib/workflows/code/api-built-source.test.ts @@ -168,3 +168,26 @@ describe('a child workflow call whose input mapping the operations route stored expect(typeCheckAgainstSdk(workDir, 'edited', [file])).toBe('') }, 120_000) }) + +describe('a child workflow call whose input mapping is one whole reference', () => { + it('stores an object written over the reference natively, not as JSON text', () => { + const stored = builtWorkflow() + const call = createBlockFromParams('call-block', { + type: 'workflow_input', + name: 'Record Audit', + inputs: { workflowId: 'child-workflow', inputMapping: '' }, + }) + stored.blocks[call.id] = { ...call, position: { x: 800, y: 0 } } + const written = getThenApply(stored, (text) => + text.replace( + 'inputMapping: start.input,', + "inputMapping: { ticketId: start.input, source: 'api' }," + ) + ) + expect(written.errors).toEqual([]) + expect(written.state.blocks['call-block']?.subBlocks.inputMapping?.value).toEqual({ + ticketId: '', + source: 'api', + }) + }) +}) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts b/packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts index 2e27a8b1d0e..c6fbaf87637 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-find.test.ts @@ -60,7 +60,7 @@ beforeEach(() => { writeFileSync(join(dir, 'workflow.ts'), WORKFLOW_TS) writeFileSync( join(dir, 'functions/score.js'), - "const s = 1\nreturn $ref.fetchpolicy.data\nconst tag = ''\n" + "const s = 1\nreturn $ref.fetchpolicy.data ?? $ref.fetchpolicy.status\nconst tag = ''\n" ) writeFileSync(join(dir, 'functions/audit.py'), 'import json\nprint()\n') vi.stubEnv('SIM_CONFIG_DIR', join(dir, 'config')) @@ -128,4 +128,30 @@ describe('sim workflows source find', () => { message: expect.stringContaining('Did you mean Fetch Policy?'), }) }) + + it('says the source does not compile instead of only that no block matches', async () => { + writeFileSync( + join(dir, 'workflow.ts'), + WORKFLOW_TS.replace("api('Fetch Policy', {", "api('Fetch Policy', {{") + ) + await expect(find('Fetch Policy')).rejects.toMatchObject({ + code: 'BLOCK_UNKNOWN', + message: expect.stringContaining('does not compile'), + }) + }) + + it('reads a wiring statement the printer wrapped as one statement', async () => { + const wrapped = WORKFLOW_TS.replace('fetchPolicy.to(audit)', 'fetchPolicy.to(\n audit,\n )') + writeFileSync(join(dir, 'workflow.ts'), wrapped) + await find('Audit') + const [block] = stdoutJson().blocks + expect(block.incoming).toMatchObject([ + { block: 'Fetch Policy', statement: 'fetchPolicy.to(audit)' }, + ]) + }) + + it('refuses an empty name rather than matching every block', async () => { + await expect(find(' ')).rejects.toMatchObject({ code: 'BLOCK_UNKNOWN' }) + await expect(find('.')).rejects.toMatchObject({ code: 'BLOCK_UNKNOWN' }) + }) }) diff --git a/packages/sim-cli/src/commands/protocol/workflow-source-find.ts b/packages/sim-cli/src/commands/protocol/workflow-source-find.ts index 1d12869bcfa..b536ddd465c 100644 --- a/packages/sim-cli/src/commands/protocol/workflow-source-find.ts +++ b/packages/sim-cli/src/commands/protocol/workflow-source-find.ts @@ -11,6 +11,7 @@ import { fromCodeFile, LineIndex, referencedHeads, + type SourceSpan, type StoredEdgeRef, } from '@sim/workflow-code' import { SOURCE_ENTRY_FILE } from '@sim/workflow-code/limits' @@ -35,6 +36,7 @@ incoming and outgoing edges, and every block that reads its outputs (a param, a function file's $ref), each as file:line. is a block name (Security Score), its key (securityscore) or its identifier (securityScore); with no exact match, every block whose name contains it is printed (at most ${MAX_FOUND}). Run it from a workflow source directory, or pass --dir. +When the source does not compile, readers are left out (JSON output carries compiles: false). Exit codes: 0 printed; 1 no block matches (the closest name is suggested), or the directory is not a workflow source directory.` @@ -132,7 +134,11 @@ function blockFields(block: CanonicalBlock): Array<{ field: string; texts: strin */ function readersByKey(index: SourceIndex): Map { const readers = new Map() + const seen = new Set() const add = (key: BlockKey, reader: Reader) => { + const id = JSON.stringify([key, reader.file, reader.line, reader.block, reader.field]) + if (seen.has(id)) return + seen.add(id) const list = readers.get(key) if (list) list.push(reader) else readers.set(key, [reader]) @@ -184,14 +190,38 @@ function matchBlocks(index: SourceIndex, query: string): BlockKey[] { .filter((key) => key.includes(normalized) || index.nameOf(key).toLowerCase().includes(needle)) } -/** The refusal for a query no block matches, naming the closest block. */ +/** + * The refusal for a query no block matches, naming the closest block, and saying so when the + * source does not compile (a parse failure names no blocks at all). + */ function unknownBlock(index: SourceIndex, query: string): CliUsageError { const names = index .keys() .map((key) => index.nameOf(key)) .sort(compareStrings) const hint = didYouMean(query, names) ?? `It has ${names.length} blocks.` - return new CliUsageError(`No block is named ${query}. ${hint}`, { code: 'BLOCK_UNKNOWN' }) + const compileNote = + index.compiled.workflow === null + ? ' The source does not compile: run `sim workflows source check`.' + : '' + return new CliUsageError(`No block is named ${query}. ${hint}${compileNote}`, { + code: 'BLOCK_UNKNOWN', + }) +} + +/** + * A wiring statement's text on one line, so a fan-out the printer wrapped reads whole. Only the + * line breaks are rewritten, so a raw handle's text is printed as written. + */ +function statementText(index: SourceIndex, span: SourceSpan): string { + const lines = index.linesOf(span.file)?.lines.slice(span.line - 1, span.endLine) ?? [] + return lines + .map((line) => line.trim()) + .reduce((joined, line) => { + if (joined === '') return line + if (line.startsWith(')')) return `${joined.replace(/,$/, '')}${line}` + return joined.endsWith('(') ? `${joined}${line}` : `${joined} ${line}` + }, '') } function describeBlock( @@ -209,9 +239,7 @@ function describeBlock( port: ref.port, file: written?.file ?? SOURCE_ENTRY_FILE, line: written?.line ?? span?.line ?? 0, - statement: written - ? (index.linesOf(written.file)?.lines[written.line - 1]?.trim() ?? '') - : '', + statement: written ? statementText(index, written) : '', } } const ends = (side: 'from' | 'to', other: 'from' | 'to') => @@ -273,6 +301,9 @@ export function attachWorkflowSourceFind(source: Command): void { await assertSourceDirKind(options.dir, 'workflow') const catalog = await lookupCatalog(options.dir, profile) const { compiled, files } = await compileWorkflowDir(options.dir, catalog) + if (normalizeWorkflowBlockName(query) === '') { + throw new CliUsageError('Name a block.', { code: 'BLOCK_UNKNOWN' }) + } const index = new SourceIndex(compiled, files) const keys = matchBlocks(index, query) if (keys.length === 0) throw unknownBlock(index, query) @@ -283,7 +314,11 @@ export function attachWorkflowSourceFind(source: Command): void { .sort(byLine) const more = keys.length - found.length if (isMachine(profile.output)) { - printProtocolResult(profile.output, { blocks: found, ...(more > 0 ? { more } : {}) }) + printProtocolResult(profile.output, { + blocks: found, + compiles: compiled.workflow !== null, + ...(more > 0 ? { more } : {}), + }) return } if (compiled.workflow === null) { diff --git a/packages/workflow-code/package.json b/packages/workflow-code/package.json index 234173a8267..cc7d0e40451 100644 --- a/packages/workflow-code/package.json +++ b/packages/workflow-code/package.json @@ -22,6 +22,10 @@ "types": "./src/diagnostics/codes.ts", "default": "./src/diagnostics/codes.ts" }, + "./json-text": { + "types": "./src/json-text.ts", + "default": "./src/json-text.ts" + }, "./code-files/references": { "types": "./src/code-files/references.ts", "default": "./src/code-files/references.ts" diff --git a/packages/workflow-code/src/canonicalize/params.ts b/packages/workflow-code/src/canonicalize/params.ts index 5cb7dd7f517..c9b750aef19 100644 --- a/packages/workflow-code/src/canonicalize/params.ts +++ b/packages/workflow-code/src/canonicalize/params.ts @@ -5,8 +5,9 @@ import { isConditionClause } from '../catalog/conditions' import type { CatalogBlock, CatalogCondition, CatalogSubBlock } from '../catalog/types' import { declarationsOf } from '../catalog/view' import { diagnostic } from '../diagnostics/factory' +import { JSON_TEXT_CONTAINER_TYPES, parseJsonContainer } from '../json-text' import type { BlockKey, CanonicalParam, SubBlockId, Value } from '../model' -import { parseJsonContainer, setOwn } from '../records' +import { setOwn } from '../records' import { structuredCodec } from '../structured' import type { CanonContext } from './context' import { liftTools } from './tools' @@ -60,18 +61,6 @@ function holdsJsonText(declaration: CatalogSubBlock): boolean { return declaration.structured !== undefined || declaration.storage === 'json-string' } -/** - * Field types whose runtime reads JSON text and the container it encodes alike: the workflow - * handler and the tool runners parse a child workflow's `inputMapping` either way, and the - * operations route stores either. Canonicalize decodes the text so it prints as the object source - * can type, and deploy-change detection takes the two encodings as one value. Any other native - * container field stays as stored, since its runtime reads only one form. - */ -export const JSON_TEXT_CONTAINER_TYPES: ReadonlySet = new Set([ - 'input-mapping', - 'workflow-input-mapper', -]) - /** A field of a {@link JSON_TEXT_CONTAINER_TYPES} type; text that does not parse stays a value. */ function holdsNativeContainer(declaration: CatalogSubBlock): boolean { return JSON_TEXT_CONTAINER_TYPES.has(declaration.type) diff --git a/packages/workflow-code/src/canonicalize/tools.ts b/packages/workflow-code/src/canonicalize/tools.ts index 6469d4caa36..5cb2b64ce49 100644 --- a/packages/workflow-code/src/canonicalize/tools.ts +++ b/packages/workflow-code/src/canonicalize/tools.ts @@ -3,8 +3,9 @@ import { mcpBinding, mcpToolId } from '../agent-tools' import { type CanonicalModeOverrides, scopeCanonicalModesForTool } from '../catalog/canonical-index' import type { BlockCatalog, CatalogSubBlock } from '../catalog/types' import { catalogBlock } from '../catalog/view' +import { parseJsonContainer } from '../json-text' import { type BlockKey, type CanonicalTool, isUsageControl, type Json, type Value } from '../model' -import { parseJsonContainer, setOwn } from '../records' +import { setOwn } from '../records' import type { CanonContext } from './context' import { toolModes } from './modes' import { liftResourceId, liftResourceValue, toJson, toValue } from './values' diff --git a/packages/workflow-code/src/index.ts b/packages/workflow-code/src/index.ts index cb1fbf652a3..18434935835 100644 --- a/packages/workflow-code/src/index.ts +++ b/packages/workflow-code/src/index.ts @@ -2,7 +2,6 @@ export { decodeAnchor, encodeAnchor } from './anchors' export { babelErrorShape, babelMessage } from './babel' export { type CanonicalizeResult, canonicalize, canonicalizeUnderLock } from './canonicalize' export { toolModes } from './canonicalize/modes' -export { JSON_TEXT_CONTAINER_TYPES } from './canonicalize/params' export { builderProducedOutputs, executableInactiveParams, @@ -89,6 +88,7 @@ export { executableView } from './equivalence/executable' export { sha256Hex, stableStringify } from './hash' export { readsIterationOutOfScope, type ScopeNode } from './iteration-scope' export { type ChildResultFields, parseJsonField } from './json-fields' +export { parseJsonContainer } from './json-text' export { type DefinedField, fieldNames, @@ -131,7 +131,7 @@ export type { export { isResourceKind } from './model' export { assignIdentifiers, printWorkflow, referencedHeads } from './print' export { hasSuspiciousCharacter, printKey, printNumber, quoteString } from './print/strings' -export { getOwn, invertRecord, parseJsonContainer, setOrDelete, setOwn } from './records' +export { getOwn, invertRecord, setOrDelete, setOwn } from './records' export { calledWorkflowKey, calledWorkflowKeys, diff --git a/packages/workflow-code/src/json-fields.ts b/packages/workflow-code/src/json-fields.ts index 8b2935d9399..542a4498399 100644 --- a/packages/workflow-code/src/json-fields.ts +++ b/packages/workflow-code/src/json-fields.ts @@ -25,6 +25,7 @@ import type { BlockCatalog, CatalogOutput } from './catalog/types' import { catalogBlock } from './catalog/view' import { ENV_VAR_NAME, parseStoredPath, type RefSegment } from './code-files/ref-path' import { referencedResultKind } from './compile/function-returns' +import { parseJsonContainer } from './json-text' import { type BlockKey, type CanonicalBlock, @@ -33,7 +34,7 @@ import { isSimNode, type Value, } from './model' -import { getOwn, parseJsonContainer, setOwn } from './records' +import { getOwn, setOwn } from './records' /** A reference at a leaf of a JSON field: the stored token, and whether the text quotes it. */ export class JsonRef { diff --git a/packages/workflow-code/src/json-text.ts b/packages/workflow-code/src/json-text.ts new file mode 100644 index 00000000000..6d2adfc530c --- /dev/null +++ b/packages/workflow-code/src/json-text.ts @@ -0,0 +1,33 @@ +/** + * JSON-text decoding shared by canonicalize, the app's deploy-change detection and the executor. + * Dependency-free so client bundles and the executor can import it without the compiler. + */ + +/** + * Field types whose runtime reads JSON text and the container it encodes alike: the workflow + * handler and the tool runners parse a child workflow's `inputMapping` either way, and the + * operations route stores either. Canonicalize decodes the text so it prints as the object source + * can type, deploy-change detection takes the two encodings as one value, and the executor + * escapes a reference spliced into the text's string literals. Any other native + * container field stays as stored, since its runtime reads only one form. + */ +export const JSON_TEXT_CONTAINER_TYPES: ReadonlySet = new Set([ + 'input-mapping', + 'workflow-input-mapper', +]) + +/** + * JSON text that holds an object or array, decoded; `undefined` for blank text, text that does not + * parse, and a scalar, which callers keep as the text it is. + */ +export function parseJsonContainer(text: string): Record | unknown[] | undefined { + if (text.trim() === '') return undefined + try { + const parsed: unknown = JSON.parse(text) + return typeof parsed === 'object' && parsed !== null + ? (parsed as Record | unknown[]) + : undefined + } catch { + return undefined + } +} diff --git a/packages/workflow-code/src/materialize/params.ts b/packages/workflow-code/src/materialize/params.ts index b811d57dca4..c1a7523b76a 100644 --- a/packages/workflow-code/src/materialize/params.ts +++ b/packages/workflow-code/src/materialize/params.ts @@ -3,6 +3,7 @@ import { mcpBinding, mcpToolId } from '../agent-tools' import { shouldDecode } from '../canonicalize/params' import { decodeToolParam, toolParamDeclaration } from '../canonicalize/tools' import type { CatalogSubBlock } from '../catalog/types' +import { JSON_TEXT_CONTAINER_TYPES, parseJsonContainer } from '../json-text' import type { LockItem } from '../lock' import type { BlockKey, CanonicalParam, CanonicalTool, SubBlockId } from '../model' import { deepEqual, getOwn, parseStoredList, setOwn } from '../records' @@ -25,11 +26,18 @@ export interface ParamSite { forceText: boolean } -/** Whether prev stored text, or, with no prev value, the catalog `storage` is `json-string`. */ +/** + * Whether prev stored text, or, with no prev value, the catalog `storage` is `json-string`. For a + * {@link JSON_TEXT_CONTAINER_TYPES} field, prev text counts only when it encoded a container: a + * whole-value reference there is text, and a container written over it is stored native. + */ function storesAsText(site: ParamSite): boolean { - return site.prevRaw !== undefined && site.prevRaw !== null - ? typeof site.prevRaw === 'string' - : site.declaration?.storage === 'json-string' + const { prevRaw, declaration } = site + if (prevRaw === undefined || prevRaw === null) return declaration?.storage === 'json-string' + if (typeof prevRaw !== 'string') return false + return declaration && JSON_TEXT_CONTAINER_TYPES.has(declaration.type) + ? parseJsonContainer(prevRaw) !== undefined + : true } /** diff --git a/packages/workflow-code/src/print/edges.ts b/packages/workflow-code/src/print/edges.ts index 094f6ac847f..95f42b96983 100644 --- a/packages/workflow-code/src/print/edges.ts +++ b/packages/workflow-code/src/print/edges.ts @@ -102,7 +102,7 @@ function identExpr(ctx: PrintContext, key: BlockKey): Expr { } /** One wiring statement, with its comment anchor and the blocks it names. */ -export interface WiringStatement { +export interface PrintedWiring { expr: Expr anchor: AnchorKey source: BlockKey @@ -110,8 +110,8 @@ export interface WiringStatement { } /** The wiring statements of one scope. */ -export function wiringStatements(ctx: PrintContext, scope: BlockKey | null): WiringStatement[] { - const statements: WiringStatement[] = [] +export function wiringStatements(ctx: PrintContext, scope: BlockKey | null): PrintedWiring[] { + const statements: PrintedWiring[] = [] const keys = (edges: CanonicalEdge[]) => edges.map((edge) => edge.to) const byTarget = (a: CanonicalEdge, b: CanonicalEdge) => (ctx.position.get(a.to) ?? 0) - (ctx.position.get(b.to) ?? 0) || diff --git a/packages/workflow-code/src/print/values.ts b/packages/workflow-code/src/print/values.ts index 1f3ba32d605..b93d941cb85 100644 --- a/packages/workflow-code/src/print/values.ts +++ b/packages/workflow-code/src/print/values.ts @@ -6,8 +6,9 @@ */ import type { CatalogSubBlock } from '../catalog/types' +import { parseJsonContainer } from '../json-text' import { type BlockKey, isSimNode, type Json, type SimNode, type Value } from '../model' -import { getOwn, parseJsonContainer } from '../records' +import { getOwn } from '../records' import { SDK_RESOURCE_CALLS, type TemplateTag } from '../sdk' import { type Doc, literalText } from './doc' import type { RefPrinter } from './refs' diff --git a/packages/workflow-code/src/records.ts b/packages/workflow-code/src/records.ts index 13895a6384a..0e43ccd4eec 100644 --- a/packages/workflow-code/src/records.ts +++ b/packages/workflow-code/src/records.ts @@ -1,3 +1,5 @@ +import { parseJsonContainer } from './json-text' + /** * Prototype-safe writes for records keyed by stored or authored data. A plain `record[key] = v` * with `key === '__proto__'` replaces the prototype instead of adding a key, so every write whose @@ -68,22 +70,6 @@ export function deepEqual(left: unknown, right: unknown): boolean { ) } -/** - * JSON text that holds an object or array, decoded; `undefined` for blank text, text that does not - * parse, and a scalar, which callers keep as the text it is. - */ -export function parseJsonContainer(text: string): Record | unknown[] | undefined { - if (text.trim() === '') return undefined - try { - const parsed: unknown = JSON.parse(text) - return typeof parsed === 'object' && parsed !== null - ? (parsed as Record | unknown[]) - : undefined - } catch { - return undefined - } -} - /** A stored list, native or as JSON text; `undefined` for anything else. */ export function parseStoredList(raw: unknown): unknown[] | undefined { if (Array.isArray(raw)) return raw