@tsplc/compiler 0.5.3 → 0.5.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/dist/bun-runtime.js.map +7 -7
  2. package/dist/cli.js.map +8 -8
  3. package/dist/codesys.js +2 -2
  4. package/dist/codesys.js.map +23 -23
  5. package/dist/elaborate-capture.js +3 -2
  6. package/dist/elaborate-capture.js.map +3 -3
  7. package/dist/index.js +26 -19
  8. package/dist/index.js.map +38 -38
  9. package/dist/ir.js.map +19 -19
  10. package/dist/project.js.map +1 -1
  11. package/dist/server-check.js.map +1 -1
  12. package/dist/telemetry.js.map +1 -1
  13. package/package.json +9 -9
  14. package/src/codesys/config.ts +2 -2
  15. package/src/codesys/debug.ts +2 -2
  16. package/src/codesys/emit.ts +10 -10
  17. package/src/codesys/engineering.ts +1 -1
  18. package/src/codesys/expressions.ts +1 -1
  19. package/src/codesys/global-lists.ts +6 -6
  20. package/src/codesys/global-names.ts +3 -3
  21. package/src/codesys/http.ts +3 -3
  22. package/src/codesys/index.ts +8 -8
  23. package/src/codesys/instrumentation.ts +9 -13
  24. package/src/codesys/io-paths.ts +1 -1
  25. package/src/codesys/manifest.ts +5 -5
  26. package/src/codesys/plan.ts +9 -9
  27. package/src/codesys/programs.ts +3 -3
  28. package/src/codesys/publication.ts +4 -4
  29. package/src/codesys/routines.ts +5 -5
  30. package/src/codesys/st-files.ts +4 -4
  31. package/src/codesys/symbols.ts +6 -6
  32. package/src/codesys/telemetry.ts +6 -6
  33. package/src/codesys/types.ts +2 -2
  34. package/src/codesys/vendor.ts +2 -2
  35. package/src/frontend/analyzer.ts +9 -9
  36. package/src/frontend/async.ts +6 -6
  37. package/src/frontend/blocks.ts +1 -1
  38. package/src/frontend/configuration.ts +4 -4
  39. package/src/frontend/const-functions.ts +2 -2
  40. package/src/frontend/cooperative.ts +1 -1
  41. package/src/frontend/coroutines.ts +6 -6
  42. package/src/frontend/elaborate/calls.ts +29 -18
  43. package/src/frontend/elaborate/capture.ts +3 -2
  44. package/src/frontend/elaborate/dialect.ts +9 -9
  45. package/src/frontend/elaborate/expressions.ts +12 -12
  46. package/src/frontend/elaborate/frame.ts +4 -4
  47. package/src/frontend/elaborate/graph.ts +1 -1
  48. package/src/frontend/elaborate/imports.ts +14 -15
  49. package/src/frontend/elaborate/index.ts +12 -12
  50. package/src/frontend/elaborate/initializers.ts +4 -4
  51. package/src/frontend/elaborate/layouts.ts +3 -3
  52. package/src/frontend/elaborate/model.ts +1 -1
  53. package/src/frontend/elaborate/retention.ts +5 -5
  54. package/src/frontend/elaborate/specialize.ts +11 -11
  55. package/src/frontend/elaborate/statements.ts +8 -11
  56. package/src/frontend/elaborate/storage.ts +6 -11
  57. package/src/frontend/elaborate/values.ts +2 -2
  58. package/src/frontend/exposure.ts +3 -3
  59. package/src/frontend/expressions.ts +5 -5
  60. package/src/frontend/intrinsics.ts +2 -2
  61. package/src/frontend/module-graph.ts +1 -1
  62. package/src/frontend/promise-chains.ts +2 -2
  63. package/src/frontend/promises.ts +5 -5
  64. package/src/frontend/routines.ts +2 -2
  65. package/src/frontend/sdk.ts +7 -1
  66. package/src/frontend/services.ts +3 -3
  67. package/src/frontend/statements.ts +4 -4
  68. package/src/frontend/tasks.ts +5 -10
  69. package/src/frontend/telemetry.ts +2 -2
  70. package/src/frontend/types.ts +1 -1
  71. package/src/frontend/typescript.ts +11 -15
  72. package/src/index.ts +1 -1
  73. package/src/ir/aggregates.ts +6 -6
  74. package/src/ir/allocation.ts +5 -5
  75. package/src/ir/core-model.ts +3 -3
  76. package/src/ir/declarations.ts +6 -6
  77. package/src/ir/domains.ts +3 -7
  78. package/src/ir/fold.ts +4 -9
  79. package/src/ir/index.ts +16 -16
  80. package/src/ir/layouts.ts +3 -3
  81. package/src/ir/link.ts +5 -5
  82. package/src/ir/model.ts +2 -2
  83. package/src/ir/normalization-error.ts +1 -1
  84. package/src/ir/normalize.ts +8 -8
  85. package/src/ir/numeric.ts +2 -2
  86. package/src/ir/operands.ts +2 -2
  87. package/src/ir/ranges.ts +4 -9
  88. package/src/ir/routine.ts +10 -15
  89. package/src/ir/scalars.ts +5 -5
  90. package/src/ir/share.ts +4 -4
  91. package/src/ir/temporaries.ts +4 -4
  92. package/src/project/cli.ts +3 -3
  93. package/src/project/debugger.ts +1 -1
  94. package/src/project/index.ts +1 -1
  95. package/src/project/plant.ts +2 -2
  96. package/src/project/project-commands.ts +3 -3
  97. package/src/project/project.ts +2 -2
  98. package/src/project/release.ts +2 -2
  99. package/src/project/server-check.ts +1 -1
  100. package/src/runtime/main.ts +2 -2
  101. package/src/runtime/process.ts +1 -1
  102. package/src/runtime/program.ts +2 -2
  103. package/src/runtime/retain.ts +1 -1
  104. package/src/runtime/runtime.ts +11 -16
  105. package/stdlib/telemetry.ts +2 -2
@@ -2,7 +2,7 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/project/project.ts", "../src/runtime/launch.ts", "../src/project/artifacts.ts"],
4
4
  "sourcesContent": [
5
- "import {\n\tcopyFile,\n\tmkdir,\n\tmkdtemp,\n\trealpath,\n\trm,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { installLibraries, type ProgressOptions } from \"@tsplc/build\";\nimport {\n\tanalyze,\n\ttype CompileEnvironment,\n\tcheckHostConfig,\n} from \"@tsplc/compiler\";\nimport {\n\tbuildCodesys,\n\ttype CodesysPlan,\n\ttype CodesysProject,\n\tcodesysBuildConfig,\n\tdiagnoseCodesys,\n\temitCodesys,\n\tioTargets,\n\tplanCodesys,\n\tpublicationSelectors,\n\ttype SourceMapping,\n} from \"@tsplc/compiler/codesys\";\nimport {\n\ttype Diagnostic,\n\thasErrors,\n\tnormalizeModule,\n\ttype VerifiedCoreModule,\n} from \"@tsplc/compiler/ir\";\nimport {\n\ttype BuildTarget,\n\ttype Controller,\n\tcompilerConfig,\n\ttype LoadedConfig,\n\tloadTsplcConfig,\n\ttype NormalizedConfig,\n\ttype ResolvedTsplcConfig,\n\tsimulationConfig,\n} from \"@tsplc/config\";\nimport { emittedFiles, emittedStDirectory } from \"@tsplc/config/project-files\";\nimport { debugManifestFile } from \"@tsplc/debug/manifest\";\nimport {\n\tdeviceTree,\n\tloadHardware,\n\ttype ProjectTargets,\n\tresolveIo,\n} from \"@tsplc/typegen\";\nimport { serviceRoutes } from \"../runtime/launch.ts\";\nimport {\n\tcleanArtifacts,\n\tengineeringDirectory,\n\towned,\n\tpublishArtifacts,\n} from \"./artifacts.ts\";\n\n/** The emitted ST's directory inside the compiler's artifacts directory. */\nconst emittedSt = basename(emittedStDirectory);\n\nconst failure = (\n\torigin: Diagnostic[\"origin\"],\n\tcode: string,\n\tcause: unknown,\n): Diagnostic => ({\n\torigin,\n\tcode,\n\tseverity: \"error\",\n\tmessage: cause instanceof Error ? cause.message : String(cause),\n});\n\n/**\n * `buildProject`'s `loaded` and `configured` options. With `simulate` the build omits fieldbus\n * I/O so a plant simulator can write the inputs; generated types and the debug manifest keep\n * describing the hardware project.\n */\nexport const buildConfigs = (\n\tloaded: LoadedConfig,\n\toptions: { simulate?: boolean },\n) =>\n\toptions.simulate\n\t\t? {\n\t\t\t\tloaded: { ...loaded, config: simulationConfig(loaded.config) },\n\t\t\t\tconfigured: loaded.config,\n\t\t\t}\n\t\t: { loaded };\n\ninterface ProjectOptions {\n\tloaded?: LoadedConfig;\n\tbuildTarget?: BuildTarget;\n\t/** The configuration `loaded` simulates, whose hardware the debug manifest describes. */\n\tconfigured?: ResolvedTsplcConfig;\n\t/**\n\t * The host config check's diagnostics, when the caller ran it before loading the config. The\n\t * check type-checks the config and takes seconds.\n\t */\n\thostConfigDiagnostics?: readonly Diagnostic[];\n\t/** What the program's `env()` calls, endpoints and telemetry read; this process's environment by default. */\n\tenvironment?: CompileEnvironment;\n}\n\n/** Loads the config in `environment`, this process's by default, with its only target's values. */\nconst loadEnvironment = (environment: CompileEnvironment | undefined) => ({\n\tenv: environment ?? process.env,\n\ttarget: undefined,\n\tforAgent: false,\n});\n\nasync function loadProject(\n\tfile: string,\n\t{\n\t\tloaded,\n\t\tbuildTarget,\n\t\tconfigured,\n\t\thostConfigDiagnostics,\n\t\tenvironment,\n\t}: ProjectOptions,\n): Promise<{\n\tconfig?: NormalizedConfig;\n\tconfigFile: string;\n\tshared?: ResolvedTsplcConfig;\n\tproject?: CodesysProject;\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\tlet configFile = resolve(file);\n\ttry {\n\t\tconfigFile = await realpath(configFile);\n\t\tconst diagnostics = hostConfigDiagnostics ?? checkHostConfig(configFile);\n\t\tif (hasErrors(diagnostics)) {\n\t\t\treturn { configFile, diagnostics };\n\t\t}\n\t\tconst { config: shared, env } =\n\t\t\tloaded ??\n\t\t\t(await loadTsplcConfig(configFile, loadEnvironment(environment)));\n\t\tconst root = dirname(configFile);\n\t\tconst catalog = await loadHardware(shared, root);\n\n\t\tconst config = compilerConfig(\n\t\t\tshared,\n\t\t\tresolveIo(shared, catalog),\n\t\t\tbuildTarget,\n\t\t);\n\t\treturn {\n\t\t\tconfigFile,\n\t\t\tshared,\n\t\t\tconfig: { ...config, ...sourceInput(config, root) },\n\t\t\tproject: {\n\t\t\t\troot,\n\t\t\t\tenvironment: env,\n\t\t\t\t...(shared.debug && { debug: shared.debug }),\n\t\t\t\t...(shared.telemetry && { telemetry: shared.telemetry }),\n\t\t\t\t...(shared.server && { server: shared.server }),\n\t\t\t\t// A simulation build drops fieldbus IO, but the debugger still shows the hardware it stands in for.\n\t\t\t\thardware: {\n\t\t\t\t\tcatalog: configured ? await loadHardware(configured, root) : catalog,\n\t\t\t\t\tconfig: configured ?? shared,\n\t\t\t\t\ttree: shared.codesys?.deviceTree !== undefined,\n\t\t\t\t},\n\t\t\t},\n\t\t\tdiagnostics,\n\t\t};\n\t} catch (cause) {\n\t\treturn { configFile, diagnostics: [failure(\"config\", \"PLC5003\", cause)] };\n\t}\n}\n\n/** The analyzer's entry points, resolved against the config file's directory. */\nfunction sourceInput(\n\tcompiler: {\n\t\ttsconfig: string;\n\t\tprograms: Record<string, { module: string; export: string }>;\n\t},\n\troot: string,\n) {\n\treturn {\n\t\ttsconfig: resolve(root, compiler.tsconfig),\n\t\tprograms: Object.fromEntries(\n\t\t\tObject.entries(compiler.programs).map(([name, entry]) => [\n\t\t\t\tname,\n\t\t\t\t{ ...entry, module: resolve(root, entry.module) },\n\t\t\t]),\n\t\t),\n\t};\n}\n\n/**\n * I/O keys and publication selectors from analyzed PLC source. It ignores the\n * config's own type errors, so a typo cannot switch off the types that flag it;\n * it is undefined only while the source itself fails analysis.\n */\nexport async function projectTargets(\n\tfile = \"tsplc.config.ts\",\n\toptions: Pick<ProjectOptions, \"loaded\" | \"environment\"> = {},\n): Promise<ProjectTargets | undefined> {\n\tconst configFile = await realpath(resolve(file));\n\tconst { config, env } =\n\t\toptions.loaded ??\n\t\t(await loadTsplcConfig(configFile, loadEnvironment(options.environment)));\n\tif (!config.compiler) {\n\t\treturn undefined;\n\t}\n\tconst source = analyze({\n\t\t...sourceInput(config.compiler, dirname(configFile)),\n\t\tservices: config.server,\n\t\tenvironment: env,\n\t});\n\tconst core = source.module && normalizeModule(source.module).core;\n\treturn core ? coreTargets(core) : undefined;\n}\n\nconst coreTargets = (core: VerifiedCoreModule): ProjectTargets => ({\n\tio: ioTargets(core),\n\tpublication: publicationSelectors(core),\n});\n\nexport async function checkProject(\n\tfile = \"tsplc.config.ts\",\n\toptions: ProjectOptions = {},\n): Promise<{\n\tconfigFile: string;\n\tconfig?: NormalizedConfig;\n\tshared?: ResolvedTsplcConfig;\n\tplan?: CodesysPlan;\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\tconst loaded = await loadProject(file, options);\n\tif (!loaded.config || !loaded.project) {\n\t\treturn loaded;\n\t}\n\n\tconst config = loaded.config;\n\tif (config.target.kind !== \"codesys\") {\n\t\treturn {\n\t\t\t...loaded,\n\t\t\tdiagnostics: [\n\t\t\t\tfailure(\n\t\t\t\t\t\"backend\",\n\t\t\t\t\t\"PLC7001\",\n\t\t\t\t\t`Unsupported target: ${config.target.kind}`,\n\t\t\t\t),\n\t\t\t],\n\t\t};\n\t}\n\n\tconst source = analyze({\n\t\ttsconfig: config.tsconfig,\n\t\tprograms: config.programs,\n\t\tservices: loaded.shared?.server,\n\t\tenvironment: loaded.project.environment,\n\t});\n\tif (!source.module) {\n\t\treturn { ...loaded, diagnostics: source.diagnostics };\n\t}\n\tconst normalized = normalizeModule(source.module);\n\tif (!normalized.core) {\n\t\treturn { ...loaded, diagnostics: normalized.diagnostics };\n\t}\n\n\tconst tasks = config.tasks.map((task) => ({\n\t\tname: task.name,\n\t\tintervalNanoseconds: task.schedule.interval.nanoseconds,\n\t\tpriority: task.priority,\n\t\tprograms: task.programs,\n\t}));\n\tconst planned = planCodesys(\n\t\tnormalized.core,\n\t\t{ tasks },\n\t\tconfig.target.options,\n\t\tloaded.project,\n\t);\n\treturn {\n\t\t...loaded,\n\t\t...planned,\n\t\tdiagnostics: [\n\t\t\t...loaded.diagnostics,\n\t\t\t...source.diagnostics,\n\t\t\t...normalized.diagnostics,\n\t\t\t...planned.diagnostics,\n\t\t],\n\t};\n}\n\n/** The installed libraries and fieldbus device tree a CODESYS project of this program needs. */\nasync function engineeringInputs(\n\tshared: ResolvedTsplcConfig,\n\tconfigFile: string,\n\tbundle: Pick<ReturnType<typeof emitCodesys>, \"ioMappings\">,\n\toptions: { frozen?: boolean },\n) {\n\tconst root = dirname(configFile);\n\tconst tree = await deviceTree(shared, await loadHardware(shared, root));\n\treturn {\n\t\tlibraries: await installLibraries(shared.dependencies, root, options),\n\t\t// The emitted names locate mapped IO; the tree maps their channels.\n\t\tdeviceTree: tree && {\n\t\t\t...tree,\n\t\t\tmappings: bundle.ioMappings.map(({ address, variable }) => ({\n\t\t\t\taddress,\n\t\t\t\tvariable,\n\t\t\t})),\n\t\t},\n\t};\n}\n\nexport async function buildProject(\n\tfile = \"tsplc.config.ts\",\n\toptions: ProjectOptions & {\n\t\temitOnly?: boolean;\n\t\tfrozenLockfile?: boolean;\n\t\tcontroller?: Controller;\n\t\t/** Resolve libraries and the device tree into `controllerConfig` even when only emitting. */\n\t\tforController?: boolean;\n\t} & ProgressOptions = {},\n): Promise<{\n\tdirectory?: string;\n\tstatus?: \"emitted\" | \"vendor-compiled\";\n\tcontrollerConfig?: ReturnType<typeof codesysBuildConfig>;\n\t/** What `projectTargets` reads from the program, from this build's own analysis. */\n\ttargets?: ProjectTargets;\n\t/** The route of each service procedure the program calls, as `serviceRoutes` reads them. */\n\tservices?: Readonly<Record<string, string>>;\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\tlet staging: string | undefined;\n\ttry {\n\t\tconst configFile = await realpath(resolve(file));\n\t\t// Withdraw the previous success receipt before checking the new source.\n\t\t// Old artifacts remain owned and intact until publication succeeds.\n\t\tconst previous = await owned(configFile, true);\n\t\tif (previous.unknown.length) {\n\t\t\tthrow new Error(\n\t\t\t\t`Output contains unrelated files: ${previous.unknown.join(\", \")}`,\n\t\t\t);\n\t\t}\n\n\t\tconst checked = await checkProject(configFile, options);\n\t\tif (!checked.plan || !checked.config) {\n\t\t\treturn { diagnostics: checked.diagnostics };\n\t\t}\n\t\tconst bundle = emitCodesys(checked.plan);\n\t\tif (hasErrors(bundle.diagnostics)) {\n\t\t\treturn { diagnostics: bundle.diagnostics };\n\t\t}\n\t\tconst shared = checked.shared;\n\t\tconst engineering =\n\t\t\tshared && (!options.emitOnly || options.forController)\n\t\t\t\t? await engineeringInputs(shared, configFile, bundle, {\n\t\t\t\t\t\tfrozen: options.frozenLockfile,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\t\tconst outDir =\n\t\t\tshared?.build && resolve(dirname(configFile), shared.build.outDir);\n\t\tconst controllerConfig = outDir\n\t\t\t? codesysBuildConfig(checked.plan, bundle, {\n\t\t\t\t\tconfigFile,\n\t\t\t\t\tsourceDir: join(previous.output, emittedSt),\n\t\t\t\t\toutDir,\n\t\t\t\t\tcontroller: options.controller,\n\t\t\t\t\t...engineering,\n\t\t\t\t})\n\t\t\t: undefined;\n\n\t\tawait mkdir(previous.root, { recursive: true });\n\t\tstaging = await mkdtemp(join(previous.root, \"stage-\"));\n\t\tconst artifacts = [\n\t\t\t...bundle.artifacts,\n\t\t\t{\n\t\t\t\tpath: \"mappings.json\",\n\t\t\t\tcontent: `${JSON.stringify(compactMappings(bundle.mappings))}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: emittedFiles.ioSymbols,\n\t\t\t\tcontent: `${JSON.stringify(bundle.ioSymbols, null, 2)}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: emittedFiles.publication,\n\t\t\t\tcontent: `${JSON.stringify(bundle.publication, null, 2)}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: \"config.json\",\n\t\t\t\tcontent: `${JSON.stringify(checked.config, null, 2)}\\n`,\n\t\t\t},\n\t\t\t...(bundle.debug\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: debugManifestFile,\n\t\t\t\t\t\t\tcontent: `${JSON.stringify(bundle.debug)}\\n`,\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t];\n\t\tconst stagedSt = join(staging, emittedSt);\n\t\t// Thousands of artifacts share a few hundred directories; each is made once.\n\t\tconst directories = new Set(\n\t\t\tartifacts.map((artifact) => dirname(join(stagedSt, artifact.path))),\n\t\t);\n\t\tfor (const directory of directories) {\n\t\t\tawait mkdir(directory, { recursive: true });\n\t\t}\n\t\tfor (const artifact of artifacts) {\n\t\t\tawait writeFile(join(stagedSt, artifact.path), artifact.content);\n\t\t}\n\n\t\tlet vendor: Awaited<ReturnType<typeof buildCodesys>> | undefined;\n\t\tif (!options.emitOnly) {\n\t\t\t// The engineering cache has its own ownership marker and survives clean.\n\t\t\tconst engineeringDir = outDir ?? join(previous.root, \"engineering\");\n\t\t\tawait engineeringDirectory(engineeringDir, configFile);\n\t\t\ttry {\n\t\t\t\tvendor = await buildCodesys(\n\t\t\t\t\tchecked.plan,\n\t\t\t\t\tbundle,\n\t\t\t\t\t{\n\t\t\t\t\t\tconfigFile,\n\t\t\t\t\t\tsourceDir: join(staging, emittedSt),\n\t\t\t\t\t\toutDir: engineeringDir,\n\t\t\t\t\t\tcontroller: options.controller,\n\t\t\t\t\t\t...engineering,\n\t\t\t\t\t},\n\t\t\t\t\t{ progress: options.progress },\n\t\t\t\t);\n\t\t\t} catch (cause) {\n\t\t\t\treturn { diagnostics: diagnoseCodesys(cause, bundle) };\n\t\t\t}\n\n\t\t\tconst vendorArtifacts = [\n\t\t\t\t[\"Application.project\", vendor.project],\n\t\t\t\t[\"Application.app\", vendor.output],\n\t\t\t\t[\"Application.crc\", vendor.checksum],\n\t\t\t] as const;\n\t\t\tfor (const [name, path] of vendorArtifacts) {\n\t\t\t\tif (!path) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst destination = join(staging, \"vendor\", name);\n\t\t\t\tawait mkdir(dirname(destination), { recursive: true });\n\t\t\t\tawait copyFile(path, destination);\n\t\t\t}\n\t\t}\n\n\t\tconst status = vendor ? \"vendor-compiled\" : \"emitted\";\n\t\tawait publishArtifacts(staging, previous, {\n\t\t\tconfigFile,\n\t\t\tstatus,\n\t\t\t...(vendor && {\n\t\t\t\tvendor: { application: vendor.application, tasks: vendor.tasks },\n\t\t\t}),\n\t\t});\n\t\t// Publication moved this directory into place; it is no longer staging.\n\t\tstaging = undefined;\n\t\treturn {\n\t\t\tdirectory: previous.output,\n\t\t\tstatus,\n\t\t\t...(controllerConfig && { controllerConfig }),\n\t\t\ttargets: coreTargets(checked.plan.core),\n\t\t\tservices: serviceRoutes(checked.plan.core),\n\t\t\tdiagnostics: [...checked.diagnostics, ...bundle.diagnostics],\n\t\t};\n\t} catch (cause) {\n\t\treturn { diagnostics: [failure(\"config\", \"PLC5004\", cause)] };\n\t} finally {\n\t\tif (staging) {\n\t\t\tawait rm(staging, { recursive: true, force: true });\n\t\t}\n\t}\n}\n\n/**\n * Source mappings with each ST path and source file written once: `mappings` rows are\n * `[object, line, file, start, end, sourceLine, sourceColumn]`, indexing `objects` and `files`.\n */\nfunction compactMappings(mappings: readonly SourceMapping[]) {\n\tconst objects = new Map<string, number>();\n\tconst files = new Map<string, number>();\n\tconst index = (table: Map<string, number>, value: string) => {\n\t\tconst known = table.get(value);\n\t\tif (known !== undefined) {\n\t\t\treturn known;\n\t\t}\n\t\ttable.set(value, table.size);\n\t\treturn table.size - 1;\n\t};\n\tconst rows = mappings.map(({ path, line, span }) => [\n\t\tindex(objects, path),\n\t\tline,\n\t\tindex(files, span.file),\n\t\tspan.start,\n\t\tspan.end,\n\t\tspan.line,\n\t\tspan.column,\n\t]);\n\treturn {\n\t\tobjects: [...objects.keys()],\n\t\tfiles: [...files.keys()],\n\t\tmappings: rows,\n\t};\n}\n\nexport async function cleanProject(file = \"tsplc.config.ts\"): Promise<{\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\ttry {\n\t\tawait cleanArtifacts(await realpath(resolve(file)));\n\t\treturn { diagnostics: [] };\n\t} catch (cause) {\n\t\treturn { diagnostics: [failure(\"config\", \"PLC5004\", cause)] };\n\t}\n}\n",
5
+ "import {\n\tcopyFile,\n\tmkdir,\n\tmkdtemp,\n\trealpath,\n\trm,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { basename, dirname, join, resolve } from \"node:path\";\nimport { installLibraries, type ProgressOptions } from \"@tsplc/build\";\nimport {\n\tanalyze,\n\ttype CompileEnvironment,\n\tcheckHostConfig,\n} from \"@tsplc/compiler\";\nimport {\n\tbuildCodesys,\n\ttype CodesysPlan,\n\ttype CodesysProject,\n\tcodesysBuildConfig,\n\tdiagnoseCodesys,\n\temitCodesys,\n\tioTargets,\n\tplanCodesys,\n\tpublicationSelectors,\n\ttype SourceMapping,\n} from \"@tsplc/compiler/codesys\";\nimport {\n\ttype Diagnostic,\n\thasErrors,\n\tnormalizeModule,\n\ttype VerifiedCoreModule,\n} from \"@tsplc/compiler/ir\";\nimport {\n\ttype BuildTarget,\n\ttype Controller,\n\tcompilerConfig,\n\ttype LoadedConfig,\n\tloadTsplcConfig,\n\ttype NormalizedConfig,\n\ttype ResolvedTsplcConfig,\n\tsimulationConfig,\n} from \"@tsplc/config\";\nimport { emittedFiles, emittedStDirectory } from \"@tsplc/config/project-files\";\nimport { debugManifestFile } from \"@tsplc/debug/manifest\";\nimport {\n\tdeviceTree,\n\tloadHardware,\n\ttype ProjectTargets,\n\tresolveIo,\n} from \"@tsplc/typegen\";\nimport { serviceRoutes } from \"../runtime/launch\";\nimport {\n\tcleanArtifacts,\n\tengineeringDirectory,\n\towned,\n\tpublishArtifacts,\n} from \"./artifacts\";\n\n/** The emitted ST's directory inside the compiler's artifacts directory. */\nconst emittedSt = basename(emittedStDirectory);\n\nconst failure = (\n\torigin: Diagnostic[\"origin\"],\n\tcode: string,\n\tcause: unknown,\n): Diagnostic => ({\n\torigin,\n\tcode,\n\tseverity: \"error\",\n\tmessage: cause instanceof Error ? cause.message : String(cause),\n});\n\n/**\n * `buildProject`'s `loaded` and `configured` options. With `simulate` the build omits fieldbus\n * I/O so a plant simulator can write the inputs; generated types and the debug manifest keep\n * describing the hardware project.\n */\nexport const buildConfigs = (\n\tloaded: LoadedConfig,\n\toptions: { simulate?: boolean },\n) =>\n\toptions.simulate\n\t\t? {\n\t\t\t\tloaded: { ...loaded, config: simulationConfig(loaded.config) },\n\t\t\t\tconfigured: loaded.config,\n\t\t\t}\n\t\t: { loaded };\n\ninterface ProjectOptions {\n\tloaded?: LoadedConfig;\n\tbuildTarget?: BuildTarget;\n\t/** The configuration `loaded` simulates, whose hardware the debug manifest describes. */\n\tconfigured?: ResolvedTsplcConfig;\n\t/**\n\t * The host config check's diagnostics, when the caller ran it before loading the config. The\n\t * check type-checks the config and takes seconds.\n\t */\n\thostConfigDiagnostics?: readonly Diagnostic[];\n\t/** What the program's `env()` calls, endpoints and telemetry read; this process's environment by default. */\n\tenvironment?: CompileEnvironment;\n}\n\n/** Loads the config in `environment`, this process's by default, with its only target's values. */\nconst loadEnvironment = (environment: CompileEnvironment | undefined) => ({\n\tenv: environment ?? process.env,\n\ttarget: undefined,\n\tforAgent: false,\n});\n\nasync function loadProject(\n\tfile: string,\n\t{\n\t\tloaded,\n\t\tbuildTarget,\n\t\tconfigured,\n\t\thostConfigDiagnostics,\n\t\tenvironment,\n\t}: ProjectOptions,\n): Promise<{\n\tconfig?: NormalizedConfig;\n\tconfigFile: string;\n\tshared?: ResolvedTsplcConfig;\n\tproject?: CodesysProject;\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\tlet configFile = resolve(file);\n\ttry {\n\t\tconfigFile = await realpath(configFile);\n\t\tconst diagnostics = hostConfigDiagnostics ?? checkHostConfig(configFile);\n\t\tif (hasErrors(diagnostics)) {\n\t\t\treturn { configFile, diagnostics };\n\t\t}\n\t\tconst { config: shared, env } =\n\t\t\tloaded ??\n\t\t\t(await loadTsplcConfig(configFile, loadEnvironment(environment)));\n\t\tconst root = dirname(configFile);\n\t\tconst catalog = await loadHardware(shared, root);\n\n\t\tconst config = compilerConfig(\n\t\t\tshared,\n\t\t\tresolveIo(shared, catalog),\n\t\t\tbuildTarget,\n\t\t);\n\t\treturn {\n\t\t\tconfigFile,\n\t\t\tshared,\n\t\t\tconfig: { ...config, ...sourceInput(config, root) },\n\t\t\tproject: {\n\t\t\t\troot,\n\t\t\t\tenvironment: env,\n\t\t\t\t...(shared.debug && { debug: shared.debug }),\n\t\t\t\t...(shared.telemetry && { telemetry: shared.telemetry }),\n\t\t\t\t...(shared.server && { server: shared.server }),\n\t\t\t\t// A simulation build drops fieldbus IO, but the debugger still shows the hardware it stands in for.\n\t\t\t\thardware: {\n\t\t\t\t\tcatalog: configured ? await loadHardware(configured, root) : catalog,\n\t\t\t\t\tconfig: configured ?? shared,\n\t\t\t\t\ttree: shared.codesys?.deviceTree !== undefined,\n\t\t\t\t},\n\t\t\t},\n\t\t\tdiagnostics,\n\t\t};\n\t} catch (cause) {\n\t\treturn { configFile, diagnostics: [failure(\"config\", \"PLC5003\", cause)] };\n\t}\n}\n\n/** The analyzer's entry points, resolved against the config file's directory. */\nfunction sourceInput(\n\tcompiler: {\n\t\ttsconfig: string;\n\t\tprograms: Record<string, { module: string; export: string }>;\n\t},\n\troot: string,\n) {\n\treturn {\n\t\ttsconfig: resolve(root, compiler.tsconfig),\n\t\tprograms: Object.fromEntries(\n\t\t\tObject.entries(compiler.programs).map(([name, entry]) => [\n\t\t\t\tname,\n\t\t\t\t{ ...entry, module: resolve(root, entry.module) },\n\t\t\t]),\n\t\t),\n\t};\n}\n\n/**\n * I/O keys and publication selectors from analyzed PLC source. It ignores the\n * config's own type errors, so a typo cannot switch off the types that flag it;\n * it is undefined only while the source itself fails analysis.\n */\nexport async function projectTargets(\n\tfile = \"tsplc.config.ts\",\n\toptions: Pick<ProjectOptions, \"loaded\" | \"environment\"> = {},\n): Promise<ProjectTargets | undefined> {\n\tconst configFile = await realpath(resolve(file));\n\tconst { config, env } =\n\t\toptions.loaded ??\n\t\t(await loadTsplcConfig(configFile, loadEnvironment(options.environment)));\n\tif (!config.compiler) {\n\t\treturn undefined;\n\t}\n\tconst source = analyze({\n\t\t...sourceInput(config.compiler, dirname(configFile)),\n\t\tservices: config.server,\n\t\tenvironment: env,\n\t});\n\tconst core = source.module && normalizeModule(source.module).core;\n\treturn core ? coreTargets(core) : undefined;\n}\n\nconst coreTargets = (core: VerifiedCoreModule): ProjectTargets => ({\n\tio: ioTargets(core),\n\tpublication: publicationSelectors(core),\n});\n\nexport async function checkProject(\n\tfile = \"tsplc.config.ts\",\n\toptions: ProjectOptions = {},\n): Promise<{\n\tconfigFile: string;\n\tconfig?: NormalizedConfig;\n\tshared?: ResolvedTsplcConfig;\n\tplan?: CodesysPlan;\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\tconst loaded = await loadProject(file, options);\n\tif (!loaded.config || !loaded.project) {\n\t\treturn loaded;\n\t}\n\n\tconst config = loaded.config;\n\tif (config.target.kind !== \"codesys\") {\n\t\treturn {\n\t\t\t...loaded,\n\t\t\tdiagnostics: [\n\t\t\t\tfailure(\n\t\t\t\t\t\"backend\",\n\t\t\t\t\t\"PLC7001\",\n\t\t\t\t\t`Unsupported target: ${config.target.kind}`,\n\t\t\t\t),\n\t\t\t],\n\t\t};\n\t}\n\n\tconst source = analyze({\n\t\ttsconfig: config.tsconfig,\n\t\tprograms: config.programs,\n\t\tservices: loaded.shared?.server,\n\t\tenvironment: loaded.project.environment,\n\t});\n\tif (!source.module) {\n\t\treturn { ...loaded, diagnostics: source.diagnostics };\n\t}\n\tconst normalized = normalizeModule(source.module);\n\tif (!normalized.core) {\n\t\treturn { ...loaded, diagnostics: normalized.diagnostics };\n\t}\n\n\tconst tasks = config.tasks.map((task) => ({\n\t\tname: task.name,\n\t\tintervalNanoseconds: task.schedule.interval.nanoseconds,\n\t\tpriority: task.priority,\n\t\tprograms: task.programs,\n\t}));\n\tconst planned = planCodesys(\n\t\tnormalized.core,\n\t\t{ tasks },\n\t\tconfig.target.options,\n\t\tloaded.project,\n\t);\n\treturn {\n\t\t...loaded,\n\t\t...planned,\n\t\tdiagnostics: [\n\t\t\t...loaded.diagnostics,\n\t\t\t...source.diagnostics,\n\t\t\t...normalized.diagnostics,\n\t\t\t...planned.diagnostics,\n\t\t],\n\t};\n}\n\n/** The installed libraries and fieldbus device tree a CODESYS project of this program needs. */\nasync function engineeringInputs(\n\tshared: ResolvedTsplcConfig,\n\tconfigFile: string,\n\tbundle: Pick<ReturnType<typeof emitCodesys>, \"ioMappings\">,\n\toptions: { frozen?: boolean },\n) {\n\tconst root = dirname(configFile);\n\tconst tree = await deviceTree(shared, await loadHardware(shared, root));\n\treturn {\n\t\tlibraries: await installLibraries(shared.dependencies, root, options),\n\t\t// The emitted names locate mapped IO; the tree maps their channels.\n\t\tdeviceTree: tree && {\n\t\t\t...tree,\n\t\t\tmappings: bundle.ioMappings.map(({ address, variable }) => ({\n\t\t\t\taddress,\n\t\t\t\tvariable,\n\t\t\t})),\n\t\t},\n\t};\n}\n\nexport async function buildProject(\n\tfile = \"tsplc.config.ts\",\n\toptions: ProjectOptions & {\n\t\temitOnly?: boolean;\n\t\tfrozenLockfile?: boolean;\n\t\tcontroller?: Controller;\n\t\t/** Resolve libraries and the device tree into `controllerConfig` even when only emitting. */\n\t\tforController?: boolean;\n\t} & ProgressOptions = {},\n): Promise<{\n\tdirectory?: string;\n\tstatus?: \"emitted\" | \"vendor-compiled\";\n\tcontrollerConfig?: ReturnType<typeof codesysBuildConfig>;\n\t/** What `projectTargets` reads from the program, from this build's own analysis. */\n\ttargets?: ProjectTargets;\n\t/** The route of each service procedure the program calls, as `serviceRoutes` reads them. */\n\tservices?: Readonly<Record<string, string>>;\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\tlet staging: string | undefined;\n\ttry {\n\t\tconst configFile = await realpath(resolve(file));\n\t\t// Withdraw the previous success receipt before checking the new source.\n\t\t// Old artifacts remain owned and intact until publication succeeds.\n\t\tconst previous = await owned(configFile, true);\n\t\tif (previous.unknown.length) {\n\t\t\tthrow new Error(\n\t\t\t\t`Output contains unrelated files: ${previous.unknown.join(\", \")}`,\n\t\t\t);\n\t\t}\n\n\t\tconst checked = await checkProject(configFile, options);\n\t\tif (!checked.plan || !checked.config) {\n\t\t\treturn { diagnostics: checked.diagnostics };\n\t\t}\n\t\tconst bundle = emitCodesys(checked.plan);\n\t\tif (hasErrors(bundle.diagnostics)) {\n\t\t\treturn { diagnostics: bundle.diagnostics };\n\t\t}\n\t\tconst shared = checked.shared;\n\t\tconst engineering =\n\t\t\tshared && (!options.emitOnly || options.forController)\n\t\t\t\t? await engineeringInputs(shared, configFile, bundle, {\n\t\t\t\t\t\tfrozen: options.frozenLockfile,\n\t\t\t\t\t})\n\t\t\t\t: undefined;\n\t\tconst outDir =\n\t\t\tshared?.build && resolve(dirname(configFile), shared.build.outDir);\n\t\tconst controllerConfig = outDir\n\t\t\t? codesysBuildConfig(checked.plan, bundle, {\n\t\t\t\t\tconfigFile,\n\t\t\t\t\tsourceDir: join(previous.output, emittedSt),\n\t\t\t\t\toutDir,\n\t\t\t\t\tcontroller: options.controller,\n\t\t\t\t\t...engineering,\n\t\t\t\t})\n\t\t\t: undefined;\n\n\t\tawait mkdir(previous.root, { recursive: true });\n\t\tstaging = await mkdtemp(join(previous.root, \"stage-\"));\n\t\tconst artifacts = [\n\t\t\t...bundle.artifacts,\n\t\t\t{\n\t\t\t\tpath: \"mappings.json\",\n\t\t\t\tcontent: `${JSON.stringify(compactMappings(bundle.mappings))}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: emittedFiles.ioSymbols,\n\t\t\t\tcontent: `${JSON.stringify(bundle.ioSymbols, null, 2)}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: emittedFiles.publication,\n\t\t\t\tcontent: `${JSON.stringify(bundle.publication, null, 2)}\\n`,\n\t\t\t},\n\t\t\t{\n\t\t\t\tpath: \"config.json\",\n\t\t\t\tcontent: `${JSON.stringify(checked.config, null, 2)}\\n`,\n\t\t\t},\n\t\t\t...(bundle.debug\n\t\t\t\t? [\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tpath: debugManifestFile,\n\t\t\t\t\t\t\tcontent: `${JSON.stringify(bundle.debug)}\\n`,\n\t\t\t\t\t\t},\n\t\t\t\t\t]\n\t\t\t\t: []),\n\t\t];\n\t\tconst stagedSt = join(staging, emittedSt);\n\t\t// Thousands of artifacts share a few hundred directories; each is made once.\n\t\tconst directories = new Set(\n\t\t\tartifacts.map((artifact) => dirname(join(stagedSt, artifact.path))),\n\t\t);\n\t\tfor (const directory of directories) {\n\t\t\tawait mkdir(directory, { recursive: true });\n\t\t}\n\t\tfor (const artifact of artifacts) {\n\t\t\tawait writeFile(join(stagedSt, artifact.path), artifact.content);\n\t\t}\n\n\t\tlet vendor: Awaited<ReturnType<typeof buildCodesys>> | undefined;\n\t\tif (!options.emitOnly) {\n\t\t\t// The engineering cache has its own ownership marker and survives clean.\n\t\t\tconst engineeringDir = outDir ?? join(previous.root, \"engineering\");\n\t\t\tawait engineeringDirectory(engineeringDir, configFile);\n\t\t\ttry {\n\t\t\t\tvendor = await buildCodesys(\n\t\t\t\t\tchecked.plan,\n\t\t\t\t\tbundle,\n\t\t\t\t\t{\n\t\t\t\t\t\tconfigFile,\n\t\t\t\t\t\tsourceDir: join(staging, emittedSt),\n\t\t\t\t\t\toutDir: engineeringDir,\n\t\t\t\t\t\tcontroller: options.controller,\n\t\t\t\t\t\t...engineering,\n\t\t\t\t\t},\n\t\t\t\t\t{ progress: options.progress },\n\t\t\t\t);\n\t\t\t} catch (cause) {\n\t\t\t\treturn { diagnostics: diagnoseCodesys(cause, bundle) };\n\t\t\t}\n\n\t\t\tconst vendorArtifacts = [\n\t\t\t\t[\"Application.project\", vendor.project],\n\t\t\t\t[\"Application.app\", vendor.output],\n\t\t\t\t[\"Application.crc\", vendor.checksum],\n\t\t\t] as const;\n\t\t\tfor (const [name, path] of vendorArtifacts) {\n\t\t\t\tif (!path) {\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t\tconst destination = join(staging, \"vendor\", name);\n\t\t\t\tawait mkdir(dirname(destination), { recursive: true });\n\t\t\t\tawait copyFile(path, destination);\n\t\t\t}\n\t\t}\n\n\t\tconst status = vendor ? \"vendor-compiled\" : \"emitted\";\n\t\tawait publishArtifacts(staging, previous, {\n\t\t\tconfigFile,\n\t\t\tstatus,\n\t\t\t...(vendor && {\n\t\t\t\tvendor: { application: vendor.application, tasks: vendor.tasks },\n\t\t\t}),\n\t\t});\n\t\t// Publication moved this directory into place; it is no longer staging.\n\t\tstaging = undefined;\n\t\treturn {\n\t\t\tdirectory: previous.output,\n\t\t\tstatus,\n\t\t\t...(controllerConfig && { controllerConfig }),\n\t\t\ttargets: coreTargets(checked.plan.core),\n\t\t\tservices: serviceRoutes(checked.plan.core),\n\t\t\tdiagnostics: [...checked.diagnostics, ...bundle.diagnostics],\n\t\t};\n\t} catch (cause) {\n\t\treturn { diagnostics: [failure(\"config\", \"PLC5004\", cause)] };\n\t} finally {\n\t\tif (staging) {\n\t\t\tawait rm(staging, { recursive: true, force: true });\n\t\t}\n\t}\n}\n\n/**\n * Source mappings with each ST path and source file written once: `mappings` rows are\n * `[object, line, file, start, end, sourceLine, sourceColumn]`, indexing `objects` and `files`.\n */\nfunction compactMappings(mappings: readonly SourceMapping[]) {\n\tconst objects = new Map<string, number>();\n\tconst files = new Map<string, number>();\n\tconst index = (table: Map<string, number>, value: string) => {\n\t\tconst known = table.get(value);\n\t\tif (known !== undefined) {\n\t\t\treturn known;\n\t\t}\n\t\ttable.set(value, table.size);\n\t\treturn table.size - 1;\n\t};\n\tconst rows = mappings.map(({ path, line, span }) => [\n\t\tindex(objects, path),\n\t\tline,\n\t\tindex(files, span.file),\n\t\tspan.start,\n\t\tspan.end,\n\t\tspan.line,\n\t\tspan.column,\n\t]);\n\treturn {\n\t\tobjects: [...objects.keys()],\n\t\tfiles: [...files.keys()],\n\t\tmappings: rows,\n\t};\n}\n\nexport async function cleanProject(file = \"tsplc.config.ts\"): Promise<{\n\tdiagnostics: readonly Diagnostic[];\n}> {\n\ttry {\n\t\tawait cleanArtifacts(await realpath(resolve(file)));\n\t\treturn { diagnostics: [] };\n\t} catch (cause) {\n\t\treturn { diagnostics: [failure(\"config\", \"PLC5004\", cause)] };\n\t}\n}\n",
6
6
  "import type { VerifiedCoreModule } from \"@tsplc/compiler/ir\";\nimport { generatedDirectory } from \"@tsplc/config/project-files\";\nimport { serviceOfPath } from \"@tsplc/server\";\nimport { z } from \"zod\";\n\n/** The Bun runtime's files, relative to the directory that holds a project's config. */\nexport const runtimeDirectory = `${generatedDirectory}/runtime`;\nexport const runtimeFiles = {\n\t/** What the runtime runs, written by `tsplc run --bun`. */\n\tlaunch: \"launch.json\",\n\t/** The running runtime, written once it serves and removed when it stops. */\n\tstate: \"state.json\",\n\t/** Retained globals, written when the runtime stops. */\n\tretain: \"retain.json\",\n\t/** A detached runtime's output. */\n\tlog: \"plc.log\",\n\t/** The OPC UA server's certificate store. */\n\tcertificates: \"pki\",\n} as const;\n\n/** What `tsplc run --bun` hands the runtime: the config to load, with its target, and how to reach the services the build compiled calls to. */\nexport const launchSchema = z.strictObject({\n\tconfig: z.string().nonempty(),\n\ttarget: z.string().nonempty().nullable(),\n\t/** Each service procedure's route, with its wire-contract version: `/tsplc/services/<version>/<path>` by `<path>`. */\n\tservices: z.record(z.string(), z.string().startsWith(\"/tsplc/services/\")),\n});\nexport type Launch = z.infer<typeof launchSchema>;\n\n/** A runtime that serves: its process and where it publishes OPC UA. */\nexport const runtimeStateSchema = z.strictObject({\n\tpid: z.number().int().positive(),\n\tendpoint: z.string().startsWith(\"opc.tcp://\"),\n\tstartedAt: z.iso.datetime(),\n});\nexport type RuntimeState = z.infer<typeof runtimeStateSchema>;\n\n/** The route each service call the program makes goes to, as the build compiled it. */\nexport const serviceRoutes = (core: VerifiedCoreModule) =>\n\tObject.fromEntries(\n\t\tcore.blocks.flatMap((block) => {\n\t\t\tif (block.runtime?.kind !== \"http\") {\n\t\t\t\treturn [];\n\t\t\t}\n\t\t\tconst route = URL.parse(block.runtime.url)?.pathname;\n\t\t\tconst procedure = route && serviceOfPath(route);\n\t\t\treturn route && procedure ? [[procedure, route] as const] : [];\n\t\t}),\n\t);\n",
7
7
  "import { createHash } from \"node:crypto\";\nimport {\n\tlstat,\n\tmkdir,\n\treaddir,\n\treadFile,\n\trename,\n\trm,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport type { buildCodesys } from \"@tsplc/compiler/codesys\";\nimport { sha256Digest } from \"@tsplc/config/build\";\nimport {\n\temittedStDirectory,\n\tgeneratedDirectory,\n} from \"@tsplc/config/project-files\";\nimport { z } from \"zod\";\n\nconst missing = (cause: unknown): boolean =>\n\tcause instanceof Error && \"code\" in cause && cause.code === \"ENOENT\";\nconst digest = (value: string | Uint8Array): string =>\n\tcreateHash(\"sha256\").update(value).digest(\"hex\");\n\n// Ownership is an explicit boundary: generated files must match their manifest,\n// and engineering trees must belong to this configuration before vendor writes.\nconst generatedFileSchema = z.object({\n\tpath: z\n\t\t.string()\n\t\t.regex(/^[A-Za-z0-9_ .-]+(?:\\/[A-Za-z0-9_ .-]+)*$/)\n\t\t.refine(\n\t\t\t(path) =>\n\t\t\t\t!path.split(\"/\").some((part) => part === \".\" || part === \"..\") &&\n\t\t\t\t![\"manifest.json\", \"receipt.json\"].includes(path),\n\t\t),\n\tsha256: sha256Digest,\n});\n\n/** The manifest's envelope; its entries are checked one by one to name the failure. */\nconst manifestSchema = z.object({\n\tkind: z.literal(\"tsplc-artifacts\"),\n\tversion: z.literal(1),\n\tconfigFile: z.string(),\n\tfiles: z.array(z.unknown()),\n});\n\ntype Manifest = Omit<z.infer<typeof manifestSchema>, \"files\"> & {\n\tfiles: z.infer<typeof generatedFileSchema>[];\n};\n\nconst buildStatusSchema = z.enum([\"emitted\", \"vendor-compiled\"]);\n\nconst receiptSchema = z.object({\n\tkind: z.literal(\"tsplc-build\"),\n\tversion: z.literal(1),\n\tconfigFile: z.string(),\n\tstatus: buildStatusSchema,\n});\n\nconst engineeringMarkerSchema = z.object({\n\tkind: z.literal(\"tsplc-engineering\"),\n\tversion: z.literal(1),\n\tconfigFile: z.string(),\n});\n\nfunction manifest(value: unknown, configFile: string): Manifest {\n\tconst parsed = manifestSchema.safeParse(value);\n\tif (!parsed.success || parsed.data.configFile !== configFile) {\n\t\tthrow new Error(\n\t\t\t\"Output directory has no matching tsPLC ownership manifest.\",\n\t\t);\n\t}\n\n\tconst files = parsed.data.files.map((item) => {\n\t\tconst file = generatedFileSchema.safeParse(item);\n\t\tif (!file.success) {\n\t\t\tthrow new Error(\"Invalid generated file ownership entry.\");\n\t\t}\n\t\treturn file.data;\n\t});\n\tif (new Set(files.map((item) => item.path)).size !== files.length) {\n\t\tthrow new Error(\"Duplicate generated file ownership entry.\");\n\t}\n\treturn { ...parsed.data, files };\n}\n\nasync function directory(path: string): Promise<boolean> {\n\ttry {\n\t\tconst entry = await lstat(path);\n\t\tif (!entry.isDirectory() || entry.isSymbolicLink()) {\n\t\t\tthrow new Error(`Generated directory must be a real directory: ${path}`);\n\t\t}\n\t\treturn true;\n\t} catch (cause) {\n\t\tif (missing(cause)) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow cause;\n\t}\n}\n\nasync function filesIn(path: string, prefix = \"\"): Promise<string[]> {\n\tconst result: string[] = [];\n\tfor (const entry of await readdir(path, { withFileTypes: true })) {\n\t\tconst name = prefix + entry.name;\n\t\tif (entry.isDirectory() && !entry.isSymbolicLink()) {\n\t\t\tresult.push(...(await filesIn(join(path, entry.name), `${name}/`)));\n\t\t} else {\n\t\t\tresult.push(name);\n\t\t}\n\t}\n\treturn result;\n}\n\nexport async function engineeringDirectory(\n\tpath: string,\n\tconfigFile: string,\n): Promise<void> {\n\tconst marker = join(path, \"ownership.json\");\n\tconst exists = await directory(path);\n\tif (!exists || !(await readdir(path)).length) {\n\t\tawait mkdir(path, { recursive: true });\n\t\tawait writeFile(\n\t\t\tmarker,\n\t\t\t`${JSON.stringify({ kind: \"tsplc-engineering\", version: 1, configFile }, null, 2)}\\n`,\n\t\t\t{ flag: \"wx\" },\n\t\t);\n\t} else {\n\t\tconst entry = await lstat(marker).catch((cause: unknown) => {\n\t\t\tif (missing(cause)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Engineering cache has no matching tsPLC ownership marker: ${path}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tthrow cause;\n\t\t});\n\t\tif (!entry.isFile() || entry.isSymbolicLink()) {\n\t\t\tthrow new Error(\"Engineering ownership marker must be a real file.\");\n\t\t}\n\t\tconst value = engineeringMarkerSchema.safeParse(\n\t\t\tJSON.parse(await readFile(marker, \"utf8\")),\n\t\t);\n\t\tif (!value.success || value.data.configFile !== configFile) {\n\t\t\tthrow new Error(\n\t\t\t\t`Engineering cache has no matching tsPLC ownership marker: ${path}`,\n\t\t\t);\n\t\t}\n\t}\n\n\tconst inspect = async (directory: string): Promise<void> => {\n\t\tfor (const entry of await readdir(directory, { withFileTypes: true })) {\n\t\t\tconst child = join(directory, entry.name);\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Engineering cache must not contain symlinks: ${child}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (entry.isDirectory()) {\n\t\t\t\tawait inspect(child);\n\t\t\t}\n\t\t}\n\t};\n\tawait inspect(path);\n}\n\nexport async function owned(\n\tconfigFile: string,\n\twithdrawReceipt = false,\n): Promise<{\n\troot: string;\n\toutput: string;\n\townership?: Manifest;\n\tunknown: string[];\n}> {\n\tconst root = join(dirname(configFile), generatedDirectory);\n\tconst output = join(dirname(configFile), dirname(emittedStDirectory));\n\tif (!(await directory(root)) || !(await directory(output))) {\n\t\treturn { root, output, unknown: [] };\n\t}\n\n\tconst manifestPath = join(output, \"manifest.json\");\n\tconst manifestEntry = await lstat(manifestPath);\n\tif (!manifestEntry.isFile() || manifestEntry.isSymbolicLink()) {\n\t\tthrow new Error(\"Ownership manifest must be a real file.\");\n\t}\n\tconst ownership = manifest(\n\t\tJSON.parse(await readFile(manifestPath, \"utf8\")),\n\t\tconfigFile,\n\t);\n\tconst receipt = join(output, \"receipt.json\");\n\ttry {\n\t\tconst entry = await lstat(receipt);\n\t\tif (!entry.isFile() || entry.isSymbolicLink()) {\n\t\t\tthrow new Error(\"Build receipt must be a real file.\");\n\t\t}\n\t\tconst value = receiptSchema.safeParse(\n\t\t\tJSON.parse(await readFile(receipt, \"utf8\")),\n\t\t);\n\t\tif (!value.success || value.data.configFile !== configFile) {\n\t\t\tthrow new Error(\"Build receipt is not owned by this configuration.\");\n\t\t}\n\t\tif (withdrawReceipt) {\n\t\t\tawait rm(receipt);\n\t\t}\n\t} catch (cause) {\n\t\tif (!missing(cause)) {\n\t\t\tthrow cause;\n\t\t}\n\t}\n\n\tconst names = new Set([\n\t\t...ownership.files.map((file) => file.path),\n\t\t\"manifest.json\",\n\t\t\"receipt.json\",\n\t]);\n\t// Thousands of files share a few hundred directories; each is checked once.\n\tconst checked = new Set<string>();\n\tfor (const file of ownership.files) {\n\t\tlet parent = output;\n\t\tfor (const part of file.path.split(\"/\").slice(0, -1)) {\n\t\t\tparent = join(parent, part);\n\t\t\tif (checked.has(parent)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!(await directory(parent))) {\n\t\t\t\tthrow new Error(`Missing generated directory: ${parent}`);\n\t\t\t}\n\t\t\tchecked.add(parent);\n\t\t}\n\t\tconst path = join(output, file.path);\n\t\tconst entry = await lstat(path);\n\t\tif (\n\t\t\t!entry.isFile() ||\n\t\t\tentry.isSymbolicLink() ||\n\t\t\tdigest(await readFile(path)) !== file.sha256\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`Generated file was replaced or edited; preserve it before rebuilding/cleaning: ${path}`,\n\t\t\t);\n\t\t}\n\t}\n\treturn {\n\t\troot,\n\t\toutput,\n\t\townership,\n\t\tunknown: (await filesIn(output)).filter((name) => !names.has(name)),\n\t};\n}\n\ninterface Receipt {\n\tconfigFile: string;\n\tstatus: z.infer<typeof buildStatusSchema>;\n\tvendor?: Pick<\n\t\tAwaited<ReturnType<typeof buildCodesys>>,\n\t\t\"application\" | \"tasks\"\n\t>;\n}\n\n// Compile in a separate staging tree. Recheck ownership immediately before the\n// swap, because the vendor build may have given the user time to edit old files.\nexport async function publishArtifacts(\n\tstaging: string,\n\tprevious: Awaited<ReturnType<typeof owned>>,\n\treceipt: Receipt,\n): Promise<void> {\n\tconst configFile = receipt.configFile;\n\tconst generated = (await filesIn(staging)).sort();\n\tconst ownership: Manifest = {\n\t\tkind: \"tsplc-artifacts\",\n\t\tversion: 1,\n\t\tconfigFile,\n\t\tfiles: [],\n\t};\n\tfor (const path of generated) {\n\t\townership.files.push({\n\t\t\tpath,\n\t\t\tsha256: digest(await readFile(join(staging, path))),\n\t\t});\n\t}\n\tawait writeFile(\n\t\tjoin(staging, \"manifest.json\"),\n\t\t`${JSON.stringify(ownership, null, 2)}\\n`,\n\t);\n\tawait writeFile(\n\t\tjoin(staging, \"receipt.json\"),\n\t\t`${JSON.stringify(\n\t\t\t{\n\t\t\t\tkind: \"tsplc-build\",\n\t\t\t\tversion: 1,\n\t\t\t\tgeneratedAt: new Date().toISOString(),\n\t\t\t\t...receipt,\n\t\t\t},\n\t\t\tnull,\n\t\t\t2,\n\t\t)}\\n`,\n\t);\n\n\tconst current = await owned(configFile);\n\tif (\n\t\tJSON.stringify(current.ownership) !== JSON.stringify(previous.ownership)\n\t) {\n\t\tthrow new Error(\n\t\t\t\"Output ownership changed during the build; preserve it before rebuilding.\",\n\t\t);\n\t}\n\tif (current.unknown.length) {\n\t\tthrow new Error(\n\t\t\t`Output contains unrelated files: ${current.unknown.join(\", \")}`,\n\t\t);\n\t}\n\n\tconst backup = `${staging}-previous`;\n\tif (previous.ownership) {\n\t\tawait rename(previous.output, backup);\n\t}\n\ttry {\n\t\tawait rename(staging, previous.output);\n\t} catch (cause) {\n\t\tif (previous.ownership) {\n\t\t\tawait rename(backup, previous.output);\n\t\t}\n\t\tthrow cause;\n\t}\n\tif (previous.ownership) {\n\t\tawait rm(backup, { recursive: true });\n\t}\n}\n\nexport async function cleanArtifacts(configFile: string): Promise<void> {\n\tconst generated = await owned(configFile);\n\tif (!generated.ownership) {\n\t\treturn;\n\t}\n\tfor (const entry of generated.ownership.files) {\n\t\tawait rm(join(generated.output, entry.path));\n\t}\n\tawait rm(join(generated.output, \"receipt.json\"), { force: true });\n\tawait rm(join(generated.output, \"manifest.json\"));\n\n\t// Remove empty generated directories while preserving unrelated files.\n\tconst removeEmpty = async (path: string): Promise<void> => {\n\t\tfor (const entry of await readdir(path, { withFileTypes: true })) {\n\t\t\tif (entry.isDirectory() && !entry.isSymbolicLink()) {\n\t\t\t\tawait removeEmpty(join(path, entry.name));\n\t\t\t}\n\t\t}\n\t\tif (!(await readdir(path)).length) {\n\t\t\tawait rm(path, { recursive: true });\n\t\t}\n\t};\n\tawait removeEmpty(generated.output);\n}\n"
8
8
  ],
@@ -2,7 +2,7 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/project/server-check.ts", "../src/project/server.ts"],
4
4
  "sourcesContent": [
5
- "import { dirname } from \"node:path\";\nimport { typeCheckOnly } from \"@tsplc/compiler\";\nimport ts from \"typescript\";\nimport type { z } from \"zod\";\nimport {\n\tserverCheckRequestSchema,\n\ttype serverCheckResultSchema,\n} from \"./server.ts\";\n\n/** Type-checks the server entry under the tsconfig beside it, as it will be built. */\nconst serverFailure = ({\n\tentry,\n\troot,\n}: z.infer<typeof serverCheckRequestSchema>): string | null => {\n\tconst tsconfig = ts.findConfigFile(dirname(entry), ts.sys.fileExists);\n\tif (!tsconfig) {\n\t\treturn \"Server entry requires a tsconfig.json.\";\n\t}\n\tconst read = ts.readConfigFile(tsconfig, ts.sys.readFile);\n\tif (read.error) {\n\t\treturn ts.flattenDiagnosticMessageText(read.error.messageText, \"\\n\");\n\t}\n\tconst parsed = ts.parseJsonConfigFileContent(\n\t\tread.config,\n\t\tts.sys,\n\t\tdirname(tsconfig),\n\t);\n\tconst program = ts.createProgram({\n\t\trootNames: [\n\t\t\tentry,\n\t\t\t...parsed.fileNames.filter((file) => /\\.d\\.[cm]?ts$/.test(file)),\n\t\t],\n\t\toptions: { ...parsed.options, ...typeCheckOnly },\n\t\tprojectReferences: parsed.projectReferences,\n\t});\n\tconst diagnostics = [...parsed.errors, ...ts.getPreEmitDiagnostics(program)];\n\tif (!diagnostics.length) {\n\t\treturn null;\n\t}\n\treturn ts.formatDiagnosticsWithColorAndContext(diagnostics, {\n\t\tgetCanonicalFileName: (path) => path,\n\t\tgetCurrentDirectory: () => root,\n\t\tgetNewLine: () => \"\\n\",\n\t});\n};\n\n// A worker thread runs this module, so the check of a server's thousands of files overlaps the PLC build.\ndeclare const self: Worker;\nself.onmessage = (event: MessageEvent) => {\n\tconst result: z.infer<typeof serverCheckResultSchema> = {\n\t\tfailure: serverFailure(serverCheckRequestSchema.parse(event.data)),\n\t};\n\tself.postMessage(result);\n};\n",
5
+ "import { dirname } from \"node:path\";\nimport { typeCheckOnly } from \"@tsplc/compiler\";\nimport ts from \"typescript\";\nimport type { z } from \"zod\";\nimport {\n\tserverCheckRequestSchema,\n\ttype serverCheckResultSchema,\n} from \"./server\";\n\n/** Type-checks the server entry under the tsconfig beside it, as it will be built. */\nconst serverFailure = ({\n\tentry,\n\troot,\n}: z.infer<typeof serverCheckRequestSchema>): string | null => {\n\tconst tsconfig = ts.findConfigFile(dirname(entry), ts.sys.fileExists);\n\tif (!tsconfig) {\n\t\treturn \"Server entry requires a tsconfig.json.\";\n\t}\n\tconst read = ts.readConfigFile(tsconfig, ts.sys.readFile);\n\tif (read.error) {\n\t\treturn ts.flattenDiagnosticMessageText(read.error.messageText, \"\\n\");\n\t}\n\tconst parsed = ts.parseJsonConfigFileContent(\n\t\tread.config,\n\t\tts.sys,\n\t\tdirname(tsconfig),\n\t);\n\tconst program = ts.createProgram({\n\t\trootNames: [\n\t\t\tentry,\n\t\t\t...parsed.fileNames.filter((file) => /\\.d\\.[cm]?ts$/.test(file)),\n\t\t],\n\t\toptions: { ...parsed.options, ...typeCheckOnly },\n\t\tprojectReferences: parsed.projectReferences,\n\t});\n\tconst diagnostics = [...parsed.errors, ...ts.getPreEmitDiagnostics(program)];\n\tif (!diagnostics.length) {\n\t\treturn null;\n\t}\n\treturn ts.formatDiagnosticsWithColorAndContext(diagnostics, {\n\t\tgetCanonicalFileName: (path) => path,\n\t\tgetCurrentDirectory: () => root,\n\t\tgetNewLine: () => \"\\n\",\n\t});\n};\n\n// A worker thread runs this module, so the check of a server's thousands of files overlaps the PLC build.\ndeclare const self: Worker;\nself.onmessage = (event: MessageEvent) => {\n\tconst result: z.infer<typeof serverCheckResultSchema> = {\n\t\tfailure: serverFailure(serverCheckRequestSchema.parse(event.data)),\n\t};\n\tself.postMessage(result);\n};\n",
6
6
  "import { existsSync } from \"node:fs\";\nimport { mkdir, mkdtemp, rename, rm } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { dirname, join, resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport type { ResolvedTsplcConfig } from \"@tsplc/config\";\nimport { z } from \"zod\";\n\nconst resolveServerModule = (root: string, name: string) =>\n\tname.startsWith(\".\") ||\n\tname.startsWith(\"/\") ||\n\texistsSync(resolve(root, name))\n\t\t? resolve(root, name)\n\t\t: createRequire(join(root, \"package.json\")).resolve(name);\n\nconst kebabCase = (name: string) =>\n\tname\n\t\t.replace(/([a-z0-9])([A-Z])|([A-Z])([A-Z][a-z])/g, \"$1$3-$2$4\")\n\t\t.replace(/[^A-Za-z0-9]+/g, \"-\")\n\t\t.replace(/^-|-$/g, \"\")\n\t\t.toLowerCase();\n\n/** `build/server/<name>-services<extension>`, where the server's script or executable goes. */\nconst serverOutput = (\n\tconfig: ResolvedTsplcConfig,\n\troot: string,\n\textension: string,\n) =>\n\tresolve(\n\t\troot,\n\t\t\"build/server\",\n\t\t`${kebabCase(config.name)}-services${extension}`,\n\t);\n\n/** What `checkServer` posts to its worker: the server entry and the project root diagnostics are relative to. */\nexport const serverCheckRequestSchema = z.strictObject({\n\tentry: z.string(),\n\troot: z.string(),\n});\n\n/** The worker's answer: why the server entry fails its type check, or null when it passes. */\nexport const serverCheckResultSchema = z.strictObject({\n\tfailure: z.string().nullable(),\n});\n\n/** The type-check script beside this module: its source, or the bundle a built package ships. */\nconst serverCheckScript = () => {\n\tconst script = [\"./server-check.ts\", \"./server-check.js\"]\n\t\t.map((path) => fileURLToPath(new URL(path, import.meta.url)))\n\t\t.find((path) => existsSync(path));\n\tif (!script) {\n\t\tthrow new Error(\"The server type-check script is missing from this build.\");\n\t}\n\treturn script;\n};\n\n/** A server entry that passed its type check, and the runtime it is built for. */\nexport interface CheckedServer {\n\tentry: string;\n\truntime: NonNullable<NonNullable<ResolvedTsplcConfig[\"server\"]>[\"runtime\"]>;\n}\n\n/**\n * Type-checks the host entry as it will be built, on a worker thread: a caller that builds the\n * PLC program meanwhile awaits the result after it. The check rejects with the diagnostics.\n */\nexport const checkServer = async (\n\tconfig: ResolvedTsplcConfig,\n\troot: string,\n): Promise<CheckedServer> => {\n\tconst runtime = config.server?.runtime;\n\tif (!runtime) {\n\t\tthrow new Error(\"Configure server.runtime to build the server.\");\n\t}\n\tconst entry = resolveServerModule(root, runtime.entry);\n\tconst worker = new Worker(serverCheckScript());\n\ttry {\n\t\tconst answer = await new Promise<unknown>((resolve, reject) => {\n\t\t\tworker.onmessage = (event: MessageEvent) => resolve(event.data);\n\t\t\tworker.onerror = (event) => reject(new Error(event.message));\n\t\t\tconst request: z.infer<typeof serverCheckRequestSchema> = {\n\t\t\t\tentry,\n\t\t\t\troot,\n\t\t\t};\n\t\t\tworker.postMessage(request);\n\t\t});\n\t\tconst { failure } = serverCheckResultSchema.parse(answer);\n\t\tif (failure !== null) {\n\t\t\tthrow new Error(failure);\n\t\t}\n\t\treturn { entry, runtime };\n\t} finally {\n\t\tworker.terminate();\n\t}\n};\n\n/**\n * Bundles the host entry, which starts its own listener, into one minified script,\n * `build/server/<name>-services.js`, which the plant agent runs on its own Bun. It is a few MB\n * where an executable, which embeds Bun, is over 100, and deployments upload it.\n */\nexport const bundleServer = async (\n\t{ entry }: CheckedServer,\n\tconfig: ResolvedTsplcConfig,\n\troot: string,\n) => {\n\tconst outFile = serverOutput(config, root, \".js\");\n\tconst result = await Bun.build({\n\t\tentrypoints: [entry],\n\t\ttarget: \"bun\",\n\t\tminify: true,\n\t\tenv: \"disable\",\n\t});\n\tif (!result.success) {\n\t\tthrow new AggregateError(result.logs, \"Server bundle build failed.\");\n\t}\n\tconst [script, ...assets] = result.outputs;\n\tif (!script || assets.length) {\n\t\tthrow new Error(\n\t\t\t`The server bundle needs files beside its script (${assets.map(({ path }) => path).join(\", \")}), which deployments don't carry.`,\n\t\t);\n\t}\n\tawait mkdir(dirname(outFile), { recursive: true });\n\tawait Bun.write(outFile, script);\n\treturn outFile;\n};\n\n/** Compiles the host entry, which starts its own listener, into `build/server/<name>-services`. */\nexport const buildServer = async (\n\t{ entry, runtime }: CheckedServer,\n\tconfig: ResolvedTsplcConfig,\n\troot: string,\n) => {\n\tconst windows = runtime.target\n\t\t? runtime.target.includes(\"windows\")\n\t\t: process.platform === \"win32\";\n\tconst outFile = serverOutput(config, root, windows ? \".exe\" : \"\");\n\tawait mkdir(dirname(outFile), { recursive: true });\n\t// Compile beside the output so dependency resolution starts from the owning project.\n\tconst staging = await mkdtemp(join(dirname(outFile), \".tsplc-server-\"));\n\ttry {\n\t\tconst binary = join(staging, \"server\");\n\t\tconst result = await Bun.build({\n\t\t\tentrypoints: [entry],\n\t\t\tenv: \"disable\",\n\t\t\tcompile: {\n\t\t\t\toutfile: binary,\n\t\t\t\t...(runtime.target ? { target: runtime.target } : {}),\n\t\t\t\tautoloadDotenv: false,\n\t\t\t\tautoloadBunfig: false,\n\t\t\t\tautoloadTsconfig: false,\n\t\t\t\tautoloadPackageJson: false,\n\t\t\t},\n\t\t});\n\t\tif (!result.success) {\n\t\t\tthrow new AggregateError(result.logs, \"Server executable build failed.\");\n\t\t}\n\t\t// Bun names a Windows executable itself.\n\t\tawait rename(windows ? `${binary}.exe` : binary, outFile);\n\t\treturn {\n\t\t\tserver: {\n\t\t\t\texecutable: outFile,\n\t\t\t\ttarget: runtime.target ?? `bun-${process.platform}-${process.arch}`,\n\t\t\t},\n\t\t};\n\t} finally {\n\t\tawait rm(staging, { recursive: true, force: true });\n\t}\n};\n"
7
7
  ],
8
8
  "mappings": ";;AAAA;AACA;AACA;;;ACIA;AA6BO,IAAM,2BAA2B,EAAE,aAAa;AAAA,EACtD,OAAO,EAAE,OAAO;AAAA,EAChB,MAAM,EAAE,OAAO;AAChB,CAAC;AAGM,IAAM,0BAA0B,EAAE,aAAa;AAAA,EACrD,SAAS,EAAE,OAAO,EAAE,SAAS;AAC9B,CAAC;;;ADjCD,IAAM,gBAAgB;AAAA,EACrB;AAAA,EACA;AAAA,MAC8D;AAAA,EAC9D,MAAM,WAAW,GAAG,eAAe,QAAQ,KAAK,GAAG,GAAG,IAAI,UAAU;AAAA,EACpE,IAAI,CAAC,UAAU;AAAA,IACd,OAAO;AAAA,EACR;AAAA,EACA,MAAM,OAAO,GAAG,eAAe,UAAU,GAAG,IAAI,QAAQ;AAAA,EACxD,IAAI,KAAK,OAAO;AAAA,IACf,OAAO,GAAG,6BAA6B,KAAK,MAAM,aAAa;AAAA,CAAI;AAAA,EACpE;AAAA,EACA,MAAM,SAAS,GAAG,2BACjB,KAAK,QACL,GAAG,KACH,QAAQ,QAAQ,CACjB;AAAA,EACA,MAAM,UAAU,GAAG,cAAc;AAAA,IAChC,WAAW;AAAA,MACV;AAAA,MACA,GAAG,OAAO,UAAU,OAAO,CAAC,SAAS,gBAAgB,KAAK,IAAI,CAAC;AAAA,IAChE;AAAA,IACA,SAAS,KAAK,OAAO,YAAY,cAAc;AAAA,IAC/C,mBAAmB,OAAO;AAAA,EAC3B,CAAC;AAAA,EACD,MAAM,cAAc,CAAC,GAAG,OAAO,QAAQ,GAAG,GAAG,sBAAsB,OAAO,CAAC;AAAA,EAC3E,IAAI,CAAC,YAAY,QAAQ;AAAA,IACxB,OAAO;AAAA,EACR;AAAA,EACA,OAAO,GAAG,qCAAqC,aAAa;AAAA,IAC3D,sBAAsB,CAAC,SAAS;AAAA,IAChC,qBAAqB,MAAM;AAAA,IAC3B,YAAY,MAAM;AAAA;AAAA,EACnB,CAAC;AAAA;AAKF,KAAK,YAAY,CAAC,UAAwB;AAAA,EACzC,MAAM,SAAkD;AAAA,IACvD,SAAS,cAAc,yBAAyB,MAAM,MAAM,IAAI,CAAC;AAAA,EAClE;AAAA,EACA,KAAK,YAAY,MAAM;AAAA;",
@@ -2,7 +2,7 @@
2
2
  "version": 3,
3
3
  "sources": ["../stdlib/telemetry.ts", "../src/ir/job-errors.ts", "../stdlib/clock.ts"],
4
4
  "sourcesContent": [
5
- "import { relative } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { errorName } from \"../src/ir/job-errors.ts\";\nimport { now } from \"./clock.ts\";\n\ntype Reported = Readonly<Record<string, unknown>>;\nclass Text {\n\tconstructor(readonly value: string) {}\n}\ntype Value = boolean | number | bigint | string | Text;\ntype Properties = Readonly<Record<string, Value>>;\n\nconst module = fileURLToPath(import.meta.url);\nlet collector: ((record: Reported) => void) | undefined;\n\n/** The program's call: the first stack frame outside this module, relative to the working directory. */\nconst source = () => {\n\tfor (const line of new Error().stack?.split(\"\\n\") ?? []) {\n\t\tconst [, file, lineNumber] =\n\t\t\t/\\(?((?:\\/|[A-Za-z]:\\\\)[^():]+):(\\d+):\\d+\\)?$/.exec(line) ?? [];\n\t\tif (file && file !== module) {\n\t\t\treturn `${relative(process.cwd(), file).replaceAll(\"\\\\\", \"/\")}:${lineNumber}`;\n\t\t}\n\t}\n\treturn \"\";\n};\n\nconst reportedValue = (value: Value) => {\n\tif (value instanceof Text) {\n\t\treturn value.value;\n\t}\n\tif (typeof value === \"bigint\") {\n\t\treturn Number(value);\n\t}\n\treturn value;\n};\n\nconst exceptionName = (error: unknown) => {\n\tif (typeof error === \"number\") {\n\t\treturn errorName(error);\n\t}\n\treturn error instanceof Error ? error.message : String(error);\n};\n\nconst report = (record: Reported, properties: Properties = {}) =>\n\tcollector?.({\n\t\t...record,\n\t\tproperties: Object.fromEntries(\n\t\t\tObject.entries(properties).map(([name, value]) => [\n\t\t\t\tname,\n\t\t\t\treportedValue(value),\n\t\t\t]),\n\t\t),\n\t\tsource: source(),\n\t\tscan: 0,\n\t\ttime: now(),\n\t});\n\n/** What a PLC program's `telemetry` calls do under Bun; see `types/telemetry.d.ts`. */\nexport const telemetry = {\n\tcapture: (event: string, properties?: Properties) =>\n\t\treport({ kind: \"event\", event }, properties),\n\tinfo: (message: string, properties?: Properties) =>\n\t\treport({ kind: \"log\", level: \"info\", message }, properties),\n\twarn: (message: string, properties?: Properties) =>\n\t\treport({ kind: \"log\", level: \"warn\", message }, properties),\n\terror: (message: string, properties?: Properties) =>\n\t\treport({ kind: \"log\", level: \"error\", message }, properties),\n\t// Under Bun a failure can be a thrown Error rather than a code; it is sent as code 0 with its message.\n\tcaptureException: (error: unknown, properties?: Properties) => {\n\t\tconst code = typeof error === \"number\" ? error : 0;\n\t\tconst name = exceptionName(error);\n\t\treport(\n\t\t\t{ kind: \"exception\", code, ...(name && { name }), handled: true },\n\t\t\tproperties,\n\t\t);\n\t},\n\ttext: (bytes: readonly number[], length: number) => {\n\t\tconst sent = bytes.slice(0, Math.max(0, Math.min(length, bytes.length)));\n\t\tconst end = sent.indexOf(0);\n\t\treturn new Text(\n\t\t\tnew TextDecoder().decode(\n\t\t\t\tUint8Array.from(end < 0 ? sent : sent.slice(0, end)),\n\t\t\t),\n\t\t);\n\t},\n};\n\nexport const onTelemetry = (next: (record: Reported) => void) => {\n\tcollector = next;\n\treturn () => {\n\t\tif (collector === next) {\n\t\t\tcollector = undefined;\n\t\t}\n\t};\n};\n",
5
+ "import { relative } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { errorName } from \"../src/ir/job-errors\";\nimport { now } from \"./clock\";\n\ntype Reported = Readonly<Record<string, unknown>>;\nclass Text {\n\tconstructor(readonly value: string) {}\n}\ntype Value = boolean | number | bigint | string | Text;\ntype Properties = Readonly<Record<string, Value>>;\n\nconst module = fileURLToPath(import.meta.url);\nlet collector: ((record: Reported) => void) | undefined;\n\n/** The program's call: the first stack frame outside this module, relative to the working directory. */\nconst source = () => {\n\tfor (const line of new Error().stack?.split(\"\\n\") ?? []) {\n\t\tconst [, file, lineNumber] =\n\t\t\t/\\(?((?:\\/|[A-Za-z]:\\\\)[^():]+):(\\d+):\\d+\\)?$/.exec(line) ?? [];\n\t\tif (file && file !== module) {\n\t\t\treturn `${relative(process.cwd(), file).replaceAll(\"\\\\\", \"/\")}:${lineNumber}`;\n\t\t}\n\t}\n\treturn \"\";\n};\n\nconst reportedValue = (value: Value) => {\n\tif (value instanceof Text) {\n\t\treturn value.value;\n\t}\n\tif (typeof value === \"bigint\") {\n\t\treturn Number(value);\n\t}\n\treturn value;\n};\n\nconst exceptionName = (error: unknown) => {\n\tif (typeof error === \"number\") {\n\t\treturn errorName(error);\n\t}\n\treturn error instanceof Error ? error.message : String(error);\n};\n\nconst report = (record: Reported, properties: Properties = {}) =>\n\tcollector?.({\n\t\t...record,\n\t\tproperties: Object.fromEntries(\n\t\t\tObject.entries(properties).map(([name, value]) => [\n\t\t\t\tname,\n\t\t\t\treportedValue(value),\n\t\t\t]),\n\t\t),\n\t\tsource: source(),\n\t\tscan: 0,\n\t\ttime: now(),\n\t});\n\n/** What a PLC program's `telemetry` calls do under Bun; see `types/telemetry.d.ts`. */\nexport const telemetry = {\n\tcapture: (event: string, properties?: Properties) =>\n\t\treport({ kind: \"event\", event }, properties),\n\tinfo: (message: string, properties?: Properties) =>\n\t\treport({ kind: \"log\", level: \"info\", message }, properties),\n\twarn: (message: string, properties?: Properties) =>\n\t\treport({ kind: \"log\", level: \"warn\", message }, properties),\n\terror: (message: string, properties?: Properties) =>\n\t\treport({ kind: \"log\", level: \"error\", message }, properties),\n\t// Under Bun a failure can be a thrown Error rather than a code; it is sent as code 0 with its message.\n\tcaptureException: (error: unknown, properties?: Properties) => {\n\t\tconst code = typeof error === \"number\" ? error : 0;\n\t\tconst name = exceptionName(error);\n\t\treport(\n\t\t\t{ kind: \"exception\", code, ...(name && { name }), handled: true },\n\t\t\tproperties,\n\t\t);\n\t},\n\ttext: (bytes: readonly number[], length: number) => {\n\t\tconst sent = bytes.slice(0, Math.max(0, Math.min(length, bytes.length)));\n\t\tconst end = sent.indexOf(0);\n\t\treturn new Text(\n\t\t\tnew TextDecoder().decode(\n\t\t\t\tUint8Array.from(end < 0 ? sent : sent.slice(0, end)),\n\t\t\t),\n\t\t);\n\t},\n};\n\nexport const onTelemetry = (next: (record: Reported) => void) => {\n\tcollector = next;\n\treturn () => {\n\t\tif (collector === next) {\n\t\t\tcollector = undefined;\n\t\t}\n\t};\n};\n",
6
6
  "/** Job error codes by meaning, as generated async blocks and service calls set them. */\nexport const jobError = {\n\tcancelled: 1,\n\ttimeout: 2,\n\ttooLarge: 3,\n\tmalformedResponse: 4,\n\tnetwork: 5,\n\ttls: 6,\n\tnoRequestSlot: 7,\n} as const;\n\n/** An HTTP response fails a job with `base` + its status, up to `last`. */\nexport const httpErrors = { base: 10000, last: 10999 };\n\n/** Job error codes, as every generated async block and service call reports them. */\nexport const jobErrors: Record<string, string> = {\n\t[jobError.cancelled]: \"cancelled\",\n\t[jobError.timeout]: \"timeout\",\n\t[jobError.tooLarge]: \"request or response too large to encode\",\n\t[jobError.malformedResponse]: \"malformed response\",\n\t[jobError.network]: \"network error or server restarted\",\n\t[jobError.tls]: \"TLS error\",\n\t[jobError.noRequestSlot]: \"no free request slot\",\n\t[httpErrors.base]: \"HTTP status: 10000 + status code\",\n};\n\n/** What a telemetry exception record calls an error code: its meaning when it is a job error. */\nexport const errorName = (code: number): string | undefined => {\n\tif (code > httpErrors.base && code <= httpErrors.last) {\n\t\treturn `HTTP ${code - httpErrors.base}`;\n\t}\n\treturn code < httpErrors.base ? jobErrors[code] : undefined;\n};\n",
7
7
  "/** Milliseconds since the process started, as the PLC's `now()` counts them; used when a program runs under Bun. */\nexport const now = (): number => Math.floor(performance.now());\n"
8
8
  ],
package/package.json CHANGED
@@ -17,7 +17,7 @@
17
17
  "url": "git+https://github.com/rip-technologies/tsplc.git",
18
18
  "directory": "packages/compiler"
19
19
  },
20
- "version": "0.5.3",
20
+ "version": "0.5.5",
21
21
  "type": "module",
22
22
  "exports": {
23
23
  ".": {
@@ -101,17 +101,17 @@
101
101
  "bun": ">=1.4.3"
102
102
  },
103
103
  "dependencies": {
104
- "@tsplc/agent": "0.5.3",
105
- "@tsplc/build": "0.5.3",
106
- "@tsplc/config": "0.5.3",
107
- "@tsplc/debug": "0.5.3",
108
- "@tsplc/opcua": "0.5.3",
109
- "@tsplc/typegen": "0.5.3",
104
+ "@tsplc/agent": "0.5.5",
105
+ "@tsplc/build": "0.5.5",
106
+ "@tsplc/config": "0.5.5",
107
+ "@tsplc/debug": "0.5.5",
108
+ "@tsplc/opcua": "0.5.5",
109
+ "@tsplc/typegen": "0.5.5",
110
110
  "typescript": "6.0.3",
111
111
  "zod": "4.3.6",
112
112
  "@types/bun": "1.4.2",
113
- "@tsplc/server": "0.5.3",
114
- "@tsplc/iec": "0.5.3"
113
+ "@tsplc/server": "0.5.5",
114
+ "@tsplc/iec": "0.5.5"
115
115
  },
116
116
  "bin": {
117
117
  "tsplc": "./dist/cli.js"
@@ -6,8 +6,8 @@ import {
6
6
  } from "@tsplc/config";
7
7
  import { directIoBindingSchema } from "@tsplc/config/build";
8
8
  import { z } from "zod";
9
- import { engineeringSchema } from "./engineering.ts";
10
- import { isIecIdentifier } from "./names.ts";
9
+ import { engineeringSchema } from "./engineering";
10
+ import { isIecIdentifier } from "./names";
11
11
 
12
12
  const addressSchema = directIoBindingSchema.extend({
13
13
  kind: z.literal("direct"),
@@ -13,8 +13,8 @@ import type {
13
13
  } from "@tsplc/compiler/ir";
14
14
  import { directWrites, instancedBlock, nestedBodies } from "@tsplc/compiler/ir";
15
15
  import type { ResolvedDebugConfig } from "@tsplc/config";
16
- import { moduleName } from "./storage.ts";
17
- import { routineTasks, variablesById } from "./task-access.ts";
16
+ import { moduleName } from "./storage";
17
+ import { routineTasks, variablesById } from "./task-access";
18
18
 
19
19
  type Routine = CoreFunction | CoreFunctionBlock;
20
20
 
@@ -10,25 +10,25 @@ import {
10
10
  emitIoList,
11
11
  type IoMapping,
12
12
  ioTarget,
13
- } from "./global-lists.ts";
14
- import { emitServiceBlock, httpNetwork, type RpcChannel } from "./http.ts";
13
+ } from "./global-lists";
14
+ import { emitServiceBlock, httpNetwork, type RpcChannel } from "./http";
15
15
  import {
16
16
  emitDebugGlobal,
17
17
  emitTelemetry,
18
18
  planInstrumentation,
19
- } from "./instrumentation.ts";
20
- import { debugManifest } from "./manifest.ts";
21
- import { type CodesysPlan, diagnostic, isCodesysPlan } from "./plan.ts";
22
- import { emitScanProgram } from "./programs.ts";
23
- import { machineInterfaces, publishedSymbols } from "./publication.ts";
24
- import { emitRoutine } from "./routines.ts";
25
- import { stFiles } from "./st-files.ts";
19
+ } from "./instrumentation";
20
+ import { debugManifest } from "./manifest";
21
+ import { type CodesysPlan, diagnostic, isCodesysPlan } from "./plan";
22
+ import { emitScanProgram } from "./programs";
23
+ import { machineInterfaces, publishedSymbols } from "./publication";
24
+ import { emitRoutine } from "./routines";
25
+ import { stFiles } from "./st-files";
26
26
  import {
27
27
  allocateBlockFields,
28
28
  allocateFunctionNames,
29
29
  allocateRoutineScope,
30
30
  createSymbols,
31
- } from "./symbols.ts";
31
+ } from "./symbols";
32
32
 
33
33
  export interface SourceMapping {
34
34
  path: string;
@@ -8,7 +8,7 @@ import type { EmitResult } from "@tsplc/compiler/ir";
8
8
  import type { Controller, DeviceTree } from "@tsplc/config";
9
9
  import { engineeringBuildSchema, resolveConfig } from "@tsplc/config/build";
10
10
  import { z } from "zod";
11
- import type { CodesysPlan } from "./plan.ts";
11
+ import type { CodesysPlan } from "./plan";
12
12
 
13
13
  export const engineeringSchema = z.strictObject({
14
14
  kind: z.literal("v3.5"),
@@ -1,5 +1,5 @@
1
1
  import type { CoreExpression, CorePath } from "@tsplc/compiler/ir";
2
- import { type CodesysSymbols, required } from "./symbols.ts";
2
+ import { type CodesysSymbols, required } from "./symbols";
3
3
 
4
4
  /** The storage a routine's ST can name: module storage, IO and its own variables, with their types. */
5
5
  export interface StorageScope {
@@ -4,16 +4,16 @@ import {
4
4
  instancedBlock,
5
5
  type Variable,
6
6
  } from "@tsplc/compiler/ir";
7
- import type { SourceMapping } from "./emit.ts";
7
+ import type { SourceMapping } from "./emit";
8
8
  import {
9
9
  isStoragePath,
10
10
  resolveStoragePath,
11
11
  type StorageBinding,
12
- } from "./io-paths.ts";
13
- import { Names } from "./names.ts";
14
- import type { CodesysPlan } from "./plan.ts";
15
- import type { GlobalStorage } from "./storage.ts";
16
- import { type CodesysSymbols, required } from "./symbols.ts";
12
+ } from "./io-paths";
13
+ import { Names } from "./names";
14
+ import type { CodesysPlan } from "./plan";
15
+ import type { GlobalStorage } from "./storage";
16
+ import { type CodesysSymbols, required } from "./symbols";
17
17
 
18
18
  const globalSections = {
19
19
  constants: "VAR_GLOBAL CONSTANT",
@@ -1,7 +1,7 @@
1
1
  import { standardBlocks, type VerifiedCoreModule } from "@tsplc/compiler/ir";
2
- import { Names, pascalCase } from "./names.ts";
3
- import { storageLayout } from "./storage.ts";
4
- import { CodesysTypes } from "./types.ts";
2
+ import { Names, pascalCase } from "./names";
3
+ import { storageLayout } from "./storage";
4
+ import { CodesysTypes } from "./types";
5
5
 
6
6
  export const planGlobalNames = (
7
7
  core: VerifiedCoreModule,
@@ -9,14 +9,14 @@ import {
9
9
  import { type HttpOptions, secretValue } from "@tsplc/config";
10
10
  import { elementaryType, integerRange } from "@tsplc/iec";
11
11
  import { plcBufferBytes } from "@tsplc/server/wire";
12
- import type { CodesysPlan } from "./plan.ts";
12
+ import type { CodesysPlan } from "./plan";
13
13
  import {
14
14
  type CodesysSymbols,
15
15
  type EmissionContext,
16
16
  instrumentationFieldTypes,
17
17
  required,
18
- } from "./symbols.ts";
19
- import { type CodesysTypes, stStringLiteral } from "./types.ts";
18
+ } from "./symbols";
19
+ import { type CodesysTypes, stStringLiteral } from "./types";
20
20
 
21
21
  const opcuaServiceCapacity = 16;
22
22
 
@@ -1,13 +1,13 @@
1
1
  export { engineeringBuildSchema } from "@tsplc/config/build";
2
- export { type CodesysOptions, codesys, direct } from "./config.ts";
3
- export { emitCodesys, type SourceMapping } from "./emit.ts";
2
+ export { type CodesysOptions, codesys, direct } from "./config";
3
+ export { emitCodesys, type SourceMapping } from "./emit";
4
4
  export {
5
5
  buildCodesys,
6
6
  type CodesysEngineeringBuild,
7
7
  codesysBuildConfig,
8
- } from "./engineering.ts";
9
- export { ioTargets } from "./io-paths.ts";
10
- export type { ProjectHardware } from "./manifest.ts";
11
- export { type CodesysPlan, type CodesysProject, planCodesys } from "./plan.ts";
12
- export { publicationSelectors } from "./publication.ts";
13
- export { diagnoseCodesys } from "./vendor.ts";
8
+ } from "./engineering";
9
+ export { ioTargets } from "./io-paths";
10
+ export type { ProjectHardware } from "./manifest";
11
+ export { type CodesysPlan, type CodesysProject, planCodesys } from "./plan";
12
+ export { publicationSelectors } from "./publication";
13
+ export { diagnoseCodesys } from "./vendor";
@@ -9,24 +9,20 @@ import type {
9
9
  } from "@tsplc/compiler/ir";
10
10
  import type { DebugManifest } from "@tsplc/debug/manifest";
11
11
  import { elementaryType, integerRange } from "@tsplc/iec";
12
- import { DebugAnalysis, type InstancePath, type Operand } from "./debug.ts";
12
+ import { DebugAnalysis, type InstancePath, type Operand } from "./debug";
13
13
  import {
14
14
  expressionText,
15
15
  placeText,
16
16
  type StorageScope,
17
17
  storageName,
18
- } from "./expressions.ts";
19
- import { isStoragePath, resolveStoragePath } from "./io-paths.ts";
20
- import { ioAddress } from "./manifest.ts";
21
- import { Names } from "./names.ts";
22
- import type { CodesysPlan } from "./plan.ts";
23
- import {
24
- type CodesysSymbols,
25
- type EmissionContext,
26
- required,
27
- } from "./symbols.ts";
28
- import { telemetryClient, telemetryObjects } from "./telemetry.ts";
29
- import { stStringLiteral } from "./types.ts";
18
+ } from "./expressions";
19
+ import { isStoragePath, resolveStoragePath } from "./io-paths";
20
+ import { ioAddress } from "./manifest";
21
+ import { Names } from "./names";
22
+ import type { CodesysPlan } from "./plan";
23
+ import { type CodesysSymbols, type EmissionContext, required } from "./symbols";
24
+ import { telemetryClient, telemetryObjects } from "./telemetry";
25
+ import { stStringLiteral } from "./types";
30
26
 
31
27
  /**
32
28
  * The debugger's and telemetry's names in the program: `GVL_TsplcDebug` and its fields, each
@@ -1,7 +1,7 @@
1
1
  // biome-ignore-all lint/style/noNonNullAssertion: Retain existing non-null assertions during the tooling migration; changing their contracts requires a separate review.
2
2
  import type { PlcType, Variable, VerifiedCoreModule } from "@tsplc/compiler/ir";
3
3
  import { type IoTarget, ioLayout } from "@tsplc/typegen/hardware";
4
- import { moduleName } from "./storage.ts";
4
+ import { moduleName } from "./storage";
5
5
 
6
6
  type StorageSegment =
7
7
  | { kind: "field"; record: string; name: string }
@@ -33,16 +33,16 @@ import type {
33
33
  import { serviceOfPath } from "@tsplc/server";
34
34
  import type { HardwareCatalog } from "@tsplc/typegen/hardware";
35
35
  import { version } from "../../package.json";
36
- import { type InstancePath, storagePath } from "./debug.ts";
37
- import { Sources } from "./sources.ts";
36
+ import { type InstancePath, storagePath } from "./debug";
37
+ import { Sources } from "./sources";
38
38
  import {
39
39
  type CodesysSymbols,
40
40
  type EmissionContext,
41
41
  instrumentationFieldTypes,
42
42
  required,
43
- } from "./symbols.ts";
44
- import { generated } from "./telemetry.ts";
45
- import { type CodesysTypes, sourceTypeName, stringTypeName } from "./types.ts";
43
+ } from "./symbols";
44
+ import { generated } from "./telemetry";
45
+ import { type CodesysTypes, sourceTypeName, stringTypeName } from "./types";
46
46
 
47
47
  /** The configured hardware a manifest describes; `tree` when this build generates the device tree. */
48
48
  export interface ProjectHardware {
@@ -28,33 +28,33 @@ import type {
28
28
  import { cyclicTasksSchema } from "@tsplc/config/build";
29
29
  import { ioScalarBits, sizePrefixes } from "@tsplc/iec";
30
30
  import { ioLayout } from "@tsplc/typegen/hardware";
31
- import { type CodesysOptions, optionsSchema } from "./config.ts";
31
+ import { type CodesysOptions, optionsSchema } from "./config";
32
32
  import {
33
33
  type HttpEndpoint,
34
34
  resolveHttpEndpoint,
35
35
  validateHttpLayout,
36
- } from "./http.ts";
36
+ } from "./http";
37
37
  import {
38
38
  iecSpelling,
39
39
  isStoragePath,
40
40
  resolveStoragePath,
41
41
  type StorageBinding,
42
- } from "./io-paths.ts";
43
- import type { ProjectHardware } from "./manifest.ts";
44
- import { isIecIdentifier } from "./names.ts";
45
- import { resolvePublication } from "./publication.ts";
46
- import { storageLayout } from "./storage.ts";
42
+ } from "./io-paths";
43
+ import type { ProjectHardware } from "./manifest";
44
+ import { isIecIdentifier } from "./names";
45
+ import { resolvePublication } from "./publication";
46
+ import { storageLayout } from "./storage";
47
47
  import {
48
48
  accessedStorage,
49
49
  routineTasks,
50
50
  schedulePrograms,
51
51
  taskStorageOwnership,
52
- } from "./task-access.ts";
52
+ } from "./task-access";
53
53
  import {
54
54
  planTelemetry,
55
55
  type TelemetryPlan,
56
56
  telemetryClient,
57
- } from "./telemetry.ts";
57
+ } from "./telemetry";
58
58
 
59
59
  // Only this planner can admit a target configuration for emission. Cloning a
60
60
  // branded-looking object does not give it membership in this private identity set.
@@ -1,7 +1,7 @@
1
1
  import type { GeneratedObject, PlcProgram } from "@tsplc/compiler/ir";
2
- import type { IoChannel } from "./global-lists.ts";
3
- import { type EmissionContext, required } from "./symbols.ts";
4
- import { accessedStorage } from "./task-access.ts";
2
+ import type { IoChannel } from "./global-lists";
3
+ import { type EmissionContext, required } from "./symbols";
4
+ import { accessedStorage } from "./task-access";
5
5
 
6
6
  /** The PROGRAM a task calls for a program: its IO scan around a call of the authored routine. */
7
7
  export function emitScanProgram(
@@ -5,10 +5,10 @@ import type {
5
5
  } from "@tsplc/compiler/ir";
6
6
  import type { Publication } from "@tsplc/config";
7
7
  import { emittedFiles } from "@tsplc/config/project-files";
8
- import type { RpcChannel } from "./http.ts";
9
- import type { CodesysPlan } from "./plan.ts";
10
- import { moduleFile, moduleName } from "./storage.ts";
11
- import { type CodesysSymbols, required } from "./symbols.ts";
8
+ import type { RpcChannel } from "./http";
9
+ import type { CodesysPlan } from "./plan";
10
+ import { moduleFile, moduleName } from "./storage";
11
+ import { type CodesysSymbols, required } from "./symbols";
12
12
 
13
13
  const globals = (core: VerifiedCoreModule) =>
14
14
  core.variables.filter(
@@ -9,27 +9,27 @@ import {
9
9
  type SourceSpan,
10
10
  type Variable,
11
11
  } from "@tsplc/compiler/ir";
12
- import type { SourceMapping } from "./emit.ts";
12
+ import type { SourceMapping } from "./emit";
13
13
  import {
14
14
  expressionText,
15
15
  placeText,
16
16
  type StorageScope,
17
17
  storageName,
18
- } from "./expressions.ts";
18
+ } from "./expressions";
19
19
  import {
20
20
  jobField,
21
21
  jobTracking,
22
22
  type RoutineProbes,
23
23
  ringTarget,
24
24
  writeProbes,
25
- } from "./instrumentation.ts";
25
+ } from "./instrumentation";
26
26
  import {
27
27
  type CodesysSymbols,
28
28
  type EmissionContext,
29
29
  instrumentationFieldTypes,
30
30
  required,
31
- } from "./symbols.ts";
32
- import { callParameters } from "./telemetry.ts";
31
+ } from "./symbols";
32
+ import { callParameters } from "./telemetry";
33
33
 
34
34
  function routineHeader(
35
35
  symbols: CodesysSymbols,
@@ -1,8 +1,8 @@
1
1
  import type { EmitResult, GeneratedObject } from "@tsplc/compiler/ir";
2
- import type { SourceMapping } from "./emit.ts";
3
- import type { CodesysPlan } from "./plan.ts";
4
- import { sourceFolders } from "./sources.ts";
5
- import { type CodesysSymbols, required } from "./symbols.ts";
2
+ import type { SourceMapping } from "./emit";
3
+ import type { CodesysPlan } from "./plan";
4
+ import { sourceFolders } from "./sources";
5
+ import { type CodesysSymbols, required } from "./symbols";
6
6
 
7
7
  /** The file that holds an object's declaration, under its path: its only file, or `declaration.st` beside its implementation. */
8
8
  export const declarationFile = (path: string, object: GeneratedObject) =>
@@ -4,12 +4,12 @@ import {
4
4
  type GeneratedObject,
5
5
  standardBlocks,
6
6
  } from "@tsplc/compiler/ir";
7
- import { planGlobalNames } from "./global-names.ts";
8
- import type { Instrumentation } from "./instrumentation.ts";
9
- import { Names } from "./names.ts";
10
- import { NumericLowering } from "./numeric.ts";
11
- import type { CodesysPlan } from "./plan.ts";
12
- import { accessedStorage } from "./task-access.ts";
7
+ import { planGlobalNames } from "./global-names";
8
+ import type { Instrumentation } from "./instrumentation";
9
+ import { Names } from "./names";
10
+ import { NumericLowering } from "./numeric";
11
+ import type { CodesysPlan } from "./plan";
12
+ import { accessedStorage } from "./task-access";
13
13
 
14
14
  // All symbol relationships were checked by normalization and planning. Failure
15
15
  // here is an emitter invariant violation, rather than a recoverable source error.
@@ -13,8 +13,8 @@ import {
13
13
  } from "@tsplc/compiler/ir";
14
14
  import { type ResolvedTelemetryConfig, telemetrySchema } from "@tsplc/config";
15
15
  import { plcBufferBytes } from "@tsplc/server/wire";
16
- import type { CodesysOptions } from "./config.ts";
17
- import { blockInstances, type InstancePath } from "./debug.ts";
16
+ import type { CodesysOptions } from "./config";
17
+ import { blockInstances, type InstancePath } from "./debug";
18
18
  import {
19
19
  type HttpEndpoint,
20
20
  httpCertificateVerifier,
@@ -22,10 +22,10 @@ import {
22
22
  jsonScalar,
23
23
  nativeHttp,
24
24
  resolveHttpEndpoint,
25
- } from "./http.ts";
26
- import { Sources } from "./sources.ts";
27
- import { routineTasks } from "./task-access.ts";
28
- import { type CodesysTypes, stStringLiteral } from "./types.ts";
25
+ } from "./http";
26
+ import { Sources } from "./sources";
27
+ import { routineTasks } from "./task-access";
28
+ import { type CodesysTypes, stStringLiteral } from "./types";
29
29
 
30
30
  /** The sender's key in `CodesysPlan.http`, and its HTTP block's id. */
31
31
  export const telemetryClient = "tsplc:telemetry";
@@ -1,8 +1,8 @@
1
1
  import type { Constant, GeneratedObject, PlcType } from "@tsplc/compiler/ir";
2
2
  import { instancedBlock, nanosecondsPerMillisecond } from "@tsplc/compiler/ir";
3
3
  import { escapeString } from "@tsplc/iec/st";
4
- import { Names } from "./names.ts";
5
- import { scalarLiteral } from "./numeric.ts";
4
+ import { Names } from "./names";
5
+ import { scalarLiteral } from "./numeric";
6
6
 
7
7
  /** A type's name as its source declares it: the last segment of its id. */
8
8
  export const sourceTypeName = (id: string) => id.slice(id.lastIndexOf(":") + 1);