@tsplc/build 0.2.21 → 0.4.0

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 (51) hide show
  1. package/README.md +2 -2
  2. package/dist/cli.js +1052 -836
  3. package/dist/cli.js.map +27 -24
  4. package/dist/images.js +165 -0
  5. package/dist/images.js.map +12 -0
  6. package/dist/index.js +888 -668
  7. package/dist/index.js.map +23 -20
  8. package/dist/libraries.js +4 -3
  9. package/dist/libraries.js.map +3 -3
  10. package/docker/Dockerfile.dockerignore +0 -4
  11. package/docker/Dockerfile.source +5 -0
  12. package/docker/build-image +30 -26
  13. package/docker/config.ts +1 -1
  14. package/docker/install/wine-signal/README.md +1 -1
  15. package/docker/runner.ts +9 -7
  16. package/package.json +24 -8
  17. package/python/build.py +231 -20
  18. package/python/codesys_online.py +121 -10
  19. package/python/worker.py +2 -0
  20. package/src/artifacts.ts +9 -7
  21. package/src/build.ts +9 -4
  22. package/src/cli.ts +11 -20
  23. package/src/controller-online.ts +145 -61
  24. package/src/controller-protocol.ts +48 -5
  25. package/src/controller-session.ts +386 -147
  26. package/src/device-tree.ts +1 -1
  27. package/src/docker-build.ts +80 -98
  28. package/src/docker-context.ts +56 -3
  29. package/src/docker-run.ts +56 -3
  30. package/src/engineering-settings.ts +3 -3
  31. package/src/host/codesys-host.ts +3 -3
  32. package/src/host/codesys-worker.ts +77 -3
  33. package/src/images.ts +105 -0
  34. package/src/import-request.ts +1 -0
  35. package/src/index.ts +30 -16
  36. package/src/io.ts +1 -1
  37. package/src/libraries.ts +3 -2
  38. package/src/project-operations.ts +48 -0
  39. package/src/run.ts +9 -6
  40. package/src/sources.ts +2 -2
  41. package/docker/install/wine-signal/check.sh +0 -34
  42. package/docker/install/wine-signal/tests/avx-registers.c +0 -53
  43. package/docker/install/wine-signal/tests/frame-and-handler.c +0 -192
  44. package/docker/install/wine-signal/tests/loader-i386.c +0 -8
  45. package/docker/install/wine-signal/tests/signal-return.c +0 -47
  46. package/python/test_build.py +0 -579
  47. package/python/test_codesys_login.py +0 -139
  48. package/python/test_codesys_online.py +0 -259
  49. package/python/test_installer_packages.py +0 -217
  50. package/python/test_installer_verification.py +0 -307
  51. package/python/test_worker.py +0 -154
package/dist/index.js.map CHANGED
@@ -1,33 +1,36 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/artifacts.ts", "../src/build.ts", "../src/docker-build.ts", "../src/docker-context.ts", "../src/package-path.ts", "../src/diagnostics.ts", "../src/docker-run.ts", "../src/host/codesys-worker.ts", "../src/host/codesys-command.ts", "../src/host/codesys-host.ts", "../src/host/windows-path.ts", "../src/sources.ts", "../src/st/parse.ts", "../src/st/declarations.ts", "../src/st/lexer.ts", "../src/st/reader.ts", "../src/io.ts", "../src/index.ts", "../src/controller-online.ts", "../src/controller-protocol.ts", "../src/engineering-settings.ts", "../src/libraries.ts", "../src/run.ts", "../src/runtime-status.ts"],
3
+ "sources": ["../src/index.ts", "../src/artifacts.ts", "../src/docker-build.ts", "../src/diagnostics.ts", "../src/docker-run.ts", "../src/images.ts", "../src/docker-context.ts", "../src/package-path.ts", "../src/host/codesys-worker.ts", "../src/controller-protocol.ts", "../src/host/codesys-command.ts", "../src/host/codesys-host.ts", "../src/host/windows-path.ts", "../src/sources.ts", "../src/io.ts", "../src/st/lexer.ts", "../src/st/parse.ts", "../src/st/declarations.ts", "../src/st/reader.ts", "../src/build.ts", "../src/controller-online.ts", "../src/controller-session.ts", "../src/engineering-settings.ts", "../src/libraries.ts", "../src/project-operations.ts", "../src/run.ts", "../src/runtime-status.ts"],
4
4
  "sourcesContent": [
5
- "import {\n\tcopyFile,\n\tcp,\n\treadFile,\n\trename,\n\trm,\n\tstat,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { identifierPattern } from \"@tsplc/iec/st\";\nimport { z } from \"zod\";\nimport { cyclicTasksSchema } from \"@tsplc/config/build\";\n\nexport const buildFiles = {\n\tproject: \"Application.project\",\n\toutput: \"runtime/Application.app\",\n\tchecksum: \"runtime/Application.crc\",\n\treceipt: \"build.json\",\n\t// Normalized EDS files of a generated device tree, imported by the worker.\n\tdevices: \"eds\",\n\t// With a generated device tree: the project plus the descriptions an IDE needs.\n\tarchive: \"Application.projectarchive\",\n} as const;\n\nconst receiptSchema = z.object({\n\tmode: z.literal(\"build\"),\n\tapplication: z.string().regex(identifierPattern),\n\ttasks: cyclicTasksSchema.optional(),\n});\n\n/** A receipt is published last, after every artifact has been checked and replaced. */\nexport const readBuild = async (directory: string) => {\n\tconst receipt = receiptSchema.safeParse(\n\t\tJSON.parse(await readFile(resolve(directory, buildFiles.receipt), \"utf8\")),\n\t);\n\tif (!receipt.success) {\n\t\tthrow new Error(\"CODESYS did not produce a valid build receipt\", {\n\t\t\tcause: receipt.error,\n\t\t});\n\t}\n\tfor (const file of [\n\t\tbuildFiles.project,\n\t\tbuildFiles.output,\n\t\tbuildFiles.checksum,\n\t]) {\n\t\tconst artifact = await stat(resolve(directory, file));\n\t\tif (!artifact.isFile() || artifact.size === 0) {\n\t\t\tthrow new Error(`CODESYS produced an empty artifact: ${file}`);\n\t\t}\n\t}\n\treturn {\n\t\t...receipt.data,\n\t\tdirectory,\n\t\tproject: resolve(directory, buildFiles.project),\n\t\toutput: resolve(directory, buildFiles.output),\n\t\tchecksum: resolve(directory, buildFiles.checksum),\n\t};\n};\n\n/** Publish a verified IDE build, with the completion receipt written last. */\nexport const publishBuild = async (\n\tcompiled: Awaited<ReturnType<typeof readBuild>>,\n\toutDir: string,\n) => {\n\tawait copyFile(compiled.project, resolve(outDir, buildFiles.project));\n\tawait rm(resolve(outDir, \"runtime\"), { recursive: true, force: true });\n\tawait rename(\n\t\tresolve(compiled.directory, \"runtime\"),\n\t\tresolve(outDir, \"runtime\"),\n\t);\n\tawait rm(resolve(outDir, buildFiles.archive), { force: true });\n\tawait cp(\n\t\tresolve(compiled.directory, buildFiles.archive),\n\t\tresolve(outDir, buildFiles.archive),\n\t).catch((cause: unknown) => {\n\t\tif (!(\n\t\t\tcause &&\n\t\t\ttypeof cause === \"object\" &&\n\t\t\t\"code\" in cause &&\n\t\t\tcause.code === \"ENOENT\"\n\t\t)) {\n\t\t\tthrow cause;\n\t\t}\n\t});\n\tawait writeFile(\n\t\tresolve(outDir, buildFiles.receipt),\n\t\tJSON.stringify(\n\t\t\t{\n\t\t\t\tmode: \"build\",\n\t\t\t\tapplication: compiled.application,\n\t\t\t\t...(compiled.tasks && { tasks: compiled.tasks }),\n\t\t\t},\n\t\t\tnull,\n\t\t\t2,\n\t\t),\n\t);\n\treturn readBuild(outDir);\n};\n",
6
- "import { createHash } from \"node:crypto\";\nimport {\n\taccess,\n\tcopyFile,\n\tmkdir,\n\treadFile,\n\trm,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { buildFiles, publishBuild, readBuild } from \"./artifacts\";\nimport { dockerImage, type ResolvedConfig } from \"@tsplc/config/build\";\nimport { buildInDocker } from \"./docker-build\";\nimport { writeDeviceTree } from \"./device-tree\";\nimport { createCodesysWorker, withWorkerLock } from \"./host/codesys-worker\";\nimport { importRequest } from \"./import-request\";\nimport { loadSources } from \"./sources\";\n\nexport const buildProject = async (config: ResolvedConfig) => {\n\tif (!config.docker) {\n\t\tthrow new Error(\"Builds require a Docker builder image.\");\n\t}\n\treturn buildInDocker(config, dockerImage);\n};\n\n/** The container runner owns Wine; this operation is not a public host build. */\nexport const buildInContainer = async (config: ResolvedConfig) => {\n\treturn withWorkerLock(config, async () => {\n\t\t// Invalidate the previous build before validation, so run cannot deploy stale\n\t\t// output after a failed rebuild. Keep the last project available for inspection.\n\t\tawait rm(resolve(config.outDir, buildFiles.receipt), { force: true });\n\t\tconst sources = await loadSources(config);\n\t\tawait access(config.template);\n\t\tconst worker = createCodesysWorker(config);\n\t\tconst session = await worker.launch();\n\t\tconst directory = resolve(config.outDir, \".codesys/build\");\n\t\tawait rm(directory, { recursive: true, force: true });\n\t\tawait mkdir(resolve(directory, \"runtime\"), { recursive: true });\n\t\tconst template = resolve(directory, \"Template.project\");\n\t\tawait copyFile(config.template, template);\n\t\tconst deviceTree =\n\t\t\tconfig.deviceTree &&\n\t\t\t(await writeDeviceTree(config.deviceTree, directory));\n\t\tconst request = {\n\t\t\tlibraryReferences: config.libraryReferences,\n\t\t\t...(await importRequest(config, sources)),\n\t\t\t...(deviceTree && { deviceTree }),\n\t\t\t...(config.controller && { controller: config.controller }),\n\t\t\tmode: \"build\",\n\t\t\toutput: buildFiles.output,\n\t\t\tproject: buildFiles.project,\n\t\t\tarchive: buildFiles.archive,\n\t\t\treceipt: buildFiles.receipt,\n\t\t\ttemplate: \"Template.project\",\n\t\t\ttemplateHash: createHash(\"sha256\")\n\t\t\t\t.update(await readFile(template))\n\t\t\t\t.digest(\"hex\"),\n\t\t};\n\t\tawait writeFile(\n\t\t\tresolve(directory, \"request.json\"),\n\t\t\tJSON.stringify(request, null, 2),\n\t\t);\n\t\tconsole.log(`CODESYS build: ${config.outDir}`);\n\t\ttry {\n\t\t\tawait worker.request(session, { action: \"build\" }, config.timeouts.build);\n\t\t\tconst compiled = await readBuild(directory);\n\t\t\tif (\n\t\t\t\tconfig.tasks &&\n\t\t\t\tJSON.stringify(compiled.tasks) !== JSON.stringify(config.tasks)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"CODESYS build receipt does not match the requested task plan\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Builds and runs share the lock. Removing the receipt above keeps a failed\n\t\t\t// publication from looking complete even if only some files were replaced.\n\t\t\treturn await publishBuild(compiled, config.outDir);\n\t\t} catch (cause) {\n\t\t\tthrow new Error(\n\t\t\t\t`CODESYS build failed. Inspect ${directory}/progress.log, error.txt and ${session.directory}/codesys.log`,\n\t\t\t\t{ cause },\n\t\t\t);\n\t\t}\n\t});\n};\n",
7
- "import { randomUUID } from \"node:crypto\";\nimport { cp, mkdir, mkdtemp, readFile, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { readBuild } from \"./artifacts\";\nimport { dockerImage, type ResolvedConfig } from \"@tsplc/config/build\";\nimport { prepareDockerContext } from \"./docker-context.ts\";\nimport {\n\tbuildFailureFile,\n\tbuildFailureSchema,\n\tCodesysCompilerError,\n} from \"./diagnostics.ts\";\nimport { captureDocker, prepareContainerRun, runDocker } from \"./docker-run.ts\";\nimport { packageDirectory } from \"./package-path.ts\";\n\n/** Each tsPLC version's images, published so that setup pulls them instead of installing CODESYS. */\nexport const publishedImage = async (image: string) => {\n\tconst { version } = z\n\t\t.object({ version: z.string() })\n\t\t.parse(\n\t\t\tJSON.parse(\n\t\t\t\tawait readFile(resolve(packageDirectory, \"package.json\"), \"utf8\"),\n\t\t\t),\n\t\t);\n\treturn `ghcr.io/livingforjesus/${image.split(\":\")[0]}:${version}`;\n};\n\n/** Pulls this version's published `image`; false when it isn't available, so the caller builds it. */\nconst pullPublished = async (image: string) => {\n\tconst published = await publishedImage(image);\n\tconsole.log(`Pulling ${published}`);\n\ttry {\n\t\tawait runDocker(\n\t\t\t[\"pull\", \"--platform\", \"linux/amd64\", published],\n\t\t\t(status) => `Docker pull failed (${status})`,\n\t\t);\n\t} catch {\n\t\tconsole.log(\n\t\t\t`${published} is not available; building ${image} locally instead.`,\n\t\t);\n\t\treturn false;\n\t}\n\tawait runDocker(\n\t\t[\"tag\", published, image],\n\t\t(status) => `Docker tag failed (${status})`,\n\t);\n\treturn true;\n};\n\n/** Install the IDE and its prerequisites in the Docker builder image. */\nexport const configureDocker = async () => {\n\tconst image = dockerImage;\n\tconst { stdout } = await captureDocker(\n\t\t[\"info\", \"--format\", \"{{.OSType}}/{{.Architecture}}\"],\n\t\t30_000,\n\t).catch((cause: unknown) => {\n\t\tthrow new Error(\n\t\t\t\"Cannot connect to Docker. Install and start Docker Desktop or Docker Engine\",\n\t\t\t{\n\t\t\t\tcause,\n\t\t\t},\n\t\t);\n\t});\n\tconst architecture = stdout.trim();\n\tconst arm =\n\t\tarchitecture === \"linux/aarch64\" || architecture === \"linux/arm64\";\n\tif (\n\t\t!arm &&\n\t\tarchitecture !== \"linux/x86_64\" &&\n\t\tarchitecture !== \"linux/amd64\"\n\t) {\n\t\tthrow new Error(\n\t\t\t\"The builder requires a Linux Docker server on ARM64 or AMD64\",\n\t\t);\n\t}\n\tif (await pullPublished(image)) {\n\t\treturn image;\n\t}\n\tconst context = await mkdtemp(resolve(tmpdir(), \"codesys-installer-\"));\n\tlet buildContext: string | undefined;\n\ttry {\n\t\tbuildContext = await prepareDockerContext();\n\t\tconst cache = resolve(context, \"winetricks\");\n\t\tawait mkdir(cache);\n\t\tif (process.env[\"CODESYS_WINETRICKS_CACHE\"]) {\n\t\t\tawait cp(process.env[\"CODESYS_WINETRICKS_CACHE\"], cache, {\n\t\t\t\trecursive: true,\n\t\t\t});\n\t\t}\n\t\tconsole.log(\n\t\t\t`Preparing Docker builder (${image}). Downloading and installing CODESYS 3.5.22.30 and prerequisites.`,\n\t\t);\n\t\tawait runDocker(\n\t\t\t[\n\t\t\t\t\"build\",\n\t\t\t\t\"--platform\",\n\t\t\t\t\"linux/amd64\",\n\t\t\t\t\"--build-arg\",\n\t\t\t\t`SETUP_BASE=${arm ? \"arm-setup\" : \"base\"}`,\n\t\t\t\t\"--build-arg\",\n\t\t\t\t`SETUP_PLATFORM=${arm ? \"linux/arm64\" : \"linux/amd64\"}`,\n\t\t\t\t\"--build-arg\",\n\t\t\t\t\"INSTALLER_SOURCE=installer-download\",\n\t\t\t\t\"--progress\",\n\t\t\t\t\"plain\",\n\t\t\t\t\"--build-context\",\n\t\t\t\t`installer=${context}`,\n\t\t\t\t\"-f\",\n\t\t\t\tresolve(buildContext, \"docker/Dockerfile\"),\n\t\t\t\t\"-t\",\n\t\t\t\timage,\n\t\t\t\tbuildContext,\n\t\t\t],\n\t\t\t(status) =>\n\t\t\t\t`Docker configuration failed (${status}). Review the image-build output and run tsplc configure again`,\n\t\t);\n\t\treturn image;\n\t} finally {\n\t\tawait Promise.all([\n\t\t\trm(context, { recursive: true, force: true }),\n\t\t\t...(buildContext\n\t\t\t\t? [rm(buildContext, { recursive: true, force: true })]\n\t\t\t\t: []),\n\t\t]);\n\t}\n};\n\nexport const runtimeImage = \"tsplc-control-linux-sl:4.22.0.0\";\n\n/** Build the local CODESYS Control for Linux SL runtime, the same device as a production build. */\nexport const configureRuntime = async () => {\n\tconst context = resolve(packageDirectory, \"docker/control-linux-sl\");\n\tconsole.log(`Preparing the local PLC runtime (${runtimeImage}).`);\n\tawait runDocker(\n\t\t[\n\t\t\t\"build\",\n\t\t\t\"--platform\",\n\t\t\t\"linux/amd64\",\n\t\t\t\"--progress\",\n\t\t\t\"plain\",\n\t\t\t\"-t\",\n\t\t\truntimeImage,\n\t\t\tcontext,\n\t\t],\n\t\t(status) =>\n\t\t\t`Runtime image build failed (${status}). Review the image-build output`,\n\t);\n\treturn runtimeImage;\n};\n\nexport const gatewayImage = \"tsplc-edge-gateway:4.22.0.0\";\n\n/** Build the CODESYS Edge Gateway that builder containers reach a plant controller through. */\nexport const configureGateway = async () => {\n\tif (await pullPublished(gatewayImage)) {\n\t\treturn gatewayImage;\n\t}\n\tconst context = resolve(packageDirectory, \"docker/edge-gateway\");\n\tconsole.log(`Preparing the CODESYS gateway (${gatewayImage}).`);\n\tawait runDocker(\n\t\t[\n\t\t\t\"build\",\n\t\t\t\"--platform\",\n\t\t\t\"linux/amd64\",\n\t\t\t\"--progress\",\n\t\t\t\"plain\",\n\t\t\t\"-t\",\n\t\t\tgatewayImage,\n\t\t\tcontext,\n\t\t],\n\t\t(status) =>\n\t\t\t`Gateway image build failed (${status}). Review the image-build output`,\n\t);\n\treturn gatewayImage;\n};\n\nexport const buildInDocker = async (config: ResolvedConfig, image: string) => {\n\tconst requestDirectory = await mkdtemp(resolve(tmpdir(), \"codesys-docker-\"));\n\ttry {\n\t\tconst operationId = randomUUID();\n\t\tawait mkdir(config.outDir, { recursive: true });\n\t\tconst failurePath = resolve(config.outDir, buildFailureFile);\n\t\tawait rm(failurePath, { force: true });\n\t\tconst args = [\n\t\t\t\"run\",\n\t\t\t\"--rm\",\n\t\t\t...(await prepareContainerRun(config, requestDirectory, {\n\t\t\t\tnetwork: \"none\",\n\t\t\t\tsources: true,\n\t\t\t})),\n\t\t\timage,\n\t\t\t\"--request\",\n\t\t\t\"/input/config.json\",\n\t\t\t\"--operation-id\",\n\t\t\toperationId,\n\t\t];\n\t\tconsole.log(`Building with Docker (${image})`);\n\t\ttry {\n\t\t\tawait runDocker(\n\t\t\t\targs,\n\t\t\t\t(status) =>\n\t\t\t\t\t`Docker build failed (${status}). Run tsplc configure if the image is missing; inspect ${config.outDir}/.codesys/docker for compiler logs`,\n\t\t\t);\n\t\t} catch (cause) {\n\t\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\t\tconst failure = await readFile(failurePath, \"utf8\")\n\t\t\t\t.then((text) => buildFailureSchema.parse(JSON.parse(text)))\n\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\terror instanceof Error &&\n\t\t\t\t\t\t\"code\" in error &&\n\t\t\t\t\t\terror.code === \"ENOENT\"\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t\t[cause, error],\n\t\t\t\t\t\t`${message}. Invalid CODESYS failure metadata (${failurePath})`,\n\t\t\t\t\t\t{ cause: error },\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\tif (!failure) {\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t\tif (failure.operationId !== operationId) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${message}. CODESYS failure metadata belongs to a different Docker build`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcause,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (cause instanceof Error) {\n\t\t\t\t// The mapper keeps ordinary error messages as notes, while vendor\n\t\t\t\t// diagnostics supply their own text. Preserve shutdown context there.\n\t\t\t\tcause.message = `${message}\\n${failure.message}`;\n\t\t\t\tif (failure.diagnostics.length) {\n\t\t\t\t\tcause.cause = new CodesysCompilerError(\n\t\t\t\t\t\tfailure.message,\n\t\t\t\t\t\tfailure.diagnostics,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow cause;\n\t\t}\n\t\treturn await readBuild(config.outDir);\n\t} finally {\n\t\tawait rm(requestDirectory, { recursive: true, force: true });\n\t}\n};\n",
8
- "import { cp, mkdir, mkdtemp, rm, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { dirname, resolve } from \"node:path\";\nimport { packageDirectory } from \"./package-path.ts\";\n\n/** The workspace packages container code imports, each copied with the files Bun runs it from. */\nconst containerPackages = [\n\t{\n\t\tentry: \"@tsplc/config/build\",\n\t\tdirectory: \"shared-config\",\n\t\tfiles: [\"src\", \"templates\", \"package.json\"],\n\t},\n\t{\n\t\tentry: \"@tsplc/iec\",\n\t\tdirectory: \"shared-iec\",\n\t\tfiles: [\"src\", \"package.json\"],\n\t},\n];\n\nexport async function prepareDockerContext() {\n\tconst context = await mkdtemp(resolve(tmpdir(), \"tsplc-docker-\"));\n\ttry {\n\t\tfor (const directory of [\"src\", \"python\", \"docker\", \"runtime\"]) {\n\t\t\tawait cp(\n\t\t\t\tresolve(packageDirectory, directory),\n\t\t\t\tresolve(context, directory),\n\t\t\t\t{\n\t\t\t\t\trecursive: true,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tfor (const { entry, directory, files } of containerPackages) {\n\t\t\tconst root = resolve(\n\t\t\t\tdirname(createRequire(import.meta.url).resolve(entry)),\n\t\t\t\t\"..\",\n\t\t\t);\n\t\t\tawait mkdir(resolve(context, directory));\n\t\t\tfor (const file of files) {\n\t\t\t\tawait cp(resolve(root, file), resolve(context, directory, file), {\n\t\t\t\t\trecursive: true,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tawait writeFile(\n\t\t\tresolve(context, \"package.json\"),\n\t\t\tJSON.stringify({\n\t\t\t\ttype: \"module\",\n\t\t\t\tdependencies: { zod: \"4.3.6\", jiti: \"2.7.0\" },\n\t\t\t}),\n\t\t);\n\t\treturn context;\n\t} catch (cause) {\n\t\tawait rm(context, { recursive: true, force: true });\n\t\tthrow cause;\n\t}\n}\n",
9
- "import { resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n// Both source modules and published bundles live one directory below the package root.\nexport const packageDirectory = resolve(\n\tfileURLToPath(new URL(\"..\", import.meta.url)),\n);\n",
5
+ "export {\n\ttype CodesysBuildConfig,\n\ttype CyclicTask,\n\tconfigSchema,\n\tdefineBuildConfig as defineConfig,\n\tloadConfig,\n\ttype ResolvedConfig,\n\tresolveConfig,\n} from \"@tsplc/config/build\";\nexport { readBuild } from \"./artifacts.ts\";\nexport { buildProject } from \"./build\";\nexport {\n\ttype ControllerLogin,\n\tfindControllerLogin,\n\tinspectController,\n\topenControllerLogin,\n\tstartWarmController,\n\tupdateController,\n\tupdateWarmController,\n} from \"./controller-online\";\nexport {\n\ttype ControllerResult,\n\texplicitDownload,\n\tfailureReason,\n\ttype LoginCommand,\n\ttype LoginResult,\n\tloginCommandSchema,\n\tloginResultSchema,\n\ttype Rollback,\n\trequiresDownload,\n\trollbackSchema,\n\tTransferFailedError,\n\ttransferRollback,\n} from \"./controller-protocol\";\nexport { controllerBaseline } from \"./controller-session.ts\";\nexport {\n\ttype CodesysCompilerDiagnostic,\n\tCodesysCompilerError,\n} from \"./diagnostics\";\nexport {\n\tconfigureDocker,\n\tconfigureGateway,\n\tconfigureRuntime,\n} from \"./docker-build.ts\";\nexport {\n\tcaptureDocker,\n\ttype ProgressOptions,\n\ttype ProgressStream,\n} from \"./docker-run.ts\";\nexport { rawEngineeringSettings } from \"./engineering-settings\";\nexport { workerScriptsDigest } from \"./host/codesys-worker.ts\";\nexport { gatewayImage } from \"./images.ts\";\nexport {\n\ttype InstalledLibrary,\n\tinstallLibraries,\n\tlibraryIndex,\n\tvalidateLibrary,\n} from \"./libraries.ts\";\nexport {\n\tcheckRawSources,\n\tinspectProjectController,\n} from \"./project-operations.ts\";\nexport { runProject } from \"./run\";\nexport { loadSources, type SourceObject } from \"./sources\";\nexport { StSyntaxError } from \"./st/lexer\";\nexport { type ObjectKind, type ParsedSource, parseSource } from \"./st/parse\";\n",
6
+ "import {\n\tcopyFile,\n\tcp,\n\treadFile,\n\trename,\n\trm,\n\tstat,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { cyclicTasksSchema } from \"@tsplc/config/build\";\nimport { identifierPattern } from \"@tsplc/iec/st\";\nimport { z } from \"zod\";\n\nexport const buildFiles = {\n\tproject: \"Application.project\",\n\toutput: \"runtime/Application.app\",\n\tchecksum: \"runtime/Application.crc\",\n\treceipt: \"build.json\",\n\t// Normalized EDS files of a generated device tree, imported by the worker.\n\tdevices: \"eds\",\n\t// With a generated device tree: the project plus the descriptions an IDE needs.\n\tarchive: \"Application.projectarchive\",\n} as const;\n\nconst receiptSchema = z.object({\n\tmode: z.literal(\"build\"),\n\tapplication: z.string().regex(identifierPattern),\n\ttasks: cyclicTasksSchema.optional(),\n});\n\n/** A receipt is published last, after every artifact has been checked and replaced. */\nexport const readBuild = async (directory: string) => {\n\tconst receipt = receiptSchema.safeParse(\n\t\tJSON.parse(await readFile(resolve(directory, buildFiles.receipt), \"utf8\")),\n\t);\n\tif (!receipt.success) {\n\t\tthrow new Error(\"CODESYS did not produce a valid build receipt\", {\n\t\t\tcause: receipt.error,\n\t\t});\n\t}\n\tfor (const file of [\n\t\tbuildFiles.project,\n\t\tbuildFiles.output,\n\t\tbuildFiles.checksum,\n\t]) {\n\t\tconst artifact = await stat(resolve(directory, file));\n\t\tif (!artifact.isFile() || artifact.size === 0) {\n\t\t\tthrow new Error(`CODESYS produced an empty artifact: ${file}`);\n\t\t}\n\t}\n\treturn {\n\t\t...receipt.data,\n\t\tdirectory,\n\t\tproject: resolve(directory, buildFiles.project),\n\t\toutput: resolve(directory, buildFiles.output),\n\t\tchecksum: resolve(directory, buildFiles.checksum),\n\t};\n};\n\n/** Publish a verified IDE build, with the completion receipt written last. */\nexport const publishBuild = async (\n\tcompiled: Awaited<ReturnType<typeof readBuild>>,\n\toutDir: string,\n) => {\n\tawait copyFile(compiled.project, resolve(outDir, buildFiles.project));\n\tawait rm(resolve(outDir, \"runtime\"), { recursive: true, force: true });\n\tawait rename(\n\t\tresolve(compiled.directory, \"runtime\"),\n\t\tresolve(outDir, \"runtime\"),\n\t);\n\tawait rm(resolve(outDir, buildFiles.archive), { force: true });\n\tawait cp(\n\t\tresolve(compiled.directory, buildFiles.archive),\n\t\tresolve(outDir, buildFiles.archive),\n\t).catch((cause: unknown) => {\n\t\tif (\n\t\t\t!(\n\t\t\t\tcause &&\n\t\t\t\ttypeof cause === \"object\" &&\n\t\t\t\t\"code\" in cause &&\n\t\t\t\tcause.code === \"ENOENT\"\n\t\t\t)\n\t\t) {\n\t\t\tthrow cause;\n\t\t}\n\t});\n\tawait writeFile(\n\t\tresolve(outDir, buildFiles.receipt),\n\t\tJSON.stringify(\n\t\t\t{\n\t\t\t\tmode: \"build\",\n\t\t\t\tapplication: compiled.application,\n\t\t\t\t...(compiled.tasks && { tasks: compiled.tasks }),\n\t\t\t},\n\t\t\tnull,\n\t\t\t2,\n\t\t),\n\t);\n\treturn readBuild(outDir);\n};\n",
7
+ "import { randomUUID } from \"node:crypto\";\nimport { mkdir, mkdtemp, readFile, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { resolve } from \"node:path\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport { readBuild } from \"./artifacts\";\nimport {\n\tbuildFailureFile,\n\tbuildFailureSchema,\n\tCodesysCompilerError,\n} from \"./diagnostics.ts\";\nimport {\n\tcaptureDocker,\n\ttype ProgressOptions,\n\ttype ProgressStream,\n\tprepareContainerRun,\n\tprogressLog,\n\trunDocker,\n} from \"./docker-run.ts\";\nimport {\n\tbuildBuilderImage,\n\tbuilderImage,\n\tbuildGatewayImage,\n\tgatewayImage,\n\tpublishedImage,\n\truntimeImage,\n\tsetupPlatformFor,\n} from \"./images.ts\";\nimport { packageDirectory } from \"./package-path.ts\";\n\nconst packageVersion = async () =>\n\tz\n\t\t.object({ version: z.string() })\n\t\t.parse(\n\t\t\tJSON.parse(\n\t\t\t\tawait readFile(resolve(packageDirectory, \"package.json\"), \"utf8\"),\n\t\t\t),\n\t\t).version;\n\n/** Pulls this version's published `image`; false when it isn't available, so the caller builds it. */\nconst pullPublished = async (image: string, progress: ProgressStream) => {\n\tconst published = publishedImage(image, await packageVersion());\n\tconst output = { progress, environment: {} };\n\tprogressLog(progress)(`Pulling ${published}`);\n\ttry {\n\t\tawait runDocker(\n\t\t\t[\"pull\", \"--platform\", \"linux/amd64\", published],\n\t\t\t(status) => `Docker pull failed (${status})`,\n\t\t\toutput,\n\t\t);\n\t} catch {\n\t\tprogressLog(progress)(\n\t\t\t`${published} is not available; building ${image} locally instead.`,\n\t\t);\n\t\treturn false;\n\t}\n\tawait runDocker(\n\t\t[\"tag\", published, image],\n\t\t(status) => `Docker tag failed (${status})`,\n\t\toutput,\n\t);\n\treturn true;\n};\n\n/** Install the IDE and its prerequisites in the Docker builder image. */\nexport const configureDocker = async ({\n\tprogress = \"stdout\",\n}: ProgressOptions = {}) => {\n\tconst image = builderImage;\n\tconst { stdout } = await captureDocker(\n\t\t[\"info\", \"--format\", \"{{.OSType}}/{{.Architecture}}\"],\n\t\t30_000,\n\t).catch((cause: unknown) => {\n\t\tthrow new Error(\n\t\t\t\"Cannot connect to Docker. Install and start Docker Desktop or Docker Engine\",\n\t\t\t{\n\t\t\t\tcause,\n\t\t\t},\n\t\t);\n\t});\n\tconst setupPlatform = setupPlatformFor(stdout.trim());\n\tif (!setupPlatform) {\n\t\tthrow new Error(\n\t\t\t\"The builder requires a Linux Docker server on ARM64 or AMD64\",\n\t\t);\n\t}\n\tif (await pullPublished(image, progress)) {\n\t\treturn image;\n\t}\n\tprogressLog(progress)(\n\t\t`Preparing Docker builder (${image}). Downloading and installing CODESYS 3.5.22.30 and prerequisites.`,\n\t);\n\tawait buildBuilderImage({\n\t\ttag: image,\n\t\tsetupPlatform,\n\t\tinstaller: null,\n\t\twinetricksCache: process.env.CODESYS_WINETRICKS_CACHE || null,\n\t\tdocker: (args) =>\n\t\t\trunDocker(\n\t\t\t\targs,\n\t\t\t\t(status) =>\n\t\t\t\t\t`Docker configuration failed (${status}). Review the image-build output and run tsplc configure again`,\n\t\t\t\t{ progress, environment: {} },\n\t\t\t),\n\t});\n\treturn image;\n};\n\n/** Build the local CODESYS Control for Linux SL runtime, the same device as a production build. */\nexport const configureRuntime = async ({\n\tprogress = \"stdout\",\n}: ProgressOptions = {}) => {\n\tconst context = resolve(packageDirectory, \"docker/control-linux-sl\");\n\tprogressLog(progress)(`Preparing the local PLC runtime (${runtimeImage}).`);\n\tawait runDocker(\n\t\t[\n\t\t\t\"build\",\n\t\t\t\"--platform\",\n\t\t\t\"linux/amd64\",\n\t\t\t\"--progress\",\n\t\t\t\"plain\",\n\t\t\t\"-t\",\n\t\t\truntimeImage,\n\t\t\tcontext,\n\t\t],\n\t\t(status) =>\n\t\t\t`Runtime image build failed (${status}). Review the image-build output`,\n\t\t{ progress, environment: {} },\n\t);\n\treturn runtimeImage;\n};\n\n/** Build the CODESYS Edge Gateway that builder containers reach a plant controller through. */\nexport const configureGateway = async ({\n\tprogress = \"stdout\",\n}: ProgressOptions = {}) => {\n\tif (await pullPublished(gatewayImage, progress)) {\n\t\treturn gatewayImage;\n\t}\n\tprogressLog(progress)(`Preparing the CODESYS gateway (${gatewayImage}).`);\n\tawait buildGatewayImage({\n\t\ttag: gatewayImage,\n\t\tdocker: (args) =>\n\t\t\trunDocker(\n\t\t\t\targs,\n\t\t\t\t(status) =>\n\t\t\t\t\t`Gateway image build failed (${status}). Review the image-build output`,\n\t\t\t\t{ progress, environment: {} },\n\t\t\t),\n\t});\n\treturn gatewayImage;\n};\n\nexport const buildInDocker = async (\n\tconfig: ResolvedConfig,\n\timage: string,\n\tprogress: ProgressStream,\n) => {\n\tconst requestDirectory = await mkdtemp(resolve(tmpdir(), \"codesys-docker-\"));\n\ttry {\n\t\tconst operationId = randomUUID();\n\t\tawait mkdir(config.outDir, { recursive: true });\n\t\tconst failurePath = resolve(config.outDir, buildFailureFile);\n\t\tawait rm(failurePath, { force: true });\n\t\tconst args = [\n\t\t\t\"run\",\n\t\t\t\"--rm\",\n\t\t\t...(await prepareContainerRun(config, requestDirectory, {\n\t\t\t\tnetwork: \"none\",\n\t\t\t\tsources: true,\n\t\t\t})),\n\t\t\timage,\n\t\t\t\"--request\",\n\t\t\t\"/input/config.json\",\n\t\t\t\"--operation-id\",\n\t\t\toperationId,\n\t\t];\n\t\tprogressLog(progress)(`Building with Docker (${image})`);\n\t\ttry {\n\t\t\tawait runDocker(\n\t\t\t\targs,\n\t\t\t\t(status) =>\n\t\t\t\t\t`Docker build failed (${status}). Run tsplc configure if the image is missing; inspect ${config.outDir}/.codesys/docker for compiler logs`,\n\t\t\t\t{ progress, environment: {} },\n\t\t\t);\n\t\t} catch (cause) {\n\t\t\tconst message = cause instanceof Error ? cause.message : String(cause);\n\t\t\tconst failure = await readFile(failurePath, \"utf8\")\n\t\t\t\t.then((text) => buildFailureSchema.parse(JSON.parse(text)))\n\t\t\t\t.catch((error: unknown) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\terror instanceof Error &&\n\t\t\t\t\t\t\"code\" in error &&\n\t\t\t\t\t\terror.code === \"ENOENT\"\n\t\t\t\t\t) {\n\t\t\t\t\t\treturn;\n\t\t\t\t\t}\n\t\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t\t[cause, error],\n\t\t\t\t\t\t`${message}. Invalid CODESYS failure metadata (${failurePath})`,\n\t\t\t\t\t\t{ cause: error },\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\tif (!failure) {\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t\tif (failure.operationId !== operationId) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${message}. CODESYS failure metadata belongs to a different Docker build`,\n\t\t\t\t\t{\n\t\t\t\t\t\tcause,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (cause instanceof Error) {\n\t\t\t\t// The mapper keeps ordinary error messages as notes, while vendor\n\t\t\t\t// diagnostics supply their own text. Preserve shutdown context there.\n\t\t\t\tcause.message = `${message}\\n${failure.message}`;\n\t\t\t\tif (failure.diagnostics.length) {\n\t\t\t\t\tcause.cause = new CodesysCompilerError(\n\t\t\t\t\t\tfailure.message,\n\t\t\t\t\t\tfailure.diagnostics,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\tthrow cause;\n\t\t}\n\t\treturn await readBuild(config.outDir);\n\t} finally {\n\t\tawait rm(requestDirectory, { recursive: true, force: true });\n\t}\n};\n",
10
8
  "import { z } from \"zod\";\n\nexport const compilerDiagnosticSchema = z\n\t.object({\n\t\tcategory: z.string(),\n\t\ttext: z.string(),\n\t\tseverity: z.string().nullable(),\n\t\tproject: z.string().nullable(),\n\t\tobject: z\n\t\t\t.object({\n\t\t\t\tname: z.string(),\n\t\t\t\tguid: z.string(),\n\t\t\t\tpath: z.array(z.string()),\n\t\t\t\t/** Verified against this message project's active application GUID. */\n\t\t\t\tisApplicationChild: z.boolean().nullable(),\n\t\t\t})\n\t\t\t.passthrough()\n\t\t\t.nullable(),\n\t\t/** Opaque vendor position. It must not be decoded as a line or column. */\n\t\tposition: z.string().nullable(),\n\t\tpositionText: z.string().nullable(),\n\t\tpositionOffset: z.int().nullable(),\n\t\tlength: z.int().nullable(),\n\t\tprefix: z.string().nullable(),\n\t\tnumber: z.int().nullable(),\n\t})\n\t.passthrough();\n\nexport type CodesysCompilerDiagnostic = z.infer<\n\ttypeof compilerDiagnosticSchema\n>;\n\n/** Preserves vendor diagnostics as the cause of a buildProject failure. */\nexport class CodesysCompilerError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\treadonly diagnostics: readonly CodesysCompilerDiagnostic[],\n\t) {\n\t\tsuper(message);\n\t\tthis.name = \"CodesysCompilerError\";\n\t}\n}\n\n// A failed container job publishes diagnostics separately from its successful build receipt.\nexport const buildFailureFile = \".codesys/docker/failure.json\";\n/** Why the last download, online change or inspection failed, for the host to report. */\nexport const controllerFailureFile = \".codesys/controller/failure.txt\";\nexport const buildFailureSchema = z.strictObject({\n\toperationId: z.uuid(),\n\tmessage: z.string(),\n\tdiagnostics: z.array(compilerDiagnosticSchema),\n});\n\n/** Keep the primary compiler location and the shutdown context across the Docker boundary. */\nexport function describeBuildFailure(cause: unknown) {\n\tconst messages: string[] = [];\n\tlet diagnostics: readonly CodesysCompilerDiagnostic[] = [];\n\tlet current = cause;\n\twhile (current instanceof Error) {\n\t\tmessages.push(current.message);\n\t\tif (current instanceof AggregateError) {\n\t\t\t// withWorkerShutdown puts the primary failure in cause and secondary failures in errors.\n\t\t\tfor (const secondary of current.errors.slice(1)) {\n\t\t\t\tmessages.push(\n\t\t\t\t\tsecondary instanceof Error ? secondary.message : String(secondary),\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tif (current instanceof CodesysCompilerError) {\n\t\t\tdiagnostics = current.diagnostics;\n\t\t}\n\t\tcurrent = current.cause;\n\t}\n\treturn {\n\t\tmessage: messages.length ? messages.join(\"\\n\") : String(cause),\n\t\tdiagnostics,\n\t};\n}\n",
11
- "import { execFile, spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { copyFile, cp, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { basename, posix, relative, resolve, sep } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\n\nconst execute = promisify(execFile);\n\n/** Run a Docker client command with its output captured instead of shown on this terminal. */\nexport const captureDocker = (args: string[], timeout: number) =>\n\texecute(\"docker\", args, { timeout, maxBuffer: 8 * 1024 * 1024 });\n\n/** Run a Docker client command attached to this terminal and forward interruption to it. */\nexport const runDocker = (\n\targs: string[],\n\tfailure: (status: string | number | null) => string,\n) =>\n\tnew Promise<void>((accept, reject) => {\n\t\tconst child = spawn(\"docker\", args, {\n\t\t\tstdio: [\n\t\t\t\t\"inherit\",\n\t\t\t\tprocess.env[\"TSPLC_LOG_STDERR\"] === \"1\" ? 2 : \"inherit\",\n\t\t\t\t\"inherit\",\n\t\t\t],\n\t\t});\n\t\tconst interrupt = () => child.kill(\"SIGINT\");\n\t\tconst terminate = () => child.kill(\"SIGTERM\");\n\t\tprocess.on(\"SIGINT\", interrupt);\n\t\tprocess.on(\"SIGTERM\", terminate);\n\t\tconst cleanup = () => {\n\t\t\tprocess.off(\"SIGINT\", interrupt);\n\t\t\tprocess.off(\"SIGTERM\", terminate);\n\t\t};\n\t\tchild.once(\"error\", (cause) => {\n\t\t\tcleanup();\n\t\t\treject(\n\t\t\t\tnew Error(\n\t\t\t\t\t\"Cannot start Docker. Install and start Docker Desktop or Docker Engine\",\n\t\t\t\t\t{\n\t\t\t\t\t\tcause,\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t);\n\t\t});\n\t\tchild.once(\"exit\", (code, signal) => {\n\t\t\tcleanup();\n\t\t\tif (code === 0) {\n\t\t\t\taccept();\n\t\t\t} else {\n\t\t\t\treject(new Error(failure(signal ?? code)));\n\t\t\t}\n\t\t});\n\t});\n\nconst bindMount = (source: string, target: string, readonly = false) =>\n\t`type=bind,\"source=${source.replaceAll('\"', '\"\"')}\",target=${target}${readonly ? \",readonly\" : \"\"}`;\n\n/** Copies the libraries to `directory`, which the container sees as `root`. */\nasync function mountLibraries(\n\tlibraries: ResolvedConfig[\"libraries\"],\n\tdirectory: string,\n\troot = \"/input\",\n) {\n\tif (!libraries?.length) {\n\t\treturn undefined;\n\t}\n\tawait mkdir(resolve(directory, \"libraries\"), { recursive: true });\n\treturn Promise.all(\n\t\tlibraries.map(async (library) => {\n\t\t\tconst data = await readFile(library.path);\n\t\t\tif (createHash(\"sha256\").update(data).digest(\"hex\") !== library.sha256) {\n\t\t\t\tthrow new Error(`Library changed after installation: ${library.title}`);\n\t\t\t}\n\t\t\tconst filename = `${library.sha256}-${basename(library.path)}`;\n\t\t\tawait writeFile(resolve(directory, \"libraries\", filename), data);\n\t\t\treturn { ...library, path: `${root}/libraries/${filename}` };\n\t\t}),\n\t);\n}\n\n/** The config a builder container reads: host-only settings removed, paths inside the container. */\nconst containerConfig = (\n\tconfig: ResolvedConfig,\n\tpaths: { sourceDir: string; template: string },\n\tlibraries: ResolvedConfig[\"libraries\"] | [],\n) => ({\n\t...config,\n\tlibraries,\n\tconfigFile: undefined,\n\tdocker: undefined,\n\tcodesys: undefined,\n\tsourceDir: paths.sourceDir,\n\tentry: posix.resolve(\n\t\tpaths.sourceDir,\n\t\trelative(config.sourceDir, config.entry).split(sep).join(\"/\"),\n\t),\n\ttemplate: paths.template,\n\toutDir: \"/output\",\n\truntime: undefined,\n});\n\n/**\n * Copies one operation's sources, template and libraries to `directory` in the output directory,\n * which a warm container sees as `root`, and writes their config there. Returns its container path.\n */\nexport const writeOperationRequest = async (\n\tconfig: ResolvedConfig,\n\tdirectory: string,\n\troot: string,\n) => {\n\tawait mkdir(directory, { recursive: true });\n\tawait cp(config.sourceDir, resolve(directory, \"sources\"), {\n\t\trecursive: true,\n\t});\n\tawait copyFile(config.template, resolve(directory, \"template.project\"));\n\tawait writeFile(\n\t\tresolve(directory, \"config.json\"),\n\t\tJSON.stringify(\n\t\t\tcontainerConfig(\n\t\t\t\tconfig,\n\t\t\t\t{ sourceDir: `${root}/sources`, template: `${root}/template.project` },\n\t\t\t\tawait mountLibraries(config.libraries, directory, root),\n\t\t\t),\n\t\t),\n\t);\n\treturn `${root}/config.json`;\n};\n\n/**\n * Write the builder container's request and return the `docker run` options that precede\n * the image; the caller chooses `--rm` or `--detach`. The request names only container paths;\n * host paths enter through these mounts, and host-only Docker, CODESYS and runtime settings\n * stay outside.\n */\nexport const prepareContainerRun = async (\n\tconfig: ResolvedConfig,\n\trequestDirectory: string,\n\toptions: { network: string; environment?: string[]; sources: boolean },\n) => {\n\tawait writeFile(\n\t\tresolve(requestDirectory, \"config.json\"),\n\t\tJSON.stringify(\n\t\t\tcontainerConfig(\n\t\t\t\tconfig,\n\t\t\t\t{ sourceDir: \"/sources\", template: \"/template.project\" },\n\t\t\t\toptions.sources\n\t\t\t\t\t? await mountLibraries(config.libraries, requestDirectory)\n\t\t\t\t\t: [],\n\t\t\t),\n\t\t),\n\t);\n\treturn [\n\t\t\"--init\",\n\t\t...(config.docker?.cpuSet ? [\"--cpuset-cpus\", config.docker.cpuSet] : []),\n\t\t\"--network\",\n\t\toptions.network,\n\t\t...(process.getuid && process.getgid\n\t\t\t? [\"--user\", `${process.getuid()}:${process.getgid()}`]\n\t\t\t: []),\n\t\t...(options.environment ?? []).flatMap((name) => [\"--env\", name]),\n\t\t\"--mount\",\n\t\tbindMount(requestDirectory, \"/input\", true),\n\t\t...(options.sources\n\t\t\t? [\"--mount\", bindMount(config.sourceDir, \"/sources\", true)]\n\t\t\t: []),\n\t\t\"--mount\",\n\t\tbindMount(config.template, \"/template.project\", true),\n\t\t\"--mount\",\n\t\tbindMount(config.outDir, \"/output\"),\n\t];\n};\n",
12
- "// Engineering CLI lifecycle and diagnostics.\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n\taccess,\n\tcopyFile,\n\tmkdir,\n\topen,\n\treadFile,\n\trename,\n\trm,\n\tunlink,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { z } from \"zod\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { CodesysCompilerError, compilerDiagnosticSchema } from \"../diagnostics\";\nimport { packageDirectory } from \"../package-path\";\nimport { codesysCommand, getHostCommand } from \"./codesys-command\";\nimport { createCodesysHost } from \"./codesys-host\";\n\nconst pythonDirectory = resolve(packageDirectory, \"python\");\n/** The scripts a worker runs from its session directory; a change to any of them restarts it. */\nconst workerScripts = [\n\t\"build.py\",\n\t\"hardware.py\",\n\t\"worker.py\",\n\t\"codesys_online.py\",\n\t\"codesys_login.py\",\n];\n\nconst sessionSchema = z.object({\n\tdirectory: z.string(),\n\tfingerprint: z.string(),\n\tpid: z.int().positive(),\n});\n\ntype Session = z.infer<typeof sessionSchema>;\n\ntype WorkerCommand =\n\t| { action: \"build\" | \"online\" | \"ping\" | \"stop\" }\n\t| { action: \"prepare\"; project: string }\n\t| { action: \"login\"; arguments: Record<string, unknown> };\n\nconst hasCode = (error: unknown, code: string) =>\n\terror instanceof Error && \"code\" in error && error.code === code;\n\nconst isProcessAlive = (pid: number) => {\n\ttry {\n\t\t// Signal 0 checks process existence and permissions without killing it.\n\t\t// Only ESRCH means it is gone; permission errors must still propagate.\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\tif (hasCode(error, \"ESRCH\")) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n};\n\nconst readJson = async (path: string): Promise<unknown> => {\n\ttry {\n\t\treturn JSON.parse(await readFile(path, \"utf8\"));\n\t} catch (error) {\n\t\tif (hasCode(error, \"ENOENT\")) {\n\t\t\treturn undefined;\n\t\t}\n\t\tthrow error;\n\t}\n};\n\nexport const writeJson = async (path: string, value: unknown) => {\n\t// Readers may poll while we write. A temporary file in the same directory\n\t// lets rename publish the complete JSON atomically, without exposing partial data.\n\tconst temporary = `${path}.${randomUUID()}.tmp`;\n\tawait writeFile(temporary, JSON.stringify(value, null, 2));\n\tawait rename(temporary, path);\n};\n\n/** Serializes startup and builds across CLI processes, including separate terminals. */\nexport const withWorkerLock = async <T>(\n\tconfig: Pick<ResolvedConfig, \"outDir\" | \"timeouts\">,\n\trun: () => Promise<T>,\n) => {\n\tawait mkdir(resolve(config.outDir, \".codesys\"), { recursive: true });\n\tconst path = resolve(config.outDir, \".codesys/command.lock\");\n\tconst deadline = Date.now() + config.timeouts.build + config.timeouts.startup;\n\twhile (true) {\n\t\tconst lock = await open(path, \"wx\").catch((error: unknown) => {\n\t\t\tif (hasCode(error, \"EEXIST\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\n\t\tif (lock) {\n\t\t\ttry {\n\t\t\t\tawait lock.writeFile(String(process.pid));\n\t\t\t\treturn await run();\n\t\t\t} finally {\n\t\t\t\tawait lock.close();\n\t\t\t\tawait unlink(path);\n\t\t\t}\n\t\t}\n\n\t\tconst owner = Number(\n\t\t\tawait readFile(path, \"utf8\").catch((error: unknown) => {\n\t\t\t\tif (hasCode(error, \"ENOENT\")) {\n\t\t\t\t\treturn \"\";\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}),\n\t\t);\n\t\tif (owner > 0 && !isProcessAlive(owner)) {\n\t\t\t// Do not race another client by deleting a lock that it may have replaced.\n\t\t\tthrow new Error(\n\t\t\t\t`An interrupted command left ${path}. Remove that lock file and retry.`,\n\t\t\t);\n\t\t}\n\t\tif (Date.now() >= deadline) {\n\t\t\tthrow new Error(\n\t\t\t\t`Timed out waiting for another CODESYS command (${path})`,\n\t\t\t);\n\t\t}\n\t\tawait delay(200);\n\t}\n};\n\n/** The caller holds withWorkerLock throughout a command, so the mailbox has one writer. */\nexport const createCodesysWorker = (config: ResolvedConfig) => {\n\tconst host = createCodesysHost(config);\n\tconst statePath = resolve(config.outDir, \".codesys/session.json\");\n\tconst verifiedProcesses = new Set<number>();\n\n\tconst readSession = async (): Promise<Session | undefined> => {\n\t\tconst value = await readJson(statePath);\n\t\tif (value === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst session = sessionSchema.safeParse(value);\n\t\tif (!session.success) {\n\t\t\tthrow new Error(`Invalid CODESYS session file: ${statePath}`, {\n\t\t\t\tcause: session.error,\n\t\t\t});\n\t\t}\n\t\treturn session.data;\n\t};\n\n\tconst terminate = async (session: Session) => {\n\t\tif (isProcessAlive(session.pid)) {\n\t\t\tawait host.terminate(session.pid).catch((error: unknown) => {\n\t\t\t\tif (isProcessAlive(session.pid)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\t// Let the launcher reap its child before another error handler or CLI\n\t\t// checks this PID. Sending a second group kill can otherwise race exit.\n\t\tconst deadline = Date.now() + config.timeouts.terminate;\n\t\twhile (isProcessAlive(session.pid)) {\n\t\t\tif (Date.now() >= deadline) {\n\t\t\t\tthrow new Error(\"CODESYS launcher did not exit after termination\");\n\t\t\t}\n\t\t\tawait delay(50);\n\t\t}\n\t};\n\n\tconst request = async (\n\t\tsession: Session,\n\t\tcommand: WorkerCommand,\n\t\ttimeoutMs: number,\n\t) => {\n\t\tconst id = randomUUID();\n\t\tconst reply = resolve(session.directory, `${id}.json`);\n\t\tawait writeJson(resolve(session.directory, \"request.json\"), {\n\t\t\t...command,\n\t\t\tid,\n\t\t});\n\t\tconst deadline = Date.now() + timeoutMs;\n\t\twhile (true) {\n\t\t\tconst result = await readJson(reply);\n\t\t\tif (result !== undefined) {\n\t\t\t\tawait unlink(reply);\n\t\t\t\tconst response = z\n\t\t\t\t\t.object({\n\t\t\t\t\t\terror: z.string().optional(),\n\t\t\t\t\t\tdiagnostics: z.array(compilerDiagnosticSchema).optional(),\n\t\t\t\t\t\tid: z.literal(id),\n\t\t\t\t\t\tok: z.boolean(),\n\t\t\t\t\t\tresult: z.unknown(),\n\t\t\t\t\t})\n\t\t\t\t\t.safeParse(result);\n\t\t\t\tif (!response.success) {\n\t\t\t\t\tthrow new Error(\"CODESYS returned an invalid worker response\", {\n\t\t\t\t\t\tcause: response.error,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tverifiedProcesses.add(session.pid);\n\t\t\t\tif (!response.data.ok) {\n\t\t\t\t\tconst message = response.data.error ?? \"CODESYS build failed\";\n\t\t\t\t\tif (response.data.diagnostics) {\n\t\t\t\t\t\tthrow new CodesysCompilerError(message, response.data.diagnostics);\n\t\t\t\t\t}\n\t\t\t\t\tthrow new Error(message);\n\t\t\t\t}\n\t\t\t\treturn response.data.result;\n\t\t\t}\n\t\t\tif (!isProcessAlive(session.pid)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`CODESYS exited before completing ${command.action}. See ${session.directory}/codesys.log`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (Date.now() >= deadline) {\n\t\t\t\t// A saved PID can belong to another process after a reboot. Only kill\n\t\t\t\t// a process we launched or whose worker answered in this invocation.\n\t\t\t\tif (!verifiedProcesses.has(session.pid)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`CODESYS ${command.action} timed out without a worker response. Close the dedicated IDE if it is still running, then retry. Log: ${session.directory}/codesys.log`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait terminate(session);\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`CODESYS ${command.action} timed out after ${timeoutMs} ms; the worker was stopped. See ${session.directory}/codesys.log`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait delay(200);\n\t\t}\n\t};\n\n\tconst launch = async () => {\n\t\tawait access(config.codesys.executable);\n\t\tconst fingerprint = createHash(\"sha256\")\n\t\t\t.update(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tscripts: await Promise.all(\n\t\t\t\t\t\tworkerScripts.map((script) =>\n\t\t\t\t\t\t\treadFile(resolve(pythonDirectory, script), \"utf8\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t\tcommand: codesysCommand,\n\t\t\t\t\tcodesys: config.codesys,\n\t\t\t\t\tlauncher: getHostCommand(config.codesys),\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.digest(\"hex\");\n\t\tconst previous = await readSession();\n\t\tif (previous && isProcessAlive(previous.pid)) {\n\t\t\tif (previous.fingerprint !== fingerprint) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"CODESYS settings or worker scripts changed. Run stop-worker, then launch-worker to reload them.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait request(previous, { action: \"ping\" }, config.timeouts.startup);\n\t\t\tconsole.log(\n\t\t\t\t`Reusing CODESYS worker (${previous.pid}). Log: ${previous.directory}/codesys.log`,\n\t\t\t);\n\t\t\treturn previous;\n\t\t}\n\n\t\tconst directory = resolve(config.outDir, \".codesys/worker\");\n\t\tawait rm(directory, { recursive: true, force: true });\n\t\tawait mkdir(directory, { recursive: true });\n\t\tfor (const script of workerScripts) {\n\t\t\tawait copyFile(\n\t\t\t\tresolve(pythonDirectory, script),\n\t\t\t\tresolve(directory, script),\n\t\t\t);\n\t\t}\n\t\tconsole.log(`Starting CODESYS. Log: ${directory}/codesys.log`);\n\t\tconst pid = await host.startWorker(directory);\n\t\tconst session = { directory, fingerprint, pid };\n\t\tverifiedProcesses.add(pid);\n\t\ttry {\n\t\t\tawait writeJson(statePath, session);\n\t\t\tawait request(session, { action: \"ping\" }, config.timeouts.startup);\n\t\t} catch (error) {\n\t\t\tawait terminate(session);\n\t\t\tthrow error;\n\t\t}\n\t\tconsole.log(`CODESYS worker ready (${session.pid})`);\n\t\treturn session;\n\t};\n\n\tconst checkExit = async (session: Session) => {\n\t\tconst status = await host.exitStatus(session.directory, session.pid);\n\t\tif (!status) {\n\t\t\tthrow new Error(\n\t\t\t\t`CODESYS launcher stopped but its exit status is unavailable. See ${session.directory}/codesys.log`,\n\t\t\t);\n\t\t}\n\t\tif (status.code !== 0 || status.signal !== null) {\n\t\t\tthrow new Error(\n\t\t\t\t`CODESYS launcher exited with ${status.signal ?? status.code ?? \"unknown status\"}. See ${session.directory}/codesys.log`,\n\t\t\t);\n\t\t}\n\t};\n\n\tconst stop = async () => {\n\t\tconst session = await readSession();\n\t\tif (!session) {\n\t\t\tconsole.log(\"CODESYS worker is already stopped\");\n\t\t\treturn;\n\t\t}\n\t\tif (!isProcessAlive(session.pid)) {\n\t\t\tawait checkExit(session);\n\t\t\tconsole.log(\"CODESYS worker is already stopped\");\n\t\t\treturn;\n\t\t}\n\t\tawait request(session, { action: \"stop\" }, config.timeouts.stop);\n\t\tconst deadline = Date.now() + config.timeouts.stop;\n\t\twhile (isProcessAlive(session.pid)) {\n\t\t\tif (Date.now() >= deadline) {\n\t\t\t\tconst message = `CODESYS stop timed out after ${config.timeouts.stop} ms. See ${session.directory}/codesys.log`;\n\t\t\t\ttry {\n\t\t\t\t\tawait terminate(session);\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tthrow new Error(`${message}; the worker could not be terminated`, {\n\t\t\t\t\t\tcause,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tthrow new Error(`${message}; the worker required forced termination`);\n\t\t\t}\n\t\t\tawait delay(200);\n\t\t}\n\t\tawait checkExit(session);\n\t\tconsole.log(\"CODESYS worker stopped\");\n\t};\n\n\t/** Whether the session's CODESYS still runs; one that died fails every request. */\n\tconst alive = (session: Session) => isProcessAlive(session.pid);\n\n\treturn { launch, request, stop, alive };\n};\n\n/** Container jobs own a temporary worker; always stop it before returning a result. */\nexport const withWorkerShutdown = async <T>(\n\tconfig: ResolvedConfig,\n\tworker: Pick<ReturnType<typeof createCodesysWorker>, \"stop\">,\n\toperation: () => Promise<T>,\n) => {\n\tconst stop = async () => {\n\t\ttry {\n\t\t\tawait withWorkerLock(config, () => worker.stop());\n\t\t} finally {\n\t\t\tawait rm(resolve(config.outDir, \".codesys/session.json\"), {\n\t\t\t\tforce: true,\n\t\t\t});\n\t\t}\n\t};\n\treturn Promise.resolve()\n\t\t.then(operation)\n\t\t.then(\n\t\t\tasync (result) => {\n\t\t\t\tawait stop();\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tasync (failure: unknown) => {\n\t\t\t\tawait stop().catch((shutdownFailure: unknown) => {\n\t\t\t\t\t// Diagnostic mapping follows cause; keep the operation there and\n\t\t\t\t\t// expose its shutdown failure alongside it in errors.\n\t\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t\t[failure, shutdownFailure],\n\t\t\t\t\t\t\"CODESYS operation and worker shutdown failed\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcause: failure,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t\tthrow failure;\n\t\t\t},\n\t\t);\n};\n",
9
+ "import { execFile, spawn } from \"node:child_process\";\nimport { createHash } from \"node:crypto\";\nimport { copyFile, cp, mkdir, readFile, writeFile } from \"node:fs/promises\";\nimport { basename, posix, relative, resolve, sep } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\n\nconst execute = promisify(execFile);\n\n/**\n * Where an operation reports progress, the Docker client's output included: standard output,\n * or standard error when standard output carries a machine-readable result.\n */\nexport type ProgressStream = \"stdout\" | \"stderr\";\n\n/** The operation-scoped settings of a command that reports progress. */\nexport interface ProgressOptions {\n\tprogress?: ProgressStream;\n}\n\nexport const progressLog = (stream: ProgressStream) =>\n\tstream === \"stderr\" ? console.error : console.log;\n\n/**\n * Variables a Docker client command passes to its container by name (`--env NAME`), added to\n * the client's own environment so their values never appear in its arguments.\n */\nexport type ContainerEnvironment = Readonly<Record<string, string>>;\n\nconst clientEnvironment = (environment: ContainerEnvironment) => ({\n\t...process.env,\n\t...environment,\n});\n\n/** Run a Docker client command with its output captured instead of shown on this terminal. */\nexport const captureDocker = (\n\targs: string[],\n\ttimeout: number,\n\tenvironment: ContainerEnvironment = {},\n) =>\n\texecute(\"docker\", args, {\n\t\ttimeout,\n\t\tmaxBuffer: 8 * 1024 * 1024,\n\t\tenv: clientEnvironment(environment),\n\t});\n\n/**\n * Run a Docker client command with `input` on its standard input, which keeps a request that can\n * hold credentials out of its arguments, and capture its output.\n */\nexport const pipeDocker = async (args: string[], input: string | null) => {\n\tconst child = Bun.spawn([\"docker\", ...args], {\n\t\tstdin: input === null ? \"ignore\" : new Blob([input]),\n\t\tstdout: \"pipe\",\n\t\tstderr: \"pipe\",\n\t});\n\tconst [stdout, stderr, status] = await Promise.all([\n\t\tnew Response(child.stdout).text(),\n\t\tnew Response(child.stderr).text(),\n\t\tchild.exited,\n\t]);\n\treturn { stdout, stderr, status };\n};\n\n/** Run a Docker client command attached to this terminal and forward interruption to it. */\nexport const runDocker = (\n\targs: string[],\n\tfailure: (status: string | number | null) => string,\n\toutput: { progress: ProgressStream; environment: ContainerEnvironment },\n) =>\n\tnew Promise<void>((accept, reject) => {\n\t\tconst child = spawn(\"docker\", args, {\n\t\t\tstdio: [\n\t\t\t\t\"inherit\",\n\t\t\t\toutput.progress === \"stderr\" ? 2 : \"inherit\",\n\t\t\t\t\"inherit\",\n\t\t\t],\n\t\t\tenv: clientEnvironment(output.environment),\n\t\t});\n\t\tconst interrupt = () => child.kill(\"SIGINT\");\n\t\tconst terminate = () => child.kill(\"SIGTERM\");\n\t\tprocess.on(\"SIGINT\", interrupt);\n\t\tprocess.on(\"SIGTERM\", terminate);\n\t\tconst cleanup = () => {\n\t\t\tprocess.off(\"SIGINT\", interrupt);\n\t\t\tprocess.off(\"SIGTERM\", terminate);\n\t\t};\n\t\tchild.once(\"error\", (cause) => {\n\t\t\tcleanup();\n\t\t\treject(\n\t\t\t\tnew Error(\n\t\t\t\t\t\"Cannot start Docker. Install and start Docker Desktop or Docker Engine\",\n\t\t\t\t\t{\n\t\t\t\t\t\tcause,\n\t\t\t\t\t},\n\t\t\t\t),\n\t\t\t);\n\t\t});\n\t\tchild.once(\"exit\", (code, signal) => {\n\t\t\tcleanup();\n\t\t\tif (code === 0) {\n\t\t\t\taccept();\n\t\t\t} else {\n\t\t\t\treject(new Error(failure(signal ?? code)));\n\t\t\t}\n\t\t});\n\t});\n\nconst bindMount = (source: string, target: string, readonly = false) =>\n\t`type=bind,\"source=${source.replaceAll('\"', '\"\"')}\",target=${target}${readonly ? \",readonly\" : \"\"}`;\n\n/** Copies the libraries to `directory`, which the container sees as `root`. */\nasync function mountLibraries(\n\tlibraries: ResolvedConfig[\"libraries\"],\n\tdirectory: string,\n\troot = \"/input\",\n) {\n\tif (!libraries?.length) {\n\t\treturn undefined;\n\t}\n\tawait mkdir(resolve(directory, \"libraries\"), { recursive: true });\n\treturn Promise.all(\n\t\tlibraries.map(async (library) => {\n\t\t\tconst data = await readFile(library.path);\n\t\t\tif (createHash(\"sha256\").update(data).digest(\"hex\") !== library.sha256) {\n\t\t\t\tthrow new Error(`Library changed after installation: ${library.title}`);\n\t\t\t}\n\t\t\tconst filename = `${library.sha256}-${basename(library.path)}`;\n\t\t\tawait writeFile(resolve(directory, \"libraries\", filename), data);\n\t\t\treturn { ...library, path: `${root}/libraries/${filename}` };\n\t\t}),\n\t);\n}\n\n/** The config a builder container reads: host-only settings removed, paths inside the container. */\nconst containerConfig = (\n\tconfig: ResolvedConfig,\n\tpaths: { sourceDir: string; template: string },\n\tlibraries: ResolvedConfig[\"libraries\"] | [],\n) => ({\n\t...config,\n\tlibraries,\n\tconfigFile: undefined,\n\tdocker: undefined,\n\tcodesys: undefined,\n\tsourceDir: paths.sourceDir,\n\tentry: posix.resolve(\n\t\tpaths.sourceDir,\n\t\trelative(config.sourceDir, config.entry).split(sep).join(\"/\"),\n\t),\n\ttemplate: paths.template,\n\toutDir: \"/output\",\n\truntime: undefined,\n});\n\n/**\n * Copies one operation's sources, template and libraries to `directory` in the output directory,\n * which a warm container sees as `root`, and writes their config there. Returns its container path.\n */\nexport const writeOperationRequest = async (\n\tconfig: ResolvedConfig,\n\tdirectory: string,\n\troot: string,\n) => {\n\tawait mkdir(directory, { recursive: true });\n\tawait cp(config.sourceDir, resolve(directory, \"sources\"), {\n\t\trecursive: true,\n\t});\n\tawait copyFile(config.template, resolve(directory, \"template.project\"));\n\tawait writeFile(\n\t\tresolve(directory, \"config.json\"),\n\t\tJSON.stringify(\n\t\t\tcontainerConfig(\n\t\t\t\tconfig,\n\t\t\t\t{ sourceDir: `${root}/sources`, template: `${root}/template.project` },\n\t\t\t\tawait mountLibraries(config.libraries, directory, root),\n\t\t\t),\n\t\t),\n\t);\n\treturn `${root}/config.json`;\n};\n\n/**\n * Write the builder container's request and return the `docker run` options that precede\n * the image; the caller chooses `--rm` or `--detach`. The request names only container paths;\n * host paths enter through these mounts, and host-only Docker, CODESYS and runtime settings\n * stay outside.\n */\nexport const prepareContainerRun = async (\n\tconfig: ResolvedConfig,\n\trequestDirectory: string,\n\toptions: { network: string; environment?: string[]; sources: boolean },\n) => {\n\tawait writeFile(\n\t\tresolve(requestDirectory, \"config.json\"),\n\t\tJSON.stringify(\n\t\t\tcontainerConfig(\n\t\t\t\tconfig,\n\t\t\t\t{ sourceDir: \"/sources\", template: \"/template.project\" },\n\t\t\t\toptions.sources\n\t\t\t\t\t? await mountLibraries(config.libraries, requestDirectory)\n\t\t\t\t\t: [],\n\t\t\t),\n\t\t),\n\t);\n\treturn [\n\t\t\"--init\",\n\t\t...(config.docker?.cpuSet ? [\"--cpuset-cpus\", config.docker.cpuSet] : []),\n\t\t\"--network\",\n\t\toptions.network,\n\t\t...(process.getuid && process.getgid\n\t\t\t? [\"--user\", `${process.getuid()}:${process.getgid()}`]\n\t\t\t: []),\n\t\t...(options.environment ?? []).flatMap((name) => [\"--env\", name]),\n\t\t\"--mount\",\n\t\tbindMount(requestDirectory, \"/input\", true),\n\t\t...(options.sources\n\t\t\t? [\"--mount\", bindMount(config.sourceDir, \"/sources\", true)]\n\t\t\t: []),\n\t\t\"--mount\",\n\t\tbindMount(config.template, \"/template.project\", true),\n\t\t\"--mount\",\n\t\tbindMount(config.outDir, \"/output\"),\n\t];\n};\n",
10
+ "import { copyFile, cp, mkdir, mkdtemp, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { resolve } from \"node:path\";\nimport { dockerImage } from \"@tsplc/config/build\";\nimport { prepareDockerContext } from \"./docker-context.ts\";\nimport { packageDirectory } from \"./package-path.ts\";\n\nexport const builderImage = dockerImage;\n\nexport const gatewayImage = \"tsplc-edge-gateway:4.22.0.0\";\n\n/** The local CODESYS Control for Linux SL runtime; it is always built here, never published. */\nexport const runtimeImage = \"tsplc-control-linux-sl:4.22.0.0\";\n\n/** The registry name each tsPLC version's copy of a local image is published under. */\nexport const publishedImage = (image: string, version: string) =>\n\t`ghcr.io/livingforjesus/${image.split(\":\")[0]}:${version}`;\n\n/** The platform the vendor installer runs on; the compiler image itself is always AMD64. */\nexport type SetupPlatform = \"linux/amd64\" | \"linux/arm64\";\n\n/** The setup platform for a Docker server's `{{.OSType}}/{{.Architecture}}`, or null when it has none. */\nexport const setupPlatformFor = (server: string): SetupPlatform | null => {\n\tif (server === \"linux/aarch64\" || server === \"linux/arm64\") {\n\t\treturn \"linux/arm64\";\n\t}\n\tif (server === \"linux/x86_64\" || server === \"linux/amd64\") {\n\t\treturn \"linux/amd64\";\n\t}\n\treturn null;\n};\n\n/**\n * Builds the builder image from the full recipe. `installer` is a local CODESYS installer,\n * or null to download the official one; `winetricksCache` seeds the prerequisite downloads.\n * `docker` runs one Docker client command, so each caller keeps its own terminal handling.\n */\nexport async function buildBuilderImage(options: {\n\ttag: string;\n\tsetupPlatform: SetupPlatform;\n\tinstaller: string | null;\n\twinetricksCache: string | null;\n\tdocker: (args: string[]) => Promise<void>;\n}) {\n\tconst installerContext = await mkdtemp(\n\t\tresolve(tmpdir(), \"codesys-installer-\"),\n\t);\n\tlet context: string | undefined;\n\ttry {\n\t\tcontext = await prepareDockerContext();\n\t\tconst cache = resolve(installerContext, \"winetricks\");\n\t\tawait mkdir(cache);\n\t\tif (options.winetricksCache) {\n\t\t\tawait cp(options.winetricksCache, cache, { recursive: true });\n\t\t}\n\t\tif (options.installer) {\n\t\t\tawait copyFile(\n\t\t\t\toptions.installer,\n\t\t\t\tresolve(installerContext, \"codesys.exe\"),\n\t\t\t);\n\t\t}\n\t\tconst arm = options.setupPlatform === \"linux/arm64\";\n\t\t// FEX handles ARM setup's 32-bit prerequisites; the compiler runtime stays AMD64.\n\t\tawait options.docker([\n\t\t\t\"build\",\n\t\t\t\"--platform\",\n\t\t\t\"linux/amd64\",\n\t\t\t\"--build-arg\",\n\t\t\t`SETUP_BASE=${arm ? \"arm-setup\" : \"base\"}`,\n\t\t\t\"--build-arg\",\n\t\t\t`SETUP_PLATFORM=${options.setupPlatform}`,\n\t\t\t\"--build-arg\",\n\t\t\t`INSTALLER_SOURCE=${options.installer ? \"installer-local\" : \"installer-download\"}`,\n\t\t\t\"--progress\",\n\t\t\t\"plain\",\n\t\t\t\"--build-context\",\n\t\t\t`installer=${installerContext}`,\n\t\t\t\"-f\",\n\t\t\tresolve(context, \"docker/Dockerfile\"),\n\t\t\t\"-t\",\n\t\t\toptions.tag,\n\t\t\tcontext,\n\t\t]);\n\t} finally {\n\t\tawait Promise.all([\n\t\t\trm(installerContext, { recursive: true, force: true }),\n\t\t\t...(context ? [rm(context, { recursive: true, force: true })] : []),\n\t\t]);\n\t}\n}\n\nexport const buildGatewayImage = (options: {\n\ttag: string;\n\tdocker: (args: string[]) => Promise<void>;\n}) =>\n\toptions.docker([\n\t\t\"build\",\n\t\t\"--platform\",\n\t\t\"linux/amd64\",\n\t\t\"--progress\",\n\t\t\"plain\",\n\t\t\"-t\",\n\t\toptions.tag,\n\t\tresolve(packageDirectory, \"docker/edge-gateway\"),\n\t]);\n",
11
+ "import { cp, mkdir, mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { createRequire } from \"node:module\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, resolve } from \"node:path\";\nimport { z } from \"zod\";\nimport { packageDirectory } from \"./package-path.ts\";\n\nconst includeSource = (source: string) => {\n\tconst name = basename(source);\n\treturn (\n\t\tname !== \"__pycache__\" &&\n\t\t!name.endsWith(\".pyc\") &&\n\t\t!name.endsWith(\".test.ts\") &&\n\t\t!name.endsWith(\".fixtures.ts\") &&\n\t\t!(name.startsWith(\"test_\") && name.endsWith(\".py\"))\n\t);\n};\n\n/** The workspace packages container code imports, each copied with the files Bun runs it from. */\nconst containerPackages = [\n\t{\n\t\tentry: \"@tsplc/config/build\",\n\t\tdirectory: \"shared-config\",\n\t\tfiles: [\"src\", \"templates\", \"package.json\"],\n\t},\n\t{\n\t\tentry: \"@tsplc/iec\",\n\t\tdirectory: \"shared-iec\",\n\t\tfiles: [\"src\", \"package.json\"],\n\t},\n];\n\nconst manifestDependencies = z.object({\n\tname: z.string(),\n\tdependencies: z.record(z.string(), z.string()).default({}),\n});\n\n/**\n * The third-party packages the image installs: what this package and each package the\n * context carries depend on, at the versions their manifests pin.\n */\nexport function containerDependencies(\n\tmanifests: z.infer<typeof manifestDependencies>[],\n) {\n\tconst selected = new Map<string, { version: string; owner: string }>();\n\tfor (const manifest of manifests) {\n\t\tfor (const [name, version] of Object.entries(manifest.dependencies)) {\n\t\t\tif (name.startsWith(\"@tsplc/\")) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst existing = selected.get(name);\n\t\t\tif (existing && existing.version !== version) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`The builder image cannot install ${name}: ${existing.owner} pins ${existing.version} and ${manifest.name} pins ${version}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tselected.set(name, { version, owner: manifest.name });\n\t\t}\n\t}\n\treturn Object.fromEntries(\n\t\t[...selected].map(([name, { version }]) => [name, version]),\n\t);\n}\n\nconst readManifest = async (directory: string) =>\n\tmanifestDependencies.parse(\n\t\tJSON.parse(await readFile(resolve(directory, \"package.json\"), \"utf8\")),\n\t);\n\nexport async function prepareDockerContext() {\n\tconst context = await mkdtemp(resolve(tmpdir(), \"tsplc-docker-\"));\n\ttry {\n\t\tfor (const directory of [\"src\", \"python\", \"docker\", \"runtime\"]) {\n\t\t\tawait cp(\n\t\t\t\tresolve(packageDirectory, directory),\n\t\t\t\tresolve(context, directory),\n\t\t\t\t{\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tfilter: includeSource,\n\t\t\t\t},\n\t\t\t);\n\t\t}\n\t\tconst manifests = [await readManifest(packageDirectory)];\n\t\tfor (const { entry, directory, files } of containerPackages) {\n\t\t\tconst root = resolve(\n\t\t\t\tdirname(createRequire(import.meta.url).resolve(entry)),\n\t\t\t\t\"..\",\n\t\t\t);\n\t\t\tmanifests.push(await readManifest(root));\n\t\t\tawait mkdir(resolve(context, directory));\n\t\t\tfor (const file of files) {\n\t\t\t\tawait cp(resolve(root, file), resolve(context, directory, file), {\n\t\t\t\t\trecursive: true,\n\t\t\t\t\tfilter: includeSource,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tawait writeFile(\n\t\t\tresolve(context, \"package.json\"),\n\t\t\tJSON.stringify({\n\t\t\t\ttype: \"module\",\n\t\t\t\tdependencies: containerDependencies(manifests),\n\t\t\t}),\n\t\t);\n\t\treturn context;\n\t} catch (cause) {\n\t\tawait rm(context, { recursive: true, force: true });\n\t\tthrow cause;\n\t}\n}\n",
12
+ "import { resolve } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\n\n// Both source modules and published bundles live one directory below the package root.\nexport const packageDirectory = resolve(\n\tfileURLToPath(new URL(\"..\", import.meta.url)),\n);\n",
13
+ "// Engineering CLI lifecycle and diagnostics.\nimport { createHash, randomUUID } from \"node:crypto\";\nimport {\n\taccess,\n\tcopyFile,\n\tmkdir,\n\topen,\n\treadFile,\n\trename,\n\trm,\n\tunlink,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport { DownloadRequiredError } from \"../controller-protocol\";\nimport { CodesysCompilerError, compilerDiagnosticSchema } from \"../diagnostics\";\nimport { packageDirectory } from \"../package-path\";\nimport { codesysCommand, getHostCommand } from \"./codesys-command\";\nimport { createCodesysHost } from \"./codesys-host\";\n\nconst pythonDirectory = resolve(packageDirectory, \"python\");\n/** The scripts a worker runs from its session directory; a change to any of them restarts it. */\nconst workerScripts = [\n\t\"build.py\",\n\t\"hardware.py\",\n\t\"worker.py\",\n\t\"codesys_online.py\",\n\t\"codesys_login.py\",\n];\n\n/**\n * A digest of the CODESYS scripts this installation runs. Two installations of one tsPLC version\n * differ in it when one is a local build, whose script fixes the other doesn't run.\n */\nexport const workerScriptsDigest = async () =>\n\tcreateHash(\"sha256\")\n\t\t.update(\n\t\t\tJSON.stringify(\n\t\t\t\tawait Promise.all(\n\t\t\t\t\tworkerScripts.map((script) =>\n\t\t\t\t\t\treadFile(resolve(pythonDirectory, script), \"utf8\"),\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t),\n\t\t)\n\t\t.digest(\"hex\");\n\nconst sessionSchema = z.object({\n\tdirectory: z.string(),\n\tfingerprint: z.string(),\n\tpid: z.int().positive(),\n});\n\ntype Session = z.infer<typeof sessionSchema>;\n\ntype WorkerCommand =\n\t| { action: \"build\" | \"online\" | \"ping\" | \"stop\" }\n\t| { action: \"prepare\"; project: string }\n\t| { action: \"login\"; arguments: Record<string, unknown> };\n\nconst phaseSchema = z.enum([\"prepare\", \"transfer\"]);\n/** Where a controller operation is: preparing, with the controller untouched, or transferring to it. */\nexport type WorkerPhase = z.infer<typeof phaseSchema>;\n\n/**\n * A controller operation's budgets, by the phase the worker writes to `file` as it enters it. A\n * `prepare` that runs out stops the worker, which leaves the controller as it was. A `transfer`\n * that runs out is reported to `overdue` each time it runs out again and is never interrupted:\n * stopping CODESYS mid-transfer can leave the controller without an application.\n */\nexport interface PhasedBudget {\n\tfile: string;\n\tprepare: number;\n\ttransfer: number;\n\toverdue: (message: string) => void;\n}\n\n/** The phase the worker last wrote to `file`; `prepare` until it writes one. */\nexport const workerPhase = async (file: string): Promise<WorkerPhase> =>\n\tphaseSchema.catch(\"prepare\").parse(\n\t\tawait readFile(file, \"utf8\").then(\n\t\t\t(text) => text.trim(),\n\t\t\t() => undefined,\n\t\t),\n\t);\n\nconst minutes = (milliseconds: number) =>\n\t`${Math.round(milliseconds / 60_000)} min`;\n\nconst hasCode = (error: unknown, code: string) =>\n\terror instanceof Error && \"code\" in error && error.code === code;\n\nconst isProcessAlive = (pid: number) => {\n\ttry {\n\t\t// Signal 0 checks process existence and permissions without killing it.\n\t\t// Only ESRCH means it is gone; permission errors must still propagate.\n\t\tprocess.kill(pid, 0);\n\t\treturn true;\n\t} catch (error) {\n\t\tif (hasCode(error, \"ESRCH\")) {\n\t\t\treturn false;\n\t\t}\n\t\tthrow error;\n\t}\n};\n\nconst readJson = async (path: string): Promise<unknown> => {\n\ttry {\n\t\treturn JSON.parse(await readFile(path, \"utf8\"));\n\t} catch (error) {\n\t\tif (hasCode(error, \"ENOENT\")) {\n\t\t\treturn undefined;\n\t\t}\n\t\tthrow error;\n\t}\n};\n\nexport const writeJson = async (path: string, value: unknown) => {\n\t// Readers may poll while we write. A temporary file in the same directory\n\t// lets rename publish the complete JSON atomically, without exposing partial data.\n\tconst temporary = `${path}.${randomUUID()}.tmp`;\n\tawait writeFile(temporary, JSON.stringify(value, null, 2));\n\tawait rename(temporary, path);\n};\n\n/** Serializes startup and builds across CLI processes, including separate terminals. */\nexport const withWorkerLock = async <T>(\n\tconfig: Pick<ResolvedConfig, \"outDir\" | \"timeouts\">,\n\trun: () => Promise<T>,\n) => {\n\tawait mkdir(resolve(config.outDir, \".codesys\"), { recursive: true });\n\tconst path = resolve(config.outDir, \".codesys/command.lock\");\n\tconst deadline = Date.now() + config.timeouts.build + config.timeouts.startup;\n\twhile (true) {\n\t\tconst lock = await open(path, \"wx\").catch((error: unknown) => {\n\t\t\tif (hasCode(error, \"EEXIST\")) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tthrow error;\n\t\t});\n\n\t\tif (lock) {\n\t\t\ttry {\n\t\t\t\tawait lock.writeFile(String(process.pid));\n\t\t\t\treturn await run();\n\t\t\t} finally {\n\t\t\t\tawait lock.close();\n\t\t\t\tawait unlink(path);\n\t\t\t}\n\t\t}\n\n\t\tconst owner = Number(\n\t\t\tawait readFile(path, \"utf8\").catch((error: unknown) => {\n\t\t\t\tif (hasCode(error, \"ENOENT\")) {\n\t\t\t\t\treturn \"\";\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t}),\n\t\t);\n\t\tif (owner > 0 && !isProcessAlive(owner)) {\n\t\t\t// Do not race another client by deleting a lock that it may have replaced.\n\t\t\tthrow new Error(\n\t\t\t\t`An interrupted command left ${path}. Remove that lock file and retry.`,\n\t\t\t);\n\t\t}\n\t\tif (Date.now() >= deadline) {\n\t\t\tthrow new Error(\n\t\t\t\t`Timed out waiting for another CODESYS command (${path})`,\n\t\t\t);\n\t\t}\n\t\tawait delay(200);\n\t}\n};\n\n/** The caller holds withWorkerLock throughout a command, so the mailbox has one writer. */\nexport const createCodesysWorker = (config: ResolvedConfig) => {\n\tconst host = createCodesysHost(config);\n\tconst statePath = resolve(config.outDir, \".codesys/session.json\");\n\tconst verifiedProcesses = new Set<number>();\n\n\tconst readSession = async (): Promise<Session | undefined> => {\n\t\tconst value = await readJson(statePath);\n\t\tif (value === undefined) {\n\t\t\treturn undefined;\n\t\t}\n\t\tconst session = sessionSchema.safeParse(value);\n\t\tif (!session.success) {\n\t\t\tthrow new Error(`Invalid CODESYS session file: ${statePath}`, {\n\t\t\t\tcause: session.error,\n\t\t\t});\n\t\t}\n\t\treturn session.data;\n\t};\n\n\tconst terminate = async (session: Session) => {\n\t\tif (isProcessAlive(session.pid)) {\n\t\t\tawait host.terminate(session.pid).catch((error: unknown) => {\n\t\t\t\tif (isProcessAlive(session.pid)) {\n\t\t\t\t\tthrow error;\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t\t// Let the launcher reap its child before another error handler or CLI\n\t\t// checks this PID. Sending a second group kill can otherwise race exit.\n\t\tconst deadline = Date.now() + config.timeouts.terminate;\n\t\twhile (isProcessAlive(session.pid)) {\n\t\t\tif (Date.now() >= deadline) {\n\t\t\t\tthrow new Error(\"CODESYS launcher did not exit after termination\");\n\t\t\t}\n\t\t\tawait delay(50);\n\t\t}\n\t};\n\n\t/** Sends `command` and waits for its reply within `budget`: milliseconds, or one per phase. */\n\tconst request = async (\n\t\tsession: Session,\n\t\tcommand: WorkerCommand,\n\t\tbudget: number | PhasedBudget,\n\t) => {\n\t\tconst id = randomUUID();\n\t\tconst reply = resolve(session.directory, `${id}.json`);\n\t\tawait writeJson(resolve(session.directory, \"request.json\"), {\n\t\t\t...command,\n\t\t\tid,\n\t\t});\n\t\tconst started = Date.now();\n\t\tconst timeoutMs = typeof budget === \"number\" ? budget : budget.prepare;\n\t\tconst deadline = started + timeoutMs;\n\t\t// When the worker entered its transfer, and how many transfer budgets it has used since.\n\t\tconst transfer: { since?: number; reported: number } = { reported: 0 };\n\t\twhile (true) {\n\t\t\tconst result = await readJson(reply);\n\t\t\tif (result !== undefined) {\n\t\t\t\tawait unlink(reply);\n\t\t\t\tconst response = z\n\t\t\t\t\t.object({\n\t\t\t\t\t\terror: z.string().optional(),\n\t\t\t\t\t\tdiagnostics: z.array(compilerDiagnosticSchema).optional(),\n\t\t\t\t\t\tdownloadRequired: z.literal(true).optional(),\n\t\t\t\t\t\tid: z.literal(id),\n\t\t\t\t\t\tok: z.boolean(),\n\t\t\t\t\t\tresult: z.unknown(),\n\t\t\t\t\t})\n\t\t\t\t\t.safeParse(result);\n\t\t\t\tif (!response.success) {\n\t\t\t\t\tthrow new Error(\"CODESYS returned an invalid worker response\", {\n\t\t\t\t\t\tcause: response.error,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tverifiedProcesses.add(session.pid);\n\t\t\t\tif (!response.data.ok) {\n\t\t\t\t\tconst message = response.data.error ?? \"CODESYS build failed\";\n\t\t\t\t\tif (response.data.diagnostics) {\n\t\t\t\t\t\tthrow new CodesysCompilerError(message, response.data.diagnostics);\n\t\t\t\t\t}\n\t\t\t\t\tif (response.data.downloadRequired) {\n\t\t\t\t\t\tthrow new DownloadRequiredError(message);\n\t\t\t\t\t}\n\t\t\t\t\tthrow new Error(message);\n\t\t\t\t}\n\t\t\t\treturn response.data.result;\n\t\t\t}\n\t\t\tif (!isProcessAlive(session.pid)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`CODESYS exited before completing ${command.action}. See ${session.directory}/codesys.log`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (typeof budget !== \"number\") {\n\t\t\t\ttransfer.since ??=\n\t\t\t\t\t(await workerPhase(budget.file)) === \"transfer\"\n\t\t\t\t\t\t? Date.now()\n\t\t\t\t\t\t: undefined;\n\t\t\t}\n\t\t\tif (typeof budget !== \"number\" && transfer.since !== undefined) {\n\t\t\t\tconst elapsed = Date.now() - transfer.since;\n\t\t\t\tconst used = Math.floor(elapsed / budget.transfer);\n\t\t\t\tif (used > transfer.reported) {\n\t\t\t\t\ttransfer.reported = used;\n\t\t\t\t\tbudget.overdue(\n\t\t\t\t\t\t`The transfer has run ${minutes(elapsed)}, past its ${minutes(budget.transfer)} budget; waiting for it, since stopping CODESYS mid-transfer could leave the controller without an application`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait delay(200);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (Date.now() >= deadline) {\n\t\t\t\t// A saved PID can belong to another process after a reboot. Only kill\n\t\t\t\t// a process we launched or whose worker answered in this invocation.\n\t\t\t\tif (!verifiedProcesses.has(session.pid)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`CODESYS ${command.action} timed out without a worker response. Close the dedicated IDE if it is still running, then retry. Log: ${session.directory}/codesys.log`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait terminate(session);\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`CODESYS ${command.action} timed out after ${timeoutMs} ms; the worker was stopped. See ${session.directory}/codesys.log`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait delay(200);\n\t\t}\n\t};\n\n\tconst launch = async () => {\n\t\tawait access(config.codesys.executable);\n\t\tconst fingerprint = createHash(\"sha256\")\n\t\t\t.update(\n\t\t\t\tJSON.stringify({\n\t\t\t\t\tscripts: await Promise.all(\n\t\t\t\t\t\tworkerScripts.map((script) =>\n\t\t\t\t\t\t\treadFile(resolve(pythonDirectory, script), \"utf8\"),\n\t\t\t\t\t\t),\n\t\t\t\t\t),\n\t\t\t\t\tcommand: codesysCommand,\n\t\t\t\t\tcodesys: config.codesys,\n\t\t\t\t\tlauncher: getHostCommand(config.codesys),\n\t\t\t\t}),\n\t\t\t)\n\t\t\t.digest(\"hex\");\n\t\tconst previous = await readSession();\n\t\tif (previous && isProcessAlive(previous.pid)) {\n\t\t\tif (previous.fingerprint !== fingerprint) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"CODESYS settings or worker scripts changed. Run stop-worker, then launch-worker to reload them.\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait request(previous, { action: \"ping\" }, config.timeouts.startup);\n\t\t\tconsole.log(\n\t\t\t\t`Reusing CODESYS worker (${previous.pid}). Log: ${previous.directory}/codesys.log`,\n\t\t\t);\n\t\t\treturn previous;\n\t\t}\n\n\t\tconst directory = resolve(config.outDir, \".codesys/worker\");\n\t\tawait rm(directory, { recursive: true, force: true });\n\t\tawait mkdir(directory, { recursive: true });\n\t\tfor (const script of workerScripts) {\n\t\t\tawait copyFile(\n\t\t\t\tresolve(pythonDirectory, script),\n\t\t\t\tresolve(directory, script),\n\t\t\t);\n\t\t}\n\t\tconsole.log(`Starting CODESYS. Log: ${directory}/codesys.log`);\n\t\tconst pid = await host.startWorker(directory);\n\t\tconst session = { directory, fingerprint, pid };\n\t\tverifiedProcesses.add(pid);\n\t\ttry {\n\t\t\tawait writeJson(statePath, session);\n\t\t\tawait request(session, { action: \"ping\" }, config.timeouts.startup);\n\t\t} catch (error) {\n\t\t\tawait terminate(session);\n\t\t\tthrow error;\n\t\t}\n\t\tconsole.log(`CODESYS worker ready (${session.pid})`);\n\t\treturn session;\n\t};\n\n\tconst checkExit = async (session: Session) => {\n\t\tconst status = await host.exitStatus(session.directory, session.pid);\n\t\tif (!status) {\n\t\t\tthrow new Error(\n\t\t\t\t`CODESYS launcher stopped but its exit status is unavailable. See ${session.directory}/codesys.log`,\n\t\t\t);\n\t\t}\n\t\tif (status.code !== 0 || status.signal !== null) {\n\t\t\tthrow new Error(\n\t\t\t\t`CODESYS launcher exited with ${status.signal ?? status.code ?? \"unknown status\"}. See ${session.directory}/codesys.log`,\n\t\t\t);\n\t\t}\n\t};\n\n\tconst stop = async () => {\n\t\tconst session = await readSession();\n\t\tif (!session) {\n\t\t\tconsole.log(\"CODESYS worker is already stopped\");\n\t\t\treturn;\n\t\t}\n\t\tif (!isProcessAlive(session.pid)) {\n\t\t\tawait checkExit(session);\n\t\t\tconsole.log(\"CODESYS worker is already stopped\");\n\t\t\treturn;\n\t\t}\n\t\tawait request(session, { action: \"stop\" }, config.timeouts.stop);\n\t\tconst deadline = Date.now() + config.timeouts.stop;\n\t\twhile (isProcessAlive(session.pid)) {\n\t\t\tif (Date.now() >= deadline) {\n\t\t\t\tconst message = `CODESYS stop timed out after ${config.timeouts.stop} ms. See ${session.directory}/codesys.log`;\n\t\t\t\ttry {\n\t\t\t\t\tawait terminate(session);\n\t\t\t\t} catch (cause) {\n\t\t\t\t\tthrow new Error(`${message}; the worker could not be terminated`, {\n\t\t\t\t\t\tcause,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t\tthrow new Error(`${message}; the worker required forced termination`);\n\t\t\t}\n\t\t\tawait delay(200);\n\t\t}\n\t\tawait checkExit(session);\n\t\tconsole.log(\"CODESYS worker stopped\");\n\t};\n\n\t/** Whether the session's CODESYS still runs; one that died fails every request. */\n\tconst alive = (session: Session) => isProcessAlive(session.pid);\n\n\treturn { launch, request, stop, alive };\n};\n\n/** Container jobs own a temporary worker; always stop it before returning a result. */\nexport const withWorkerShutdown = async <T>(\n\tconfig: ResolvedConfig,\n\tworker: Pick<ReturnType<typeof createCodesysWorker>, \"stop\">,\n\toperation: () => Promise<T>,\n) => {\n\tconst stop = async () => {\n\t\ttry {\n\t\t\tawait withWorkerLock(config, () => worker.stop());\n\t\t} finally {\n\t\t\tawait rm(resolve(config.outDir, \".codesys/session.json\"), {\n\t\t\t\tforce: true,\n\t\t\t});\n\t\t}\n\t};\n\treturn Promise.resolve()\n\t\t.then(operation)\n\t\t.then(\n\t\t\tasync (result) => {\n\t\t\t\tawait stop();\n\t\t\t\treturn result;\n\t\t\t},\n\t\t\tasync (failure: unknown) => {\n\t\t\t\tawait stop().catch((shutdownFailure: unknown) => {\n\t\t\t\t\t// Diagnostic mapping follows cause; keep the operation there and\n\t\t\t\t\t// expose its shutdown failure alongside it in errors.\n\t\t\t\t\tthrow new AggregateError(\n\t\t\t\t\t\t[failure, shutdownFailure],\n\t\t\t\t\t\t\"CODESYS operation and worker shutdown failed\",\n\t\t\t\t\t\t{\n\t\t\t\t\t\t\tcause: failure,\n\t\t\t\t\t\t},\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t\tthrow failure;\n\t\t\t},\n\t\t);\n};\n",
14
+ "// What the host and the builder container exchange for controller operations: the receipt,\n// the target a baseline is bound to, warm and login commands, and how failures are worded.\nimport { createHash } from \"node:crypto\";\nimport {\n\tcontrollerSchema,\n\ttype ResolvedConfig,\n\tsha256Digest,\n\ttcpPort,\n} from \"@tsplc/config/build\";\nimport { z } from \"zod\";\n\nexport const imageIdSchema = z.string().regex(/^sha256:[a-f0-9]{64}$/);\nconst endpointSchema = z.strictObject({\n\thost: z.string().nonempty(),\n\tport: tcpPort,\n});\nexport const controllerResultSchema = z.strictObject({\n\tschemaVersion: z.literal(1),\n\toperationId: z.uuid(),\n\toperation: z.enum([\"download\", \"online-change\", \"inspect\"]),\n\timageId: imageIdSchema,\n\ttemplateHash: sha256Digest,\n\ttarget: z.strictObject({\n\t\tnetwork: z.string().nonempty(),\n\t\tgateway: endpointSchema,\n\t\tdevice: endpointSchema,\n\t\tcontroller: controllerSchema.optional(),\n\t\tdeviceTree: sha256Digest.optional(),\n\t}),\n\tgeneration: z.string().nonempty(),\n\tapplication: z.string().nonempty(),\n\tapplicationGuid: z.string().nonempty(),\n\tcontrollerIds: z.strictObject({\n\t\tcodeId: z.string().nonempty(),\n\t\tdataId: z.string().nonempty(),\n\t}),\n\tstate: z.string().nonempty(),\n\tvalues: z.record(z.string(), z.string()),\n});\nexport type ControllerResult = z.infer<typeof controllerResultSchema>;\nexport const controllerCredentialsSchema = z.strictObject({\n\tusername: z.string().nonempty(),\n\tpassword: z.string().nonempty(),\n});\nexport type ControllerCredentials = z.infer<typeof controllerCredentialsSchema>;\n\n/** One operation for the warm builder container; `request` is the container path of its config. */\nexport const warmOperationSchema = z.strictObject({\n\toperation: z.enum([\"download\", \"online-change\"]),\n\toperationId: z.uuid(),\n\trequest: z.string().nonempty(),\n\tinitializeUser: z.boolean(),\n\tcredentials: controllerCredentialsSchema.optional(),\n});\n\n/**\n * The failure a Python traceback ends with, as `Type: message`: everything after its last frame, so\n * a message over several lines, such as one CODESYS error per line, stays whole. Other errors pass unchanged.\n */\nexport const tracebackFailure = (traceback: string) => {\n\tconst text = traceback.trim();\n\tconst lastFrame = text.lastIndexOf(\"\\n File \");\n\tif (lastFrame === -1) {\n\t\treturn text;\n\t}\n\t// Python prints the frame's source line under it, indented further, when it has the source.\n\tconst [, ...rest] = text.slice(lastFrame + 1).split(\"\\n\");\n\treturn (rest[0]?.startsWith(\" \") ? rest.slice(1) : rest).join(\"\\n\");\n};\n\n/** The message of the failure a worker traceback ends with, without its exception type. */\nexport const failureReason = (error: unknown) =>\n\ttracebackFailure(\n\t\terror instanceof Error ? error.message : String(error),\n\t).replace(/^\\w+: /, \"\");\n\n/**\n * What a download binds the controller to. An online change needs the same connection, controller\n * and device tree, because it only recompiles the program into the downloaded project.\n */\nexport const controllerTarget = (\n\tconfig: ResolvedConfig,\n\tonline: NonNullable<ResolvedConfig[\"online\"]>,\n) => ({\n\tnetwork: online.network,\n\tgateway: online.gateway,\n\tdevice: online.device,\n\tcontroller: config.controller,\n\t...(config.deviceTree && {\n\t\tdeviceTree: createHash(\"sha256\")\n\t\t\t.update(JSON.stringify(config.deviceTree))\n\t\t\t.digest(\"hex\"),\n\t}),\n});\n\nexport type Baseline = Pick<\n\tControllerResult,\n\t\"imageId\" | \"templateHash\" | \"target\"\n>;\n\n/** Whether two controller states share an image, template and target, so one can follow the other. */\nexport const sameBaseline = (state: Baseline, expected: Baseline) =>\n\tstate.imageId === expected.imageId &&\n\tstate.templateHash === expected.templateHash &&\n\tJSON.stringify(state.target) === JSON.stringify(expected.target);\n\n/** Ends the message of every refusal that only a full download resolves. */\nexport const explicitDownload = \"use an explicit download\";\n\n/**\n * A refusal that only a full download resolves, so callers can offer one instead of failing.\n * Worker and container replies carry it as `downloadRequired: true`.\n */\nexport class DownloadRequiredError extends Error {\n\treadonly downloadRequired = true;\n}\n\n/**\n * What became of the controller after a download failed mid-transfer: it still ran the previous\n * application (`intact`), runs it again from the last committed download (`restored`), or may hold\n * no application, because restoring failed (`failed`) or no committed download exists (`unavailable`).\n */\nexport const rollbackSchema = z.enum([\n\t\"intact\",\n\t\"restored\",\n\t\"failed\",\n\t\"unavailable\",\n]);\nexport type Rollback = z.infer<typeof rollbackSchema>;\n\n/** A download that failed once it had started transferring, and what its rollback did. */\nexport class TransferFailedError extends Error {\n\tconstructor(\n\t\tmessage: string,\n\t\treadonly rollback: Rollback,\n\t\toptions?: ErrorOptions,\n\t) {\n\t\tsuper(message, options);\n\t}\n}\n\n/** The rollback a failed download reports, from whichever package raised it. */\nexport const transferRollback = (error: unknown): Rollback | undefined => {\n\tif (!(error instanceof Error) || !(\"rollback\" in error)) {\n\t\treturn undefined;\n\t}\n\treturn rollbackSchema.safeParse(error.rollback).data;\n};\n\n/** Whether `error` is a refusal only a full download resolves, from whichever package raised it. */\nexport const requiresDownload = (error: unknown) =>\n\terror instanceof Error &&\n\t\"downloadRequired\" in error &&\n\terror.downloadRequired === true;\n\nexport const loginCommandSchema = z.discriminatedUnion(\"command\", [\n\tz.strictObject({ command: z.literal(\"state\") }),\n\tz.strictObject({\n\t\tcommand: z.literal(\"read\"),\n\t\texpressions: z.array(z.string().nonempty()).nonempty(),\n\t}),\n\tz.strictObject({\n\t\tcommand: z.enum([\"write\", \"force\"]),\n\t\tvalues: z.record(z.string().nonempty(), z.string().nonempty()),\n\t}),\n\t// No expressions unforces everything; `restore` puts back the value from before forcing.\n\tz.strictObject({\n\t\tcommand: z.literal(\"unforce\"),\n\t\texpressions: z.array(z.string().nonempty()),\n\t\trestore: z.boolean(),\n\t}),\n\tz.strictObject({ command: z.enum([\"start\", \"stop\"]) }),\n\tz.strictObject({\n\t\tcommand: z.literal(\"reset\"),\n\t\tkind: z.enum([\"Warm\", \"Cold\"]),\n\t}),\n]);\nexport type LoginCommand = z.infer<typeof loginCommandSchema>;\nexport const loginResultSchema = z.union([\n\tz.strictObject({ values: z.record(z.string(), z.string()) }),\n\tz.strictObject({ state: z.string(), forced: z.array(z.string()) }),\n]);\nexport type LoginResult = z.infer<typeof loginResultSchema>;\n",
13
15
  "import type { ResolvedConfig } from \"@tsplc/config/build\";\n\nexport const codesysCommandFilename = \"run.cmd\";\n\n// Keep arguments in the Windows command line: Wine's direct launcher loses the\n// quoting CODESYS needs around profile names containing spaces.\nexport const codesysCommand = [\n\t\"@echo off\",\n\t\"setlocal DisableDelayedExpansion\",\n\t'\"%CODESYS_BUILD_EXE%\" --profile=\"%CODESYS_BUILD_PROFILE%\" --noUI --runscript=\"%CODESYS_BUILD_SCRIPT%\"',\n\t'set \"CODESYS_BUILD_STATUS=%errorlevel%\"',\n\t'if not \"%CODESYS_BUILD_STATUS%\"==\"0\" echo CODESYS Windows exit status: %CODESYS_BUILD_STATUS%',\n\t\"exit /b %CODESYS_BUILD_STATUS%\",\n\t\"\",\n].join(\"\\r\\n\");\n\nexport const getHostCommand = (\n\tconfig: Pick<ResolvedConfig[\"codesys\"], \"commandProcessor\" | \"wine\">,\n\tplatform: NodeJS.Platform = process.platform,\n) => {\n\tif (platform === \"win32\") {\n\t\treturn {\n\t\t\targs: [\"/d\", \"/c\", codesysCommandFilename],\n\t\t\texecutable: config.commandProcessor,\n\t\t};\n\t}\n\tconst wine = config.wine?.binary ?? \"wine\";\n\tconst args = [\"cmd\", \"/d\", \"/c\", codesysCommandFilename];\n\t// --noUI suppresses the IDE, but CODESYS can still allocate a Wine console.\n\t// A private PTY makes Wine use its Unix console instead of a desktop window.\n\treturn {\n\t\targs:\n\t\t\tplatform === \"darwin\"\n\t\t\t\t? [\"-q\", \"/dev/null\", wine, ...args]\n\t\t\t\t: [\n\t\t\t\t\t\t\"-q\",\n\t\t\t\t\t\t\"-e\",\n\t\t\t\t\t\t\"-c\",\n\t\t\t\t\t\t[wine, ...args]\n\t\t\t\t\t\t\t.map((argument) => `'${argument.replaceAll(\"'\", \"'\\\\''\")}'`)\n\t\t\t\t\t\t\t.join(\" \"),\n\t\t\t\t\t\t\"/dev/null\",\n\t\t\t\t\t],\n\t\texecutable: \"script\",\n\t};\n};\n",
14
- "import { execFile, spawn } from \"node:child_process\";\nimport { appendFileSync, constants, renameSync, writeFileSync } from \"node:fs\";\nimport { access, open, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { delimiter, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport { z } from \"zod\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport {\n\tcodesysCommand,\n\tcodesysCommandFilename,\n\tgetHostCommand,\n} from \"./codesys-command\";\nimport { toWindowsPath } from \"./windows-path\";\n\nconst execute = promisify(execFile);\nconst exitSchema = z.object({\n\tpid: z.int().positive(),\n\tcode: z.int().nullable(),\n\tsignal: z.string().nullable(),\n});\n\nexport const createCodesysHost = (config: ResolvedConfig) => {\n\tconst native = process.platform === \"win32\";\n\tconst { codesys, timeouts } = config;\n\tconst hostEnv = {\n\t\t// Child processes inherit OS settings such as PATH and DISPLAY.\n\t\t...process.env,\n\t\tWINEPREFIX: codesys.wine?.prefix,\n\t\tWINEDEBUG: codesys.wine?.debug,\n\t\tCODESYS_BUILD_NATIVE_EXIT: String(codesys.wine?.nativeExit ?? false),\n\t};\n\n\t/** Start the headless worker script; its launcher outlives this CLI process. */\n\tconst startWorker = async (directory: string) => {\n\t\tif (!native) {\n\t\t\tawait execute(codesys.wine?.binary ?? \"wine\", [\"--version\"], {\n\t\t\t\tenv: hostEnv,\n\t\t\t\ttimeout: timeouts.hostCommand,\n\t\t\t}).catch((cause: unknown) => {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Wine is missing. Install Wine; Winetricks alone cannot run CODESYS\",\n\t\t\t\t\t{\n\t\t\t\t\t\tcause,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t\tconst candidates = (process.env[\"PATH\"] ?? \"\").split(delimiter);\n\t\t\tconst available = await Promise.all(\n\t\t\t\tcandidates.map((path) =>\n\t\t\t\t\taccess(resolve(path, \"script\"), constants.X_OK).then(\n\t\t\t\t\t\t() => true,\n\t\t\t\t\t\t() => false,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t);\n\t\t\tif (!available.some(Boolean)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Headless Wine builds require the script utility (install util-linux on Linux)\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tawait writeFile(resolve(directory, codesysCommandFilename), codesysCommand);\n\t\tconst env = {\n\t\t\t...hostEnv,\n\t\t\tCODESYS_BUILD_SCRIPT: await toWindowsPath(\n\t\t\t\tresolve(directory, \"worker.py\"),\n\t\t\t\tcodesys.wine,\n\t\t\t),\n\t\t\tCODESYS_BUILD_SESSION: await toWindowsPath(directory, codesys.wine),\n\t\t\tCODESYS_BUILD_EXE: await toWindowsPath(codesys.executable, codesys.wine),\n\t\t\tCODESYS_BUILD_PROFILE: codesys.profile,\n\t\t};\n\t\tconst launcher = getHostCommand(codesys);\n\t\tconst logPath = resolve(directory, \"codesys.log\");\n\t\tconst exitPath = resolve(directory, \"launcher-exit.json\");\n\t\tawait rm(exitPath, { force: true });\n\t\tconst log = await open(logPath, \"w\");\n\t\ttry {\n\t\t\tconst child = spawn(launcher.executable, launcher.args, {\n\t\t\t\tcwd: directory,\n\t\t\t\tdetached: true,\n\t\t\t\twindowsHide: true,\n\t\t\t\tenv,\n\t\t\t\tstdio: [\"ignore\", log.fd, log.fd],\n\t\t\t});\n\t\t\tchild.once(\"exit\", (code, signal) => {\n\t\t\t\ttry {\n\t\t\t\t\tappendFileSync(\n\t\t\t\t\t\tlogPath,\n\t\t\t\t\t\t`\\nCODESYS launcher exit status: ${signal ?? code}\\n`,\n\t\t\t\t\t);\n\t\t\t\t} catch {\n\t\t\t\t\t// A failed diagnostic write must preserve the original process failure.\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst temporary = `${exitPath}.${child.pid}.tmp`;\n\t\t\t\t\twriteFileSync(\n\t\t\t\t\t\ttemporary,\n\t\t\t\t\t\tJSON.stringify({ pid: child.pid, code, signal }),\n\t\t\t\t\t);\n\t\t\t\t\trenameSync(temporary, exitPath);\n\t\t\t\t} catch {\n\t\t\t\t\t// The log still records the exit if the optional status file cannot be published.\n\t\t\t\t}\n\t\t\t});\n\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\tchild.once(\"error\", reject);\n\t\t\t\tchild.once(\"spawn\", resolve);\n\t\t\t});\n\t\t\tif (!child.pid) {\n\t\t\t\tthrow new Error(\"CODESYS launcher has no process ID\");\n\t\t\t}\n\t\t\tchild.unref();\n\t\t\treturn child.pid;\n\t\t} finally {\n\t\t\tawait log.close();\n\t\t}\n\t};\n\n\treturn {\n\t\texitStatus: async (directory: string, pid: number) => {\n\t\t\tconst path = resolve(directory, \"launcher-exit.json\");\n\t\t\tconst value = await readFile(path, \"utf8\").catch((error: unknown) => {\n\t\t\t\tif (\n\t\t\t\t\terror instanceof Error &&\n\t\t\t\t\t\"code\" in error &&\n\t\t\t\t\terror.code === \"ENOENT\"\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\tif (value === undefined) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst status = exitSchema.parse(JSON.parse(value));\n\t\t\tif (status.pid !== pid) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!native && status.code === 0 && status.signal === null) {\n\t\t\t\tconst logPath = resolve(directory, \"codesys.log\");\n\t\t\t\tconst log = (await readFile(logPath, \"utf8\"))\n\t\t\t\t\t// Terminal color escapes must not hide a native assertion signature.\n\t\t\t\t\t// eslint-disable-next-line no-control-regex\n\t\t\t\t\t.replace(/\\u001b\\[[0-?]*[ -/]*[@-~]/g, \"\")\n\t\t\t\t\t.replace(/\\r/g, \"\");\n\t\t\t\t// A Wine helper can abort under Rosetta while the main launcher returns 0.\n\t\t\t\t// That command still failed; publishing its artifacts would hide the fault.\n\t\t\t\tconst assertion =\n\t\t\t\t\t/^assertion failed \\[[^\\n]+\\]:[^\\n]*\\n[ \\t]*\\(ThreadContext[^\\n]*\\)/m.exec(\n\t\t\t\t\t\tlog,\n\t\t\t\t\t);\n\t\t\t\tif (assertion) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Wine translation aborted: ${assertion[0].replace(/\\s+/g, \" \")}. See ${logPath}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn status;\n\t\t},\n\t\tstartWorker,\n\t\tterminate: async (pid: number) => {\n\t\t\tif (native) {\n\t\t\t\tawait execute(\"taskkill.exe\", [\"/pid\", String(pid), \"/t\", \"/f\"], {\n\t\t\t\t\tenv: hostEnv,\n\t\t\t\t\ttimeout: timeouts.hostCommand,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tprocess.kill(-pid, \"SIGKILL\");\n\t\t},\n\t};\n};\n",
16
+ "import { execFile, spawn } from \"node:child_process\";\nimport { appendFileSync, constants, renameSync, writeFileSync } from \"node:fs\";\nimport { access, open, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { delimiter, resolve } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport {\n\tcodesysCommand,\n\tcodesysCommandFilename,\n\tgetHostCommand,\n} from \"./codesys-command\";\nimport { toWindowsPath } from \"./windows-path\";\n\nconst execute = promisify(execFile);\nconst exitSchema = z.object({\n\tpid: z.int().positive(),\n\tcode: z.int().nullable(),\n\tsignal: z.string().nullable(),\n});\n\nexport const createCodesysHost = (config: ResolvedConfig) => {\n\tconst native = process.platform === \"win32\";\n\tconst { codesys, timeouts } = config;\n\tconst hostEnv = {\n\t\t// Child processes inherit OS settings such as PATH and DISPLAY.\n\t\t...process.env,\n\t\tWINEPREFIX: codesys.wine?.prefix,\n\t\tWINEDEBUG: codesys.wine?.debug,\n\t\tCODESYS_BUILD_NATIVE_EXIT: String(codesys.wine?.nativeExit ?? false),\n\t};\n\n\t/** Start the headless worker script; its launcher outlives this CLI process. */\n\tconst startWorker = async (directory: string) => {\n\t\tif (!native) {\n\t\t\tawait execute(codesys.wine?.binary ?? \"wine\", [\"--version\"], {\n\t\t\t\tenv: hostEnv,\n\t\t\t\ttimeout: timeouts.hostCommand,\n\t\t\t}).catch((cause: unknown) => {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Wine is missing. Install Wine; Winetricks alone cannot run CODESYS\",\n\t\t\t\t\t{\n\t\t\t\t\t\tcause,\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t});\n\t\t\tconst candidates = (process.env.PATH ?? \"\").split(delimiter);\n\t\t\tconst available = await Promise.all(\n\t\t\t\tcandidates.map((path) =>\n\t\t\t\t\taccess(resolve(path, \"script\"), constants.X_OK).then(\n\t\t\t\t\t\t() => true,\n\t\t\t\t\t\t() => false,\n\t\t\t\t\t),\n\t\t\t\t),\n\t\t\t);\n\t\t\tif (!available.some(Boolean)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"Headless Wine builds require the script utility (install util-linux on Linux)\",\n\t\t\t\t);\n\t\t\t}\n\t\t}\n\t\tawait writeFile(resolve(directory, codesysCommandFilename), codesysCommand);\n\t\tconst env = {\n\t\t\t...hostEnv,\n\t\t\tCODESYS_BUILD_SCRIPT: await toWindowsPath(\n\t\t\t\tresolve(directory, \"worker.py\"),\n\t\t\t\tcodesys.wine,\n\t\t\t),\n\t\t\tCODESYS_BUILD_SESSION: await toWindowsPath(directory, codesys.wine),\n\t\t\tCODESYS_BUILD_EXE: await toWindowsPath(codesys.executable, codesys.wine),\n\t\t\tCODESYS_BUILD_PROFILE: codesys.profile,\n\t\t};\n\t\tconst launcher = getHostCommand(codesys);\n\t\tconst logPath = resolve(directory, \"codesys.log\");\n\t\tconst exitPath = resolve(directory, \"launcher-exit.json\");\n\t\tawait rm(exitPath, { force: true });\n\t\tconst log = await open(logPath, \"w\");\n\t\ttry {\n\t\t\tconst child = spawn(launcher.executable, launcher.args, {\n\t\t\t\tcwd: directory,\n\t\t\t\tdetached: true,\n\t\t\t\twindowsHide: true,\n\t\t\t\tenv,\n\t\t\t\tstdio: [\"ignore\", log.fd, log.fd],\n\t\t\t});\n\t\t\tchild.once(\"exit\", (code, signal) => {\n\t\t\t\ttry {\n\t\t\t\t\tappendFileSync(\n\t\t\t\t\t\tlogPath,\n\t\t\t\t\t\t`\\nCODESYS launcher exit status: ${signal ?? code}\\n`,\n\t\t\t\t\t);\n\t\t\t\t} catch {\n\t\t\t\t\t// A failed diagnostic write must preserve the original process failure.\n\t\t\t\t}\n\t\t\t\ttry {\n\t\t\t\t\tconst temporary = `${exitPath}.${child.pid}.tmp`;\n\t\t\t\t\twriteFileSync(\n\t\t\t\t\t\ttemporary,\n\t\t\t\t\t\tJSON.stringify({ pid: child.pid, code, signal }),\n\t\t\t\t\t);\n\t\t\t\t\trenameSync(temporary, exitPath);\n\t\t\t\t} catch {\n\t\t\t\t\t// The log still records the exit if the optional status file cannot be published.\n\t\t\t\t}\n\t\t\t});\n\t\t\tawait new Promise<void>((resolve, reject) => {\n\t\t\t\tchild.once(\"error\", reject);\n\t\t\t\tchild.once(\"spawn\", resolve);\n\t\t\t});\n\t\t\tif (!child.pid) {\n\t\t\t\tthrow new Error(\"CODESYS launcher has no process ID\");\n\t\t\t}\n\t\t\tchild.unref();\n\t\t\treturn child.pid;\n\t\t} finally {\n\t\t\tawait log.close();\n\t\t}\n\t};\n\n\treturn {\n\t\texitStatus: async (directory: string, pid: number) => {\n\t\t\tconst path = resolve(directory, \"launcher-exit.json\");\n\t\t\tconst value = await readFile(path, \"utf8\").catch((error: unknown) => {\n\t\t\t\tif (\n\t\t\t\t\terror instanceof Error &&\n\t\t\t\t\t\"code\" in error &&\n\t\t\t\t\terror.code === \"ENOENT\"\n\t\t\t\t) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\t\t\t\tthrow error;\n\t\t\t});\n\t\t\tif (value === undefined) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tconst status = exitSchema.parse(JSON.parse(value));\n\t\t\tif (status.pid !== pid) {\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tif (!native && status.code === 0 && status.signal === null) {\n\t\t\t\tconst logPath = resolve(directory, \"codesys.log\");\n\t\t\t\tconst log = (await readFile(logPath, \"utf8\"))\n\t\t\t\t\t// Terminal color escapes must not hide a native assertion signature.\n\t\t\t\t\t// biome-ignore lint/suspicious/noControlCharactersInRegex: Match the terminal ESC character before inspecting diagnostics.\n\t\t\t\t\t.replace(/\\u001b\\[[0-?]*[ -/]*[@-~]/g, \"\")\n\t\t\t\t\t.replace(/\\r/g, \"\");\n\t\t\t\t// A Wine helper can abort under Rosetta while the main launcher returns 0.\n\t\t\t\t// That command still failed; publishing its artifacts would hide the fault.\n\t\t\t\tconst assertion =\n\t\t\t\t\t/^assertion failed \\[[^\\n]+\\]:[^\\n]*\\n[ \\t]*\\(ThreadContext[^\\n]*\\)/m.exec(\n\t\t\t\t\t\tlog,\n\t\t\t\t\t);\n\t\t\t\tif (assertion) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Wine translation aborted: ${assertion[0].replace(/\\s+/g, \" \")}. See ${logPath}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn status;\n\t\t},\n\t\tstartWorker,\n\t\tterminate: async (pid: number) => {\n\t\t\tif (native) {\n\t\t\t\tawait execute(\"taskkill.exe\", [\"/pid\", String(pid), \"/t\", \"/f\"], {\n\t\t\t\t\tenv: hostEnv,\n\t\t\t\t\ttimeout: timeouts.hostCommand,\n\t\t\t\t});\n\t\t\t\treturn;\n\t\t\t}\n\t\t\tprocess.kill(-pid, \"SIGKILL\");\n\t\t},\n\t};\n};\n",
15
17
  "import { execFile } from \"node:child_process\";\nimport { readdir, realpath } from \"node:fs/promises\";\nimport { relative, resolve, sep, win32 } from \"node:path\";\nimport { promisify } from \"node:util\";\nimport {\n\tcodesysTimeouts,\n\tcommandArgumentSchema,\n\ttype ResolvedConfig,\n} from \"@tsplc/config/build\";\n\nconst execute = promisify(execFile);\n\nexport const toWindowsPath = async (\n\tpath: string,\n\twine: ResolvedConfig[\"codesys\"][\"wine\"],\n\tplatform: NodeJS.Platform = process.platform,\n) => {\n\tif (platform === \"win32\") {\n\t\treturn commandArgumentSchema.parse(win32.resolve(path));\n\t}\n\tif (!wine?.prefix) {\n\t\tthrow new Error(\"Configure codesys.wine.prefix for CODESYS on macOS/Linux\");\n\t}\n\n\t// Resolve filesystem aliases (e.g. macOS /var -> /private/var) so the file\n\t// and drive roots are compared using the same paths. Fall back to the absolute\n\t// spelling when realpath cannot resolve the file, such as before it exists.\n\tconst absolute = await realpath(resolve(path)).catch(() => resolve(path));\n\t// Wine stores drive mappings as symlinks, e.g. dosdevices/c: -> ../drive_c.\n\t// Reading these links avoids starting Wine just to convert a path.\n\tconst devices = resolve(wine.prefix, \"dosdevices\");\n\tconst drives = await readdir(devices).catch(() => []);\n\tconst mappings = await Promise.all(\n\t\tdrives\n\t\t\t.filter((drive) => /^[a-z]:$/i.test(drive))\n\t\t\t.map(async (drive) => {\n\t\t\t\tconst root = await realpath(resolve(devices, drive)).catch(\n\t\t\t\t\t() => undefined,\n\t\t\t\t);\n\t\t\t\tif (!root) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\tconst suffix = relative(root, absolute);\n\t\t\t\t// \"..\" or \"../...\" means the file is outside this drive's root.\n\t\t\t\t// Match a full segment so a name such as \"..notes\" remains valid.\n\t\t\t\tif (suffix === \"..\" || suffix.startsWith(`..${sep}`)) {\n\t\t\t\t\treturn;\n\t\t\t\t}\n\n\t\t\t\treturn {\n\t\t\t\t\troot,\n\t\t\t\t\twindows: win32.join(`${drive.toUpperCase()}\\\\`, ...suffix.split(sep)),\n\t\t\t\t};\n\t\t\t}),\n\t);\n\t// Mappings can overlap: C: -> /wine/drive_c and Z: -> / may both contain\n\t// the file. Prefer the longest matching root to use the most specific drive.\n\tconst [mapping] = mappings\n\t\t.filter((value) => value !== undefined)\n\t\t.sort((a, b) => b.root.length - a.root.length);\n\tif (mapping) {\n\t\treturn commandArgumentSchema.parse(mapping.windows);\n\t}\n\n\t// No readable drive mapping covers the path; ask Wine to convert it instead.\n\tconst result = await execute(\n\t\twine.pathBinary,\n\t\t[\"-w\", resolve(path)],\n\t\t// Wine inherits OS process settings.\n\t\t{\n\t\t\tenv: { ...process.env, WINEPREFIX: wine.prefix, WINEDEBUG: wine.debug },\n\t\t\ttimeout: codesysTimeouts.hostCommand,\n\t\t},\n\t);\n\treturn commandArgumentSchema.parse(result.stdout.trim());\n};\n",
16
- "import { readdir, readFile } from \"node:fs/promises\";\nimport { basename, resolve } from \"node:path\";\nimport { identifierPattern } from \"@tsplc/iec/st\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { type ObjectKind, type ParsedSource, parseSource } from \"./st/parse\";\nimport { bindStructuredTextIo } from \"./io.ts\";\n\nexport type SourceObject = ParsedSource & {\n\tsource: string;\n\tfolder: string[];\n\tchildren: SourceObject[];\n};\ninterface Files {\n\tcombined: string[];\n\tdeclaration: string[];\n\timplementation: string[];\n}\nconst prefixes: Record<string, ObjectKind> = {\n\tFB: \"function_block\",\n\tPRG: \"program\",\n\tFUN: \"function\",\n\tF: \"function\",\n\tI: \"interface\",\n\tST: \"dut\",\n\tE: \"dut\",\n\tT: \"dut\",\n\tU: \"dut\",\n\tGVL: \"gvl\",\n};\nconst childFolders: Record<string, ObjectKind> = {\n\tmethods: \"method\",\n\tproperties: \"property\",\n\tactions: \"action\",\n};\nconst canOwn = (kind: ObjectKind) =>\n\t[\"program\", \"function_block\", \"interface\", \"property\"].includes(kind);\nconst assertUnique = (objects: SourceObject[], scope: string) => {\n\tconst seen = new Map<string, string>();\n\tfor (const object of objects) {\n\t\tconst key = object.name.toLowerCase();\n\t\tconst previous = seen.get(key);\n\t\tif (previous) {\n\t\t\tthrow new Error(\n\t\t\t\t`Duplicate IEC name ${object.name} in ${scope}: ${previous} and ${object.source}`,\n\t\t\t);\n\t\t}\n\t\tseen.set(key, object.source);\n\t\tassertUnique(object.children, `${scope}.${object.name}`);\n\t}\n};\n\nconst readUnit = async (\n\tname: string,\n\tfiles: Files,\n\trole?: ObjectKind,\n\tinterfaceMember = false,\n): Promise<ParsedSource & { source: string }> => {\n\tif (!identifierPattern.test(name)) {\n\t\tthrow new Error(`Invalid IEC object name: ${name}`);\n\t}\n\tfor (const [part, candidates] of Object.entries(files)) {\n\t\tif (candidates.length > 1) {\n\t\t\tthrow new Error(\n\t\t\t\t`Ambiguous ${part} for ${name}: ${candidates.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\tconst combined = files.combined[0];\n\tconst declaration = files.declaration[0];\n\tconst implementation = files.implementation[0];\n\tif (combined && (declaration || implementation)) {\n\t\tthrow new Error(`Both combined and split sources exist for ${name}`);\n\t}\n\tconst path = combined ?? declaration ?? implementation;\n\tif (!path) {\n\t\tthrow new Error(`Missing source for ${name}`);\n\t}\n\tif (role === \"action\") {\n\t\tif (!combined) {\n\t\t\tthrow new Error(`Actions use one implementation-only .st file: ${path}`);\n\t\t}\n\t\treturn {\n\t\t\tkind: \"action\",\n\t\t\tname,\n\t\t\tdeclaration: \"\",\n\t\t\timplementation: await readFile(combined, \"utf8\"),\n\t\t\tsource: combined,\n\t\t};\n\t}\n\tif (role === \"get\" || role === \"set\") {\n\t\tif (!combined) {\n\t\t\tthrow new Error(`Property accessors use one .st file: ${path}`);\n\t\t}\n\t\tconst body = await readFile(combined, \"utf8\");\n\t\tconst header = `METHOD ${name}\\n`;\n\t\tconst parsed = parseSource(`${header}${body}\\nEND_METHOD`, {\n\t\t\tfilename: combined,\n\t\t});\n\t\treturn {\n\t\t\t...parsed,\n\t\t\tkind: role,\n\t\t\tname,\n\t\t\tdeclaration: parsed.declaration.slice(header.length),\n\t\t\tsource: combined,\n\t\t};\n\t}\n\tif (!combined && !declaration) {\n\t\tthrow new Error(`Missing declaration for ${path}`);\n\t}\n\tconst sourcePath = combined ?? declaration ?? path;\n\tconst parsed = parseSource(await readFile(sourcePath, \"utf8\"), {\n\t\tfilename: sourcePath,\n\t\tname,\n\t\tdeclarationOnly: !combined || interfaceMember,\n\t});\n\tif (parsed.name.toLowerCase() !== name.toLowerCase()) {\n\t\tthrow new Error(\n\t\t\t`Source name ${name} does not match declaration ${parsed.name}: ${sourcePath}`,\n\t\t);\n\t}\n\tif (role && parsed.kind !== role) {\n\t\tthrow new Error(`Expected ${role}, found ${parsed.kind}: ${sourcePath}`);\n\t}\n\tif (!role && [\"method\", \"property\"].includes(parsed.kind)) {\n\t\tthrow new Error(`Child object has no enclosing POU: ${sourcePath}`);\n\t}\n\tconst prefix = /^([A-Z]+)_/.exec(name.toUpperCase())?.[1];\n\tif (!role && prefix && prefixes[prefix] && prefixes[prefix] !== parsed.kind) {\n\t\tthrow new Error(\n\t\t\t`Prefix ${prefix}_ conflicts with ${parsed.kind}: ${sourcePath}`,\n\t\t);\n\t}\n\tconst declarationOnly =\n\t\t[\"dut\", \"gvl\", \"interface\", \"property\"].includes(parsed.kind) ||\n\t\tinterfaceMember;\n\tif (declarationOnly && implementation) {\n\t\tthrow new Error(`This object has no implementation: ${implementation}`);\n\t}\n\tif (!combined && !declarationOnly && !implementation) {\n\t\tthrow new Error(`Missing implementation for ${sourcePath}`);\n\t}\n\treturn {\n\t\t...parsed,\n\t\t...(implementation\n\t\t\t? { implementation: await readFile(implementation, \"utf8\") }\n\t\t\t: {}),\n\t\tsource: sourcePath,\n\t};\n};\n\n/** Folder placement organizes the IDE; it never changes IEC names or execution order. */\nexport const loadSources = async (\n\tconfig: Pick<ResolvedConfig, \"sourceDir\" | \"entry\" | \"io\" | \"tasks\">,\n) => {\n\tconst objects: SourceObject[] = [];\n\tconst visit = async (\n\t\tdirectory: string,\n\t\tfolder: string[],\n\t\tparent?: SourceObject,\n\t\trole?: ObjectKind,\n\t): Promise<void> => {\n\t\tconst entries = (await readdir(directory, { withFileTypes: true })).sort(\n\t\t\t(a, b) => a.name.localeCompare(b.name, \"en\"),\n\t\t);\n\t\tconst groups = new Map<string, { name: string; files: Files }>();\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Source symlinks are not supported: ${resolve(directory, entry.name)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!entry.isFile() || !/\\.st$/i.test(entry.name)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst stem = entry.name.slice(0, -3);\n\t\t\tconst suffix = /^(.*)\\.(declaration|implementation)$/.exec(stem);\n\t\t\tconst generic = [\"source\", \"declaration\", \"implementation\"].includes(\n\t\t\t\tstem,\n\t\t\t);\n\t\t\tconst name = generic ? basename(directory) : (suffix?.[1] ?? stem);\n\t\t\tconst section = suffix?.[2] ?? stem;\n\t\t\tconst part =\n\t\t\t\tsection === \"declaration\" || section === \"implementation\"\n\t\t\t\t\t? section\n\t\t\t\t\t: \"combined\";\n\t\t\tconst key = name.toLowerCase();\n\t\t\tconst group = groups.get(key) ?? {\n\t\t\t\tname,\n\t\t\t\tfiles: { combined: [], declaration: [], implementation: [] },\n\t\t\t};\n\t\t\tgroup.files[part].push(resolve(directory, entry.name));\n\t\t\tgroups.set(key, group);\n\t\t}\n\t\tconst units: SourceObject[] = [];\n\t\tconst ownKey = basename(directory).toLowerCase();\n\t\t// Read an object's own source before its Get/Set files, which have no POU header.\n\t\tconst ordered = [...groups].sort(\n\t\t\t([a], [b]) => Number(b === ownKey) - Number(a === ownKey),\n\t\t);\n\t\tfor (const [key, { name, files }] of ordered) {\n\t\t\tconst ownProperty = units.find(\n\t\t\t\t(unit) =>\n\t\t\t\t\tunit.kind === \"property\" && unit.name.toLowerCase() === ownKey,\n\t\t\t);\n\t\t\tconst accessor =\n\t\t\t\townProperty && (key === \"get\" || key === \"set\") ? key : undefined;\n\t\t\tconst unit: SourceObject = {\n\t\t\t\t...(await readUnit(\n\t\t\t\t\taccessor ? `${accessor[0]?.toUpperCase()}${accessor.slice(1)}` : name,\n\t\t\t\t\tfiles,\n\t\t\t\t\taccessor ?? role,\n\t\t\t\t\tparent?.kind === \"interface\",\n\t\t\t\t)),\n\t\t\t\tfolder: parent ? [] : folder,\n\t\t\t\tchildren: [],\n\t\t\t};\n\t\t\tif (accessor && ownProperty) {\n\t\t\t\tif (parent?.kind === \"interface\") {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Interface properties cannot implement accessors: ${unit.source}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\townProperty.children.push(unit);\n\t\t\t} else {\n\t\t\t\tunits.push(unit);\n\t\t\t\tif (parent) {\n\t\t\t\t\tparent.children.push(unit);\n\t\t\t\t} else {\n\t\t\t\t\tobjects.push(unit);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst own = units.find(\n\t\t\t(unit) => unit.name.toLowerCase() === ownKey && canOwn(unit.kind),\n\t\t);\n\t\tif (own && !parent) {\n\t\t\town.folder = folder.slice(0, -1);\n\t\t}\n\t\tfor (const entry of entries.filter((entry) => entry.isDirectory())) {\n\t\t\tconst childRole = childFolders[entry.name];\n\t\t\tif (own && childRole) {\n\t\t\t\tif (\n\t\t\t\t\town.kind === \"property\" ||\n\t\t\t\t\t(own.kind === \"interface\" && childRole === \"action\")\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`Unsupported ${entry.name} under ${own.name}`);\n\t\t\t\t}\n\t\t\t\tawait visit(resolve(directory, entry.name), [], own, childRole);\n\t\t\t} else if (parent) {\n\t\t\t\tawait visit(resolve(directory, entry.name), [], parent, role);\n\t\t\t} else {\n\t\t\t\tawait visit(resolve(directory, entry.name), [...folder, entry.name]);\n\t\t\t}\n\t\t}\n\t};\n\tawait visit(resolve(config.sourceDir), []);\n\tassertUnique(objects, \"Application\");\n\tif (config.io) {\n\t\tbindStructuredTextIo(objects, config.io);\n\t}\n\tconst entry = objects.find(\n\t\t(object) => object.source === resolve(config.entry),\n\t);\n\tif (!entry) {\n\t\tthrow new Error(`Entry is not a discovered source: ${config.entry}`);\n\t}\n\tif (entry.kind !== \"program\") {\n\t\tthrow new Error(`Entry must be a PROGRAM: ${config.entry}`);\n\t}\n\tif (config.tasks) {\n\t\tconst programs = new Set(\n\t\t\tobjects\n\t\t\t\t.filter((object) => object.kind === \"program\")\n\t\t\t\t.map((object) => object.name),\n\t\t);\n\t\tfor (const task of config.tasks) {\n\t\t\tfor (const program of task.programs) {\n\t\t\t\tif (!programs.has(program)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${task.name} references an undiscovered PROGRAM ${program}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn { entry: entry.name, objects };\n};\n",
18
+ "import { readdir, readFile } from \"node:fs/promises\";\nimport { basename, resolve } from \"node:path\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { identifierPattern } from \"@tsplc/iec/st\";\nimport { bindStructuredTextIo } from \"./io.ts\";\nimport { type ObjectKind, type ParsedSource, parseSource } from \"./st/parse\";\n\nexport type SourceObject = ParsedSource & {\n\tsource: string;\n\tfolder: string[];\n\tchildren: SourceObject[];\n};\ninterface Files {\n\tcombined: string[];\n\tdeclaration: string[];\n\timplementation: string[];\n}\nconst prefixes: Record<string, ObjectKind> = {\n\tFB: \"function_block\",\n\tPRG: \"program\",\n\tFUN: \"function\",\n\tF: \"function\",\n\tI: \"interface\",\n\tST: \"dut\",\n\tE: \"dut\",\n\tT: \"dut\",\n\tU: \"dut\",\n\tGVL: \"gvl\",\n};\nconst childFolders: Record<string, ObjectKind> = {\n\tmethods: \"method\",\n\tproperties: \"property\",\n\tactions: \"action\",\n};\nconst canOwn = (kind: ObjectKind) =>\n\t[\"program\", \"function_block\", \"interface\", \"property\"].includes(kind);\nconst assertUnique = (objects: SourceObject[], scope: string) => {\n\tconst seen = new Map<string, string>();\n\tfor (const object of objects) {\n\t\tconst key = object.name.toLowerCase();\n\t\tconst previous = seen.get(key);\n\t\tif (previous) {\n\t\t\tthrow new Error(\n\t\t\t\t`Duplicate IEC name ${object.name} in ${scope}: ${previous} and ${object.source}`,\n\t\t\t);\n\t\t}\n\t\tseen.set(key, object.source);\n\t\tassertUnique(object.children, `${scope}.${object.name}`);\n\t}\n};\n\nconst readUnit = async (\n\tname: string,\n\tfiles: Files,\n\trole?: ObjectKind,\n\tinterfaceMember = false,\n): Promise<ParsedSource & { source: string }> => {\n\tif (!identifierPattern.test(name)) {\n\t\tthrow new Error(`Invalid IEC object name: ${name}`);\n\t}\n\tfor (const [part, candidates] of Object.entries(files)) {\n\t\tif (candidates.length > 1) {\n\t\t\tthrow new Error(\n\t\t\t\t`Ambiguous ${part} for ${name}: ${candidates.join(\", \")}`,\n\t\t\t);\n\t\t}\n\t}\n\tconst combined = files.combined[0];\n\tconst declaration = files.declaration[0];\n\tconst implementation = files.implementation[0];\n\tif (combined && (declaration || implementation)) {\n\t\tthrow new Error(`Both combined and split sources exist for ${name}`);\n\t}\n\tconst path = combined ?? declaration ?? implementation;\n\tif (!path) {\n\t\tthrow new Error(`Missing source for ${name}`);\n\t}\n\tif (role === \"action\") {\n\t\tif (!combined) {\n\t\t\tthrow new Error(`Actions use one implementation-only .st file: ${path}`);\n\t\t}\n\t\treturn {\n\t\t\tkind: \"action\",\n\t\t\tname,\n\t\t\tdeclaration: \"\",\n\t\t\timplementation: await readFile(combined, \"utf8\"),\n\t\t\tsource: combined,\n\t\t};\n\t}\n\tif (role === \"get\" || role === \"set\") {\n\t\tif (!combined) {\n\t\t\tthrow new Error(`Property accessors use one .st file: ${path}`);\n\t\t}\n\t\tconst body = await readFile(combined, \"utf8\");\n\t\tconst header = `METHOD ${name}\\n`;\n\t\tconst parsed = parseSource(`${header}${body}\\nEND_METHOD`, {\n\t\t\tfilename: combined,\n\t\t});\n\t\treturn {\n\t\t\t...parsed,\n\t\t\tkind: role,\n\t\t\tname,\n\t\t\tdeclaration: parsed.declaration.slice(header.length),\n\t\t\tsource: combined,\n\t\t};\n\t}\n\tif (!combined && !declaration) {\n\t\tthrow new Error(`Missing declaration for ${path}`);\n\t}\n\tconst sourcePath = combined ?? declaration ?? path;\n\tconst parsed = parseSource(await readFile(sourcePath, \"utf8\"), {\n\t\tfilename: sourcePath,\n\t\tname,\n\t\tdeclarationOnly: !combined || interfaceMember,\n\t});\n\tif (parsed.name.toLowerCase() !== name.toLowerCase()) {\n\t\tthrow new Error(\n\t\t\t`Source name ${name} does not match declaration ${parsed.name}: ${sourcePath}`,\n\t\t);\n\t}\n\tif (role && parsed.kind !== role) {\n\t\tthrow new Error(`Expected ${role}, found ${parsed.kind}: ${sourcePath}`);\n\t}\n\tif (!role && [\"method\", \"property\"].includes(parsed.kind)) {\n\t\tthrow new Error(`Child object has no enclosing POU: ${sourcePath}`);\n\t}\n\tconst prefix = /^([A-Z]+)_/.exec(name.toUpperCase())?.[1];\n\tif (!role && prefix && prefixes[prefix] && prefixes[prefix] !== parsed.kind) {\n\t\tthrow new Error(\n\t\t\t`Prefix ${prefix}_ conflicts with ${parsed.kind}: ${sourcePath}`,\n\t\t);\n\t}\n\tconst declarationOnly =\n\t\t[\"dut\", \"gvl\", \"interface\", \"property\"].includes(parsed.kind) ||\n\t\tinterfaceMember;\n\tif (declarationOnly && implementation) {\n\t\tthrow new Error(`This object has no implementation: ${implementation}`);\n\t}\n\tif (!combined && !declarationOnly && !implementation) {\n\t\tthrow new Error(`Missing implementation for ${sourcePath}`);\n\t}\n\treturn {\n\t\t...parsed,\n\t\t...(implementation\n\t\t\t? { implementation: await readFile(implementation, \"utf8\") }\n\t\t\t: {}),\n\t\tsource: sourcePath,\n\t};\n};\n\n/** Folder placement organizes the IDE; it never changes IEC names or execution order. */\nexport const loadSources = async (\n\tconfig: Pick<ResolvedConfig, \"sourceDir\" | \"entry\" | \"io\" | \"tasks\">,\n) => {\n\tconst objects: SourceObject[] = [];\n\tconst visit = async (\n\t\tdirectory: string,\n\t\tfolder: string[],\n\t\tparent?: SourceObject,\n\t\trole?: ObjectKind,\n\t): Promise<void> => {\n\t\tconst entries = (await readdir(directory, { withFileTypes: true })).sort(\n\t\t\t(a, b) => a.name.localeCompare(b.name, \"en\"),\n\t\t);\n\t\tconst groups = new Map<string, { name: string; files: Files }>();\n\t\tfor (const entry of entries) {\n\t\t\tif (entry.isSymbolicLink()) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Source symlinks are not supported: ${resolve(directory, entry.name)}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tif (!entry.isFile() || !/\\.st$/i.test(entry.name)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst stem = entry.name.slice(0, -3);\n\t\t\tconst suffix = /^(.*)\\.(declaration|implementation)$/.exec(stem);\n\t\t\tconst generic = [\"source\", \"declaration\", \"implementation\"].includes(\n\t\t\t\tstem,\n\t\t\t);\n\t\t\tconst name = generic ? basename(directory) : (suffix?.[1] ?? stem);\n\t\t\tconst section = suffix?.[2] ?? stem;\n\t\t\tconst part =\n\t\t\t\tsection === \"declaration\" || section === \"implementation\"\n\t\t\t\t\t? section\n\t\t\t\t\t: \"combined\";\n\t\t\tconst key = name.toLowerCase();\n\t\t\tconst group = groups.get(key) ?? {\n\t\t\t\tname,\n\t\t\t\tfiles: { combined: [], declaration: [], implementation: [] },\n\t\t\t};\n\t\t\tgroup.files[part].push(resolve(directory, entry.name));\n\t\t\tgroups.set(key, group);\n\t\t}\n\t\tconst units: SourceObject[] = [];\n\t\tconst ownKey = basename(directory).toLowerCase();\n\t\t// Read an object's own source before its Get/Set files, which have no POU header.\n\t\tconst ordered = [...groups].sort(\n\t\t\t([a], [b]) => Number(b === ownKey) - Number(a === ownKey),\n\t\t);\n\t\tfor (const [key, { name, files }] of ordered) {\n\t\t\tconst ownProperty = units.find(\n\t\t\t\t(unit) =>\n\t\t\t\t\tunit.kind === \"property\" && unit.name.toLowerCase() === ownKey,\n\t\t\t);\n\t\t\tconst accessor =\n\t\t\t\townProperty && (key === \"get\" || key === \"set\") ? key : undefined;\n\t\t\tconst unit: SourceObject = {\n\t\t\t\t...(await readUnit(\n\t\t\t\t\taccessor ? `${accessor[0]?.toUpperCase()}${accessor.slice(1)}` : name,\n\t\t\t\t\tfiles,\n\t\t\t\t\taccessor ?? role,\n\t\t\t\t\tparent?.kind === \"interface\",\n\t\t\t\t)),\n\t\t\t\tfolder: parent ? [] : folder,\n\t\t\t\tchildren: [],\n\t\t\t};\n\t\t\tif (accessor && ownProperty) {\n\t\t\t\tif (parent?.kind === \"interface\") {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Interface properties cannot implement accessors: ${unit.source}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\townProperty.children.push(unit);\n\t\t\t} else {\n\t\t\t\tunits.push(unit);\n\t\t\t\tif (parent) {\n\t\t\t\t\tparent.children.push(unit);\n\t\t\t\t} else {\n\t\t\t\t\tobjects.push(unit);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t\tconst own = units.find(\n\t\t\t(unit) => unit.name.toLowerCase() === ownKey && canOwn(unit.kind),\n\t\t);\n\t\tif (own && !parent) {\n\t\t\town.folder = folder.slice(0, -1);\n\t\t}\n\t\tfor (const entry of entries.filter((entry) => entry.isDirectory())) {\n\t\t\tconst childRole = childFolders[entry.name];\n\t\t\tif (own && childRole) {\n\t\t\t\tif (\n\t\t\t\t\town.kind === \"property\" ||\n\t\t\t\t\t(own.kind === \"interface\" && childRole === \"action\")\n\t\t\t\t) {\n\t\t\t\t\tthrow new Error(`Unsupported ${entry.name} under ${own.name}`);\n\t\t\t\t}\n\t\t\t\tawait visit(resolve(directory, entry.name), [], own, childRole);\n\t\t\t} else if (parent) {\n\t\t\t\tawait visit(resolve(directory, entry.name), [], parent, role);\n\t\t\t} else {\n\t\t\t\tawait visit(resolve(directory, entry.name), [...folder, entry.name]);\n\t\t\t}\n\t\t}\n\t};\n\tawait visit(resolve(config.sourceDir), []);\n\tassertUnique(objects, \"Application\");\n\tif (config.io) {\n\t\tbindStructuredTextIo(objects, config.io);\n\t}\n\tconst entry = objects.find(\n\t\t(object) => object.source === resolve(config.entry),\n\t);\n\tif (!entry) {\n\t\tthrow new Error(`Entry is not a discovered source: ${config.entry}`);\n\t}\n\tif (entry.kind !== \"program\") {\n\t\tthrow new Error(`Entry must be a PROGRAM: ${config.entry}`);\n\t}\n\tif (config.tasks) {\n\t\tconst programs = new Set(\n\t\t\tobjects\n\t\t\t\t.filter((object) => object.kind === \"program\")\n\t\t\t\t.map((object) => object.name),\n\t\t);\n\t\tfor (const task of config.tasks) {\n\t\t\tfor (const program of task.programs) {\n\t\t\t\tif (!programs.has(program)) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Task ${task.name} references an undiscovered PROGRAM ${program}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\treturn { entry: entry.name, objects };\n};\n",
19
+ "import { ioArray, ioScalarBits, sizePrefix } from \"@tsplc/iec\";\nimport { qualifiers, variableSections } from \"@tsplc/iec/st\";\nimport type { SourceObject } from \"./sources.ts\";\nimport { type Token, tokenize } from \"./st/lexer.ts\";\n\nexport interface DirectIoBinding {\n\taddress: string;\n\ttype?: string;\n}\nconst span = (type: string) => ioArray(type) ?? { element: type, length: 1 };\n// Direct addresses by the width of one element; 64-bit types have no direct form.\nconst addressSize = (type: string) => {\n\tconst bits = ioScalarBits(type);\n\treturn bits === undefined || bits === 64 ? undefined : sizePrefix(bits);\n};\n\n/** Apply the shared mapping to declarations in memory; authored ST stays untouched. */\nexport function bindStructuredTextIo(\n\tobjects: SourceObject[],\n\tbindings: Record<string, DirectIoBinding>,\n) {\n\tconst declarations: {\n\t\tobject: SourceObject;\n\t\tname: string;\n\t\tnames: Token[];\n\t\tcolon: Token;\n\t\ttype: string;\n\t}[] = [];\n\tconst visit = (object: SourceObject) => {\n\t\tconst tokens = tokenize(object.declaration, object.source);\n\t\tlet section = false;\n\t\tlet start = 0;\n\t\tfor (const [index, token] of tokens.entries()) {\n\t\t\tif (variableSections.has(token.value)) {\n\t\t\t\tsection = true;\n\t\t\t\tstart = index + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (token.value === \"END_VAR\") {\n\t\t\t\tsection = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!section || token.value !== \";\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst part = tokens\n\t\t\t\t.slice(start, index)\n\t\t\t\t.filter((t) => t.kind !== \"pragma\");\n\t\t\tstart = index + 1;\n\t\t\tconst colon = part.find((t) => t.value === \":\");\n\t\t\tif (!colon) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst colonIndex = part.indexOf(colon);\n\t\t\tif (colonIndex < 1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst names = part\n\t\t\t\t.slice(0, colonIndex)\n\t\t\t\t.filter(\n\t\t\t\t\t(t) =>\n\t\t\t\t\t\tt.kind === \"word\" && !qualifiers.has(t.value) && t.value !== \"AT\",\n\t\t\t\t);\n\t\t\tconst at = part.find((t) => t.value === \"AT\");\n\t\t\tconst variables = at ? names.filter((t) => t.start < at.start) : names;\n\t\t\tconst initializer = part.findIndex(\n\t\t\t\t(t, index) => index > colonIndex && t.value === \":=\",\n\t\t\t);\n\t\t\tconst typeTokens = part.slice(\n\t\t\t\tcolonIndex + 1,\n\t\t\t\tinitializer < 0 ? undefined : initializer,\n\t\t\t);\n\t\t\tconst [first] = typeTokens;\n\t\t\tconst last = typeTokens.at(-1);\n\t\t\tconst type =\n\t\t\t\tfirst && last\n\t\t\t\t\t? object.declaration\n\t\t\t\t\t\t\t.slice(first.start, last.end)\n\t\t\t\t\t\t\t.replace(/\\s+/g, \" \")\n\t\t\t\t\t\t\t.toUpperCase()\n\t\t\t\t\t: \"\";\n\t\t\tfor (const name of variables) {\n\t\t\t\tdeclarations.push({\n\t\t\t\t\tobject,\n\t\t\t\t\tname: name.value,\n\t\t\t\t\tnames: variables,\n\t\t\t\t\tcolon,\n\t\t\t\t\ttype,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tobject.children.forEach(visit);\n\t};\n\tobjects.forEach(visit);\n\tconst edits = new Map<\n\t\tSourceObject,\n\t\t{ start: number; end: number; text: string }[]\n\t>();\n\tfor (const [symbol, binding] of Object.entries(bindings)) {\n\t\tconst parts = symbol.toUpperCase().split(\".\");\n\t\tif (parts.length > 2) {\n\t\t\tthrow new Error(\n\t\t\t\t`${symbol}: direct IO maps a scalar declaration, not a nested field.`,\n\t\t\t);\n\t\t}\n\t\tconst matches = declarations.filter(\n\t\t\t(d) =>\n\t\t\t\td.name === parts.at(-1) &&\n\t\t\t\t(parts.length === 1 || d.object.name.toUpperCase() === parts[0]),\n\t\t);\n\t\tconst [declaration, ...others] = matches;\n\t\tif (!declaration || others.length) {\n\t\t\tthrow new Error(\n\t\t\t\t`${symbol}: expected one ST variable declaration, found ${matches.length}. Use Object.Variable to disambiguate.`,\n\t\t\t);\n\t\t}\n\t\tconst [variable, ...siblings] = declaration.names;\n\t\tif (!variable || siblings.length) {\n\t\t\tthrow new Error(`${symbol}: declare mapped IO variables separately.`);\n\t\t}\n\t\tconst declared = span(declaration.type);\n\t\tconst size = addressSize(declared.element);\n\t\tif (\n\t\t\t!size ||\n\t\t\t(declared.length > 1 && declared.element === \"BOOL\") ||\n\t\t\tbinding.address[2] !== size\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`${symbol}: ${declaration.type} is incompatible with ${binding.address}.`,\n\t\t\t);\n\t\t}\n\t\tconst expected =\n\t\t\tbinding.type && span(binding.type.replace(/\\s+/g, \" \").toUpperCase());\n\t\tif (\n\t\t\texpected &&\n\t\t\t(expected.element !== declared.element ||\n\t\t\t\texpected.length !== declared.length)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`${symbol}: expected ${binding.type}, found ${declaration.type}.`,\n\t\t\t);\n\t\t}\n\t\tconst list = edits.get(declaration.object) ?? [];\n\t\tconst start = variable.end;\n\t\tif (list.some((e) => e.start === start)) {\n\t\t\tthrow new Error(`${symbol}: the variable has more than one IO binding.`);\n\t\t}\n\t\tlist.push({\n\t\t\tstart,\n\t\t\tend: declaration.colon.start,\n\t\t\ttext: ` AT ${binding.address} `,\n\t\t});\n\t\tedits.set(declaration.object, list);\n\t}\n\tfor (const [object, list] of edits) {\n\t\tfor (const edit of list.sort((a, b) => b.start - a.start)) {\n\t\t\tobject.declaration =\n\t\t\t\tobject.declaration.slice(0, edit.start) +\n\t\t\t\tedit.text +\n\t\t\t\tobject.declaration.slice(edit.end);\n\t\t}\n\t}\n}\n",
20
+ "import { blockCommentEnd, lineCommentEnd, stringEnd } from \"@tsplc/iec/st\";\n\nexport interface Token {\n\tkind: \"word\" | \"string\" | \"pragma\" | \"symbol\";\n\tvalue: string;\n\tstart: number;\n\tend: number;\n}\n\nexport class StSyntaxError extends Error {\n\tconstructor(\n\t\tsource: string,\n\t\toffset: number,\n\t\tfilename: string,\n\t\tmessage: string,\n\t) {\n\t\tconst lines = source.slice(0, offset).split(/\\r\\n|\\r|\\n/);\n\t\tsuper(\n\t\t\t`${filename}:${lines.length}:${(lines.at(-1)?.length ?? 0) + 1}: ${message}`,\n\t\t);\n\t\tthis.name = \"StSyntaxError\";\n\t}\n}\n\n/** Keep original offsets: splitting must preserve comments, pragmas and source spelling. */\nexport const tokenize = (source: string, filename = \"<source>\"): Token[] => {\n\tconst tokens: Token[] = [];\n\tlet offset = 0;\n\tconst fail = (start: number, message: string): never => {\n\t\tthrow new StSyntaxError(source, start, filename, message);\n\t};\n\tconst quoted = () => {\n\t\toffset = stringEnd(source, offset) ?? fail(offset, \"Unterminated string\");\n\t};\n\twhile (offset < source.length) {\n\t\tconst start = offset;\n\t\tconst character = source[offset] ?? \"\";\n\t\tif (/\\s|\\uFEFF/.test(character)) {\n\t\t\toffset++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (source.startsWith(\"//\", offset)) {\n\t\t\toffset = lineCommentEnd(source, start);\n\t\t\tcontinue;\n\t\t}\n\t\tif (source.startsWith(\"(*\", offset)) {\n\t\t\toffset =\n\t\t\t\tblockCommentEnd(source, start) ??\n\t\t\t\tfail(start, \"Unterminated block comment\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"'\" || character === '\"') {\n\t\t\tquoted();\n\t\t\ttokens.push({\n\t\t\t\tkind: \"string\",\n\t\t\t\tvalue: source.slice(start, offset),\n\t\t\t\tstart,\n\t\t\t\tend: offset,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"{\") {\n\t\t\toffset++;\n\t\t\twhile (offset < source.length && source[offset] !== \"}\") {\n\t\t\t\tif (source[offset] === \"'\" || source[offset] === '\"') {\n\t\t\t\t\tquoted();\n\t\t\t\t} else {\n\t\t\t\t\toffset++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (offset === source.length) {\n\t\t\t\tfail(start, \"Unterminated pragma\");\n\t\t\t}\n\t\t\toffset++;\n\t\t\ttokens.push({\n\t\t\t\tkind: \"pragma\",\n\t\t\t\tvalue: source.slice(start, offset),\n\t\t\t\tstart,\n\t\t\t\tend: offset,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (/[A-Za-z_]/.test(character)) {\n\t\t\toffset++;\n\t\t\twhile (/[A-Za-z_0-9]/.test(source[offset] ?? \"\")) {\n\t\t\t\toffset++;\n\t\t\t}\n\t\t\ttokens.push({\n\t\t\t\tkind: \"word\",\n\t\t\t\tvalue: source.slice(start, offset).toUpperCase(),\n\t\t\t\tstart,\n\t\t\t\tend: offset,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\toffset++;\n\t\tconst pair = source.slice(start, offset + 1);\n\t\tif ([\":=\", \"=>\", \"..\", \"<=\", \">=\", \"<>\", \"**\"].includes(pair)) {\n\t\t\toffset++;\n\t\t}\n\t\ttokens.push({\n\t\t\tkind: \"symbol\",\n\t\t\tvalue: source.slice(start, offset),\n\t\t\tstart,\n\t\t\tend: offset,\n\t\t});\n\t}\n\treturn tokens;\n};\n",
17
21
  "import { basename } from \"node:path\";\nimport {\n\tglobalSections,\n\tidentifierPattern,\n\tqualifiers,\n\tvariableSections,\n} from \"@tsplc/iec/st\";\nimport {\n\tdeclarationKeywords,\n\tobjectKinds,\n\treadDeclarationPragmas,\n\treadDeclarationSections,\n\treadDeclarationSemicolon,\n\treadIdentifier,\n\treadModifiers,\n\treadType,\n\treadVariableSection,\n} from \"./declarations\";\nimport type { Token } from \"./lexer\";\nimport { createTokenReader, type TokenReader } from \"./reader\";\n\nexport type ObjectKind =\n\t| (typeof objectKinds)[keyof typeof objectKinds]\n\t| \"dut\"\n\t| \"gvl\"\n\t| \"action\"\n\t| \"get\"\n\t| \"set\";\nexport interface ParsedSource {\n\tkind: ObjectKind;\n\tname: string;\n\tdeclaration: string;\n\timplementation?: string;\n\treturnType?: string;\n\tdutType?: \"structure\" | \"enumeration\" | \"union\" | \"alias\";\n\tpersistent?: boolean;\n}\n\ninterface ParseOptions {\n\tfilename?: string;\n\tdeclarationOnly?: boolean;\n\tname?: string;\n}\n\nconst dutTypes: Record<string, NonNullable<ParsedSource[\"dutType\"]>> = {\n\tSTRUCT: \"structure\",\n\tUNION: \"union\",\n\t\"(\": \"enumeration\",\n};\n\nconst parseDut = (reader: TokenReader): ParsedSource => {\n\treader.expect(\"TYPE\");\n\treadModifiers(reader);\n\tconst name = readIdentifier(reader);\n\tif (reader.consume(\"EXTENDS\")) {\n\t\treadType(reader);\n\t}\n\treader.expect(\":\");\n\treadDeclarationPragmas(reader);\n\tconst dutType = dutTypes[reader.peek()?.value ?? \"\"] ?? \"alias\";\n\twhile (reader.peek()?.value !== \"END_TYPE\") {\n\t\tif (reader.peek()?.value === \"TYPE\") {\n\t\t\treader.fail(\"Only one TYPE declaration is allowed per file\");\n\t\t}\n\t\treader.take();\n\t}\n\treader.take();\n\treader.consume(\";\");\n\tif (reader.peek()) {\n\t\treader.fail(\"Unexpected content after END_TYPE\");\n\t}\n\treturn { kind: \"dut\", name, declaration: reader.source, dutType };\n};\n\nconst parseGlobals = (\n\treader: TokenReader,\n\toptions: ParseOptions,\n): ParsedSource => {\n\tconst header = reader.peek();\n\tlet persistent = false;\n\twhile (reader.peek()) {\n\t\treadDeclarationPragmas(reader);\n\t\tif (!reader.peek()) {\n\t\t\tbreak;\n\t\t}\n\t\tif (!globalSections.has(reader.peek()?.value ?? \"\")) {\n\t\t\treader.fail(\"Expected a global variable section\");\n\t\t}\n\t\tconst start = reader.index;\n\t\treadVariableSection(reader);\n\t\t// Only the section modifiers select the CODESYS persistent-list object.\n\t\t// Comments, pragma strings, and variable names cannot select this role.\n\t\tfor (const token of reader.tokens.slice(start + 1, reader.index)) {\n\t\t\tif (token.kind !== \"word\" || !qualifiers.has(token.value)) {\n\t\t\t\tbreak;\n\t\t\t}\n\t\t\tpersistent ||= token.value === \"PERSISTENT\";\n\t\t}\n\t}\n\tconst name = options.name ?? basename(reader.filename, \".st\");\n\tif (!identifierPattern.test(name)) {\n\t\treader.fail(\n\t\t\t\"Global list requires an IEC filename or an explicit name\",\n\t\t\theader,\n\t\t);\n\t}\n\treturn {\n\t\tkind: \"gvl\",\n\t\tname,\n\t\tdeclaration: reader.source,\n\t\t...(persistent && { persistent: true }),\n\t};\n};\n\nconst validateImplementation = (reader: TokenReader, tokens: Token[]) => {\n\tfor (const token of tokens) {\n\t\tif (token.kind !== \"word\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (variableSections.has(token.value) || token.value === \"END_VAR\") {\n\t\t\treader.fail(\n\t\t\t\t\"Variable declaration outside the declaration section; conditional declaration envelopes are not supported\",\n\t\t\t\ttoken,\n\t\t\t);\n\t\t}\n\t\tif (declarationKeywords.has(token.value)) {\n\t\t\treader.fail(\n\t\t\t\t\"Nested objects must be separate child files, or the object terminator is mismatched\",\n\t\t\t\ttoken,\n\t\t\t);\n\t\t}\n\t}\n};\n\nconst splitObject = (\n\treader: TokenReader,\n\theader: Token,\n\tkind: ObjectKind,\n\toptions: ParseOptions,\n): Pick<ParsedSource, \"declaration\" | \"implementation\"> => {\n\tconst terminator =\n\t\theader.value === \"FUNCTIONBLOCK\"\n\t\t\t? \"END_FUNCTION_BLOCK\"\n\t\t\t: `END_${header.value}`;\n\tconst remaining = reader.tokens.slice(reader.index);\n\tconst terminatorIndex = remaining.findIndex(\n\t\t(token) => token.kind === \"word\" && token.value === terminator,\n\t);\n\t// Even interfaces and properties need END_* in combined files. Only an explicit\n\t// declaration-only input (e.g. a paired declaration.st) may omit it.\n\tif (terminatorIndex < 0 && !options.declarationOnly) {\n\t\treader.fail(`Missing ${terminator}`);\n\t}\n\tconst bodyTokens =\n\t\tterminatorIndex < 0 ? remaining : remaining.slice(0, terminatorIndex);\n\tconst [endToken, next, afterSemicolon] =\n\t\tterminatorIndex < 0 ? [] : remaining.slice(terminatorIndex);\n\tconst semicolon = next?.value === \";\" ? next : undefined;\n\tconst unexpected = semicolon ? afterSemicolon : next;\n\tif (unexpected) {\n\t\treader.fail(`Unexpected content after ${terminator}`, unexpected);\n\t}\n\tvalidateImplementation(reader, bodyTokens);\n\n\tconst declarationOnly =\n\t\toptions.declarationOnly || kind === \"interface\" || kind === \"property\";\n\tif (declarationOnly && bodyTokens.length) {\n\t\treader.fail(\n\t\t\t\"Unexpected implementation in a declaration-only object\",\n\t\t\tbodyTokens[0],\n\t\t);\n\t}\n\n\tconst declaration = reader.source.slice(0, reader.end);\n\t// Remove only END_* and its optional semicolon. Keep whitespace and trailing\n\t// comments in the body, or in the declaration for objects without a body.\n\tconst body =\n\t\treader.source.slice(reader.end, endToken?.start) +\n\t\t(endToken ? reader.source.slice((semicolon ?? endToken).end) : \"\");\n\tif (declarationOnly) {\n\t\treturn { declaration: declaration + body };\n\t}\n\treturn { declaration, implementation: body };\n};\n\nconst parsePou = (reader: TokenReader, options: ParseOptions): ParsedSource => {\n\tconst header = reader.take();\n\tif (!(header.value in objectKinds)) {\n\t\treader.fail(`Unsupported object header ${header.value}`, header);\n\t}\n\tconst kind = objectKinds[header.value as keyof typeof objectKinds];\n\treadModifiers(reader);\n\tconst name = readIdentifier(reader);\n\tconst returnType = reader.consume(\":\") ? readType(reader) : undefined;\n\tif (returnType === undefined && kind === \"property\") {\n\t\treader.fail(`${header.value} requires a return type`);\n\t}\n\t// Exported declarations may terminate the header itself with a semicolon.\n\treadDeclarationSemicolon(reader);\n\treadDeclarationSections(reader);\n\treturn {\n\t\tkind,\n\t\tname,\n\t\t...(returnType === undefined ? {} : { returnType }),\n\t\t...splitObject(reader, header, kind, options),\n\t};\n};\n\n/** Parse only the object envelope and declarations. CODESYS validates executable ST. */\nexport const parseSource = (\n\tsource: string,\n\toptions: ParseOptions = {},\n): ParsedSource => {\n\tconst reader = createTokenReader(source, options.filename ?? \"<source>\");\n\treadDeclarationPragmas(reader);\n\tconst header = reader.peek();\n\tif (header?.value === \"TYPE\") {\n\t\treturn parseDut(reader);\n\t}\n\tif (header && globalSections.has(header.value)) {\n\t\treturn parseGlobals(reader, options);\n\t}\n\treturn parsePou(reader, options);\n};\n",
18
22
  "import {\n\tconditionalDirective,\n\tmodifiers,\n\ttype ObjectKeyword,\n\tvariableSections,\n} from \"@tsplc/iec/st\";\nimport type { Token } from \"./lexer\";\nimport type { TokenReader } from \"./reader\";\n\nexport const objectKinds = {\n\tPROGRAM: \"program\",\n\tFUNCTION_BLOCK: \"function_block\",\n\tFUNCTIONBLOCK: \"function_block\",\n\tFUNCTION: \"function\",\n\tMETHOD: \"method\",\n\tINTERFACE: \"interface\",\n\tPROPERTY: \"property\",\n} as const satisfies Record<ObjectKeyword | \"FUNCTIONBLOCK\", string>;\nconst closingObjects = new Set(\n\tObject.keys(objectKinds).map((kind) => `END_${kind}`),\n);\nexport const declarationKeywords = new Set([\n\t...Object.keys(objectKinds),\n\t...closingObjects,\n\t...variableSections,\n\t\"END_VAR\",\n\t\"TYPE\",\n\t\"END_TYPE\",\n\t\"STRUCT\",\n\t\"END_STRUCT\",\n\t\"UNION\",\n\t\"END_UNION\",\n\t\"ACTION\",\n\t\"END_ACTION\",\n\t\"CONFIGURATION\",\n\t\"END_CONFIGURATION\",\n]);\n\nconst isDeclarationPragma = (token?: Token) =>\n\ttoken?.kind === \"pragma\" && !conditionalDirective(token.value);\n\nexport const readDeclarationPragmas = (reader: TokenReader) => {\n\twhile (isDeclarationPragma(reader.peek())) {\n\t\treader.take();\n\t}\n};\n\nexport const readDeclarationSemicolon = (reader: TokenReader) => {\n\tconst token = reader.peek();\n\t// A semicolon on the next line may be the body's first empty statement.\n\t// Only attach it to a declaration when it terminates that same line.\n\tif (\n\t\ttoken?.value === \";\" &&\n\t\t!/[\\r\\n]/.test(reader.source.slice(reader.end, token.start))\n\t) {\n\t\treader.take();\n\t}\n};\n\nexport const readIdentifier = (reader: TokenReader) => {\n\tconst token = reader.take();\n\tif (token.kind !== \"word\" || declarationKeywords.has(token.value)) {\n\t\treader.fail(\"Expected an IEC identifier\", token);\n\t}\n\treturn reader.source.slice(token.start, token.end);\n};\n\nconst isOverrideModifier = (reader: TokenReader) => {\n\t// OVERRIDE is also an established IEC name (e.g. OSCAT's function).\n\t// A modifier needs a following name on the same line, not a body statement.\n\tconst name = reader.peek(1);\n\treturn (\n\t\tname?.kind === \"word\" &&\n\t\t!declarationKeywords.has(name.value) &&\n\t\t![\"(\", \"[\", \":=\", \".\", \"^\"].includes(reader.peek(2)?.value ?? \"\") &&\n\t\t!/[\\r\\n]/.test(reader.source.slice(reader.peek()?.end, name.start))\n\t);\n};\n\nexport const readModifiers = (reader: TokenReader) => {\n\twhile (modifiers.has(reader.peek()?.value ?? \"\")) {\n\t\tif (reader.peek()?.value === \"OVERRIDE\" && !isOverrideModifier(reader)) {\n\t\t\treturn;\n\t\t}\n\t\treader.take();\n\t}\n};\n\nconst typeDelimiters = { \"(\": \")\", \"[\": \"]\", \"<\": \">\" } as const;\n\nconst readDelimitedType = (\n\treader: TokenReader,\n\topen: keyof typeof typeDelimiters,\n) => {\n\treader.expect(open);\n\tconst closings = [typeDelimiters[open]];\n\twhile (closings.length) {\n\t\tconst token = reader.take();\n\t\tif (token.kind === \"string\" || token.kind === \"pragma\") {\n\t\t\tcontinue;\n\t\t}\n\t\tif (token.value === \"(\" || token.value === \"[\") {\n\t\t\tclosings.push(typeDelimiters[token.value]);\n\t\t} else if (token.value === \")\" || token.value === \"]\") {\n\t\t\tif (closings.pop() !== token.value) {\n\t\t\t\treader.fail(`Mismatched delimiter ${token.value}`, token);\n\t\t\t}\n\t\t} else if (open === \"<\" && closings.at(-1) === \">\") {\n\t\t\t// Inside parentheses, < and > are comparisons, not generic delimiters:\n\t\t\t// FB_Base<(Size := BOOL_TO_INT(1 < 2))>.\n\t\t\tif (token.value === \"<\") {\n\t\t\t\tclosings.push(\">\");\n\t\t\t}\n\t\t\tif (token.value === \">\") {\n\t\t\t\tclosings.pop();\n\t\t\t}\n\t\t}\n\t\tif (declarationKeywords.has(token.value) || token.value === \";\") {\n\t\t\treader.fail(`Unclosed ${open}`, token);\n\t\t}\n\t}\n};\n\nexport const readType = (reader: TokenReader): string => {\n\tconst start = reader.peek()?.start ?? reader.source.length;\n\t// Prefix types can nest arbitrarily; iteration avoids a JavaScript stack limit.\n\twhile (true) {\n\t\tif (\n\t\t\t[\"POINTER\", \"REFERENCE\", \"REF_TO\"].includes(reader.peek()?.value ?? \"\")\n\t\t) {\n\t\t\tif (reader.take().value !== \"REF_TO\") {\n\t\t\t\treader.expect(\"TO\");\n\t\t\t}\n\t\t\tcontinue;\n\t\t}\n\t\tif (reader.consume(\"ARRAY\")) {\n\t\t\treadDelimitedType(reader, \"[\");\n\t\t\treader.expect(\"OF\");\n\t\t\tcontinue;\n\t\t}\n\t\tbreak;\n\t}\n\treadIdentifier(reader);\n\twhile (reader.consume(\".\")) {\n\t\treadIdentifier(reader);\n\t}\n\tfor (const open of [\"(\", \"[\", \"<\"] as const) {\n\t\tif (reader.peek()?.value === open) {\n\t\t\treadDelimitedType(reader, open);\n\t\t}\n\t}\n\treturn reader.source.slice(start, reader.end);\n};\n\nexport const readVariableSection = (reader: TokenReader) => {\n\treader.take();\n\tconst conditionals: { hasElse: boolean }[] = [];\n\twhile (reader.peek()?.value !== \"END_VAR\") {\n\t\tconst token = reader.take();\n\t\tif (variableSections.has(token.value) || closingObjects.has(token.value)) {\n\t\t\treader.fail(\"Missing END_VAR\", token);\n\t\t}\n\t\tconst directive =\n\t\t\ttoken.kind === \"pragma\" && conditionalDirective(token.value);\n\t\tif (!directive) {\n\t\t\tcontinue;\n\t\t}\n\t\tif (directive === \"IF\") {\n\t\t\tconditionals.push({ hasElse: false });\n\t\t\tcontinue;\n\t\t}\n\t\tconst current = conditionals.at(-1);\n\t\tif (!current) {\n\t\t\treturn reader.fail(\"Unmatched conditional pragma\", token);\n\t\t}\n\t\tif (directive === \"END_IF\") {\n\t\t\tconditionals.pop();\n\t\t\tcontinue;\n\t\t}\n\t\tif (current.hasElse) {\n\t\t\treader.fail(\"Conditional branch after ELSE\", token);\n\t\t}\n\t\tcurrent.hasElse = directive === \"ELSE\";\n\t}\n\tif (conditionals.length) {\n\t\treader.fail(\"Conditional pragmas must remain inside one variable section\");\n\t}\n\treader.take();\n\treadDeclarationSemicolon(reader);\n};\n\nexport const readDeclarationSections = (reader: TokenReader) => {\n\twhile (reader.peek()) {\n\t\t// Pragmas belong to the declaration only when another declaration follows.\n\t\t// Look ahead without consuming them so a pragma-only body stays intact.\n\t\tlet ahead = 0;\n\t\twhile (isDeclarationPragma(reader.peek(ahead))) {\n\t\t\tahead++;\n\t\t}\n\t\tconst next = reader.peek(ahead)?.value ?? \"\";\n\t\tif (variableSections.has(next)) {\n\t\t\treadDeclarationPragmas(reader);\n\t\t\treadVariableSection(reader);\n\t\t\tcontinue;\n\t\t}\n\t\tif (next !== \"EXTENDS\" && next !== \"IMPLEMENTS\") {\n\t\t\treturn;\n\t\t}\n\t\t// CODESYS generic FBs can place these clauses after VAR_GENERIC.\n\t\treadDeclarationPragmas(reader);\n\t\treader.take();\n\t\treadType(reader);\n\t\twhile (reader.consume(\",\")) {\n\t\t\treadType(reader);\n\t\t}\n\t}\n};\n",
19
- "import { blockCommentEnd, lineCommentEnd, stringEnd } from \"@tsplc/iec/st\";\n\nexport interface Token {\n\tkind: \"word\" | \"string\" | \"pragma\" | \"symbol\";\n\tvalue: string;\n\tstart: number;\n\tend: number;\n}\n\nexport class StSyntaxError extends Error {\n\tconstructor(\n\t\tsource: string,\n\t\toffset: number,\n\t\tfilename: string,\n\t\tmessage: string,\n\t) {\n\t\tconst lines = source.slice(0, offset).split(/\\r\\n|\\r|\\n/);\n\t\tsuper(\n\t\t\t`${filename}:${lines.length}:${(lines.at(-1)?.length ?? 0) + 1}: ${message}`,\n\t\t);\n\t\tthis.name = \"StSyntaxError\";\n\t}\n}\n\n/** Keep original offsets: splitting must preserve comments, pragmas and source spelling. */\nexport const tokenize = (source: string, filename = \"<source>\"): Token[] => {\n\tconst tokens: Token[] = [];\n\tlet offset = 0;\n\tconst fail = (start: number, message: string): never => {\n\t\tthrow new StSyntaxError(source, start, filename, message);\n\t};\n\tconst quoted = () => {\n\t\toffset = stringEnd(source, offset) ?? fail(offset, \"Unterminated string\");\n\t};\n\twhile (offset < source.length) {\n\t\tconst start = offset;\n\t\tconst character = source[offset] ?? \"\";\n\t\tif (/\\s|\\uFEFF/.test(character)) {\n\t\t\toffset++;\n\t\t\tcontinue;\n\t\t}\n\t\tif (source.startsWith(\"//\", offset)) {\n\t\t\toffset = lineCommentEnd(source, start);\n\t\t\tcontinue;\n\t\t}\n\t\tif (source.startsWith(\"(*\", offset)) {\n\t\t\toffset =\n\t\t\t\tblockCommentEnd(source, start) ??\n\t\t\t\tfail(start, \"Unterminated block comment\");\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"'\" || character === '\"') {\n\t\t\tquoted();\n\t\t\ttokens.push({\n\t\t\t\tkind: \"string\",\n\t\t\t\tvalue: source.slice(start, offset),\n\t\t\t\tstart,\n\t\t\t\tend: offset,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (character === \"{\") {\n\t\t\toffset++;\n\t\t\twhile (offset < source.length && source[offset] !== \"}\") {\n\t\t\t\tif (source[offset] === \"'\" || source[offset] === '\"') {\n\t\t\t\t\tquoted();\n\t\t\t\t} else {\n\t\t\t\t\toffset++;\n\t\t\t\t}\n\t\t\t}\n\t\t\tif (offset === source.length) {\n\t\t\t\tfail(start, \"Unterminated pragma\");\n\t\t\t}\n\t\t\toffset++;\n\t\t\ttokens.push({\n\t\t\t\tkind: \"pragma\",\n\t\t\t\tvalue: source.slice(start, offset),\n\t\t\t\tstart,\n\t\t\t\tend: offset,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\tif (/[A-Za-z_]/.test(character)) {\n\t\t\toffset++;\n\t\t\twhile (/[A-Za-z_0-9]/.test(source[offset] ?? \"\")) {\n\t\t\t\toffset++;\n\t\t\t}\n\t\t\ttokens.push({\n\t\t\t\tkind: \"word\",\n\t\t\t\tvalue: source.slice(start, offset).toUpperCase(),\n\t\t\t\tstart,\n\t\t\t\tend: offset,\n\t\t\t});\n\t\t\tcontinue;\n\t\t}\n\t\toffset++;\n\t\tconst pair = source.slice(start, offset + 1);\n\t\tif ([\":=\", \"=>\", \"..\", \"<=\", \">=\", \"<>\", \"**\"].includes(pair)) {\n\t\t\toffset++;\n\t\t}\n\t\ttokens.push({\n\t\t\tkind: \"symbol\",\n\t\t\tvalue: source.slice(start, offset),\n\t\t\tstart,\n\t\t\tend: offset,\n\t\t});\n\t}\n\treturn tokens;\n};\n",
20
23
  "import { StSyntaxError, type Token, tokenize } from \"./lexer\";\n\n/** Traverse tokens without losing the source offsets needed for an exact split. */\nexport const createTokenReader = (source: string, filename: string) => {\n\tconst tokens = tokenize(source, filename);\n\tlet index = 0;\n\tconst peek = (ahead = 0) => tokens[index + ahead];\n\tconst fail = (message: string, token = peek()): never => {\n\t\tthrow new StSyntaxError(\n\t\t\tsource,\n\t\t\ttoken?.start ?? source.length,\n\t\t\tfilename,\n\t\t\tmessage,\n\t\t);\n\t};\n\tconst take = (): Token => {\n\t\tconst token = peek();\n\t\tif (!token) {\n\t\t\treturn fail(\"Unexpected end of declaration\");\n\t\t}\n\t\tindex++;\n\t\treturn token;\n\t};\n\tconst expect = (value: string) => {\n\t\tif (peek()?.value !== value) {\n\t\t\tfail(`Expected ${value}`);\n\t\t}\n\t\treturn take();\n\t};\n\tconst consume = (value: string) => {\n\t\tif (peek()?.value === value) {\n\t\t\treturn take();\n\t\t}\n\t};\n\n\treturn {\n\t\tsource,\n\t\tfilename,\n\t\ttokens,\n\t\tpeek,\n\t\ttake,\n\t\texpect,\n\t\tconsume,\n\t\tfail,\n\t\tget index() {\n\t\t\treturn index;\n\t\t},\n\t\t// The declaration ends at the last consumed token, before any body whitespace.\n\t\tget end() {\n\t\t\treturn tokens[index - 1]?.end ?? 0;\n\t\t},\n\t};\n};\n\nexport type TokenReader = ReturnType<typeof createTokenReader>;\n",
21
- "import { ioArray, ioScalarBits, sizePrefix } from \"@tsplc/iec\";\nimport { qualifiers, variableSections } from \"@tsplc/iec/st\";\nimport type { SourceObject } from \"./sources.ts\";\nimport { tokenize, type Token } from \"./st/lexer.ts\";\n\nexport interface DirectIoBinding {\n\taddress: string;\n\ttype?: string;\n}\nconst span = (type: string) => ioArray(type) ?? { element: type, length: 1 };\n// Direct addresses by the width of one element; 64-bit types have no direct form.\nconst addressSize = (type: string) => {\n\tconst bits = ioScalarBits(type);\n\treturn bits === undefined || bits === 64 ? undefined : sizePrefix(bits);\n};\n\n/** Apply the shared mapping to declarations in memory; authored ST stays untouched. */\nexport function bindStructuredTextIo(\n\tobjects: SourceObject[],\n\tbindings: Record<string, DirectIoBinding>,\n) {\n\tconst declarations: {\n\t\tobject: SourceObject;\n\t\tname: string;\n\t\tnames: Token[];\n\t\tcolon: Token;\n\t\ttype: string;\n\t}[] = [];\n\tconst visit = (object: SourceObject) => {\n\t\tconst tokens = tokenize(object.declaration, object.source);\n\t\tlet section = false;\n\t\tlet start = 0;\n\t\tfor (const [index, token] of tokens.entries()) {\n\t\t\tif (variableSections.has(token.value)) {\n\t\t\t\tsection = true;\n\t\t\t\tstart = index + 1;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (token.value === \"END_VAR\") {\n\t\t\t\tsection = false;\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tif (!section || token.value !== \";\") {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst part = tokens\n\t\t\t\t.slice(start, index)\n\t\t\t\t.filter((t) => t.kind !== \"pragma\");\n\t\t\tstart = index + 1;\n\t\t\tconst colon = part.find((t) => t.value === \":\");\n\t\t\tif (!colon) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst colonIndex = part.indexOf(colon);\n\t\t\tif (colonIndex < 1) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst names = part\n\t\t\t\t.slice(0, colonIndex)\n\t\t\t\t.filter(\n\t\t\t\t\t(t) =>\n\t\t\t\t\t\tt.kind === \"word\" && !qualifiers.has(t.value) && t.value !== \"AT\",\n\t\t\t\t);\n\t\t\tconst at = part.find((t) => t.value === \"AT\");\n\t\t\tconst variables = at ? names.filter((t) => t.start < at.start) : names;\n\t\t\tconst initializer = part.findIndex(\n\t\t\t\t(t, index) => index > colonIndex && t.value === \":=\",\n\t\t\t);\n\t\t\tconst typeTokens = part.slice(\n\t\t\t\tcolonIndex + 1,\n\t\t\t\tinitializer < 0 ? undefined : initializer,\n\t\t\t);\n\t\t\tconst [first] = typeTokens;\n\t\t\tconst last = typeTokens.at(-1);\n\t\t\tconst type =\n\t\t\t\tfirst && last\n\t\t\t\t\t? object.declaration\n\t\t\t\t\t\t\t.slice(first.start, last.end)\n\t\t\t\t\t\t\t.replace(/\\s+/g, \" \")\n\t\t\t\t\t\t\t.toUpperCase()\n\t\t\t\t\t: \"\";\n\t\t\tfor (const name of variables) {\n\t\t\t\tdeclarations.push({\n\t\t\t\t\tobject,\n\t\t\t\t\tname: name.value,\n\t\t\t\t\tnames: variables,\n\t\t\t\t\tcolon,\n\t\t\t\t\ttype,\n\t\t\t\t});\n\t\t\t}\n\t\t}\n\t\tobject.children.forEach(visit);\n\t};\n\tobjects.forEach(visit);\n\tconst edits = new Map<\n\t\tSourceObject,\n\t\t{ start: number; end: number; text: string }[]\n\t>();\n\tfor (const [symbol, binding] of Object.entries(bindings)) {\n\t\tconst parts = symbol.toUpperCase().split(\".\");\n\t\tif (parts.length > 2) {\n\t\t\tthrow new Error(\n\t\t\t\t`${symbol}: direct IO maps a scalar declaration, not a nested field.`,\n\t\t\t);\n\t\t}\n\t\tconst matches = declarations.filter(\n\t\t\t(d) =>\n\t\t\t\td.name === parts.at(-1) &&\n\t\t\t\t(parts.length === 1 || d.object.name.toUpperCase() === parts[0]),\n\t\t);\n\t\tconst [declaration, ...others] = matches;\n\t\tif (!declaration || others.length) {\n\t\t\tthrow new Error(\n\t\t\t\t`${symbol}: expected one ST variable declaration, found ${matches.length}. Use Object.Variable to disambiguate.`,\n\t\t\t);\n\t\t}\n\t\tconst [variable, ...siblings] = declaration.names;\n\t\tif (!variable || siblings.length) {\n\t\t\tthrow new Error(`${symbol}: declare mapped IO variables separately.`);\n\t\t}\n\t\tconst declared = span(declaration.type);\n\t\tconst size = addressSize(declared.element);\n\t\tif (\n\t\t\t!size ||\n\t\t\t(declared.length > 1 && declared.element === \"BOOL\") ||\n\t\t\tbinding.address[2] !== size\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`${symbol}: ${declaration.type} is incompatible with ${binding.address}.`,\n\t\t\t);\n\t\t}\n\t\tconst expected =\n\t\t\tbinding.type && span(binding.type.replace(/\\s+/g, \" \").toUpperCase());\n\t\tif (\n\t\t\texpected &&\n\t\t\t(expected.element !== declared.element ||\n\t\t\t\texpected.length !== declared.length)\n\t\t) {\n\t\t\tthrow new Error(\n\t\t\t\t`${symbol}: expected ${binding.type}, found ${declaration.type}.`,\n\t\t\t);\n\t\t}\n\t\tconst list = edits.get(declaration.object) ?? [];\n\t\tconst start = variable.end;\n\t\tif (list.some((e) => e.start === start)) {\n\t\t\tthrow new Error(`${symbol}: the variable has more than one IO binding.`);\n\t\t}\n\t\tlist.push({\n\t\t\tstart,\n\t\t\tend: declaration.colon.start,\n\t\t\ttext: ` AT ${binding.address} `,\n\t\t});\n\t\tedits.set(declaration.object, list);\n\t}\n\tfor (const [object, list] of edits) {\n\t\tfor (const edit of list.sort((a, b) => b.start - a.start)) {\n\t\t\tobject.declaration =\n\t\t\t\tobject.declaration.slice(0, edit.start) +\n\t\t\t\tedit.text +\n\t\t\t\tobject.declaration.slice(edit.end);\n\t\t}\n\t}\n}\n",
22
- "export { buildProject } from \"./build\";\nexport {\n\ttype CodesysBuildConfig,\n\ttype CyclicTask,\n\tconfigSchema,\n\tdefineBuildConfig as defineConfig,\n\tloadConfig,\n\ttype ResolvedConfig,\n\tresolveConfig,\n} from \"@tsplc/config/build\";\nexport {\n\ttype ControllerLogin,\n\tfindControllerLogin,\n\tinspectController,\n\topenControllerLogin,\n\tstartWarmController,\n\tupdateController,\n\tupdateWarmController,\n} from \"./controller-online\";\nexport {\n\ttype ControllerResult,\n\texplicitDownload,\n\tfailureReason,\n\ttype LoginCommand,\n\tloginCommandSchema,\n\ttype LoginResult,\n\tloginResultSchema,\n} from \"./controller-protocol\";\nexport {\n\ttype CodesysCompilerDiagnostic,\n\tCodesysCompilerError,\n} from \"./diagnostics\";\nexport { rawEngineeringSettings } from \"./engineering-settings\";\nexport { runProject } from \"./run\";\nexport { loadSources, type SourceObject } from \"./sources\";\nexport { StSyntaxError } from \"./st/lexer\";\nexport { type ObjectKind, type ParsedSource, parseSource } from \"./st/parse\";\n\nexport {\n\tinstallLibraries,\n\tvalidateLibrary,\n\tlibraryIndex,\n\ttype InstalledLibrary,\n} from \"./libraries.ts\";\n\nexport {\n\tconfigureDocker,\n\tconfigureGateway,\n\tconfigureRuntime,\n\tgatewayImage,\n} from \"./docker-build.ts\";\nexport { readBuild } from \"./artifacts.ts\";\n",
23
- "import { existsSync } from \"node:fs\";\nimport { createHash, randomUUID } from \"node:crypto\";\nimport { mkdir, mkdtemp, readFile, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { posix, resolve } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { z } from \"zod\";\nimport { dockerImage, type ResolvedConfig } from \"@tsplc/config/build\";\nimport {\n\ttype Baseline,\n\ttype ControllerCredentials,\n\ttype ControllerResult,\n\tcontrollerResultSchema,\n\tcontrollerTarget,\n\tfailureReason,\n\timageIdSchema,\n\ttype LoginCommand,\n\tloginResultSchema,\n\tsameBaseline,\n\ttracebackFailure,\n\ttype warmOperationSchema,\n} from \"./controller-protocol.ts\";\nimport { controllerFailureFile } from \"./diagnostics.ts\";\nimport {\n\tcaptureDocker,\n\tprepareContainerRun,\n\trunDocker,\n\twriteOperationRequest,\n} from \"./docker-run.ts\";\n\nexport interface ControllerUpdateOptions {\n\tinitializeUser?: boolean;\n\tread?: string[];\n}\n\n/** The controller user's environment variables, which a container started now passes to CODESYS. */\nconst credentialEnvironment = (config: ResolvedConfig) => {\n\tconst names = config.online?.credentials\n\t\t? [\n\t\t\t\tconfig.online.credentials.usernameEnv,\n\t\t\t\tconfig.online.credentials.passwordEnv,\n\t\t\t]\n\t\t: [];\n\tfor (const name of names) {\n\t\tif (process.env[name] === undefined) {\n\t\t\tthrow new Error(\n\t\t\t\t`Controller credential environment variable ${name} is not set`,\n\t\t\t);\n\t\t}\n\t}\n\treturn names;\n};\n\n/** Checks the settings every engineering connection needs and names its builder image and target. */\nconst controllerConnection = async (config: ResolvedConfig) => {\n\tif (!config.docker || !config.online) {\n\t\tthrow new Error(\n\t\t\t\"Docker image and online gateway/device configuration are required for controller operations\",\n\t\t);\n\t}\n\tconst { stdout } = await captureDocker(\n\t\t[\"image\", \"inspect\", \"--format\", \"{{.Id}}\", dockerImage],\n\t\tconfig.timeouts.hostCommand,\n\t).catch((cause: unknown) => {\n\t\tthrow new Error(\n\t\t\t`Cannot inspect Docker builder image ${dockerImage}. Install and start Docker, then run tsplc-build configure if the image is missing`,\n\t\t\t{ cause },\n\t\t);\n\t});\n\treturn {\n\t\timageId: imageIdSchema.parse(stdout.trim()),\n\t\ttemplateHash: createHash(\"sha256\")\n\t\t\t.update(await readFile(config.template))\n\t\t\t.digest(\"hex\"),\n\t\ttarget: controllerTarget(config, config.online),\n\t};\n};\n\nconst checkReceipt = (\n\tresult: ControllerResult,\n\texpected: Baseline & Pick<ControllerResult, \"operationId\" | \"operation\">,\n\tdiagnostics: string,\n) => {\n\tif (\n\t\tresult.operationId !== expected.operationId ||\n\t\tresult.operation !== expected.operation ||\n\t\t!sameBaseline(result, expected)\n\t) {\n\t\tthrow new Error(\n\t\t\t`Controller receipt does not match this operation's image, template or target. Inspect ${diagnostics} for diagnostics`,\n\t\t);\n\t}\n\treturn result;\n};\n\nconst controllerOperation = async (\n\tconfig: ResolvedConfig,\n\toperation: ControllerResult[\"operation\"],\n\toptions: ControllerUpdateOptions,\n): Promise<ControllerResult> => {\n\tconst environmentNames = credentialEnvironment(config);\n\tconst { imageId, templateHash, target } = await controllerConnection(config);\n\tconst operationId = randomUUID();\n\tconst requestDirectory = await mkdtemp(\n\t\tresolve(tmpdir(), \"codesys-controller-\"),\n\t);\n\tconst diagnostics = resolve(config.outDir, \".codesys/controller\");\n\tconst failure = resolve(config.outDir, controllerFailureFile);\n\ttry {\n\t\tawait mkdir(config.outDir, { recursive: true });\n\t\tawait rm(failure, { force: true });\n\t\tawait runDocker(\n\t\t\t[\n\t\t\t\t\"run\",\n\t\t\t\t\"--rm\",\n\t\t\t\t...(await prepareContainerRun(config, requestDirectory, {\n\t\t\t\t\tnetwork: target.network,\n\t\t\t\t\tenvironment: environmentNames,\n\t\t\t\t\tsources: operation !== \"inspect\",\n\t\t\t\t})),\n\t\t\t\timageId,\n\t\t\t\toperation,\n\t\t\t\t\"--request\",\n\t\t\t\t\"/input/config.json\",\n\t\t\t\t\"--operation-id\",\n\t\t\t\toperationId,\n\t\t\t\t\"--image-id\",\n\t\t\t\timageId,\n\t\t\t\t...(options.initializeUser ? [\"--initialize-user\"] : []),\n\t\t\t\t...(options.read ? [\"--read\", JSON.stringify(options.read)] : []),\n\t\t\t],\n\t\t\t(status) =>\n\t\t\t\t`Docker controller operation failed (${status}). Inspect ${diagnostics} for diagnostics`,\n\t\t).catch(async (cause: unknown) => {\n\t\t\tif (!existsSync(failure)) {\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t\tconst reason = tracebackFailure(await readFile(failure, \"utf8\"));\n\t\t\tthrow new Error(`${reason}. Inspect ${diagnostics} for diagnostics`, {\n\t\t\t\tcause,\n\t\t\t});\n\t\t});\n\t\tconst result = await readFile(resolve(diagnostics, \"result.json\"), \"utf8\")\n\t\t\t.then((content) => controllerResultSchema.parse(JSON.parse(content)))\n\t\t\t.catch((cause: unknown) => {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Docker did not produce a valid controller receipt. Inspect ${diagnostics} for diagnostics`,\n\t\t\t\t\t{ cause },\n\t\t\t\t);\n\t\t\t});\n\t\treturn checkReceipt(\n\t\t\tresult,\n\t\t\t{ operationId, operation, imageId, templateHash, target },\n\t\t\tdiagnostics,\n\t\t);\n\t} finally {\n\t\tawait rm(requestDirectory, { recursive: true, force: true });\n\t}\n};\n\n/** Download or apply an online change using the original CODESYS Docker compiler. */\nexport const updateController = (\n\tconfig: ResolvedConfig,\n\toperation: \"download\" | \"online-change\",\n\toptions: ControllerUpdateOptions = {},\n) => controllerOperation(config, operation, options);\n\n/** Read the controller using the runner's saved compilation baseline. */\nexport const inspectController = (config: ResolvedConfig, read?: string[]) =>\n\tcontrollerOperation(config, \"inspect\", { read });\n\nconst loginReplySchema = z.discriminatedUnion(\"ok\", [\n\tz.strictObject({ ok: z.literal(true), result: z.unknown() }),\n\tz.strictObject({ ok: z.literal(false), error: z.string() }),\n]);\n\n/** The ports login and warm containers serve on, inside the container. */\nconst loginPort = 4851;\nconst warmPort = 4852;\n\nconst docker = (args: string[], timeout: number) =>\n\tcaptureDocker(args, timeout).then(({ stdout }) => stdout.trim());\n\n/** The end of container `name`'s output, which shows why it stopped. */\nconst recentLogs = async (name: string, timeout: number) => {\n\tconst logs = await captureDocker([\"logs\", \"--tail\", \"40\", name], timeout);\n\treturn `${logs.stdout}${logs.stderr}`;\n};\n\nconst isRunning = async (name: string, timeout: number) =>\n\t(await docker(\n\t\t[\"container\", \"ls\", \"--quiet\", \"--filter\", `name=^${name}$`],\n\t\ttimeout,\n\t)) !== \"\";\n\n/**\n * Calls the server builder container `name` runs on `port`. The container's internal network\n * publishes no ports, so the request goes through `docker exec`; the body, which can hold\n * credentials, through its standard input.\n */\nconst callContainer = async (\n\tname: string,\n\tport: number,\n\tmethod: \"GET\" | \"POST\" | \"DELETE\",\n\tbody?: unknown,\n) => {\n\tconst child = Bun.spawn(\n\t\t[\n\t\t\t\"docker\",\n\t\t\t\"exec\",\n\t\t\t...(body === undefined ? [] : [\"--interactive\"]),\n\t\t\tname,\n\t\t\t\"curl\",\n\t\t\t\"--silent\",\n\t\t\t\"--show-error\",\n\t\t\t...(method === \"GET\" ? [\"--max-time\", \"5\"] : []),\n\t\t\t\"--request\",\n\t\t\tmethod,\n\t\t\t...(body === undefined\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t\"--header\",\n\t\t\t\t\t\t\"Content-Type: application/json\",\n\t\t\t\t\t\t\"--data-binary\",\n\t\t\t\t\t\t\"@-\",\n\t\t\t\t\t]),\n\t\t\t`http://127.0.0.1:${port}/`,\n\t\t],\n\t\t{\n\t\t\tstdin: body === undefined ? \"ignore\" : new Blob([JSON.stringify(body)]),\n\t\t\tstdout: \"pipe\",\n\t\t\tstderr: \"pipe\",\n\t\t},\n\t);\n\tconst [output, errors, code] = await Promise.all([\n\t\tnew Response(child.stdout).text(),\n\t\tnew Response(child.stderr).text(),\n\t\tchild.exited,\n\t]);\n\tif (code !== 0) {\n\t\tthrow new Error(errors.trim() || `docker exec failed (${code})`);\n\t}\n\tconst reply = loginReplySchema.parse(JSON.parse(output));\n\tif (!reply.ok) {\n\t\tthrow new Error(reply.error);\n\t}\n\treturn reply.result;\n};\n\n/** The container answers once its server listens, which for a login is once CODESYS has logged in. */\nconst answers = (name: string, port: number) =>\n\tcallContainer(name, port, \"GET\").then(\n\t\t() => true,\n\t\t() => false,\n\t);\n\n/** A logout takes seconds; one still running after this waits on a worker that stopped answering. */\nconst logoutTimeout = 60_000;\n\n/** A login held open in builder container `name`; it ends with `close` or when the container stops. */\nconst attachLogin = (name: string, timeout: number) => ({\n\tname,\n\tready: () => answers(name, loginPort),\n\tsend: async (command: LoginCommand) =>\n\t\tloginResultSchema.parse(\n\t\t\tawait callContainer(name, loginPort, \"POST\", command),\n\t\t),\n\t/**\n\t * Logs out and removes the container. A login that can't log out, such as one whose CODESYS\n\t * worker died, still has its container removed, and returns why it couldn't.\n\t */\n\tclose: async () => {\n\t\tconst logout = async () => {\n\t\t\tawait callContainer(name, loginPort, \"DELETE\");\n\t\t\tawait docker([\"wait\", name], timeout);\n\t\t};\n\t\tconst failure = await Promise.race([\n\t\t\tlogout().then(() => undefined, failureReason),\n\t\t\tdelay(\n\t\t\t\tlogoutTimeout,\n\t\t\t\t`The login didn't log out within ${logoutTimeout / 1000} s`,\n\t\t\t),\n\t\t]);\n\t\tawait docker([\"rm\", \"--force\", name], timeout);\n\t\treturn failure;\n\t},\n});\nexport type ControllerLogin = ReturnType<typeof attachLogin>;\n\n/** The login in container `name`, if one is running; it outlives the process that opened it. */\nexport const findControllerLogin = async (name: string) =>\n\t(await isRunning(name, 15_000)) ? attachLogin(name, 15_000) : undefined;\n\n/**\n * Logs in to the running application from the saved download baseline, in a detached builder\n * container named `name`. Commands then take seconds instead of a CODESYS start each.\n */\nexport const openControllerLogin = async (\n\tconfig: ResolvedConfig,\n\tname: string,\n) => {\n\tconst environmentNames = credentialEnvironment(config);\n\tconst { imageId, target } = await controllerConnection(config);\n\tconst timeout = config.timeouts.hostCommand;\n\t// A login that failed to open leaves its stopped container for diagnostics until the next one.\n\tawait docker([\"rm\", \"--force\", name], timeout);\n\t// The request is overwritten in place: a bind mount of a recreated directory can still show\n\t// Docker Desktop's cached, empty view of the deleted one.\n\tconst requestDirectory = resolve(config.outDir, \".codesys/login-request\");\n\tawait mkdir(requestDirectory, { recursive: true });\n\tawait docker(\n\t\t[\n\t\t\t\"run\",\n\t\t\t\"--detach\",\n\t\t\t\"--name\",\n\t\t\tname,\n\t\t\t...(await prepareContainerRun(config, requestDirectory, {\n\t\t\t\tnetwork: target.network,\n\t\t\t\tenvironment: environmentNames,\n\t\t\t\tsources: false,\n\t\t\t})),\n\t\t\timageId,\n\t\t\t\"login\",\n\t\t\t\"--request\",\n\t\t\t\"/input/config.json\",\n\t\t\t\"--image-id\",\n\t\t\timageId,\n\t\t\t\"--port\",\n\t\t\tString(loginPort),\n\t\t],\n\t\ttimeout,\n\t);\n\tconst login = attachLogin(name, timeout);\n\tconst deadline = Date.now() + config.timeouts.startup + config.timeouts.build;\n\twhile (Date.now() < deadline) {\n\t\tif (!(await isRunning(name, timeout))) {\n\t\t\tthrow new Error(\n\t\t\t\t`The controller login failed:\\n${await recentLogs(name, timeout)}`,\n\t\t\t);\n\t\t}\n\t\tif (await login.ready()) {\n\t\t\treturn login;\n\t\t}\n\t\tawait delay(2000);\n\t}\n\tawait docker([\"rm\", \"--force\", name], timeout);\n\tthrow new Error(\"The controller login did not open in time\");\n};\n\n/** Builder container `name`, running warm on this image, target and settings, started if needed. */\nconst warmController = async (\n\tconfig: ResolvedConfig,\n\tname: string,\n\tconnection: Awaited<ReturnType<typeof controllerConnection>>,\n) => {\n\tconst timeout = config.timeouts.hostCommand;\n\tconst { imageId, target } = connection;\n\tconst settings = createHash(\"sha256\")\n\t\t.update(\n\t\t\tJSON.stringify({\n\t\t\t\timageId,\n\t\t\t\ttarget,\n\t\t\t\ttimeouts: config.timeouts,\n\t\t\t\tdocker: config.docker,\n\t\t\t}),\n\t\t)\n\t\t.digest(\"hex\");\n\tconst label = `tsplc.warm=${settings}`;\n\tconst running = async () =>\n\t\t(await docker(\n\t\t\t[\n\t\t\t\t\"container\",\n\t\t\t\t\"ls\",\n\t\t\t\t\"--quiet\",\n\t\t\t\t\"--filter\",\n\t\t\t\t`name=^${name}$`,\n\t\t\t\t\"--filter\",\n\t\t\t\t`label=${label}`,\n\t\t\t],\n\t\t\ttimeout,\n\t\t)) !== \"\";\n\t// One whose CODESYS died, which its server reports, is replaced too.\n\tif (!(await running()) || !(await answers(name, warmPort))) {\n\t\tawait docker([\"rm\", \"--force\", name], timeout);\n\t\t// Its own request: the operations' configs come later, one per release.\n\t\tconst requestDirectory = resolve(config.outDir, \".codesys/warm-request\");\n\t\tawait mkdir(requestDirectory, { recursive: true });\n\t\tawait docker(\n\t\t\t[\n\t\t\t\t\"run\",\n\t\t\t\t\"--detach\",\n\t\t\t\t\"--name\",\n\t\t\t\tname,\n\t\t\t\t\"--label\",\n\t\t\t\tlabel,\n\t\t\t\t...(await prepareContainerRun(config, requestDirectory, {\n\t\t\t\t\tnetwork: target.network,\n\t\t\t\t\tsources: false,\n\t\t\t\t})),\n\t\t\t\timageId,\n\t\t\t\t\"warm\",\n\t\t\t\t\"--request\",\n\t\t\t\t\"/input/config.json\",\n\t\t\t\t\"--image-id\",\n\t\t\t\timageId,\n\t\t\t\t\"--port\",\n\t\t\t\tString(warmPort),\n\t\t\t],\n\t\t\ttimeout,\n\t\t);\n\t}\n\tconst deadline = Date.now() + config.timeouts.startup;\n\twhile (Date.now() < deadline) {\n\t\tif (!(await running())) {\n\t\t\tthrow new Error(\n\t\t\t\t`CODESYS failed to start:\\n${await recentLogs(name, timeout)}`,\n\t\t\t);\n\t\t}\n\t\tif (await answers(name, warmPort)) {\n\t\t\treturn;\n\t\t}\n\t\tawait delay(2000);\n\t}\n\tawait docker([\"rm\", \"--force\", name], timeout);\n\tthrow new Error(\"CODESYS did not start in time\");\n};\n\n/** Starts warm builder container `name` ahead of the first operation, unless it already runs. */\nexport const startWarmController = async (\n\tconfig: ResolvedConfig,\n\tname: string,\n) => {\n\tawait warmController(config, name, await controllerConnection(config));\n};\n\n/**\n * A download or online change in builder container `name`, which keeps CODESYS running between\n * operations so each skips starting the container, Wine and CODESYS. The first operation, or one\n * with a new image, target or settings, starts it. Credentials go to CODESYS for this operation only.\n */\nexport const updateWarmController = async (\n\tconfig: ResolvedConfig,\n\tname: string,\n\toperation: \"download\" | \"online-change\",\n\toptions: {\n\t\tinitializeUser?: boolean;\n\t\tcredentials?: ControllerCredentials;\n\t} = {},\n): Promise<ControllerResult> => {\n\tconst connection = await controllerConnection(config);\n\tawait warmController(config, name, connection);\n\tconst operationId = randomUUID();\n\tconst diagnostics = resolve(config.outDir, \".codesys/controller\");\n\tconst directory = resolve(config.outDir, \".codesys/requests\", operationId);\n\ttry {\n\t\tconst request = await writeOperationRequest(\n\t\t\tconfig,\n\t\t\tdirectory,\n\t\t\tposix.join(\"/output/.codesys/requests\", operationId),\n\t\t);\n\t\tconst result = await callContainer(name, warmPort, \"POST\", {\n\t\t\toperation,\n\t\t\toperationId,\n\t\t\trequest,\n\t\t\tinitializeUser: options.initializeUser ?? false,\n\t\t\tcredentials: options.credentials,\n\t\t} satisfies z.input<typeof warmOperationSchema>).catch((error: unknown) => {\n\t\t\tthrow new Error(\n\t\t\t\t`${failureReason(error)}. Inspect ${diagnostics} for diagnostics`,\n\t\t\t\t{\n\t\t\t\t\tcause: error,\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t\treturn checkReceipt(\n\t\t\tcontrollerResultSchema.parse(result),\n\t\t\t{\n\t\t\t\toperationId,\n\t\t\t\toperation,\n\t\t\t\timageId: connection.imageId,\n\t\t\t\ttemplateHash: connection.templateHash,\n\t\t\t\ttarget: connection.target,\n\t\t\t},\n\t\t\tdiagnostics,\n\t\t);\n\t} finally {\n\t\tawait rm(directory, { recursive: true, force: true });\n\t}\n};\n",
24
- "// What the host and the builder container exchange for controller operations: the receipt,\n// the target a baseline is bound to, warm and login commands, and how failures are worded.\nimport { createHash } from \"node:crypto\";\nimport { z } from \"zod\";\nimport {\n\tcontrollerSchema,\n\tsha256Digest,\n\ttcpPort,\n\ttype ResolvedConfig,\n} from \"@tsplc/config/build\";\n\nexport const imageIdSchema = z.string().regex(/^sha256:[a-f0-9]{64}$/);\nconst endpointSchema = z.strictObject({\n\thost: z.string().nonempty(),\n\tport: tcpPort,\n});\nexport const controllerResultSchema = z.strictObject({\n\tschemaVersion: z.literal(1),\n\toperationId: z.uuid(),\n\toperation: z.enum([\"download\", \"online-change\", \"inspect\"]),\n\timageId: imageIdSchema,\n\ttemplateHash: sha256Digest,\n\ttarget: z.strictObject({\n\t\tnetwork: z.string().nonempty(),\n\t\tgateway: endpointSchema,\n\t\tdevice: endpointSchema,\n\t\tcontroller: controllerSchema.optional(),\n\t\tdeviceTree: sha256Digest.optional(),\n\t}),\n\tgeneration: z.string().nonempty(),\n\tapplication: z.string().nonempty(),\n\tapplicationGuid: z.string().nonempty(),\n\tcontrollerIds: z.strictObject({\n\t\tcodeId: z.string().nonempty(),\n\t\tdataId: z.string().nonempty(),\n\t}),\n\tstate: z.string().nonempty(),\n\tvalues: z.record(z.string(), z.string()),\n});\nexport type ControllerResult = z.infer<typeof controllerResultSchema>;\nexport const controllerCredentialsSchema = z.strictObject({\n\tusername: z.string().nonempty(),\n\tpassword: z.string().nonempty(),\n});\nexport type ControllerCredentials = z.infer<typeof controllerCredentialsSchema>;\n\n/** One operation for the warm builder container; `request` is the container path of its config. */\nexport const warmOperationSchema = z.strictObject({\n\toperation: z.enum([\"download\", \"online-change\"]),\n\toperationId: z.uuid(),\n\trequest: z.string().nonempty(),\n\tinitializeUser: z.boolean(),\n\tcredentials: controllerCredentialsSchema.optional(),\n});\n\n/**\n * The failure a Python traceback ends with, as `Type: message`: everything after its last frame, so\n * a message over several lines, such as one CODESYS error per line, stays whole. Other errors pass unchanged.\n */\nexport const tracebackFailure = (traceback: string) => {\n\tconst text = traceback.trim();\n\tconst lastFrame = text.lastIndexOf(\"\\n File \");\n\tif (lastFrame === -1) {\n\t\treturn text;\n\t}\n\t// Python prints the frame's source line under it, indented further, when it has the source.\n\tconst [, ...rest] = text.slice(lastFrame + 1).split(\"\\n\");\n\treturn (rest[0]?.startsWith(\" \") ? rest.slice(1) : rest).join(\"\\n\");\n};\n\n/** The message of the failure a worker traceback ends with, without its exception type. */\nexport const failureReason = (error: unknown) =>\n\ttracebackFailure(\n\t\terror instanceof Error ? error.message : String(error),\n\t).replace(/^\\w+: /, \"\");\n\n/**\n * What a download binds the controller to. An online change needs the same connection, controller\n * and device tree, because it only recompiles the program into the downloaded project.\n */\nexport const controllerTarget = (\n\tconfig: ResolvedConfig,\n\tonline: NonNullable<ResolvedConfig[\"online\"]>,\n) => ({\n\tnetwork: online.network,\n\tgateway: online.gateway,\n\tdevice: online.device,\n\tcontroller: config.controller,\n\t...(config.deviceTree && {\n\t\tdeviceTree: createHash(\"sha256\")\n\t\t\t.update(JSON.stringify(config.deviceTree))\n\t\t\t.digest(\"hex\"),\n\t}),\n});\n\nexport type Baseline = Pick<\n\tControllerResult,\n\t\"imageId\" | \"templateHash\" | \"target\"\n>;\n\n/** Whether two controller states share an image, template and target, so one can follow the other. */\nexport const sameBaseline = (state: Baseline, expected: Baseline) =>\n\tstate.imageId === expected.imageId &&\n\tstate.templateHash === expected.templateHash &&\n\tJSON.stringify(state.target) === JSON.stringify(expected.target);\n\n/**\n * Ends every refusal that only a full download resolves, so callers can offer one. The Python\n * online operations end theirs with the same words.\n */\nexport const explicitDownload = \"use an explicit download\";\n\nexport const loginCommandSchema = z.discriminatedUnion(\"command\", [\n\tz.strictObject({ command: z.literal(\"state\") }),\n\tz.strictObject({\n\t\tcommand: z.literal(\"read\"),\n\t\texpressions: z.array(z.string().nonempty()).nonempty(),\n\t}),\n\tz.strictObject({\n\t\tcommand: z.enum([\"write\", \"force\"]),\n\t\tvalues: z.record(z.string().nonempty(), z.string().nonempty()),\n\t}),\n\t// No expressions unforces everything; `restore` puts back the value from before forcing.\n\tz.strictObject({\n\t\tcommand: z.literal(\"unforce\"),\n\t\texpressions: z.array(z.string().nonempty()),\n\t\trestore: z.boolean(),\n\t}),\n\tz.strictObject({ command: z.enum([\"start\", \"stop\"]) }),\n\tz.strictObject({\n\t\tcommand: z.literal(\"reset\"),\n\t\tkind: z.enum([\"Warm\", \"Cold\"]),\n\t}),\n]);\nexport type LoginCommand = z.infer<typeof loginCommandSchema>;\nexport const loginResultSchema = z.union([\n\tz.strictObject({ values: z.record(z.string(), z.string()) }),\n\tz.strictObject({ state: z.string(), forced: z.array(z.string()) }),\n]);\nexport type LoginResult = z.infer<typeof loginResultSchema>;\n",
25
- "import {\n\tcontrollerFor,\n\ttype loadTsplcConfig,\n\trawBuildConfig,\n\tsimulationConfig,\n} from \"@tsplc/config\";\nimport { deviceTree } from \"@tsplc/typegen\";\nimport { loadHardware, resolveIo } from \"@tsplc/typegen/hardware\";\nimport { resolveConfig } from \"@tsplc/config/build\";\nimport { installLibraries } from \"./libraries.ts\";\n\n/**\n * The settings a raw Structured Text project builds, runs and updates its controller with:\n * libraries installed, IO bound and the device tree generated from the project's hardware.\n * A simulated project leaves out the fieldbus IO and device tree, so a plant simulator writes\n * the inputs instead.\n */\nexport const rawEngineeringSettings = async (\n\t{ config, configFile, root }: Awaited<ReturnType<typeof loadTsplcConfig>>,\n\toptions: {\n\t\tcommand: \"build\" | \"run\" | \"download\" | \"online-change\";\n\t\tfrozenLockfile?: boolean;\n\t\tsimulate?: boolean;\n\t},\n) => {\n\tconst hardwareConfig = options.simulate ? simulationConfig(config) : config;\n\tconst build = rawBuildConfig(config);\n\tconst libraries = await installLibraries(config.dependencies, root, {\n\t\tfrozen: options.frozenLockfile,\n\t});\n\tconst hardware = await loadHardware(hardwareConfig, root);\n\treturn resolveConfig(\n\t\t{\n\t\t\t...build,\n\t\t\tlibraries,\n\t\t\tio: resolveIo(hardwareConfig, hardware),\n\t\t\tdeviceTree: await deviceTree(hardwareConfig, hardware),\n\t\t\tcontroller: controllerFor(config, options.command),\n\t\t},\n\t\tconfigFile,\n\t);\n};\n",
26
- "import { createHash, randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { basename, relative, resolve } from \"node:path\";\nimport type { LibraryDependency } from \"@tsplc/config\";\nimport { sha256Digest } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\n\nexport const libraryRegistry = \"https://store-archive.codesys.com/CODESYSLibs\";\nconst libraryFile = /\\.(?:compiled-library(?:-v\\d+)?|library)$/i;\ntype Fetcher = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\nconst installedLibrarySchema = z.object({\n\ttitle: z.string(),\n\tcompany: z.string().optional(),\n\tversion: z.string().optional(),\n\tnamespace: z.string().optional(),\n\tpath: z.string(),\n\tsha256: sha256Digest,\n\turl: z.string().optional(),\n});\nexport type InstalledLibrary = z.infer<typeof installedLibrarySchema>;\nconst libraryLockSchema = z.object({\n\tversion: z.literal(1),\n\tdependencies: z.record(z.string(), installedLibrarySchema),\n});\n\n/** The project's lockfile; a project without one has locked nothing yet. */\nconst readLock = async (\n\tfile: string,\n): Promise<z.infer<typeof libraryLockSchema>> => {\n\tconst text = await readFile(file, \"utf8\").catch((cause: unknown) => {\n\t\tif (\n\t\t\tcause &&\n\t\t\ttypeof cause === \"object\" &&\n\t\t\t\"code\" in cause &&\n\t\t\tcause.code === \"ENOENT\"\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\tthrow cause;\n\t});\n\tif (text === undefined) {\n\t\treturn { version: 1, dependencies: {} };\n\t}\n\tconst lock = libraryLockSchema.safeParse(JSON.parse(text));\n\tif (!lock.success) {\n\t\tthrow new Error(\"Invalid tsplc.lock.json.\", { cause: lock.error });\n\t}\n\treturn lock.data;\n};\nconst hash = (data: Uint8Array) =>\n\tcreateHash(\"sha256\").update(data).digest(\"hex\");\nconst component = (name: string) => {\n\tif (\n\t\t!name.trim() ||\n\t\t/[/\\\\\\0\\r\\n]/.test(name) ||\n\t\tname === \".\" ||\n\t\tname === \"..\"\n\t) {\n\t\tthrow new Error(`Invalid library registry component: ${name}.`);\n\t}\n\treturn encodeURIComponent(name);\n};\nasync function response(url: string, fetcher: Fetcher) {\n\tconst result = await fetcher(url, { signal: AbortSignal.timeout(30_000) });\n\tif (!result.ok) {\n\t\tthrow new Error(`Library registry ${result.status}: ${url}`);\n\t}\n\treturn result;\n}\nexport async function libraryIndex(\n\tpath: string[] = [\"System\"],\n\tfetcher: Fetcher = fetch,\n): Promise<string[]> {\n\tconst url = `${libraryRegistry}/${path.map(component).join(\"/\")}/index`;\n\tconst result = await response(url, fetcher);\n\tconst text = await result.text();\n\tif (text.length > 4_000_000 || /<html/i.test(text)) {\n\t\tthrow new Error(`Invalid library registry index: ${url}`);\n\t}\n\treturn text\n\t\t.split(/\\r?\\n/)\n\t\t.map((s) => s.trim())\n\t\t.filter(Boolean);\n}\nexport async function validateLibrary(\n\ttitle: string,\n\tversion: string,\n\tcompany = \"System\",\n\tfetcher: Fetcher = fetch,\n) {\n\tif (!(await libraryIndex([company], fetcher)).includes(title)) {\n\t\tthrow new Error(\n\t\t\t`Unknown CODESYS library ${company}/${title}. Names are case sensitive.`,\n\t\t);\n\t}\n\tconst versions = await libraryIndex([company, title], fetcher);\n\tif (!versions.includes(version)) {\n\t\tthrow new Error(\n\t\t\t`Unknown version ${version} for ${title}. Available: ${versions.join(\", \")}`,\n\t\t);\n\t}\n\tconst filenames = (\n\t\tawait libraryIndex([company, title, version], fetcher)\n\t).filter((name) => libraryFile.test(name));\n\tconst [filename, ...others] = filenames;\n\tif (filename === undefined || others.length) {\n\t\tthrow new Error(\n\t\t\t`Expected one library payload for ${title} ${version}, received ${filenames.length}.`,\n\t\t);\n\t}\n\treturn {\n\t\tfilename,\n\t\turl: `${libraryRegistry}/${[company, title, version, filename].map(component).join(\"/\")}`,\n\t};\n}\nexport async function installLibraries(\n\tdependencies: Record<string, LibraryDependency>,\n\troot: string,\n\toptions: { frozen?: boolean; fetcher?: Fetcher } = {},\n) {\n\tconst file = resolve(root, \"tsplc.lock.json\");\n\tconst store = resolve(root, \".tsplc/libraries\");\n\tconst previous = await readLock(file);\n\tconst installed: Record<string, InstalledLibrary> = {};\n\tconst fetcher = options.fetcher ?? fetch;\n\tawait mkdir(store, { recursive: true });\n\tfor (const [title, dependency] of Object.entries(dependencies)) {\n\t\tcomponent(title);\n\t\tconst settings =\n\t\t\ttypeof dependency === \"string\" ? { version: dependency } : dependency;\n\t\tconst locked = previous.dependencies[title];\n\t\tconst prior = locked\n\t\t\t? { ...locked, path: resolve(root, locked.path) }\n\t\t\t: undefined;\n\t\tconst same =\n\t\t\tprior !== undefined &&\n\t\t\tprior.namespace === settings.namespace &&\n\t\t\t(\"path\" in settings\n\t\t\t\t? prior.url === undefined && prior.path === resolve(root, settings.path)\n\t\t\t\t: prior.version === settings.version &&\n\t\t\t\t\tprior.company === (settings.company ?? \"System\"));\n\t\tif (same) {\n\t\t\ttry {\n\t\t\t\tif (hash(await readFile(prior.path)) === prior.sha256) {\n\t\t\t\t\tinstalled[title] = prior;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t/* Missing cache can be restored from the exact URL. */\n\t\t\t}\n\t\t\tif (options.frozen) {\n\t\t\t\tthrow new Error(`Locked library ${title} is missing or changed.`);\n\t\t\t}\n\t\t} else if (options.frozen) {\n\t\t\tthrow new Error(`Dependency ${title} differs from tsplc.lock.json.`);\n\t\t}\n\t\tif (\"path\" in settings) {\n\t\t\tconst path = resolve(root, settings.path);\n\t\t\tif (!libraryFile.test(path)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${title}: expected a .library or .compiled-library file.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tinstalled[title] = {\n\t\t\t\ttitle,\n\t\t\t\tpath,\n\t\t\t\tsha256: hash(await readFile(path)),\n\t\t\t\t...(settings.namespace ? { namespace: settings.namespace } : {}),\n\t\t\t};\n\t\t} else {\n\t\t\tconst company = settings.company ?? \"System\";\n\t\t\tconst payload = await validateLibrary(\n\t\t\t\ttitle,\n\t\t\t\tsettings.version,\n\t\t\t\tcompany,\n\t\t\t\tfetcher,\n\t\t\t);\n\t\t\tconst result = await response(payload.url, fetcher);\n\t\t\tconst data = new Uint8Array(await result.arrayBuffer());\n\t\t\tif (!data.length || data.length > 256 * 1024 * 1024) {\n\t\t\t\tthrow new Error(`${title}: invalid library payload size.`);\n\t\t\t}\n\t\t\tconst sha256 = hash(data);\n\t\t\t// An existing lock pins the payload, even if the registry later changes it.\n\t\t\tif (same && prior.sha256 !== sha256) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Registry payload changed for locked library ${title} ${settings.version}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst path = resolve(store, `${sha256}-${basename(payload.filename)}`);\n\t\t\tconst temp = `${path}.${randomUUID()}.tmp`;\n\t\t\tawait writeFile(temp, data, { flag: \"wx\" });\n\t\t\tawait rename(temp, path);\n\t\t\tinstalled[title] = {\n\t\t\t\ttitle,\n\t\t\t\tcompany,\n\t\t\t\tversion: settings.version,\n\t\t\t\tpath,\n\t\t\t\tsha256,\n\t\t\t\turl: payload.url,\n\t\t\t\t...(settings.namespace ? { namespace: settings.namespace } : {}),\n\t\t\t};\n\t\t}\n\t}\n\tif (\n\t\toptions.frozen &&\n\t\tObject.keys(previous.dependencies).some(\n\t\t\t(name) => !Object.hasOwn(dependencies, name),\n\t\t)\n\t) {\n\t\tthrow new Error(\"Removed dependencies differ from tsplc.lock.json.\");\n\t}\n\tif (!options.frozen) {\n\t\tconst temp = `${file}.${randomUUID()}.tmp`;\n\t\tconst portable = Object.fromEntries(\n\t\t\tObject.entries(installed).map(([title, library]) => [\n\t\t\t\ttitle,\n\t\t\t\t{\n\t\t\t\t\t...library,\n\t\t\t\t\tpath: relative(root, library.path).replaceAll(\"\\\\\", \"/\"),\n\t\t\t\t},\n\t\t\t]),\n\t\t);\n\t\tawait writeFile(\n\t\t\ttemp,\n\t\t\tJSON.stringify({ version: 1, dependencies: portable }, null, 2) + \"\\n\",\n\t\t);\n\t\tawait rename(temp, file);\n\t}\n\treturn Object.values(installed);\n}\n",
27
- "import { mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport { z } from \"zod\";\nimport { readBuild } from \"./artifacts\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { runtimeImage } from \"./docker-build\";\nimport { captureDocker } from \"./docker-run\";\nimport { withWorkerLock } from \"./host/codesys-worker\";\nimport { getApplicationStatus } from \"./runtime-status\";\n\nconst stateSchema = z.object({\n\tRunning: z.boolean(),\n\tStartedAt: z.iso.datetime({ offset: true }),\n});\n\nconst service = \"plc\";\n\n/** The Docker Compose project of a tsPLC project: `FrameAssembly` runs as `frame-assembly`. */\nexport const runtimeProject = (name: string) =>\n\tname\n\t\t.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9_-]+/g, \"-\");\n\n/** The local PLC: named volumes keep its provisioning and the installed application across restarts. */\nexport const runtimeDefinition = (name: string) => ({\n\tservices: {\n\t\t[service]: {\n\t\t\timage: runtimeImage,\n\t\t\tplatform: \"linux/amd64\",\n\t\t\thostname: `${runtimeProject(name)}-${service}`,\n\t\t\tinit: true,\n\t\t\tports: [\"127.0.0.1:4840:4840\", \"127.0.0.1:11740:11740\"],\n\t\t\tcap_add: [\"SYS_NICE\", \"IPC_LOCK\"],\n\t\t\tvolumes: [\n\t\t\t\t\"control-conf:/conf/codesyscontrol\",\n\t\t\t\t\"control-data:/data/codesyscontrol\",\n\t\t\t],\n\t\t\trestart: \"no\",\n\t\t},\n\t},\n\tvolumes: { \"control-conf\": {}, \"control-data\": {} },\n});\n\n/** Deploy the completed boot application to the project's local PLC container. */\nexport const runProject = async (\n\tconfig: Pick<ResolvedConfig, \"outDir\" | \"timeouts\">,\n\tname: string,\n) =>\n\twithWorkerLock(config, async () => {\n\t\t// Validate before stopping anything. A missing receipt includes a failed rebuild.\n\t\tconst build = await readBuild(config.outDir).catch((cause: unknown) => {\n\t\t\tthrow new Error(\n\t\t\t\t`No complete build in ${config.outDir}. Run tsplc-build build first.`,\n\t\t\t\t{\n\t\t\t\t\tcause,\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t\tconst definitionDirectory = await mkdtemp(join(tmpdir(), \"tsplc-runtime-\"));\n\t\ttry {\n\t\t\tconst composeFile = join(definitionDirectory, \"compose.yaml\");\n\t\t\t// JSON is valid YAML.\n\t\t\tawait writeFile(composeFile, JSON.stringify(runtimeDefinition(name)));\n\t\t\tconst docker = (...args: string[]) =>\n\t\t\t\tcaptureDocker(args, config.timeouts.runtime);\n\t\t\tconst compose = (...args: string[]) =>\n\t\t\t\tdocker(\n\t\t\t\t\t\"compose\",\n\t\t\t\t\t\"--project-name\",\n\t\t\t\t\truntimeProject(name),\n\t\t\t\t\t\"--file\",\n\t\t\t\t\tcomposeFile,\n\t\t\t\t\t...args,\n\t\t\t\t);\n\t\t\tconst installer = await readFile(\n\t\t\t\tnew URL(\"../runtime/install.sh\", import.meta.url),\n\t\t\t\t\"utf8\",\n\t\t\t);\n\t\t\tconsole.log(\n\t\t\t\t`Installing ${build.application} in Docker service ${service}`,\n\t\t\t);\n\t\t\tawait compose(\"stop\", service);\n\t\t\t// The helper uses the service's volumes without starting its PLC or publishing\n\t\t\t// ports. Its read-only artifact mount is removed with the helper container.\n\t\t\tawait compose(\n\t\t\t\t\"run\",\n\t\t\t\t\"--rm\",\n\t\t\t\t\"--no-deps\",\n\t\t\t\t\"-T\",\n\t\t\t\t\"--volume\",\n\t\t\t\t`${dirname(build.output)}:/codesys-build:ro`,\n\t\t\t\t\"--entrypoint\",\n\t\t\t\t\"/bin/sh\",\n\t\t\t\tservice,\n\t\t\t\t\"-c\",\n\t\t\t\tinstaller,\n\t\t\t\t\"codesys-build-install\",\n\t\t\t\tbuild.application,\n\t\t\t\tbasename(build.output, \".app\"),\n\t\t\t);\n\t\t\tawait compose(\"up\", \"--detach\", \"--no-deps\", service);\n\t\t\tconst containers = (\n\t\t\t\tawait compose(\"ps\", \"--all\", \"--quiet\", service)\n\t\t\t).stdout\n\t\t\t\t.trim()\n\t\t\t\t.split(/\\s+/)\n\t\t\t\t.filter(Boolean);\n\t\t\tif (containers.length !== 1 || !containers[0]) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Expected one container for Compose service ${service}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst container = containers[0];\n\t\t\tconst deadline = Date.now() + config.timeouts.runtime;\n\t\t\twhile (true) {\n\t\t\t\tconst state = stateSchema.parse(\n\t\t\t\t\tJSON.parse(\n\t\t\t\t\t\t(await docker(\"inspect\", \"--format\", \"{{json .State}}\", container))\n\t\t\t\t\t\t\t.stdout,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tif (!state.Running) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Docker service ${service} exited before the application started. Check docker logs ${container}.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// Use this container start time, not the host clock or an old \"started\" event.\n\t\t\t\tconst { stdout: log } = await docker(\n\t\t\t\t\t\"exec\",\n\t\t\t\t\tcontainer,\n\t\t\t\t\t\"/bin/sh\",\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"if [ -f /data/codesyscontrol/codesyscontrol.log ]; then cat /data/codesyscontrol/codesyscontrol.log; fi\",\n\t\t\t\t);\n\t\t\t\tconst status = getApplicationStatus(\n\t\t\t\t\tlog,\n\t\t\t\t\tbuild.application,\n\t\t\t\t\tDate.parse(state.StartedAt),\n\t\t\t\t);\n\t\t\t\tif (status === \"running\") {\n\t\t\t\t\tconsole.log(`${build.application} is running in ${service}`);\n\t\t\t\t\treturn { ...build, container };\n\t\t\t\t}\n\t\t\t\tif (status === \"failed\" || Date.now() >= deadline) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`CODESYS did not start ${build.application}. Runtime log:\\n${log.split(\"\\n\").slice(-25).join(\"\\n\")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait delay(250);\n\t\t\t}\n\t\t} finally {\n\t\t\tawait rm(definitionDirectory, { force: true, recursive: true });\n\t\t}\n\t});\n",
24
+ "import { createHash } from \"node:crypto\";\nimport {\n\taccess,\n\tcopyFile,\n\tmkdir,\n\treadFile,\n\trm,\n\twriteFile,\n} from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { buildFiles, publishBuild, readBuild } from \"./artifacts\";\nimport { writeDeviceTree } from \"./device-tree\";\nimport { buildInDocker } from \"./docker-build\";\nimport type { ProgressOptions } from \"./docker-run.ts\";\nimport { createCodesysWorker, withWorkerLock } from \"./host/codesys-worker\";\nimport { builderImage } from \"./images.ts\";\nimport { importRequest } from \"./import-request\";\nimport { loadSources } from \"./sources\";\n\nexport const buildProject = async (\n\tconfig: ResolvedConfig,\n\t{ progress = \"stdout\" }: ProgressOptions = {},\n) => {\n\tif (!config.docker) {\n\t\tthrow new Error(\"Builds require a Docker builder image.\");\n\t}\n\treturn buildInDocker(config, builderImage, progress);\n};\n\n/** The container runner owns Wine; this operation is not a public host build. */\nexport const buildInContainer = async (config: ResolvedConfig) => {\n\treturn withWorkerLock(config, async () => {\n\t\t// Invalidate the previous build before validation, so run cannot deploy stale\n\t\t// output after a failed rebuild. Keep the last project available for inspection.\n\t\tawait rm(resolve(config.outDir, buildFiles.receipt), { force: true });\n\t\tconst sources = await loadSources(config);\n\t\tawait access(config.template);\n\t\tconst worker = createCodesysWorker(config);\n\t\tconst session = await worker.launch();\n\t\tconst directory = resolve(config.outDir, \".codesys/build\");\n\t\tawait rm(directory, { recursive: true, force: true });\n\t\tawait mkdir(resolve(directory, \"runtime\"), { recursive: true });\n\t\tconst template = resolve(directory, \"Template.project\");\n\t\tawait copyFile(config.template, template);\n\t\tconst deviceTree =\n\t\t\tconfig.deviceTree &&\n\t\t\t(await writeDeviceTree(config.deviceTree, directory));\n\t\tconst request = {\n\t\t\tlibraryReferences: config.libraryReferences,\n\t\t\t...(await importRequest(config, sources)),\n\t\t\t...(deviceTree && { deviceTree }),\n\t\t\t...(config.controller && { controller: config.controller }),\n\t\t\tmode: \"build\",\n\t\t\toutput: buildFiles.output,\n\t\t\tproject: buildFiles.project,\n\t\t\tarchive: buildFiles.archive,\n\t\t\treceipt: buildFiles.receipt,\n\t\t\ttemplate: \"Template.project\",\n\t\t\ttemplateHash: createHash(\"sha256\")\n\t\t\t\t.update(await readFile(template))\n\t\t\t\t.digest(\"hex\"),\n\t\t};\n\t\tawait writeFile(\n\t\t\tresolve(directory, \"request.json\"),\n\t\t\tJSON.stringify(request, null, 2),\n\t\t);\n\t\tconsole.log(`CODESYS build: ${config.outDir}`);\n\t\ttry {\n\t\t\tawait worker.request(session, { action: \"build\" }, config.timeouts.build);\n\t\t\tconst compiled = await readBuild(directory);\n\t\t\tif (\n\t\t\t\tconfig.tasks &&\n\t\t\t\tJSON.stringify(compiled.tasks) !== JSON.stringify(config.tasks)\n\t\t\t) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"CODESYS build receipt does not match the requested task plan\",\n\t\t\t\t);\n\t\t\t}\n\t\t\t// Builds and runs share the lock. Removing the receipt above keeps a failed\n\t\t\t// publication from looking complete even if only some files were replaced.\n\t\t\treturn await publishBuild(compiled, config.outDir);\n\t\t} catch (cause) {\n\t\t\tthrow new Error(\n\t\t\t\t`CODESYS build failed. Inspect ${directory}/progress.log, error.txt and ${session.directory}/codesys.log`,\n\t\t\t\t{ cause },\n\t\t\t);\n\t\t}\n\t});\n};\n",
25
+ "import { createHash, randomUUID } from \"node:crypto\";\nimport { existsSync } from \"node:fs\";\nimport { mkdir, mkdtemp, readFile, rm } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { posix, resolve } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport {\n\ttype Baseline,\n\ttype ControllerCredentials,\n\ttype ControllerResult,\n\tcontrollerResultSchema,\n\tcontrollerTarget,\n\tDownloadRequiredError,\n\texplicitDownload,\n\tfailureReason,\n\timageIdSchema,\n\ttype LoginCommand,\n\tloginResultSchema,\n\trequiresDownload,\n\trollbackSchema,\n\tsameBaseline,\n\tTransferFailedError,\n\ttracebackFailure,\n\ttransferRollback,\n\ttype warmOperationSchema,\n} from \"./controller-protocol.ts\";\nimport { controllerDirectory, jobProgressLog } from \"./controller-session.ts\";\nimport { controllerFailureFile } from \"./diagnostics.ts\";\nimport {\n\ttype ContainerEnvironment,\n\tcaptureDocker,\n\ttype ProgressOptions,\n\tpipeDocker,\n\tprepareContainerRun,\n\trunDocker,\n\twriteOperationRequest,\n} from \"./docker-run.ts\";\nimport { builderImage } from \"./images.ts\";\n\n/** Where an operation reads the controller user's environment variables from; this process's environment by default. */\nexport interface CredentialSource {\n\tenvironment?: Readonly<Record<string, string | undefined>>;\n}\n\nexport interface ControllerUpdateOptions\n\textends ProgressOptions,\n\t\tCredentialSource {\n\tinitializeUser?: boolean;\n\tread?: string[];\n}\n\n/** The controller user's environment variables, which a container started now passes to CODESYS. */\nconst credentialEnvironment = (\n\tconfig: ResolvedConfig,\n\t{ environment = process.env }: CredentialSource,\n): ContainerEnvironment => {\n\tconst names = config.online?.credentials\n\t\t? [\n\t\t\t\tconfig.online.credentials.usernameEnv,\n\t\t\t\tconfig.online.credentials.passwordEnv,\n\t\t\t]\n\t\t: [];\n\treturn Object.fromEntries(\n\t\tnames.map((name) => {\n\t\t\tconst value = environment[name];\n\t\t\tif (value === undefined) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Controller credential environment variable ${name} is not set`,\n\t\t\t\t);\n\t\t\t}\n\t\t\treturn [name, value];\n\t\t}),\n\t);\n};\n\n/** Checks the settings every engineering connection needs and names its builder image and target. */\nconst controllerConnection = async (config: ResolvedConfig) => {\n\tif (!config.docker || !config.online) {\n\t\tthrow new Error(\n\t\t\t\"Docker image and online gateway/device configuration are required for controller operations\",\n\t\t);\n\t}\n\tconst { stdout } = await captureDocker(\n\t\t[\"image\", \"inspect\", \"--format\", \"{{.Id}}\", builderImage],\n\t\tconfig.timeouts.hostCommand,\n\t).catch((cause: unknown) => {\n\t\tthrow new Error(\n\t\t\t`Cannot inspect Docker builder image ${builderImage}. Install and start Docker, then run tsplc-build configure if the image is missing`,\n\t\t\t{ cause },\n\t\t);\n\t});\n\treturn {\n\t\timageId: imageIdSchema.parse(stdout.trim()),\n\t\ttemplateHash: createHash(\"sha256\")\n\t\t\t.update(await readFile(config.template))\n\t\t\t.digest(\"hex\"),\n\t\ttarget: controllerTarget(config, config.online),\n\t};\n};\n\nconst checkReceipt = (\n\tresult: ControllerResult,\n\texpected: Baseline & Pick<ControllerResult, \"operationId\" | \"operation\">,\n\tdiagnostics: string,\n) => {\n\tif (\n\t\tresult.operationId !== expected.operationId ||\n\t\tresult.operation !== expected.operation ||\n\t\t!sameBaseline(result, expected)\n\t) {\n\t\tthrow new Error(\n\t\t\t`Controller receipt does not match this operation's image, template or target. Inspect ${diagnostics} for diagnostics`,\n\t\t);\n\t}\n\treturn result;\n};\n\nconst controllerOperation = async (\n\tconfig: ResolvedConfig,\n\toperation: ControllerResult[\"operation\"],\n\toptions: ControllerUpdateOptions,\n): Promise<ControllerResult> => {\n\tconst credentials = credentialEnvironment(config, options);\n\tconst { imageId, templateHash, target } = await controllerConnection(config);\n\tconst operationId = randomUUID();\n\tconst requestDirectory = await mkdtemp(\n\t\tresolve(tmpdir(), \"codesys-controller-\"),\n\t);\n\tconst diagnostics = controllerDirectory(config.outDir);\n\tconst failure = resolve(config.outDir, controllerFailureFile);\n\ttry {\n\t\tawait mkdir(config.outDir, { recursive: true });\n\t\tawait rm(failure, { force: true });\n\t\tawait runDocker(\n\t\t\t[\n\t\t\t\t\"run\",\n\t\t\t\t\"--rm\",\n\t\t\t\t...(await prepareContainerRun(config, requestDirectory, {\n\t\t\t\t\tnetwork: target.network,\n\t\t\t\t\tenvironment: Object.keys(credentials),\n\t\t\t\t\tsources: operation !== \"inspect\",\n\t\t\t\t})),\n\t\t\t\timageId,\n\t\t\t\toperation,\n\t\t\t\t\"--request\",\n\t\t\t\t\"/input/config.json\",\n\t\t\t\t\"--operation-id\",\n\t\t\t\toperationId,\n\t\t\t\t\"--image-id\",\n\t\t\t\timageId,\n\t\t\t\t...(options.initializeUser ? [\"--initialize-user\"] : []),\n\t\t\t\t...(options.read ? [\"--read\", JSON.stringify(options.read)] : []),\n\t\t\t],\n\t\t\t(status) =>\n\t\t\t\t`Docker controller operation failed (${status}). Inspect ${diagnostics} for diagnostics`,\n\t\t\t{ progress: options.progress ?? \"stdout\", environment: credentials },\n\t\t).catch(async (cause: unknown) => {\n\t\t\tif (!existsSync(failure)) {\n\t\t\t\tthrow cause;\n\t\t\t}\n\t\t\tconst reason = tracebackFailure(await readFile(failure, \"utf8\"));\n\t\t\tthrow new Error(`${reason}. Inspect ${diagnostics} for diagnostics`, {\n\t\t\t\tcause,\n\t\t\t});\n\t\t});\n\t\tconst result = await readFile(resolve(diagnostics, \"result.json\"), \"utf8\")\n\t\t\t.then((content) => controllerResultSchema.parse(JSON.parse(content)))\n\t\t\t.catch((cause: unknown) => {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Docker did not produce a valid controller receipt. Inspect ${diagnostics} for diagnostics`,\n\t\t\t\t\t{ cause },\n\t\t\t\t);\n\t\t\t});\n\t\treturn checkReceipt(\n\t\t\tresult,\n\t\t\t{ operationId, operation, imageId, templateHash, target },\n\t\t\tdiagnostics,\n\t\t);\n\t} finally {\n\t\tawait rm(requestDirectory, { recursive: true, force: true });\n\t}\n};\n\n/** Download or apply an online change using the original CODESYS Docker compiler. */\nexport const updateController = (\n\tconfig: ResolvedConfig,\n\toperation: \"download\" | \"online-change\",\n\toptions: ControllerUpdateOptions = {},\n) => controllerOperation(config, operation, options);\n\n/** Read the controller using the runner's saved compilation baseline. */\nexport const inspectController = (\n\tconfig: ResolvedConfig,\n\tread?: string[],\n\toptions: ProgressOptions & CredentialSource = {},\n) => controllerOperation(config, \"inspect\", { ...options, read });\n\nconst loginReplySchema = z.discriminatedUnion(\"ok\", [\n\tz.strictObject({ ok: z.literal(true), result: z.unknown() }),\n\tz.strictObject({\n\t\tok: z.literal(false),\n\t\terror: z.string(),\n\t\tdownloadRequired: z.literal(true).optional(),\n\t\trollback: rollbackSchema.optional(),\n\t}),\n]);\n\n/** The ports login and warm containers serve on, inside the container. */\nconst loginPort = 4851;\nconst warmPort = 4852;\n\nconst docker = (\n\targs: string[],\n\ttimeout: number,\n\tenvironment: ContainerEnvironment = {},\n) =>\n\tcaptureDocker(args, timeout, environment).then(({ stdout }) => stdout.trim());\n\n/** The end of container `name`'s output, which shows why it stopped. */\nconst recentLogs = async (name: string, timeout: number) => {\n\tconst logs = await captureDocker([\"logs\", \"--tail\", \"40\", name], timeout);\n\treturn `${logs.stdout}${logs.stderr}`;\n};\n\nconst isRunning = async (name: string, timeout: number) =>\n\t(await docker(\n\t\t[\"container\", \"ls\", \"--quiet\", \"--filter\", `name=^${name}$`],\n\t\ttimeout,\n\t)) !== \"\";\n\n/**\n * Calls the server builder container `name` runs on `port`. The container's internal network\n * publishes no ports, so the request goes through `docker exec`; the body, which can hold\n * credentials, through its standard input.\n */\nconst callContainer = async (\n\tname: string,\n\tport: number,\n\tmethod: \"GET\" | \"POST\" | \"DELETE\",\n\tbody?: unknown,\n) => {\n\tconst { stdout, stderr, status } = await pipeDocker(\n\t\t[\n\t\t\t\"exec\",\n\t\t\t...(body === undefined ? [] : [\"--interactive\"]),\n\t\t\tname,\n\t\t\t\"curl\",\n\t\t\t\"--silent\",\n\t\t\t\"--show-error\",\n\t\t\t...(method === \"GET\" ? [\"--max-time\", \"5\"] : []),\n\t\t\t\"--request\",\n\t\t\tmethod,\n\t\t\t...(body === undefined\n\t\t\t\t? []\n\t\t\t\t: [\n\t\t\t\t\t\t\"--header\",\n\t\t\t\t\t\t\"Content-Type: application/json\",\n\t\t\t\t\t\t\"--data-binary\",\n\t\t\t\t\t\t\"@-\",\n\t\t\t\t\t]),\n\t\t\t`http://127.0.0.1:${port}/`,\n\t\t],\n\t\tbody === undefined ? null : JSON.stringify(body),\n\t);\n\tif (status !== 0) {\n\t\tthrow new Error(stderr.trim() || `docker exec failed (${status})`);\n\t}\n\tconst reply = loginReplySchema.parse(JSON.parse(stdout));\n\tif (!reply.ok) {\n\t\tif (reply.rollback) {\n\t\t\tthrow new TransferFailedError(reply.error, reply.rollback);\n\t\t}\n\t\t// Builder images from before `downloadRequired` existed only end such a refusal with these words.\n\t\tthrow reply.downloadRequired || reply.error.endsWith(explicitDownload)\n\t\t\t? new DownloadRequiredError(reply.error)\n\t\t\t: new Error(reply.error);\n\t}\n\treturn reply.result;\n};\n\n/** The container answers once its server listens, which for a login is once CODESYS has logged in. */\nconst answers = (name: string, port: number) =>\n\tcallContainer(name, port, \"GET\").then(\n\t\t() => true,\n\t\t() => false,\n\t);\n\n/** A logout takes seconds; one still running after this waits on a worker that stopped answering. */\nconst logoutTimeout = 60_000;\n\n/** A login held open in builder container `name`; it ends with `close` or when the container stops. */\nconst attachLogin = (name: string, timeout: number) => ({\n\tname,\n\tready: () => answers(name, loginPort),\n\tsend: async (command: LoginCommand) =>\n\t\tloginResultSchema.parse(\n\t\t\tawait callContainer(name, loginPort, \"POST\", command),\n\t\t),\n\t/**\n\t * Logs out and removes the container. A login that can't log out, such as one whose CODESYS\n\t * worker died, still has its container removed, and returns why it couldn't.\n\t */\n\tclose: async () => {\n\t\tconst logout = async () => {\n\t\t\tawait callContainer(name, loginPort, \"DELETE\");\n\t\t\tawait docker([\"wait\", name], timeout);\n\t\t};\n\t\tconst failure = await Promise.race([\n\t\t\tlogout().then(() => undefined, failureReason),\n\t\t\tdelay(\n\t\t\t\tlogoutTimeout,\n\t\t\t\t`The login didn't log out within ${logoutTimeout / 1000} s`,\n\t\t\t),\n\t\t]);\n\t\tawait docker([\"rm\", \"--force\", name], timeout);\n\t\treturn failure;\n\t},\n});\nexport type ControllerLogin = ReturnType<typeof attachLogin>;\n\n/** The login in container `name`, if one is running; it outlives the process that opened it. */\nexport const findControllerLogin = async (name: string) =>\n\t(await isRunning(name, 15_000)) ? attachLogin(name, 15_000) : undefined;\n\n/**\n * Logs in to the running application from the saved download baseline, in a detached builder\n * container named `name`. Commands then take seconds instead of a CODESYS start each.\n */\nexport const openControllerLogin = async (\n\tconfig: ResolvedConfig,\n\tname: string,\n\toptions: CredentialSource = {},\n) => {\n\tconst credentials = credentialEnvironment(config, options);\n\tconst { imageId, target } = await controllerConnection(config);\n\tconst timeout = config.timeouts.hostCommand;\n\t// A login that failed to open leaves its stopped container for diagnostics until the next one.\n\tawait docker([\"rm\", \"--force\", name], timeout);\n\t// The request is overwritten in place: a bind mount of a recreated directory can still show\n\t// Docker Desktop's cached, empty view of the deleted one.\n\tconst requestDirectory = resolve(config.outDir, \".codesys/login-request\");\n\tawait mkdir(requestDirectory, { recursive: true });\n\tawait docker(\n\t\t[\n\t\t\t\"run\",\n\t\t\t\"--detach\",\n\t\t\t\"--name\",\n\t\t\tname,\n\t\t\t...(await prepareContainerRun(config, requestDirectory, {\n\t\t\t\tnetwork: target.network,\n\t\t\t\tenvironment: Object.keys(credentials),\n\t\t\t\tsources: false,\n\t\t\t})),\n\t\t\timageId,\n\t\t\t\"login\",\n\t\t\t\"--request\",\n\t\t\t\"/input/config.json\",\n\t\t\t\"--image-id\",\n\t\t\timageId,\n\t\t\t\"--port\",\n\t\t\tString(loginPort),\n\t\t],\n\t\ttimeout,\n\t\tcredentials,\n\t);\n\tconst login = attachLogin(name, timeout);\n\tconst deadline = Date.now() + config.timeouts.startup + config.timeouts.build;\n\twhile (Date.now() < deadline) {\n\t\tif (!(await isRunning(name, timeout))) {\n\t\t\tthrow new Error(\n\t\t\t\t`The controller login failed:\\n${await recentLogs(name, timeout)}`,\n\t\t\t);\n\t\t}\n\t\tif (await login.ready()) {\n\t\t\treturn login;\n\t\t}\n\t\tawait delay(2000);\n\t}\n\tawait docker([\"rm\", \"--force\", name], timeout);\n\tthrow new Error(\"The controller login did not open in time\");\n};\n\n/** Builder container `name`, running warm on this image, target and settings, started if needed. */\nconst warmController = async (\n\tconfig: ResolvedConfig,\n\tname: string,\n\tconnection: Awaited<ReturnType<typeof controllerConnection>>,\n\treport: (message: string) => void,\n) => {\n\tconst timeout = config.timeouts.hostCommand;\n\tconst { imageId, target } = connection;\n\tconst settings = createHash(\"sha256\")\n\t\t// Each operation brings its own timeouts, so a release that changes them needn't restart CODESYS.\n\t\t.update(JSON.stringify({ imageId, target, docker: config.docker }))\n\t\t.digest(\"hex\");\n\tconst label = `tsplc.warm=${settings}`;\n\tconst running = async () =>\n\t\t(await docker(\n\t\t\t[\n\t\t\t\t\"container\",\n\t\t\t\t\"ls\",\n\t\t\t\t\"--quiet\",\n\t\t\t\t\"--filter\",\n\t\t\t\t`name=^${name}$`,\n\t\t\t\t\"--filter\",\n\t\t\t\t`label=${label}`,\n\t\t\t],\n\t\t\ttimeout,\n\t\t)) !== \"\";\n\t// One whose CODESYS died, which its server reports, is replaced too.\n\tif (!(await running()) || !(await answers(name, warmPort))) {\n\t\treport(\n\t\t\t\"Starting CODESYS: no running builder matches this image, controller and Docker settings, which takes minutes\",\n\t\t);\n\t\tawait docker([\"rm\", \"--force\", name], timeout);\n\t\t// Its own request: the operations' configs come later, one per release.\n\t\tconst requestDirectory = resolve(config.outDir, \".codesys/warm-request\");\n\t\tawait mkdir(requestDirectory, { recursive: true });\n\t\tawait docker(\n\t\t\t[\n\t\t\t\t\"run\",\n\t\t\t\t\"--detach\",\n\t\t\t\t\"--name\",\n\t\t\t\tname,\n\t\t\t\t\"--label\",\n\t\t\t\tlabel,\n\t\t\t\t...(await prepareContainerRun(config, requestDirectory, {\n\t\t\t\t\tnetwork: target.network,\n\t\t\t\t\tsources: false,\n\t\t\t\t})),\n\t\t\t\timageId,\n\t\t\t\t\"warm\",\n\t\t\t\t\"--request\",\n\t\t\t\t\"/input/config.json\",\n\t\t\t\t\"--image-id\",\n\t\t\t\timageId,\n\t\t\t\t\"--port\",\n\t\t\t\tString(warmPort),\n\t\t\t],\n\t\t\ttimeout,\n\t\t);\n\t}\n\tconst deadline = Date.now() + config.timeouts.startup;\n\twhile (Date.now() < deadline) {\n\t\tif (!(await running())) {\n\t\t\tthrow new Error(\n\t\t\t\t`CODESYS failed to start:\\n${await recentLogs(name, timeout)}`,\n\t\t\t);\n\t\t}\n\t\tif (await answers(name, warmPort)) {\n\t\t\treturn;\n\t\t}\n\t\tawait delay(2000);\n\t}\n\tawait docker([\"rm\", \"--force\", name], timeout);\n\tthrow new Error(\"CODESYS did not start in time\");\n};\n\n/**\n * Relays the progress log of one operation, which CODESYS appends to as it works, as messages\n * without their timestamps, until the returned function stops it.\n */\nconst followProgress = (log: string, report: (message: string) => void) => {\n\tconst stopped = new AbortController();\n\tconst done = (async () => {\n\t\tlet offset = 0;\n\t\twhile (!stopped.signal.aborted) {\n\t\t\tawait delay(2000);\n\t\t\tif (!existsSync(log)) {\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\tconst text = await readFile(log, \"utf8\");\n\t\t\tfor (const line of text.slice(offset).split(\"\\n\").filter(Boolean)) {\n\t\t\t\treport(line.replace(/^\\S+Z /, \"\"));\n\t\t\t}\n\t\t\toffset = text.length;\n\t\t}\n\t})();\n\treturn async () => {\n\t\tstopped.abort();\n\t\tawait done;\n\t};\n};\n\n/** Starts warm builder container `name` ahead of the first operation, unless it already runs. */\nexport const startWarmController = async (\n\tconfig: ResolvedConfig,\n\tname: string,\n) => {\n\tawait warmController(\n\t\tconfig,\n\t\tname,\n\t\tawait controllerConnection(config),\n\t\t() => {},\n\t);\n};\n\n/**\n * A download or online change in builder container `name`, which keeps CODESYS running between\n * operations so each skips starting the container, Wine and CODESYS. The first operation, or one\n * with a new image, target or Docker settings, starts it. Credentials go to CODESYS for this\n * operation only. A download that fails mid-transfer throws a `TransferFailedError` naming its rollback.\n */\nexport const updateWarmController = async (\n\tconfig: ResolvedConfig,\n\tname: string,\n\toperation: \"download\" | \"online-change\",\n\toptions: {\n\t\tinitializeUser?: boolean;\n\t\tcredentials?: ControllerCredentials;\n\t\t/** Receives each step CODESYS reports while this operation runs. */\n\t\tonProgress?: (message: string) => void;\n\t} = {},\n): Promise<ControllerResult> => {\n\tconst report = options.onProgress ?? (() => {});\n\tconst connection = await controllerConnection(config);\n\tconst operationId = randomUUID();\n\tconst diagnostics = controllerDirectory(config.outDir);\n\tconst directory = resolve(config.outDir, \".codesys/requests\", operationId);\n\treport(\"Copying the release for CODESYS\");\n\t// A container that has to start takes minutes, which the copy needn't wait for.\n\tconst [request] = await Promise.all([\n\t\twriteOperationRequest(\n\t\t\tconfig,\n\t\t\tdirectory,\n\t\t\tposix.join(\"/output/.codesys/requests\", operationId),\n\t\t),\n\t\twarmController(config, name, connection, report),\n\t]).catch(async (error: unknown) => {\n\t\tawait rm(directory, { recursive: true, force: true });\n\t\tthrow error;\n\t});\n\tconst stopFollowing = options.onProgress\n\t\t? followProgress(\n\t\t\t\tjobProgressLog(config.outDir, operationId),\n\t\t\t\toptions.onProgress,\n\t\t\t)\n\t\t: async () => {};\n\ttry {\n\t\tconst result = await callContainer(name, warmPort, \"POST\", {\n\t\t\toperation,\n\t\t\toperationId,\n\t\t\trequest,\n\t\t\tinitializeUser: options.initializeUser ?? false,\n\t\t\tcredentials: options.credentials,\n\t\t} satisfies z.input<typeof warmOperationSchema>).catch((error: unknown) => {\n\t\t\tconst message = `${failureReason(error)}. Inspect ${diagnostics} for diagnostics`;\n\t\t\tconst rollback = transferRollback(error);\n\t\t\tif (rollback) {\n\t\t\t\tthrow new TransferFailedError(message, rollback, { cause: error });\n\t\t\t}\n\t\t\tthrow requiresDownload(error)\n\t\t\t\t? new DownloadRequiredError(message, { cause: error })\n\t\t\t\t: new Error(message, { cause: error });\n\t\t});\n\t\treturn checkReceipt(\n\t\t\tcontrollerResultSchema.parse(result),\n\t\t\t{\n\t\t\t\toperationId,\n\t\t\t\toperation,\n\t\t\t\timageId: connection.imageId,\n\t\t\t\ttemplateHash: connection.templateHash,\n\t\t\t\ttarget: connection.target,\n\t\t\t},\n\t\t\tdiagnostics,\n\t\t);\n\t} finally {\n\t\tawait stopFollowing();\n\t\tawait rm(directory, { recursive: true, force: true });\n\t}\n};\n",
26
+ "import { createHash, randomUUID } from \"node:crypto\";\nimport { appendFileSync } from \"node:fs\";\nimport { cp, mkdir, readdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { resolve } from \"node:path\";\nimport {\n\tcontrollerBudgets,\n\ttype ResolvedConfig,\n\tsha256Digest,\n} from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport {\n\ttype ControllerCredentials,\n\tcontrollerResultSchema,\n\tcontrollerTarget,\n\tDownloadRequiredError,\n\texplicitDownload,\n\tfailureReason,\n\tloginCommandSchema,\n\trequiresDownload,\n\tsameBaseline,\n\tTransferFailedError,\n\ttracebackFailure,\n\ttransferRollback,\n\twarmOperationSchema,\n} from \"./controller-protocol\";\nimport { writeDeviceTree } from \"./device-tree\";\nimport {\n\tcreateCodesysWorker,\n\ttype PhasedBudget,\n\twithWorkerLock,\n\twithWorkerShutdown,\n\tworkerPhase,\n\twriteJson,\n} from \"./host/codesys-worker\";\nimport { toWindowsPath } from \"./host/windows-path\";\nimport { importRequest } from \"./import-request\";\nimport { loadSources } from \"./sources\";\n\n// Vendor code/data IDs are .NET Guid values derived from the compiler's data;\n// they do not carry RFC UUID version/variant bits.\nconst guid = z\n\t.string()\n\t.regex(/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/i);\nconst pointerSchema = z.strictObject({\n\tschemaVersion: z.literal(1),\n\tgeneration: z.uuid(),\n});\nconst baselineSchema = controllerResultSchema.extend({\n\tobjects: z.array(z.record(z.string(), z.unknown())),\n\tfiles: z.record(z.string(), sha256Digest),\n});\nconst sha256 = (data: Uint8Array) =>\n\tcreateHash(\"sha256\").update(data).digest(\"hex\");\n\nconst guidBytes = (value: string): Buffer => {\n\tconst bytes = Buffer.from(value.replaceAll(\"-\", \"\"), \"hex\");\n\tbytes.subarray(0, 4).reverse();\n\tbytes.subarray(4, 6).reverse();\n\tbytes.subarray(6, 8).reverse();\n\treturn bytes;\n};\n\n/** Hash the complete project directory, including the vendor's downloaded reference. */\nconst projectFiles = async (\n\tdirectory: string,\n): Promise<Record<string, string>> => {\n\tconst files: Record<string, string> = {};\n\tconst visit = async (folder: string, prefix: string) => {\n\t\tfor (const item of await readdir(folder, { withFileTypes: true })) {\n\t\t\tconst name = prefix + item.name;\n\t\t\tif (item.isSymbolicLink()) {\n\t\t\t\tthrow new Error(`Online project state contains a symlink: ${name}`);\n\t\t\t}\n\t\t\tif (item.isDirectory()) {\n\t\t\t\tawait visit(resolve(folder, item.name), `${name}/`);\n\t\t\t} else if (item.isFile()) {\n\t\t\t\tfiles[name] = sha256(await readFile(resolve(folder, item.name)));\n\t\t\t}\n\t\t}\n\t};\n\tawait visit(directory, \"\");\n\treturn Object.fromEntries(\n\t\tObject.entries(files).sort(([a], [b]) => a.localeCompare(b)),\n\t);\n};\n\n/** A build output directory's controller state: download baseline generations, jobs and results. */\nexport const controllerDirectory = (outDir: string) =>\n\tresolve(outDir, \".codesys/controller\");\n\n/** Operation `operationId`'s own output directory, which keeps its progress and descriptions. */\nconst jobOutput = (outDir: string, operationId: string) =>\n\tresolve(controllerDirectory(outDir), \"jobs\", operationId);\n\n/** The progress CODESYS reports for operation `operationId`, one timestamped line per step. */\nexport const jobProgressLog = (outDir: string, operationId: string) =>\n\tresolve(controllerDirectory(jobOutput(outDir, operationId)), \"progress.log\");\n\nconst missingFile = (error: unknown) =>\n\terror instanceof Error && \"code\" in error && error.code === \"ENOENT\";\n\n/**\n * Whether a download baseline exists for an online change: `missing` before the first download,\n * `malformed` when its pointer or committed generation can't be read. A valid baseline can still\n * belong to another image, template or target, which the operation itself refuses.\n */\nexport const controllerBaseline = async (\n\toutDir: string,\n): Promise<\"valid\" | \"missing\" | \"malformed\"> => {\n\tconst root = controllerDirectory(outDir);\n\tconst pointer = await readFile(resolve(root, \"current.json\"), \"utf8\").then(\n\t\t(text) => ({ text }),\n\t\t(error: unknown) => ({ error }),\n\t);\n\tif (\"error\" in pointer) {\n\t\treturn missingFile(pointer.error) ? \"missing\" : \"malformed\";\n\t}\n\ttry {\n\t\tconst { generation } = pointerSchema.parse(JSON.parse(pointer.text));\n\t\tbaselineSchema.parse(\n\t\t\tJSON.parse(\n\t\t\t\tawait readFile(\n\t\t\t\t\tresolve(root, \"generations\", generation, \"manifest.json\"),\n\t\t\t\t\t\"utf8\",\n\t\t\t\t),\n\t\t\t),\n\t\t);\n\t\treturn \"valid\";\n\t} catch {\n\t\treturn \"malformed\";\n\t}\n};\n\n/**\n * Where CODESYS opens and edits an operation's projects inside the builder container: its own\n * filesystem. The output directory is a bind mount of the plant PC's disk, through which each of\n * the many small writes CODESYS makes saving and compiling a large project is slow. Only a\n * committed generation is copied out to it.\n */\nexport const containerScratch = \"/tmp/tsplc-controller\";\n\n/** The committed generation, as its pointer and manifest name it. */\nconst readCommitted = async (root: string) => {\n\tconst pointer = pointerSchema.parse(\n\t\tJSON.parse(await readFile(resolve(root, \"current.json\"), \"utf8\")),\n\t);\n\tconst directory = resolve(root, \"generations\", pointer.generation);\n\tconst baseline = baselineSchema.parse(\n\t\tJSON.parse(await readFile(resolve(directory, \"manifest.json\"), \"utf8\")),\n\t);\n\tif (baseline.generation !== pointer.generation) {\n\t\tthrow new DownloadRequiredError(\n\t\t\t`Downloaded baseline pointer and manifest disagree; ${explicitDownload}`,\n\t\t);\n\t}\n\treturn { baseline, project: resolve(directory, \"project\") };\n};\ntype Committed = Awaited<ReturnType<typeof readCommitted>>;\n\n/** The committed generation, once proven to match this image, template and target. */\nconst committedBaseline = async (\n\troot: string,\n\texpected: Pick<\n\t\tz.infer<typeof baselineSchema>,\n\t\t\"imageId\" | \"templateHash\" | \"target\"\n\t>,\n) => {\n\tconst committed = await readCommitted(root);\n\tif (!sameBaseline(committed.baseline, expected)) {\n\t\tthrow new DownloadRequiredError(\n\t\t\t`Downloaded baseline uses a different image, template, controller or device tree; ${explicitDownload}`,\n\t\t);\n\t}\n\treturn committed;\n};\n\n/**\n * Copies the committed project to `destination`, where CODESYS may write to it, and proves the\n * copy holds the files that were committed, which reads the output directory only once.\n */\nconst copyCommitted = async (committed: Committed, destination: string) => {\n\tawait rm(destination, { recursive: true, force: true });\n\tawait cp(committed.project, destination, { recursive: true });\n\tif (\n\t\tJSON.stringify(await projectFiles(destination)) !==\n\t\tJSON.stringify(committed.baseline.files)\n\t) {\n\t\tthrow new DownloadRequiredError(\n\t\t\t`Saved online project/reference files changed; ${explicitDownload}`,\n\t\t);\n\t}\n};\n\n/** A CODESYS worker that handles the `online` request written to `requestDirectory` when `run`. */\ninterface OnlineWorker {\n\trequestDirectory: string;\n\trun: (budget: PhasedBudget) => Promise<unknown>;\n\t/** A verified copy of baseline generation `baseline` in the scratch directory, which the worker has open. */\n\tprepared?: { baseline: string; generation: string };\n}\n\n/** A worker started for one operation and stopped after it. */\nconst oneShotWorker = (config: ResolvedConfig): OnlineWorker => {\n\tconst worker = createCodesysWorker(config);\n\treturn {\n\t\trequestDirectory: controllerDirectory(config.outDir),\n\t\trun: (budget) =>\n\t\t\twithWorkerShutdown(config, worker, () =>\n\t\t\t\twithWorkerLock(config, async () =>\n\t\t\t\t\tworker.request(await worker.launch(), { action: \"online\" }, budget),\n\t\t\t\t),\n\t\t\t),\n\t};\n};\n\nconst restoreResultSchema = z.object({\n\trestored: z.boolean(),\n\tcontrollerIds: z.strictObject({ codeId: guid, dataId: guid }),\n\tstate: z.string(),\n});\n\n/**\n * Called inside the builder container, while its output-directory flock is held or, for a warm\n * `worker`, while the agent runs nothing else. Without `credentials`, CODESYS reads the controller\n * user from the environment variables `config.online` names. CODESYS works on projects in\n * `scratch`; a download or online change the controller confirms is committed to the output directory.\n */\nexport const runControllerSession = async (\n\tconfig: ResolvedConfig,\n\toperation: \"download\" | \"online-change\" | \"inspect\",\n\toptions: {\n\t\timageId: string;\n\t\toperationId: string;\n\t\tscratch: string;\n\t\tinitializeUser?: boolean;\n\t\tread?: string[];\n\t\tcredentials?: ControllerCredentials;\n\t},\n\tworker?: OnlineWorker,\n) => {\n\tconst settings = config.online;\n\tif (!settings) {\n\t\tthrow new Error(\"Controller operations require online settings\");\n\t}\n\tif (options.initializeUser && operation !== \"download\") {\n\t\tthrow new DownloadRequiredError(\n\t\t\t\"Initial user creation requires an explicit download\",\n\t\t);\n\t}\n\tconst root = controllerDirectory(config.outDir);\n\tawait mkdir(root, { recursive: true });\n\tconst resultPath = resolve(root, \"result.json\");\n\tawait rm(resultPath, { force: true });\n\tconst templateHash = sha256(await readFile(config.template));\n\t// A different image, template, controller or device tree needs a fresh download from the template.\n\tconst target = controllerTarget(config, settings);\n\tconst expected = { imageId: options.imageId, templateHash, target };\n\tconst jobConfig = {\n\t\t...config,\n\t\toutDir: jobOutput(config.outDir, options.operationId),\n\t};\n\t// The job directory keeps this operation's progress and descriptions; the worker its mailbox.\n\tconst jobDirectory = controllerDirectory(jobConfig.outDir);\n\tawait mkdir(jobDirectory, { recursive: true });\n\tconst progressLog = jobProgressLog(config.outDir, options.operationId);\n\t// The host's steps join CODESYS's in the log the agent relays, in the same format.\n\tconst progress = (message: string) =>\n\t\tappendFileSync(\n\t\t\tprogressLog,\n\t\t\t`${new Date().toISOString().replace(/\\.\\d+Z$/, \"Z\")} ${message}\\n`,\n\t\t);\n\tconst online = worker ?? oneShotWorker(jobConfig);\n\tconst { requestDirectory } = online;\n\tawait mkdir(requestDirectory, { recursive: true });\n\tconst opened = online.prepared;\n\tprogress(\"Reading the committed download\");\n\t// A download reuses the baseline when it still fits, and imports only what changed since.\n\tconst committed = await committedBaseline(root, expected).catch(\n\t\t(error: unknown) => {\n\t\t\tif (operation === \"download\") {\n\t\t\t\treturn undefined;\n\t\t\t}\n\t\t\tthrow error;\n\t\t},\n\t);\n\tconst prepared =\n\t\toperation !== \"inspect\" &&\n\t\tcommitted &&\n\t\topened?.baseline === committed.baseline.generation\n\t\t\t? opened\n\t\t\t: undefined;\n\tconst generation = prepared?.generation ?? randomUUID();\n\tconst candidate = resolve(options.scratch, \"generations\", generation);\n\tconst candidateProject = resolve(candidate, \"project\");\n\tconst project = resolve(candidateProject, \"Application.project\");\n\t// Only this container reads it; the worker deletes it once CODESYS has the user.\n\tconst credentialsFile =\n\t\toptions.credentials && `/tmp/tsplc-credentials-${options.operationId}.json`;\n\tconst writeCredentials = async () => {\n\t\tif (credentialsFile) {\n\t\t\tawait writeFile(credentialsFile, JSON.stringify(options.credentials), {\n\t\t\t\tmode: 0o600,\n\t\t\t});\n\t\t}\n\t};\n\tconst phase = resolve(requestDirectory, \"phase\");\n\tconst budget: PhasedBudget = {\n\t\tfile: phase,\n\t\t...controllerBudgets(config.timeouts),\n\t\toverdue: progress,\n\t};\n\tconst windowsPath = (path: string) =>\n\t\ttoWindowsPath(path, config.codesys.wine);\n\t/** Runs one request in the worker and returns the result it wrote. */\n\tconst runRequest = async (request: Record<string, unknown>) => {\n\t\tawait rm(resolve(requestDirectory, \"result.json\"), { force: true });\n\t\tawait rm(phase, { force: true });\n\t\tawait writeCredentials();\n\t\tawait writeFile(\n\t\t\tresolve(requestDirectory, \"request.json\"),\n\t\t\tJSON.stringify(\n\t\t\t\t{\n\t\t\t\t\t...request,\n\t\t\t\t\tonline: settings,\n\t\t\t\t\tprogress: await windowsPath(progressLog),\n\t\t\t\t\tphase: await windowsPath(phase),\n\t\t\t\t\t...(credentialsFile && {\n\t\t\t\t\t\tcredentialsFile: await windowsPath(credentialsFile),\n\t\t\t\t\t}),\n\t\t\t\t},\n\t\t\t\tnull,\n\t\t\t\t2,\n\t\t\t),\n\t\t);\n\t\tawait online.run(budget);\n\t\treturn JSON.parse(\n\t\t\tawait readFile(resolve(requestDirectory, \"result.json\"), \"utf8\"),\n\t\t);\n\t};\n\t/**\n\t * After a download failed mid-transfer, the controller may hold neither application. Downloads\n\t * the committed one again unless the controller still runs it, and describes the outcome. One\n\t * made with another builder image or template is restored too, as the first download after\n\t * updating tsPLC needs; one made for another controller or device tree never is.\n\t */\n\tconst rollBack = async (failure: unknown) => {\n\t\tconst reason = `The download failed during the transfer: ${failureReason(failure)}`;\n\t\tconst previous = await readCommitted(root).then(\n\t\t\t(committed) =>\n\t\t\t\tJSON.stringify(committed.baseline.target) === JSON.stringify(target)\n\t\t\t\t\t? committed\n\t\t\t\t\t: undefined,\n\t\t\t() => undefined,\n\t\t);\n\t\tif (!previous) {\n\t\t\treturn new TransferFailedError(\n\t\t\t\t`${reason}. This agent has committed no download to this controller to restore, so the controller may hold no application: deploy again with a full download`,\n\t\t\t\t\"unavailable\",\n\t\t\t\t{ cause: failure },\n\t\t\t);\n\t\t}\n\t\tconst restore = resolve(options.scratch, \"restore\", options.operationId);\n\t\ttry {\n\t\t\tprogress(\n\t\t\t\t`${reason}. Restoring the last committed download (generation ${previous.baseline.generation})`,\n\t\t\t);\n\t\t\tawait copyCommitted(previous, resolve(restore, \"project\"));\n\t\t\tconst restored = restoreResultSchema.parse(\n\t\t\t\tawait runRequest({\n\t\t\t\t\toperation: \"restore\",\n\t\t\t\t\tproject: await windowsPath(\n\t\t\t\t\t\tresolve(restore, \"project\", \"Application.project\"),\n\t\t\t\t\t),\n\t\t\t\t\tbaseline: previous.baseline,\n\t\t\t\t}),\n\t\t\t);\n\t\t\tif (!restored.restored) {\n\t\t\t\treturn new TransferFailedError(\n\t\t\t\t\t`${reason}. The controller still runs the previous application`,\n\t\t\t\t\t\"intact\",\n\t\t\t\t\t{ cause: failure },\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst changed =\n\t\t\t\tJSON.stringify(restored.controllerIds) !==\n\t\t\t\tJSON.stringify(previous.baseline.controllerIds);\n\t\t\treturn new TransferFailedError(\n\t\t\t\t`${reason}. The controller runs the previous application again, downloaded from the last committed download (generation ${previous.baseline.generation})${changed ? \"; its code/data identity changed, so the next deployment needs a full download\" : \"\"}`,\n\t\t\t\t\"restored\",\n\t\t\t\t{ cause: failure },\n\t\t\t);\n\t\t} catch (restoreFailure) {\n\t\t\treturn new TransferFailedError(\n\t\t\t\t`${reason}. Restoring the previous application failed too: ${failureReason(restoreFailure)}. The controller may hold no application: deploy again with a full download`,\n\t\t\t\t\"failed\",\n\t\t\t\t{ cause: failure },\n\t\t\t);\n\t\t} finally {\n\t\t\tawait rm(restore, { recursive: true, force: true });\n\t\t}\n\t};\n\ttry {\n\t\t// Opens a copy of the baseline unless the worker opened one ahead; a download without one saves the template here.\n\t\tconst previous =\n\t\t\tcommitted && !prepared\n\t\t\t\t? await (async () => {\n\t\t\t\t\t\tprogress(\"Copying the committed project\");\n\t\t\t\t\t\treturn copyCommitted(committed, candidateProject).then(\n\t\t\t\t\t\t\t() => committed,\n\t\t\t\t\t\t\tasync (error: unknown) => {\n\t\t\t\t\t\t\t\tif (operation !== \"download\") {\n\t\t\t\t\t\t\t\t\tthrow error;\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t\tprogress(\n\t\t\t\t\t\t\t\t\t`${failureReason(error)}; downloading from the template`,\n\t\t\t\t\t\t\t\t);\n\t\t\t\t\t\t\t\tawait rm(candidateProject, { recursive: true, force: true });\n\t\t\t\t\t\t\t\treturn undefined;\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t);\n\t\t\t\t\t})()\n\t\t\t\t: committed;\n\t\tawait mkdir(candidateProject, { recursive: true });\n\t\tconst baseline = previous?.baseline;\n\t\tprogress(\"Loading the program's sources\");\n\t\tconst sources = operation === \"inspect\" ? null : await loadSources(config);\n\t\tconst request = {\n\t\t\tlibraryReferences: config.libraryReferences,\n\t\t\t// Only a download without a baseline starts from the template; the others keep the downloaded project's tree.\n\t\t\t...(operation === \"download\" &&\n\t\t\t\t!previous && {\n\t\t\t\t\ttemplate: await windowsPath(config.template),\n\t\t\t\t\ttemplateHash,\n\t\t\t\t\t// Kept across jobs: generating a device tree takes minutes, and the same inputs make the same one.\n\t\t\t\t\tcaches: await windowsPath(root),\n\t\t\t\t\t...(config.deviceTree && {\n\t\t\t\t\t\tdeviceTree: await writeDeviceTree(config.deviceTree, jobDirectory),\n\t\t\t\t\t\tdevices: await windowsPath(jobDirectory),\n\t\t\t\t\t}),\n\t\t\t\t}),\n\t\t\t...(await importRequest(config, sources)),\n\t\t\toperation,\n\t\t\tinitializeUser: options.initializeUser ?? false,\n\t\t\tcontroller: config.controller,\n\t\t\tproject: await windowsPath(project),\n\t\t\tbaseline,\n\t\t\tread: options.read ?? [],\n\t\t};\n\t\tconst result = z\n\t\t\t.object({\n\t\t\t\tapplicationGuid: guid,\n\t\t\t\tapplication: z.string().optional(),\n\t\t\t\tcontrollerIds: z.strictObject({ codeId: guid, dataId: guid }),\n\t\t\t\tstate: z.string(),\n\t\t\t\tvalues: z.record(z.string(), z.string()),\n\t\t\t})\n\t\t\t.parse(\n\t\t\t\tawait runRequest(request).catch(async (failure: unknown) => {\n\t\t\t\t\tif (\n\t\t\t\t\t\toperation !== \"download\" ||\n\t\t\t\t\t\t(await workerPhase(phase)) !== \"transfer\"\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow failure;\n\t\t\t\t\t}\n\t\t\t\t\tthrow await rollBack(failure);\n\t\t\t\t}),\n\t\t\t);\n\t\tconst receipt = controllerResultSchema.parse({\n\t\t\t...result,\n\t\t\tapplication: result.application ?? baseline?.application,\n\t\t\tschemaVersion: 1,\n\t\t\toperationId: options.operationId,\n\t\t\toperation,\n\t\t\timageId: options.imageId,\n\t\t\ttemplateHash,\n\t\t\ttarget,\n\t\t\tgeneration: operation === \"inspect\" ? baseline?.generation : generation,\n\t\t});\n\t\tif (operation !== \"inspect\") {\n\t\t\tconst committedDirectory = resolve(root, \"generations\", generation);\n\t\t\t/** Keeps the candidate in the output directory, where it outlives the container. */\n\t\t\tconst retain = async (message: string) => {\n\t\t\t\tawait cp(candidateProject, resolve(committedDirectory, \"project\"), {\n\t\t\t\t\trecursive: true,\n\t\t\t\t});\n\t\t\t\treturn new Error(\n\t\t\t\t\t`${message}; candidate is retained for recovery in ${committedDirectory}`,\n\t\t\t\t);\n\t\t\t};\n\t\t\tconst files = await projectFiles(candidateProject);\n\t\t\tif (!Object.keys(files).some((name) => name.endsWith(\".compileinfo\"))) {\n\t\t\t\tthrow await retain(\n\t\t\t\t\t\"CODESYS acknowledged the operation but no downloaded compiler reference was saved\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst bootIds = Object.keys(files).filter((name) =>\n\t\t\t\tname.endsWith(`.${receipt.applicationGuid}.bootinfo_guids`),\n\t\t\t);\n\t\t\tconst expectedBootIds = Buffer.concat([\n\t\t\t\tguidBytes(receipt.controllerIds.codeId),\n\t\t\t\tguidBytes(receipt.controllerIds.dataId),\n\t\t\t]);\n\t\t\tconst bootReference = bootIds[0]?.replace(/_guids$/, \"\") ?? \"\";\n\t\t\tconst downloadedReference = bootReference.replace(\n\t\t\t\t/\\.bootinfo$/,\n\t\t\t\t\".compileinfo\",\n\t\t\t);\n\t\t\tif (\n\t\t\t\tbootIds.length !== 1 ||\n\t\t\t\t!files[bootReference] ||\n\t\t\t\tfiles[bootReference] === sha256(new Uint8Array()) ||\n\t\t\t\tfiles[bootReference] !== files[downloadedReference] ||\n\t\t\t\t!(await readFile(resolve(candidateProject, bootIds[0] ?? \"\"))).equals(\n\t\t\t\t\texpectedBootIds,\n\t\t\t\t)\n\t\t\t) {\n\t\t\t\tthrow await retain(\n\t\t\t\t\t\"CODESYS acknowledged the operation but matching boot reference was not saved\",\n\t\t\t\t);\n\t\t\t}\n\t\t\tprogress(\"Committing the downloaded project\");\n\t\t\tawait rm(committedDirectory, { recursive: true, force: true });\n\t\t\tawait cp(candidateProject, resolve(committedDirectory, \"project\"), {\n\t\t\t\trecursive: true,\n\t\t\t});\n\t\t\tawait writeJson(resolve(committedDirectory, \"manifest.json\"), {\n\t\t\t\t...receipt,\n\t\t\t\tobjects: sources?.objects,\n\t\t\t\tfiles,\n\t\t\t});\n\t\t\t// Each generation is immutable. A single atomic pointer commits it only\n\t\t\t// after controller acknowledgement and matching downloaded/boot references.\n\t\t\tawait writeJson(resolve(root, \"current.json\"), {\n\t\t\t\tschemaVersion: 1,\n\t\t\t\tgeneration,\n\t\t\t});\n\t\t}\n\t\tawait writeJson(resultPath, receipt);\n\t\treturn receipt;\n\t} finally {\n\t\tif (credentialsFile) {\n\t\t\tawait rm(credentialsFile, { force: true });\n\t\t}\n\t\t// CODESYS closed the candidate, and an opened project this operation didn't use.\n\t\tawait rm(candidate, { recursive: true, force: true });\n\t\tif (opened && opened !== prepared) {\n\t\t\tawait rm(resolve(options.scratch, \"generations\", opened.generation), {\n\t\t\t\trecursive: true,\n\t\t\t\tforce: true,\n\t\t\t});\n\t\t}\n\t}\n};\n\n/**\n * Called inside the builder container: holds one login to the running application, made\n * from the committed baseline, and serves its commands on `port` until a DELETE closes it.\n */\nexport const serveControllerLogin = async (\n\tconfig: ResolvedConfig,\n\toptions: { imageId: string; port: number },\n) => {\n\tif (!config.online) {\n\t\tthrow new Error(\"Controller logins require online settings\");\n\t}\n\tconst root = controllerDirectory(config.outDir);\n\tconst committed = await committedBaseline(root, {\n\t\timageId: options.imageId,\n\t\ttemplateHash: sha256(await readFile(config.template)),\n\t\ttarget: controllerTarget(config, config.online),\n\t});\n\tconst { baseline } = committed;\n\tconst jobConfig = { ...config, outDir: resolve(root, \"login\") };\n\tawait rm(jobConfig.outDir, { recursive: true, force: true });\n\t// CODESYS writes into an open project, and the committed baseline must not change.\n\tawait copyCommitted(committed, resolve(jobConfig.outDir, \"project\"));\n\tconst worker = createCodesysWorker(jobConfig);\n\tawait withWorkerShutdown(jobConfig, worker, () =>\n\t\twithWorkerLock(jobConfig, async () => {\n\t\t\tconst session = await worker.launch();\n\t\t\tconst send = (command: Record<string, unknown>) =>\n\t\t\t\tworker.request(\n\t\t\t\t\tsession,\n\t\t\t\t\t{ action: \"login\", arguments: command },\n\t\t\t\t\tconfig.timeouts.build,\n\t\t\t\t);\n\t\t\tawait send({\n\t\t\t\tcommand: \"open\",\n\t\t\t\tproject: await toWindowsPath(\n\t\t\t\t\tresolve(jobConfig.outDir, \"project\", \"Application.project\"),\n\t\t\t\t\tconfig.codesys.wine,\n\t\t\t\t),\n\t\t\t\tonline: config.online,\n\t\t\t\tbaseline,\n\t\t\t});\n\t\t\tconst closed = Promise.withResolvers<void>();\n\t\t\t// The worker has one mailbox, so commands run one at a time.\n\t\t\tlet previous: Promise<unknown> = Promise.resolve();\n\t\t\tconst server = Bun.serve({\n\t\t\t\t// The agent calls through `docker exec`, so nothing else on the network can.\n\t\t\t\thostname: \"127.0.0.1\",\n\t\t\t\tport: options.port,\n\t\t\t\tidleTimeout: 0,\n\t\t\t\tfetch: async (request) => {\n\t\t\t\t\tif (request.method === \"GET\") {\n\t\t\t\t\t\treturn Response.json({ ok: true });\n\t\t\t\t\t}\n\t\t\t\t\tconst close = request.method === \"DELETE\";\n\t\t\t\t\tconst command = close\n\t\t\t\t\t\t? { command: \"close\" }\n\t\t\t\t\t\t: loginCommandSchema.parse(await request.json());\n\t\t\t\t\tconst result = previous.then(() => send(command));\n\t\t\t\t\tprevious = result.catch(() => undefined);\n\t\t\t\t\ttry {\n\t\t\t\t\t\treturn Response.json({ ok: true, result: await result });\n\t\t\t\t\t} catch (error) {\n\t\t\t\t\t\t// The login raises a RuntimeError to tell the user something; any other error comes\n\t\t\t\t\t\t// from CODESYS, and only its traceback shows which call failed.\n\t\t\t\t\t\tconst traceback =\n\t\t\t\t\t\t\terror instanceof Error ? error.message : String(error);\n\t\t\t\t\t\tconst raised =\n\t\t\t\t\t\t\ttracebackFailure(traceback).startsWith(\"RuntimeError: \");\n\t\t\t\t\t\treturn Response.json({\n\t\t\t\t\t\t\tok: false,\n\t\t\t\t\t\t\terror: raised ? failureReason(error) : traceback,\n\t\t\t\t\t\t});\n\t\t\t\t\t} finally {\n\t\t\t\t\t\tif (close) {\n\t\t\t\t\t\t\tclosed.resolve();\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t},\n\t\t\t});\n\t\t\tawait closed.promise;\n\t\t\tawait server.stop();\n\t\t}),\n\t);\n};\n\n/**\n * Called inside the builder container: keeps one CODESYS worker running and serves downloads and\n * online changes on `port`, so each skips starting the container and CODESYS. Each\n * POST names its own config, written for that release. The agent runs one operation at a time, and\n * none while a login is open, so this container doesn't hold the output directory's flock.\n */\nexport const serveWarmController = async (\n\tconfig: ResolvedConfig,\n\toptions: {\n\t\timageId: string;\n\t\tport: number;\n\t\tloadConfig: (path: string) => Promise<ResolvedConfig>;\n\t},\n) => {\n\tconst warmConfig = {\n\t\t...config,\n\t\toutDir: resolve(controllerDirectory(config.outDir), \"warm\"),\n\t};\n\t// One container owns this directory at a time; a stopped one can leave its worker session behind.\n\tawait rm(warmConfig.outDir, { recursive: true, force: true });\n\tawait rm(containerScratch, { recursive: true, force: true });\n\tconst worker = createCodesysWorker(warmConfig);\n\t// CODESYS can die mid-operation; the next request, such as restoring after a failed transfer, starts it again.\n\tconst session = { current: await worker.launch() };\n\tconst running = async () => {\n\t\tif (!worker.alive(session.current)) {\n\t\t\tsession.current = await worker.launch();\n\t\t}\n\t\treturn session.current;\n\t};\n\tconst root = controllerDirectory(config.outDir);\n\tconst online: OnlineWorker = {\n\t\trequestDirectory: controllerDirectory(warmConfig.outDir),\n\t\trun: async (budget) =>\n\t\t\tworker.request(await running(), { action: \"online\" }, budget),\n\t};\n\t/** Opens a verified copy of the committed baseline, so the next operation needn't copy and open one. */\n\tconst prepare = async () => {\n\t\tconst committed = await readCommitted(root).catch(() => undefined);\n\t\tif (!committed) {\n\t\t\treturn;\n\t\t}\n\t\tconst generation = randomUUID();\n\t\tconst project = resolve(\n\t\t\tcontainerScratch,\n\t\t\t\"generations\",\n\t\t\tgeneration,\n\t\t\t\"project\",\n\t\t);\n\t\tawait copyCommitted(committed, project);\n\t\tawait worker.request(\n\t\t\tawait running(),\n\t\t\t{\n\t\t\t\taction: \"prepare\",\n\t\t\t\tproject: await toWindowsPath(\n\t\t\t\t\tresolve(project, \"Application.project\"),\n\t\t\t\t\tconfig.codesys.wine,\n\t\t\t\t),\n\t\t\t},\n\t\t\tconfig.timeouts.build,\n\t\t);\n\t\tonline.prepared = { baseline: committed.baseline.generation, generation };\n\t};\n\t// A failed prepare only costs the next operation the time to open the project itself.\n\tconst prepareNext = () =>\n\t\tprepare().catch((error: unknown) => {\n\t\t\tconsole.error(\n\t\t\t\t`Could not open the next project ahead: ${failureReason(error)}`,\n\t\t\t);\n\t\t});\n\tlet preparing = prepareNext();\n\tBun.serve({\n\t\thostname: \"127.0.0.1\",\n\t\tport: options.port,\n\t\tidleTimeout: 0,\n\t\tfetch: async (request) => {\n\t\t\tif (request.method === \"GET\") {\n\t\t\t\treturn Response.json(\n\t\t\t\t\tworker.alive(session.current)\n\t\t\t\t\t\t? { ok: true }\n\t\t\t\t\t\t: { ok: false, error: \"CODESYS exited\" },\n\t\t\t\t);\n\t\t\t}\n\t\t\tawait preparing;\n\t\t\ttry {\n\t\t\t\tconst body = warmOperationSchema.parse(await request.json());\n\t\t\t\tconst result = await runControllerSession(\n\t\t\t\t\tawait options.loadConfig(body.request),\n\t\t\t\t\tbody.operation,\n\t\t\t\t\t{\n\t\t\t\t\t\timageId: options.imageId,\n\t\t\t\t\t\toperationId: body.operationId,\n\t\t\t\t\t\tscratch: containerScratch,\n\t\t\t\t\t\tinitializeUser: body.initializeUser,\n\t\t\t\t\t\tcredentials: body.credentials,\n\t\t\t\t\t},\n\t\t\t\t\tonline,\n\t\t\t\t).catch((error: unknown) => {\n\t\t\t\t\t// CODESYS crashes generating an online change that moves a block holding a network\n\t\t\t\t\t// client, such as a job with a service call. The controller keeps its running program.\n\t\t\t\t\tif (\n\t\t\t\t\t\tbody.operation !== \"online-change\" ||\n\t\t\t\t\t\tworker.alive(session.current)\n\t\t\t\t\t) {\n\t\t\t\t\t\tthrow error;\n\t\t\t\t\t}\n\t\t\t\t\tthrow new DownloadRequiredError(\n\t\t\t\t\t\t`CODESYS crashed on this online change, as it does when one moves a block that holds a network client; ${explicitDownload}`,\n\t\t\t\t\t\t{ cause: error },\n\t\t\t\t\t);\n\t\t\t\t});\n\t\t\t\treturn Response.json({ ok: true, result });\n\t\t\t} catch (error) {\n\t\t\t\tconst rollback = transferRollback(error);\n\t\t\t\treturn Response.json({\n\t\t\t\t\tok: false,\n\t\t\t\t\terror: failureReason(error),\n\t\t\t\t\t...(requiresDownload(error) && { downloadRequired: true }),\n\t\t\t\t\t...(rollback && { rollback }),\n\t\t\t\t});\n\t\t\t} finally {\n\t\t\t\tonline.prepared = undefined;\n\t\t\t\tpreparing = prepareNext();\n\t\t\t}\n\t\t},\n\t});\n\t// Serves until the container stops; the next one clears what this one leaves behind.\n\tawait new Promise(() => {});\n};\n",
27
+ "import {\n\tcontrollerFor,\n\ttype LoadedConfig,\n\trawBuildConfig,\n\tsimulationConfig,\n} from \"@tsplc/config\";\nimport { resolveConfig } from \"@tsplc/config/build\";\nimport { deviceTree } from \"@tsplc/typegen\";\nimport { loadHardware, resolveIo } from \"@tsplc/typegen/hardware\";\nimport { installLibraries } from \"./libraries.ts\";\n\n/**\n * The settings a raw Structured Text project builds, runs and updates its controller with:\n * libraries installed, IO bound and the device tree generated from the project's hardware.\n * A simulated project leaves out the fieldbus IO and device tree, so a plant simulator writes\n * the inputs instead.\n */\nexport const rawEngineeringSettings = async (\n\t{ config, configFile, root }: LoadedConfig,\n\toptions: {\n\t\tcommand: \"build\" | \"run\" | \"download\" | \"online-change\";\n\t\tfrozenLockfile?: boolean;\n\t\tsimulate?: boolean;\n\t},\n) => {\n\tconst hardwareConfig = options.simulate ? simulationConfig(config) : config;\n\tconst build = rawBuildConfig(config);\n\tconst libraries = await installLibraries(config.dependencies, root, {\n\t\tfrozen: options.frozenLockfile,\n\t});\n\tconst hardware = await loadHardware(hardwareConfig, root);\n\treturn resolveConfig(\n\t\t{\n\t\t\t...build,\n\t\t\tlibraries,\n\t\t\tio: resolveIo(hardwareConfig, hardware),\n\t\t\tdeviceTree: await deviceTree(hardwareConfig, hardware),\n\t\t\tcontroller: controllerFor(config, options.command),\n\t\t},\n\t\tconfigFile,\n\t);\n};\n",
28
+ "import { createHash, randomUUID } from \"node:crypto\";\nimport { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { basename, relative, resolve } from \"node:path\";\nimport type { LibraryDependency } from \"@tsplc/config\";\nimport { sha256Digest } from \"@tsplc/config/build\";\nimport { generatedDirectory } from \"@tsplc/config/project-files\";\nimport { z } from \"zod\";\n\nexport const libraryRegistry = \"https://store-archive.codesys.com/CODESYSLibs\";\nconst libraryFile = /\\.(?:compiled-library(?:-v\\d+)?|library)$/i;\ntype Fetcher = (\n\tinput: string | URL | Request,\n\tinit?: RequestInit,\n) => Promise<Response>;\nconst installedLibrarySchema = z.object({\n\ttitle: z.string(),\n\tcompany: z.string().optional(),\n\tversion: z.string().optional(),\n\tnamespace: z.string().optional(),\n\tpath: z.string(),\n\tsha256: sha256Digest,\n\turl: z.string().optional(),\n});\nexport type InstalledLibrary = z.infer<typeof installedLibrarySchema>;\nconst libraryLockSchema = z.object({\n\tversion: z.literal(1),\n\tdependencies: z.record(z.string(), installedLibrarySchema),\n});\n\n/** The project's lockfile; a project without one has locked nothing yet. */\nconst readLock = async (\n\tfile: string,\n): Promise<z.infer<typeof libraryLockSchema>> => {\n\tconst text = await readFile(file, \"utf8\").catch((cause: unknown) => {\n\t\tif (\n\t\t\tcause &&\n\t\t\ttypeof cause === \"object\" &&\n\t\t\t\"code\" in cause &&\n\t\t\tcause.code === \"ENOENT\"\n\t\t) {\n\t\t\treturn undefined;\n\t\t}\n\t\tthrow cause;\n\t});\n\tif (text === undefined) {\n\t\treturn { version: 1, dependencies: {} };\n\t}\n\tconst lock = libraryLockSchema.safeParse(JSON.parse(text));\n\tif (!lock.success) {\n\t\tthrow new Error(\"Invalid tsplc.lock.json.\", { cause: lock.error });\n\t}\n\treturn lock.data;\n};\nconst hash = (data: Uint8Array) =>\n\tcreateHash(\"sha256\").update(data).digest(\"hex\");\nconst component = (name: string) => {\n\tif (\n\t\t!name.trim() ||\n\t\t/[/\\\\\\0\\r\\n]/.test(name) ||\n\t\tname === \".\" ||\n\t\tname === \"..\"\n\t) {\n\t\tthrow new Error(`Invalid library registry component: ${name}.`);\n\t}\n\treturn encodeURIComponent(name);\n};\nasync function response(url: string, fetcher: Fetcher) {\n\tconst result = await fetcher(url, { signal: AbortSignal.timeout(30_000) });\n\tif (!result.ok) {\n\t\tthrow new Error(`Library registry ${result.status}: ${url}`);\n\t}\n\treturn result;\n}\nexport async function libraryIndex(\n\tpath: string[] = [\"System\"],\n\tfetcher: Fetcher = fetch,\n): Promise<string[]> {\n\tconst url = `${libraryRegistry}/${path.map(component).join(\"/\")}/index`;\n\tconst result = await response(url, fetcher);\n\tconst text = await result.text();\n\tif (text.length > 4_000_000 || /<html/i.test(text)) {\n\t\tthrow new Error(`Invalid library registry index: ${url}`);\n\t}\n\treturn text\n\t\t.split(/\\r?\\n/)\n\t\t.map((s) => s.trim())\n\t\t.filter(Boolean);\n}\nexport async function validateLibrary(\n\ttitle: string,\n\tversion: string,\n\tcompany = \"System\",\n\tfetcher: Fetcher = fetch,\n) {\n\tif (!(await libraryIndex([company], fetcher)).includes(title)) {\n\t\tthrow new Error(\n\t\t\t`Unknown CODESYS library ${company}/${title}. Names are case sensitive.`,\n\t\t);\n\t}\n\tconst versions = await libraryIndex([company, title], fetcher);\n\tif (!versions.includes(version)) {\n\t\tthrow new Error(\n\t\t\t`Unknown version ${version} for ${title}. Available: ${versions.join(\", \")}`,\n\t\t);\n\t}\n\tconst filenames = (\n\t\tawait libraryIndex([company, title, version], fetcher)\n\t).filter((name) => libraryFile.test(name));\n\tconst [filename, ...others] = filenames;\n\tif (filename === undefined || others.length) {\n\t\tthrow new Error(\n\t\t\t`Expected one library payload for ${title} ${version}, received ${filenames.length}.`,\n\t\t);\n\t}\n\treturn {\n\t\tfilename,\n\t\turl: `${libraryRegistry}/${[company, title, version, filename].map(component).join(\"/\")}`,\n\t};\n}\nexport async function installLibraries(\n\tdependencies: Record<string, LibraryDependency>,\n\troot: string,\n\toptions: { frozen?: boolean; fetcher?: Fetcher } = {},\n) {\n\tconst file = resolve(root, \"tsplc.lock.json\");\n\tconst store = resolve(root, generatedDirectory, \"libraries\");\n\tconst previous = await readLock(file);\n\tconst installed: Record<string, InstalledLibrary> = {};\n\tconst fetcher = options.fetcher ?? fetch;\n\tawait mkdir(store, { recursive: true });\n\tfor (const [title, dependency] of Object.entries(dependencies)) {\n\t\tcomponent(title);\n\t\tconst settings =\n\t\t\ttypeof dependency === \"string\" ? { version: dependency } : dependency;\n\t\tconst locked = previous.dependencies[title];\n\t\tconst prior = locked\n\t\t\t? { ...locked, path: resolve(root, locked.path) }\n\t\t\t: undefined;\n\t\tconst same =\n\t\t\tprior !== undefined &&\n\t\t\tprior.namespace === settings.namespace &&\n\t\t\t(\"path\" in settings\n\t\t\t\t? prior.url === undefined && prior.path === resolve(root, settings.path)\n\t\t\t\t: prior.version === settings.version &&\n\t\t\t\t\tprior.company === (settings.company ?? \"System\"));\n\t\tif (same) {\n\t\t\ttry {\n\t\t\t\tif (hash(await readFile(prior.path)) === prior.sha256) {\n\t\t\t\t\tinstalled[title] = prior;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t} catch {\n\t\t\t\t/* Missing cache can be restored from the exact URL. */\n\t\t\t}\n\t\t\tif (options.frozen) {\n\t\t\t\tthrow new Error(`Locked library ${title} is missing or changed.`);\n\t\t\t}\n\t\t} else if (options.frozen) {\n\t\t\tthrow new Error(`Dependency ${title} differs from tsplc.lock.json.`);\n\t\t}\n\t\tif (\"path\" in settings) {\n\t\t\tconst path = resolve(root, settings.path);\n\t\t\tif (!libraryFile.test(path)) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`${title}: expected a .library or .compiled-library file.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tinstalled[title] = {\n\t\t\t\ttitle,\n\t\t\t\tpath,\n\t\t\t\tsha256: hash(await readFile(path)),\n\t\t\t\t...(settings.namespace ? { namespace: settings.namespace } : {}),\n\t\t\t};\n\t\t} else {\n\t\t\tconst company = settings.company ?? \"System\";\n\t\t\tconst payload = await validateLibrary(\n\t\t\t\ttitle,\n\t\t\t\tsettings.version,\n\t\t\t\tcompany,\n\t\t\t\tfetcher,\n\t\t\t);\n\t\t\tconst result = await response(payload.url, fetcher);\n\t\t\tconst data = new Uint8Array(await result.arrayBuffer());\n\t\t\tif (!data.length || data.length > 256 * 1024 * 1024) {\n\t\t\t\tthrow new Error(`${title}: invalid library payload size.`);\n\t\t\t}\n\t\t\tconst sha256 = hash(data);\n\t\t\t// An existing lock pins the payload, even if the registry later changes it.\n\t\t\tif (same && prior.sha256 !== sha256) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Registry payload changed for locked library ${title} ${settings.version}.`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst path = resolve(store, `${sha256}-${basename(payload.filename)}`);\n\t\t\tconst temp = `${path}.${randomUUID()}.tmp`;\n\t\t\tawait writeFile(temp, data, { flag: \"wx\" });\n\t\t\tawait rename(temp, path);\n\t\t\tinstalled[title] = {\n\t\t\t\ttitle,\n\t\t\t\tcompany,\n\t\t\t\tversion: settings.version,\n\t\t\t\tpath,\n\t\t\t\tsha256,\n\t\t\t\turl: payload.url,\n\t\t\t\t...(settings.namespace ? { namespace: settings.namespace } : {}),\n\t\t\t};\n\t\t}\n\t}\n\tif (\n\t\toptions.frozen &&\n\t\tObject.keys(previous.dependencies).some(\n\t\t\t(name) => !Object.hasOwn(dependencies, name),\n\t\t)\n\t) {\n\t\tthrow new Error(\"Removed dependencies differ from tsplc.lock.json.\");\n\t}\n\tif (!options.frozen) {\n\t\tconst temp = `${file}.${randomUUID()}.tmp`;\n\t\tconst portable = Object.fromEntries(\n\t\t\tObject.entries(installed).map(([title, library]) => [\n\t\t\t\ttitle,\n\t\t\t\t{\n\t\t\t\t\t...library,\n\t\t\t\t\tpath: relative(root, library.path).replaceAll(\"\\\\\", \"/\"),\n\t\t\t\t},\n\t\t\t]),\n\t\t);\n\t\tawait writeFile(\n\t\t\ttemp,\n\t\t\t`${JSON.stringify({ version: 1, dependencies: portable }, null, 2)}\\n`,\n\t\t);\n\t\tawait rename(temp, file);\n\t}\n\treturn Object.values(installed);\n}\n",
29
+ "import {\n\tcontrollerFor,\n\ttype LoadedConfig,\n\trawBuildConfig,\n} from \"@tsplc/config\";\nimport { resolveConfig } from \"@tsplc/config/build\";\nimport { loadHardware, resolveIo } from \"@tsplc/typegen/hardware\";\nimport { inspectController } from \"./controller-online.ts\";\nimport type { ProgressOptions } from \"./docker-run.ts\";\nimport { loadSources } from \"./sources.ts\";\n\n/** Parses a raw Structured Text project's sources with its IO bound, without installing libraries or building. */\nexport const checkRawSources = async ({\n\tconfig,\n\tconfigFile,\n\troot,\n}: LoadedConfig) =>\n\tloadSources(\n\t\tresolveConfig(\n\t\t\t{\n\t\t\t\t...rawBuildConfig(config),\n\t\t\t\tio: resolveIo(config, await loadHardware(config, root)),\n\t\t\t},\n\t\t\tconfigFile,\n\t\t),\n\t);\n\n/**\n * Reads the configured controller's state. Inspection needs only the connection and baseline,\n * so it stays usable without local sources, EDS descriptors or installed library payloads.\n */\nexport const inspectProjectController = (\n\t{ config, configFile }: LoadedConfig,\n\tread: string[] | undefined,\n\toptions: ProgressOptions,\n) => {\n\tif (!config.build) {\n\t\tthrow new Error(\"Configure build settings and controller connection.\");\n\t}\n\treturn inspectController(\n\t\tresolveConfig(\n\t\t\t{ ...config.build, controller: controllerFor(config, \"inspect\") },\n\t\t\tconfigFile,\n\t\t),\n\t\tread,\n\t\toptions,\n\t);\n};\n",
30
+ "import { mkdtemp, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { tmpdir } from \"node:os\";\nimport { basename, dirname, join } from \"node:path\";\nimport { setTimeout as delay } from \"node:timers/promises\";\nimport type { ResolvedConfig } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport { readBuild } from \"./artifacts\";\nimport { captureDocker, type ProgressOptions, progressLog } from \"./docker-run\";\nimport { withWorkerLock } from \"./host/codesys-worker\";\nimport { runtimeImage } from \"./images.ts\";\nimport { getApplicationStatus } from \"./runtime-status\";\n\nconst stateSchema = z.object({\n\tRunning: z.boolean(),\n\tStartedAt: z.iso.datetime({ offset: true }),\n});\n\nconst service = \"plc\";\n\n/** The Docker Compose project of a tsPLC project: `DemoController` runs as `demo-controller`. */\nexport const runtimeProject = (name: string) =>\n\tname\n\t\t.replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9_-]+/g, \"-\");\n\n/** The local PLC: named volumes keep its provisioning and the installed application across restarts. */\nexport const runtimeDefinition = (name: string) => ({\n\tservices: {\n\t\t[service]: {\n\t\t\timage: runtimeImage,\n\t\t\tplatform: \"linux/amd64\",\n\t\t\thostname: `${runtimeProject(name)}-${service}`,\n\t\t\tinit: true,\n\t\t\tports: [\"127.0.0.1:4840:4840\", \"127.0.0.1:11740:11740\"],\n\t\t\tcap_add: [\"SYS_NICE\", \"IPC_LOCK\"],\n\t\t\tvolumes: [\n\t\t\t\t\"control-conf:/conf/codesyscontrol\",\n\t\t\t\t\"control-data:/data/codesyscontrol\",\n\t\t\t],\n\t\t\trestart: \"no\",\n\t\t},\n\t},\n\tvolumes: { \"control-conf\": {}, \"control-data\": {} },\n});\n\n/** Deploy the completed boot application to the project's local PLC container. */\nexport const runProject = async (\n\tconfig: Pick<ResolvedConfig, \"outDir\" | \"timeouts\">,\n\tname: string,\n\t{ progress = \"stdout\" }: ProgressOptions = {},\n) =>\n\twithWorkerLock(config, async () => {\n\t\t// Validate before stopping anything. A missing receipt includes a failed rebuild.\n\t\tconst build = await readBuild(config.outDir).catch((cause: unknown) => {\n\t\t\tthrow new Error(\n\t\t\t\t`No complete build in ${config.outDir}. Run tsplc-build build first.`,\n\t\t\t\t{\n\t\t\t\t\tcause,\n\t\t\t\t},\n\t\t\t);\n\t\t});\n\t\tconst definitionDirectory = await mkdtemp(join(tmpdir(), \"tsplc-runtime-\"));\n\t\ttry {\n\t\t\tconst composeFile = join(definitionDirectory, \"compose.yaml\");\n\t\t\t// JSON is valid YAML.\n\t\t\tawait writeFile(composeFile, JSON.stringify(runtimeDefinition(name)));\n\t\t\tconst docker = (...args: string[]) =>\n\t\t\t\tcaptureDocker(args, config.timeouts.runtime);\n\t\t\tconst compose = (...args: string[]) =>\n\t\t\t\tdocker(\n\t\t\t\t\t\"compose\",\n\t\t\t\t\t\"--project-name\",\n\t\t\t\t\truntimeProject(name),\n\t\t\t\t\t\"--file\",\n\t\t\t\t\tcomposeFile,\n\t\t\t\t\t...args,\n\t\t\t\t);\n\t\t\tconst installer = await readFile(\n\t\t\t\tnew URL(\"../runtime/install.sh\", import.meta.url),\n\t\t\t\t\"utf8\",\n\t\t\t);\n\t\t\tprogressLog(progress)(\n\t\t\t\t`Installing ${build.application} in Docker service ${service}`,\n\t\t\t);\n\t\t\tawait compose(\"stop\", service);\n\t\t\t// The helper uses the service's volumes without starting its PLC or publishing\n\t\t\t// ports. Its read-only artifact mount is removed with the helper container.\n\t\t\tawait compose(\n\t\t\t\t\"run\",\n\t\t\t\t\"--rm\",\n\t\t\t\t\"--no-deps\",\n\t\t\t\t\"-T\",\n\t\t\t\t\"--volume\",\n\t\t\t\t`${dirname(build.output)}:/codesys-build:ro`,\n\t\t\t\t\"--entrypoint\",\n\t\t\t\t\"/bin/sh\",\n\t\t\t\tservice,\n\t\t\t\t\"-c\",\n\t\t\t\tinstaller,\n\t\t\t\t\"codesys-build-install\",\n\t\t\t\tbuild.application,\n\t\t\t\tbasename(build.output, \".app\"),\n\t\t\t);\n\t\t\tawait compose(\"up\", \"--detach\", \"--no-deps\", service);\n\t\t\tconst containers = (\n\t\t\t\tawait compose(\"ps\", \"--all\", \"--quiet\", service)\n\t\t\t).stdout\n\t\t\t\t.trim()\n\t\t\t\t.split(/\\s+/)\n\t\t\t\t.filter(Boolean);\n\t\t\tif (containers.length !== 1 || !containers[0]) {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t`Expected one container for Compose service ${service}`,\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst container = containers[0];\n\t\t\tconst deadline = Date.now() + config.timeouts.runtime;\n\t\t\twhile (true) {\n\t\t\t\tconst state = stateSchema.parse(\n\t\t\t\t\tJSON.parse(\n\t\t\t\t\t\t(await docker(\"inspect\", \"--format\", \"{{json .State}}\", container))\n\t\t\t\t\t\t\t.stdout,\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tif (!state.Running) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`Docker service ${service} exited before the application started. Check docker logs ${container}.`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\t// Use this container start time, not the host clock or an old \"started\" event.\n\t\t\t\tconst { stdout: log } = await docker(\n\t\t\t\t\t\"exec\",\n\t\t\t\t\tcontainer,\n\t\t\t\t\t\"/bin/sh\",\n\t\t\t\t\t\"-c\",\n\t\t\t\t\t\"if [ -f /data/codesyscontrol/codesyscontrol.log ]; then cat /data/codesyscontrol/codesyscontrol.log; fi\",\n\t\t\t\t);\n\t\t\t\tconst status = getApplicationStatus(\n\t\t\t\t\tlog,\n\t\t\t\t\tbuild.application,\n\t\t\t\t\tDate.parse(state.StartedAt),\n\t\t\t\t);\n\t\t\t\tif (status === \"running\") {\n\t\t\t\t\tprogressLog(progress)(\n\t\t\t\t\t\t`${build.application} is running in ${service}`,\n\t\t\t\t\t);\n\t\t\t\t\treturn { ...build, container };\n\t\t\t\t}\n\t\t\t\tif (status === \"failed\" || Date.now() >= deadline) {\n\t\t\t\t\tthrow new Error(\n\t\t\t\t\t\t`CODESYS did not start ${build.application}. Runtime log:\\n${log.split(\"\\n\").slice(-25).join(\"\\n\")}`,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t\tawait delay(250);\n\t\t\t}\n\t\t} finally {\n\t\t\tawait rm(definitionDirectory, { force: true, recursive: true });\n\t\t}\n\t});\n",
28
31
  "/** Runtime stdout is buffered in Docker. Its log file records start/stop events immediately. */\nexport const getApplicationStatus = (\n\tlog: string,\n\tapplication: string,\n\tstartedAt: number,\n) => {\n\tconst event = log\n\t\t.split(/\\r?\\n/)\n\t\t.reverse()\n\t\t.find((line) => {\n\t\t\tconst timestamp = Date.parse(line.split(\",\")[0] ?? \"\");\n\t\t\tif (!Number.isFinite(timestamp) || timestamp < startedAt) {\n\t\t\t\treturn false;\n\t\t\t}\n\t\t\treturn (\n\t\t\t\tline.includes(`<app>${application}</app>`) &&\n\t\t\t\t/\\b(started|stopped|exception|corrupt|failed|denied)\\b/i.test(line) &&\n\t\t\t\t!line.includes(\"load started\")\n\t\t\t);\n\t\t});\n\tif (!event) {\n\t\treturn \"pending\";\n\t}\n\treturn event.includes(`Application [<app>${application}</app>] started`)\n\t\t? \"running\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