@tsplc/agent 0.4.4 → 0.5.1

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.
package/dist/client.js CHANGED
@@ -12,7 +12,7 @@ import { tsplcConfigSchema } from "@tsplc/config";
12
12
  import { releaseConfigSchema, tcpPort } from "@tsplc/config/build";
13
13
  import { z } from "zod";
14
14
  // packages/agent/package.json
15
- var version = "0.4.4";
15
+ var version = "0.5.1";
16
16
 
17
17
  // packages/agent/src/protocol.ts
18
18
  var tsplcVersion = version;
@@ -117,7 +117,18 @@ var clientHeaders = {
117
117
  scripts: "x-tsplc-scripts"
118
118
  };
119
119
  var agentVersionHeader = "x-tsplc-agent-version";
120
- var versionMismatch = (versions) => `The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : "a tsPLC older than 0.3.0"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: update the plant agent to ${versions.client} and run tsplc-agent setup there${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : ""}`;
120
+ var atLeast = (version, minimum) => {
121
+ const parts = version.split(/[.+-]/).slice(0, 3).map(Number);
122
+ for (const [index, wanted] of minimum.entries()) {
123
+ const part = parts[index] ?? 0;
124
+ if (part !== wanted) {
125
+ return part > wanted;
126
+ }
127
+ }
128
+ return true;
129
+ };
130
+ var upgradesItself = (version) => version !== null && atLeast(version, [0, 5, 0]);
131
+ var versionMismatch = (versions) => `The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : "a tsPLC older than 0.3.0"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: on the plant PC, run ${versions.agentUpgrades ? `tsplc-agent upgrade ${versions.client}` : `bun add --global @tsplc/agent@${versions.client}, then restart tsplc-agent serve`}${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : ""}`;
121
132
  var deploymentSchema = z.strictObject({
122
133
  at: z.iso.datetime(),
123
134
  release: z.string(),
@@ -253,7 +264,11 @@ var createAgentClient = (options) => {
253
264
  deploy: async (release, settings, onProgress) => {
254
265
  const agentVersion = (await call("/status")).headers.get(agentVersionHeader);
255
266
  if (agentVersion !== tsplcVersion) {
256
- throw new AgentOperationError(versionMismatch({ agent: agentVersion, client: tsplcVersion }));
267
+ throw new AgentOperationError(versionMismatch({
268
+ agent: agentVersion,
269
+ client: tsplcVersion,
270
+ agentUpgrades: upgradesItself(agentVersion)
271
+ }));
257
272
  }
258
273
  const files = await Promise.all(release.files.map(async ({ path, content }) => ({
259
274
  path,
@@ -293,5 +308,5 @@ export {
293
308
  createAgentClient
294
309
  };
295
310
 
296
- //# debugId=083334A026BAA03E64756E2164756E21
311
+ //# debugId=650B88C3010D1A1A64756E2164756E21
297
312
  //# sourceMappingURL=client.js.map
@@ -2,11 +2,11 @@
2
2
  "version": 3,
3
3
  "sources": ["../src/client.ts", "../src/protocol.ts", "../src/transfer.ts"],
4
4
  "sourcesContent": [
5
- "import { hostname, userInfo } from \"node:os\";\nimport {\n\ttype LoginCommand,\n\tloginResultSchema,\n\ttype Rollback,\n\tworkerScriptsDigest,\n} from \"@tsplc/build\";\nimport { z } from \"zod\";\nimport {\n\tagentVersionHeader,\n\ttype Comparison,\n\ttype Credentials,\n\tclientHeaders,\n\tcomparisonSchema,\n\tcontrollerSchema,\n\ttype DeployOptions,\n\terrorSchema,\n\teventSchema,\n\tlogoutSchema,\n\tnetworkInterfaceSchema,\n\ttype ReleaseManifest,\n\ttype ReleaseUpload,\n\treleaseSchema,\n\treleaseUploadType,\n\tstatusSchema,\n\ttype Target,\n\ttargetSchema,\n\ttsplcVersion,\n\tvariableSchema,\n\tversionMismatch,\n} from \"./protocol\";\nimport {\n\tbucketDigests,\n\tencodeUpload,\n\tfileBucket,\n\ttype ReleaseContent,\n\tshortDigest,\n} from \"./transfer\";\n\n/**\n * A failed agent operation; `downloadRequired` means only a full download can deploy, and\n * `rollback` what became of the controller after a download failed mid-transfer.\n */\nexport class AgentOperationError extends Error {\n\treadonly downloadRequired: boolean;\n\treadonly rollback: Rollback | undefined;\n\n\tconstructor(\n\t\tmessage: string,\n\t\t{\n\t\t\tdownloadRequired = false,\n\t\t\trollback,\n\t\t}: { downloadRequired?: boolean; rollback?: Rollback } = {},\n\t) {\n\t\tsuper(message);\n\t\tthis.downloadRequired = downloadRequired;\n\t\tthis.rollback = rollback;\n\t}\n}\n\n/** A file to upload, at its path in the release. */\nexport interface ReleaseFile {\n\tpath: string;\n\tcontent: Blob;\n}\n\n/** Talks to a plant agent at `url`, such as its Tailscale name and port. */\nexport const createAgentClient = (options: { url: string; token: string }) => {\n\t// The agent records who deployed and who changed the controller, and refuses another tsPLC version.\n\tconst identity = workerScriptsDigest()\n\t\t.then(\n\t\t\t(scripts) => ({ [clientHeaders.scripts]: scripts }),\n\t\t\t// The digest only tells local builds apart; an installation that can't read its scripts still deploys.\n\t\t\t() => ({}),\n\t\t)\n\t\t.then((scripts) => ({\n\t\t\t[clientHeaders.user]: userInfo().username,\n\t\t\t[clientHeaders.host]: hostname(),\n\t\t\t[clientHeaders.version]: tsplcVersion,\n\t\t\t...scripts,\n\t\t}));\n\tconst call = async (path: string, init: RequestInit = {}) => {\n\t\tconst response = await fetch(new URL(path, options.url), {\n\t\t\t...init,\n\t\t\theaders: {\n\t\t\t\t...init.headers,\n\t\t\t\t...(await identity),\n\t\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t},\n\t\t}).catch((cause: unknown) => {\n\t\t\tthrow new Error(`Cannot reach the plant agent at ${options.url}`, {\n\t\t\t\tcause,\n\t\t\t});\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tconst body = await response.json().catch(() => ({}));\n\t\t\tthrow new AgentOperationError(\n\t\t\t\terrorSchema.safeParse(body).data?.error ??\n\t\t\t\t\t`The agent answered ${response.status}`,\n\t\t\t);\n\t\t}\n\t\treturn response;\n\t};\n\tconst get = async <T>(path: string, schema: z.ZodType<T>) =>\n\t\tschema.parse(await (await call(path)).json());\n\tconst send = async <T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody: unknown,\n\t\tschema: z.ZodType<T>,\n\t) =>\n\t\tschema.parse(\n\t\t\tawait (\n\t\t\t\tawait call(path, {\n\t\t\t\t\tmethod,\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t})\n\t\t\t).json(),\n\t\t);\n\n\t/** Reads a streamed operation, reporting progress, until its result or failure. */\n\tconst operation = async (\n\t\tresponse: Response,\n\t\tonProgress: (message: string) => void,\n\t) => {\n\t\tconst reader = response.body\n\t\t\t?.pipeThrough(new TextDecoderStream())\n\t\t\t.getReader();\n\t\tif (!reader) {\n\t\t\tthrow new Error(\"The agent returned no operation stream\");\n\t\t}\n\t\tlet buffered = \"\";\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tthrow new Error(\"The agent closed the operation without a result\");\n\t\t\t}\n\t\t\tbuffered += value;\n\t\t\tconst lines = buffered.split(\"\\n\");\n\t\t\tbuffered = lines.pop() ?? \"\";\n\t\t\tfor (const line of lines.filter(Boolean)) {\n\t\t\t\tconst event = eventSchema.parse(JSON.parse(line));\n\t\t\t\tif (event.kind === \"progress\") {\n\t\t\t\t\tonProgress(event.message);\n\t\t\t\t} else if (event.kind === \"done\") {\n\t\t\t\t\treturn event.result;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new AgentOperationError(event.message, {\n\t\t\t\t\t\tdownloadRequired: event.downloadRequired,\n\t\t\t\t\t\trollback: event.rollback,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\t/** What the agent holds of a release with these bucket digests. */\n\tconst compare = (buckets: string[]) =>\n\t\tsend(\"POST\", \"/releases/compare\", { buckets }, comparisonSchema);\n\n\treturn {\n\t\tstatus: () => get(\"/status\", statusSchema),\n\t\tinterfaces: () => get(\"/interfaces\", z.array(networkInterfaceSchema)),\n\t\tdiscover: (name: string) =>\n\t\t\tsend(\"POST\", \"/discover\", { name }, z.array(controllerSchema)),\n\t\tsetTarget: (target: Target) => send(\"PUT\", \"/target\", target, targetSchema),\n\t\tvariables: () => get(\"/variables\", z.array(variableSchema)),\n\t\tdeploy: async (\n\t\t\trelease: { manifest: ReleaseManifest; files: ReleaseFile[] },\n\t\t\tsettings: DeployOptions,\n\t\t\tonProgress: (message: string) => void,\n\t\t) => {\n\t\t\t// Before uploading: an agent of another version, including one from before version checks,\n\t\t\t// would compile the release with scripts this client doesn't expect.\n\t\t\tconst agentVersion = (await call(\"/status\")).headers.get(\n\t\t\t\tagentVersionHeader,\n\t\t\t);\n\t\t\tif (agentVersion !== tsplcVersion) {\n\t\t\t\tthrow new AgentOperationError(\n\t\t\t\t\tversionMismatch({ agent: agentVersion, client: tsplcVersion }),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst files = await Promise.all(\n\t\t\t\trelease.files.map(async ({ path, content }) => ({\n\t\t\t\t\tpath,\n\t\t\t\t\tcontent: await content.bytes(),\n\t\t\t\t})),\n\t\t\t);\n\t\t\tconst digests = files.map(({ path, content }) => ({\n\t\t\t\tpath,\n\t\t\t\tdigest: shortDigest(content),\n\t\t\t}));\n\t\t\tconst buckets = bucketDigests(digests);\n\t\t\tconst body = await releaseUpload(\n\t\t\t\t{ manifest: release.manifest, options: settings, buckets },\n\t\t\t\tfiles,\n\t\t\t\tawait compare(buckets),\n\t\t\t\tonProgress,\n\t\t\t);\n\t\t\treturn releaseSchema.parse(\n\t\t\t\tawait operation(\n\t\t\t\t\tawait call(\"/deploy\", { method: \"POST\", ...body }),\n\t\t\t\t\tonProgress,\n\t\t\t\t),\n\t\t\t);\n\t\t},\n\t\tlogin: async (\n\t\t\tcredentials: Credentials | null,\n\t\t\tonProgress: (message: string) => void,\n\t\t) =>\n\t\t\tloginResultSchema.parse(\n\t\t\t\tawait operation(\n\t\t\t\t\tawait call(\"/login\", {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\t\tbody: JSON.stringify(credentials),\n\t\t\t\t\t}),\n\t\t\t\t\tonProgress,\n\t\t\t\t),\n\t\t\t),\n\t\tcommand: (command: LoginCommand) =>\n\t\t\tsend(\"POST\", \"/login/command\", command, loginResultSchema),\n\t\tlogout: () => send(\"DELETE\", \"/login\", undefined, logoutSchema),\n\t};\n};\nexport type AgentClient = ReturnType<typeof createAgentClient>;\n\n/**\n * A release upload built on the release the agent compared it with: in each bucket that differs,\n * the files the agent lacks and the paths to drop. Without a base, every file.\n */\nconst releaseUpload = async (\n\theader: Pick<ReleaseUpload, \"manifest\" | \"options\" | \"buckets\">,\n\tfiles: readonly ReleaseContent[],\n\t{ base, changed }: Comparison,\n\tonProgress: (message: string) => void,\n) => {\n\tconst stored = new Map(changed.map(({ bucket, files }) => [bucket, files]));\n\tconst uploaded =\n\t\tbase === null\n\t\t\t? files\n\t\t\t: files.filter(({ path, content }) => {\n\t\t\t\t\tconst held = stored.get(fileBucket(path));\n\t\t\t\t\treturn held !== undefined && held[path] !== shortDigest(content);\n\t\t\t\t});\n\tconst paths = new Set(files.map(({ path }) => path));\n\tconst remove = [...stored.values()].flatMap((held) =>\n\t\tObject.keys(held).filter((path) => !paths.has(path)),\n\t);\n\tconst body = await encodeUpload(\n\t\t{ ...header, base, remove } satisfies ReleaseUpload,\n\t\tuploaded,\n\t);\n\tonProgress(\n\t\t`Uploading ${uploaded.length} of ${files.length} files (${Math.ceil(body.length / 1024)} KB)`,\n\t);\n\treturn { headers: { \"Content-Type\": releaseUploadType }, body };\n};\n",
6
- "import { rollbackSchema } from \"@tsplc/build\";\nimport { tsplcConfigSchema } from \"@tsplc/config\";\nimport { releaseConfigSchema, tcpPort } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport { version } from \"../package.json\";\n\n/** The tsPLC version a client and the agent it deploys through must share. */\nexport const tsplcVersion = version;\n\n/** The controller the agent deploys to, as its runtime's TCP block driver address. */\nexport const targetSchema = z.strictObject({\n\thost: z.string().nonempty(),\n\tport: tcpPort,\n});\nexport type Target = z.infer<typeof targetSchema>;\n\nexport const networkInterfaceSchema = z.strictObject({\n\tname: z.string(),\n\taddress: z.ipv4(),\n\tprefixLength: z.number().int().min(0).max(32),\n});\nexport type NetworkInterface = z.infer<typeof networkInterfaceSchema>;\n\n/** A host on the scanned subnet that accepts connections on the CODESYS runtime port. */\nexport const controllerSchema = z.strictObject({\n\taddress: z.ipv4(),\n\tport: z.number().int(),\n\thostname: z.string().nullable(),\n});\nexport type DiscoveredController = z.infer<typeof controllerSchema>;\n\n/** `POST /discover`: the network interface to scan for controllers. */\nexport const discoverSchema = z.strictObject({ name: z.string() });\n\n/**\n * The controller's user, which the agent passes to CODESYS for one operation. A request sends\n * null instead to use the one stored on the agent's PC.\n */\nexport const credentialsSchema = z.strictObject({\n\tusername: z.string().nonempty(),\n\tpassword: z.string().nonempty(),\n});\nexport type Credentials = z.infer<typeof credentialsSchema>;\n\n/** A published leaf of the deployed program, as CODESYS expressions name it. */\nexport const variableSchema = z.strictObject({\n\tpath: z.string(),\n\ttype: z.string(),\n});\nexport type Variable = z.infer<typeof variableSchema>;\n\n/**\n * What `tsplc deploy` uploads beside its files. `config` is the build config with paths\n * relative to the release: `st/`, `template.project` and `libraries/`.\n */\nexport const releaseManifestSchema = z.strictObject({\n\t// Checked against the owner's schema but kept as uploaded: the release id hashes the manifest.\n\tconfig: z.record(z.string(), z.unknown()).superRefine((config, context) => {\n\t\tconst release = releaseConfigSchema.safeParse(config);\n\t\tif (!release.success) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tmessage: `Invalid release config: ${z.prettifyError(release.error)}`,\n\t\t\t});\n\t\t}\n\t}),\n\tvariables: z.array(variableSchema),\n\t/** The server executable's path in the release, when the project builds one. */\n\tserver: z.string().nonempty().optional(),\n\t/** The project's `debug` section; the program's debug manifest is the release's `debug.json`. */\n\tdebug: tsplcConfigSchema.shape.debug,\n\t/** The variable in the agent's environment holding the server's bearer token, for its telemetry and request trace. */\n\tserverTokenEnv: z.string().nonempty().optional(),\n\t/** The project's `secrets`, whose placeholders in the ST the agent fills in from Bun.secrets. */\n\tsecrets: tsplcConfigSchema.shape.secrets,\n});\nexport type ReleaseManifest = z.infer<typeof releaseManifestSchema>;\n\n/** How `tsplc deploy` compresses each file of a multipart upload, the only form agents without `POST /releases/compare` accept. */\nexport const uploadEncoding = \"gzip\";\n\nexport const deployOptionsSchema = z\n\t.strictObject({\n\t\tcredentials: credentialsSchema.nullable(),\n\t\t/** A full download stops the application; without it only an online change is applied. */\n\t\tdownload: z.boolean(),\n\t\tinitializeUser: z.boolean(),\n\t})\n\t.refine(\n\t\t(options) => options.credentials || !options.initializeUser,\n\t\t\"Initializing the controller's user needs the user's credentials.\",\n\t);\nexport type DeployOptions = z.infer<typeof deployOptionsSchema>;\n\n/** How many buckets a release's files fall into for `POST /releases/compare`. */\nexport const releaseBuckets = 256;\n\n/** A release id, or the start of a SHA-256 of content: 16 lowercase hex digits. */\nconst shortHex = z.string().regex(/^[a-f0-9]{16}$/);\n\n/** `POST /releases/compare`: the digest of each bucket of the release about to be deployed. */\nexport const compareRequestSchema = z.strictObject({\n\tbuckets: z.array(shortHex).length(releaseBuckets),\n});\n\n/**\n * Its answer: the stored release the upload can build on, and that release's files, by path and\n * digest, in each bucket that differs. Without a base the whole release is uploaded.\n */\nexport const comparisonSchema = z.strictObject({\n\tbase: shortHex.nullable(),\n\tchanged: z.array(\n\t\tz.strictObject({\n\t\t\tbucket: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(0)\n\t\t\t\t.max(releaseBuckets - 1),\n\t\t\tfiles: z.record(z.string(), shortHex),\n\t\t}),\n\t),\n});\nexport type Comparison = z.infer<typeof comparisonSchema>;\n\n/** A `POST /deploy` body in this form is one release upload rather than a multipart form. */\nexport const releaseUploadType = \"application/vnd.tsplc.release+zstd\";\n\n/**\n * A release upload's header. The release is `base`'s files without the `remove` paths, with the\n * uploaded files added or replacing theirs; `buckets` are the digests it must then have.\n */\nexport const releaseUploadSchema = z.strictObject({\n\tmanifest: releaseManifestSchema,\n\toptions: deployOptionsSchema,\n\tbase: shortHex.nullable(),\n\tbuckets: compareRequestSchema.shape.buckets,\n\tremove: z.array(z.string()),\n});\nexport type ReleaseUpload = z.infer<typeof releaseUploadSchema>;\n\n/** Long operations stream one of these per line. */\nexport const eventSchema = z.discriminatedUnion(\"kind\", [\n\tz.strictObject({ kind: z.literal(\"progress\"), message: z.string() }),\n\tz.strictObject({ kind: z.literal(\"done\"), result: z.unknown() }),\n\tz.strictObject({\n\t\tkind: z.literal(\"error\"),\n\t\tmessage: z.string(),\n\t\t/** The controller has no application from this agent yet, so only a full download can deploy. */\n\t\tdownloadRequired: z.boolean(),\n\t\t/**\n\t\t * What became of the controller after a download failed mid-transfer. Sent only to clients that\n\t\t * send their version, since earlier clients reject an event with fields they don't know.\n\t\t */\n\t\trollback: rollbackSchema.optional(),\n\t}),\n]);\nexport type AgentEvent = z.infer<typeof eventSchema>;\n\n/** A failed request's body. */\nexport const errorSchema = z.object({ error: z.string() });\n\nconst deployOperationSchema = z.enum([\"download\", \"online-change\"]);\n\nexport const releaseSchema = z.strictObject({\n\tid: z.string(),\n\tdeployedAt: z.iso.datetime(),\n\toperation: deployOperationSchema,\n\tcontrollerIds: z.strictObject({ codeId: z.string(), dataId: z.string() }),\n\t/** The running server executable, relative to the releases directory. */\n\tserver: z.string().optional(),\n});\nexport type Release = z.infer<typeof releaseSchema>;\n\nexport const statusSchema = z.strictObject({\n\ttarget: targetSchema.nullable(),\n\trelease: releaseSchema.nullable(),\n\tserver: z\n\t\t.strictObject({ executable: z.string(), running: z.boolean() })\n\t\t.nullable(),\n\t/** The open login's application state and forced expressions, or why it can't report them. */\n\tlogin: z\n\t\t.union([\n\t\t\tz.strictObject({ state: z.string(), forced: z.array(z.string()) }),\n\t\t\tz.strictObject({ error: z.string() }),\n\t\t])\n\t\t.nullable(),\n\t/** A controller user is stored on the agent's PC, so requests may leave theirs out. */\n\tcredentialsStored: z.boolean(),\n});\nexport type AgentStatus = z.infer<typeof statusSchema>;\n\n/** A logout's result: why the login couldn't log out, when its container had to be removed instead. */\nexport const logoutSchema = z.strictObject({ failure: z.string().optional() });\n\n/** Who ran a command, and with which tsPLC, as the client reports it in these headers. */\nexport const clientHeaders = {\n\tuser: \"x-tsplc-user\",\n\thost: \"x-tsplc-host\",\n\tversion: \"x-tsplc-version\",\n\t/** The client's `workerScriptsDigest`, which tells a local build from a release of its version. */\n\tscripts: \"x-tsplc-scripts\",\n} as const;\n\n/** The header each agent response names the agent's tsPLC version in; agents before 0.3.0 send none. */\nexport const agentVersionHeader = \"x-tsplc-agent-version\";\n\n/** Why a client and an agent of different tsPLC versions don't deploy, and what to do about it. */\nexport const versionMismatch = (versions: {\n\tagent: string | null;\n\tclient: string;\n}) =>\n\t`The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : \"a tsPLC older than 0.3.0\"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: update the plant agent to ${versions.client} and run tsplc-agent setup there${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : \"\"}`;\n\n/** Who sent a request, as the client reports it. */\nexport const clientIdentity = (request: Request) => {\n\tconst header = (name: string) =>\n\t\trequest.headers.get(name)?.slice(0, 200) || undefined;\n\treturn { user: header(clientHeaders.user), host: header(clientHeaders.host) };\n};\nexport type ClientIdentity = ReturnType<typeof clientIdentity>;\n\n/** The tsPLC a request's client runs, as it reports it; clients before 0.3.0 report none. */\nexport const clientRelease = (request: Request) => ({\n\tversion:\n\t\trequest.headers.get(clientHeaders.version)?.slice(0, 50) || undefined,\n\tscripts:\n\t\trequest.headers.get(clientHeaders.scripts)?.slice(0, 100) || undefined,\n});\nexport type ClientRelease = ReturnType<typeof clientRelease>;\n\n/** A line of the agent's `deployments.jsonl`. */\nexport const deploymentSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\trelease: z.string(),\n\t/** The debug manifest's build id, when the release has one. */\n\tbuild: z.string().optional(),\n\toperation: deployOperationSchema,\n\t/** Whether the request sent the controller user or the agent used its stored one; lines from before 0.2.18 lack it. */\n\tcredentials: z.enum([\"provided\", \"stored\"]).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n});\nexport type Deployment = z.infer<typeof deploymentSchema>;\n\n/** A line of the agent's `audit.jsonl`: a login command that changed the controller. */\nexport const auditSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\t/** As typed after `tsplc`, such as `force` or `reset cold`. */\n\tcommand: z.string(),\n\t/** Expressions written or forced, with their values; unforced expressions map to \"\". */\n\tvalues: z.record(z.string(), z.string()),\n\t/** The values read just before the command, when the read succeeded. */\n\tprevious: z.record(z.string(), z.string()).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n\trelease: z.string().optional(),\n\terror: z.string().optional(),\n});\nexport type Audit = z.infer<typeof auditSchema>;\n",
5
+ "import { hostname, userInfo } from \"node:os\";\nimport {\n\ttype LoginCommand,\n\tloginResultSchema,\n\ttype Rollback,\n\tworkerScriptsDigest,\n} from \"@tsplc/build\";\nimport { z } from \"zod\";\nimport {\n\tagentVersionHeader,\n\ttype Comparison,\n\ttype Credentials,\n\tclientHeaders,\n\tcomparisonSchema,\n\tcontrollerSchema,\n\ttype DeployOptions,\n\terrorSchema,\n\teventSchema,\n\tlogoutSchema,\n\tnetworkInterfaceSchema,\n\ttype ReleaseManifest,\n\ttype ReleaseUpload,\n\treleaseSchema,\n\treleaseUploadType,\n\tstatusSchema,\n\ttype Target,\n\ttargetSchema,\n\ttsplcVersion,\n\tupgradesItself,\n\tvariableSchema,\n\tversionMismatch,\n} from \"./protocol\";\nimport {\n\tbucketDigests,\n\tencodeUpload,\n\tfileBucket,\n\ttype ReleaseContent,\n\tshortDigest,\n} from \"./transfer\";\n\n/**\n * A failed agent operation; `downloadRequired` means only a full download can deploy, and\n * `rollback` what became of the controller after a download failed mid-transfer.\n */\nexport class AgentOperationError extends Error {\n\treadonly downloadRequired: boolean;\n\treadonly rollback: Rollback | undefined;\n\n\tconstructor(\n\t\tmessage: string,\n\t\t{\n\t\t\tdownloadRequired = false,\n\t\t\trollback,\n\t\t}: { downloadRequired?: boolean; rollback?: Rollback } = {},\n\t) {\n\t\tsuper(message);\n\t\tthis.downloadRequired = downloadRequired;\n\t\tthis.rollback = rollback;\n\t}\n}\n\n/** A file to upload, at its path in the release. */\nexport interface ReleaseFile {\n\tpath: string;\n\tcontent: Blob;\n}\n\n/** Talks to a plant agent at `url`, such as its Tailscale name and port. */\nexport const createAgentClient = (options: { url: string; token: string }) => {\n\t// The agent records who deployed and who changed the controller, and refuses another tsPLC version.\n\tconst identity = workerScriptsDigest()\n\t\t.then(\n\t\t\t(scripts) => ({ [clientHeaders.scripts]: scripts }),\n\t\t\t// The digest only tells local builds apart; an installation that can't read its scripts still deploys.\n\t\t\t() => ({}),\n\t\t)\n\t\t.then((scripts) => ({\n\t\t\t[clientHeaders.user]: userInfo().username,\n\t\t\t[clientHeaders.host]: hostname(),\n\t\t\t[clientHeaders.version]: tsplcVersion,\n\t\t\t...scripts,\n\t\t}));\n\tconst call = async (path: string, init: RequestInit = {}) => {\n\t\tconst response = await fetch(new URL(path, options.url), {\n\t\t\t...init,\n\t\t\theaders: {\n\t\t\t\t...init.headers,\n\t\t\t\t...(await identity),\n\t\t\t\tAuthorization: `Bearer ${options.token}`,\n\t\t\t},\n\t\t}).catch((cause: unknown) => {\n\t\t\tthrow new Error(`Cannot reach the plant agent at ${options.url}`, {\n\t\t\t\tcause,\n\t\t\t});\n\t\t});\n\t\tif (!response.ok) {\n\t\t\tconst body = await response.json().catch(() => ({}));\n\t\t\tthrow new AgentOperationError(\n\t\t\t\terrorSchema.safeParse(body).data?.error ??\n\t\t\t\t\t`The agent answered ${response.status}`,\n\t\t\t);\n\t\t}\n\t\treturn response;\n\t};\n\tconst get = async <T>(path: string, schema: z.ZodType<T>) =>\n\t\tschema.parse(await (await call(path)).json());\n\tconst send = async <T>(\n\t\tmethod: string,\n\t\tpath: string,\n\t\tbody: unknown,\n\t\tschema: z.ZodType<T>,\n\t) =>\n\t\tschema.parse(\n\t\t\tawait (\n\t\t\t\tawait call(path, {\n\t\t\t\t\tmethod,\n\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\tbody: JSON.stringify(body),\n\t\t\t\t})\n\t\t\t).json(),\n\t\t);\n\n\t/** Reads a streamed operation, reporting progress, until its result or failure. */\n\tconst operation = async (\n\t\tresponse: Response,\n\t\tonProgress: (message: string) => void,\n\t) => {\n\t\tconst reader = response.body\n\t\t\t?.pipeThrough(new TextDecoderStream())\n\t\t\t.getReader();\n\t\tif (!reader) {\n\t\t\tthrow new Error(\"The agent returned no operation stream\");\n\t\t}\n\t\tlet buffered = \"\";\n\t\twhile (true) {\n\t\t\tconst { done, value } = await reader.read();\n\t\t\tif (done) {\n\t\t\t\tthrow new Error(\"The agent closed the operation without a result\");\n\t\t\t}\n\t\t\tbuffered += value;\n\t\t\tconst lines = buffered.split(\"\\n\");\n\t\t\tbuffered = lines.pop() ?? \"\";\n\t\t\tfor (const line of lines.filter(Boolean)) {\n\t\t\t\tconst event = eventSchema.parse(JSON.parse(line));\n\t\t\t\tif (event.kind === \"progress\") {\n\t\t\t\t\tonProgress(event.message);\n\t\t\t\t} else if (event.kind === \"done\") {\n\t\t\t\t\treturn event.result;\n\t\t\t\t} else {\n\t\t\t\t\tthrow new AgentOperationError(event.message, {\n\t\t\t\t\t\tdownloadRequired: event.downloadRequired,\n\t\t\t\t\t\trollback: event.rollback,\n\t\t\t\t\t});\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t};\n\n\t/** What the agent holds of a release with these bucket digests. */\n\tconst compare = (buckets: string[]) =>\n\t\tsend(\"POST\", \"/releases/compare\", { buckets }, comparisonSchema);\n\n\treturn {\n\t\tstatus: () => get(\"/status\", statusSchema),\n\t\tinterfaces: () => get(\"/interfaces\", z.array(networkInterfaceSchema)),\n\t\tdiscover: (name: string) =>\n\t\t\tsend(\"POST\", \"/discover\", { name }, z.array(controllerSchema)),\n\t\tsetTarget: (target: Target) => send(\"PUT\", \"/target\", target, targetSchema),\n\t\tvariables: () => get(\"/variables\", z.array(variableSchema)),\n\t\tdeploy: async (\n\t\t\trelease: { manifest: ReleaseManifest; files: ReleaseFile[] },\n\t\t\tsettings: DeployOptions,\n\t\t\tonProgress: (message: string) => void,\n\t\t) => {\n\t\t\t// Before uploading: an agent of another version, including one from before version checks,\n\t\t\t// would compile the release with scripts this client doesn't expect.\n\t\t\tconst agentVersion = (await call(\"/status\")).headers.get(\n\t\t\t\tagentVersionHeader,\n\t\t\t);\n\t\t\tif (agentVersion !== tsplcVersion) {\n\t\t\t\tthrow new AgentOperationError(\n\t\t\t\t\tversionMismatch({\n\t\t\t\t\t\tagent: agentVersion,\n\t\t\t\t\t\tclient: tsplcVersion,\n\t\t\t\t\t\tagentUpgrades: upgradesItself(agentVersion),\n\t\t\t\t\t}),\n\t\t\t\t);\n\t\t\t}\n\t\t\tconst files = await Promise.all(\n\t\t\t\trelease.files.map(async ({ path, content }) => ({\n\t\t\t\t\tpath,\n\t\t\t\t\tcontent: await content.bytes(),\n\t\t\t\t})),\n\t\t\t);\n\t\t\tconst digests = files.map(({ path, content }) => ({\n\t\t\t\tpath,\n\t\t\t\tdigest: shortDigest(content),\n\t\t\t}));\n\t\t\tconst buckets = bucketDigests(digests);\n\t\t\tconst body = await releaseUpload(\n\t\t\t\t{ manifest: release.manifest, options: settings, buckets },\n\t\t\t\tfiles,\n\t\t\t\tawait compare(buckets),\n\t\t\t\tonProgress,\n\t\t\t);\n\t\t\treturn releaseSchema.parse(\n\t\t\t\tawait operation(\n\t\t\t\t\tawait call(\"/deploy\", { method: \"POST\", ...body }),\n\t\t\t\t\tonProgress,\n\t\t\t\t),\n\t\t\t);\n\t\t},\n\t\tlogin: async (\n\t\t\tcredentials: Credentials | null,\n\t\t\tonProgress: (message: string) => void,\n\t\t) =>\n\t\t\tloginResultSchema.parse(\n\t\t\t\tawait operation(\n\t\t\t\t\tawait call(\"/login\", {\n\t\t\t\t\t\tmethod: \"POST\",\n\t\t\t\t\t\theaders: { \"Content-Type\": \"application/json\" },\n\t\t\t\t\t\tbody: JSON.stringify(credentials),\n\t\t\t\t\t}),\n\t\t\t\t\tonProgress,\n\t\t\t\t),\n\t\t\t),\n\t\tcommand: (command: LoginCommand) =>\n\t\t\tsend(\"POST\", \"/login/command\", command, loginResultSchema),\n\t\tlogout: () => send(\"DELETE\", \"/login\", undefined, logoutSchema),\n\t};\n};\nexport type AgentClient = ReturnType<typeof createAgentClient>;\n\n/**\n * A release upload built on the release the agent compared it with: in each bucket that differs,\n * the files the agent lacks and the paths to drop. Without a base, every file.\n */\nconst releaseUpload = async (\n\theader: Pick<ReleaseUpload, \"manifest\" | \"options\" | \"buckets\">,\n\tfiles: readonly ReleaseContent[],\n\t{ base, changed }: Comparison,\n\tonProgress: (message: string) => void,\n) => {\n\tconst stored = new Map(changed.map(({ bucket, files }) => [bucket, files]));\n\tconst uploaded =\n\t\tbase === null\n\t\t\t? files\n\t\t\t: files.filter(({ path, content }) => {\n\t\t\t\t\tconst held = stored.get(fileBucket(path));\n\t\t\t\t\treturn held !== undefined && held[path] !== shortDigest(content);\n\t\t\t\t});\n\tconst paths = new Set(files.map(({ path }) => path));\n\tconst remove = [...stored.values()].flatMap((held) =>\n\t\tObject.keys(held).filter((path) => !paths.has(path)),\n\t);\n\tconst body = await encodeUpload(\n\t\t{ ...header, base, remove } satisfies ReleaseUpload,\n\t\tuploaded,\n\t);\n\tonProgress(\n\t\t`Uploading ${uploaded.length} of ${files.length} files (${Math.ceil(body.length / 1024)} KB)`,\n\t);\n\treturn { headers: { \"Content-Type\": releaseUploadType }, body };\n};\n",
6
+ "import { rollbackSchema } from \"@tsplc/build\";\nimport { tsplcConfigSchema } from \"@tsplc/config\";\nimport { releaseConfigSchema, tcpPort } from \"@tsplc/config/build\";\nimport { z } from \"zod\";\nimport { version } from \"../package.json\";\n\n/** The tsPLC version a client and the agent it deploys through must share. */\nexport const tsplcVersion = version;\n\n/** The controller the agent deploys to, as its runtime's TCP block driver address. */\nexport const targetSchema = z.strictObject({\n\thost: z.string().nonempty(),\n\tport: tcpPort,\n});\nexport type Target = z.infer<typeof targetSchema>;\n\nexport const networkInterfaceSchema = z.strictObject({\n\tname: z.string(),\n\taddress: z.ipv4(),\n\tprefixLength: z.number().int().min(0).max(32),\n});\nexport type NetworkInterface = z.infer<typeof networkInterfaceSchema>;\n\n/** A host on the scanned subnet that accepts connections on the CODESYS runtime port. */\nexport const controllerSchema = z.strictObject({\n\taddress: z.ipv4(),\n\tport: z.number().int(),\n\thostname: z.string().nullable(),\n});\nexport type DiscoveredController = z.infer<typeof controllerSchema>;\n\n/** `POST /discover`: the network interface to scan for controllers. */\nexport const discoverSchema = z.strictObject({ name: z.string() });\n\n/**\n * The controller's user, which the agent passes to CODESYS for one operation. A request sends\n * null instead to use the one stored on the agent's PC.\n */\nexport const credentialsSchema = z.strictObject({\n\tusername: z.string().nonempty(),\n\tpassword: z.string().nonempty(),\n});\nexport type Credentials = z.infer<typeof credentialsSchema>;\n\n/** A published leaf of the deployed program, as CODESYS expressions name it. */\nexport const variableSchema = z.strictObject({\n\tpath: z.string(),\n\ttype: z.string(),\n});\nexport type Variable = z.infer<typeof variableSchema>;\n\n/**\n * What `tsplc deploy` uploads beside its files. `config` is the build config with paths\n * relative to the release: `st/`, `template.project` and `libraries/`.\n */\nexport const releaseManifestSchema = z.strictObject({\n\t// Checked against the owner's schema but kept as uploaded: the release id hashes the manifest.\n\tconfig: z.record(z.string(), z.unknown()).superRefine((config, context) => {\n\t\tconst release = releaseConfigSchema.safeParse(config);\n\t\tif (!release.success) {\n\t\t\tcontext.addIssue({\n\t\t\t\tcode: \"custom\",\n\t\t\t\tmessage: `Invalid release config: ${z.prettifyError(release.error)}`,\n\t\t\t});\n\t\t}\n\t}),\n\tvariables: z.array(variableSchema),\n\t/** The server executable's path in the release, when the project builds one. */\n\tserver: z.string().nonempty().optional(),\n\t/** The project's `debug` section; the program's debug manifest is the release's `debug.json`. */\n\tdebug: tsplcConfigSchema.shape.debug,\n\t/** The variable in the agent's environment holding the server's bearer token, for its telemetry and request trace. */\n\tserverTokenEnv: z.string().nonempty().optional(),\n\t/** The project's `secrets`, whose placeholders in the ST the agent fills in from Bun.secrets. */\n\tsecrets: tsplcConfigSchema.shape.secrets,\n});\nexport type ReleaseManifest = z.infer<typeof releaseManifestSchema>;\n\n/** How `tsplc deploy` compresses each file of a multipart upload, the only form agents without `POST /releases/compare` accept. */\nexport const uploadEncoding = \"gzip\";\n\nexport const deployOptionsSchema = z\n\t.strictObject({\n\t\tcredentials: credentialsSchema.nullable(),\n\t\t/** A full download stops the application; without it only an online change is applied. */\n\t\tdownload: z.boolean(),\n\t\tinitializeUser: z.boolean(),\n\t})\n\t.refine(\n\t\t(options) => options.credentials || !options.initializeUser,\n\t\t\"Initializing the controller's user needs the user's credentials.\",\n\t);\nexport type DeployOptions = z.infer<typeof deployOptionsSchema>;\n\n/** How many buckets a release's files fall into for `POST /releases/compare`. */\nexport const releaseBuckets = 256;\n\n/** A release id, or the start of a SHA-256 of content: 16 lowercase hex digits. */\nconst shortHex = z.string().regex(/^[a-f0-9]{16}$/);\n\n/** `POST /releases/compare`: the digest of each bucket of the release about to be deployed. */\nexport const compareRequestSchema = z.strictObject({\n\tbuckets: z.array(shortHex).length(releaseBuckets),\n});\n\n/**\n * Its answer: the stored release the upload can build on, and that release's files, by path and\n * digest, in each bucket that differs. Without a base the whole release is uploaded.\n */\nexport const comparisonSchema = z.strictObject({\n\tbase: shortHex.nullable(),\n\tchanged: z.array(\n\t\tz.strictObject({\n\t\t\tbucket: z\n\t\t\t\t.number()\n\t\t\t\t.int()\n\t\t\t\t.min(0)\n\t\t\t\t.max(releaseBuckets - 1),\n\t\t\tfiles: z.record(z.string(), shortHex),\n\t\t}),\n\t),\n});\nexport type Comparison = z.infer<typeof comparisonSchema>;\n\n/** A `POST /deploy` body in this form is one release upload rather than a multipart form. */\nexport const releaseUploadType = \"application/vnd.tsplc.release+zstd\";\n\n/**\n * A release upload's header. The release is `base`'s files without the `remove` paths, with the\n * uploaded files added or replacing theirs; `buckets` are the digests it must then have.\n */\nexport const releaseUploadSchema = z.strictObject({\n\tmanifest: releaseManifestSchema,\n\toptions: deployOptionsSchema,\n\tbase: shortHex.nullable(),\n\tbuckets: compareRequestSchema.shape.buckets,\n\tremove: z.array(z.string()),\n});\nexport type ReleaseUpload = z.infer<typeof releaseUploadSchema>;\n\n/** Long operations stream one of these per line. */\nexport const eventSchema = z.discriminatedUnion(\"kind\", [\n\tz.strictObject({ kind: z.literal(\"progress\"), message: z.string() }),\n\tz.strictObject({ kind: z.literal(\"done\"), result: z.unknown() }),\n\tz.strictObject({\n\t\tkind: z.literal(\"error\"),\n\t\tmessage: z.string(),\n\t\t/** The controller has no application from this agent yet, so only a full download can deploy. */\n\t\tdownloadRequired: z.boolean(),\n\t\t/**\n\t\t * What became of the controller after a download failed mid-transfer. Sent only to clients that\n\t\t * send their version, since earlier clients reject an event with fields they don't know.\n\t\t */\n\t\trollback: rollbackSchema.optional(),\n\t}),\n]);\nexport type AgentEvent = z.infer<typeof eventSchema>;\n\n/** A failed request's body. */\nexport const errorSchema = z.object({ error: z.string() });\n\nconst deployOperationSchema = z.enum([\"download\", \"online-change\"]);\n\nexport const releaseSchema = z.strictObject({\n\tid: z.string(),\n\tdeployedAt: z.iso.datetime(),\n\toperation: deployOperationSchema,\n\tcontrollerIds: z.strictObject({ codeId: z.string(), dataId: z.string() }),\n\t/** The running server executable, relative to the releases directory. */\n\tserver: z.string().optional(),\n});\nexport type Release = z.infer<typeof releaseSchema>;\n\nexport const statusSchema = z.strictObject({\n\ttarget: targetSchema.nullable(),\n\trelease: releaseSchema.nullable(),\n\tserver: z\n\t\t.strictObject({ executable: z.string(), running: z.boolean() })\n\t\t.nullable(),\n\t/** The open login's application state and forced expressions, or why it can't report them. */\n\tlogin: z\n\t\t.union([\n\t\t\tz.strictObject({ state: z.string(), forced: z.array(z.string()) }),\n\t\t\tz.strictObject({ error: z.string() }),\n\t\t])\n\t\t.nullable(),\n\t/** A controller user is stored on the agent's PC, so requests may leave theirs out. */\n\tcredentialsStored: z.boolean(),\n});\nexport type AgentStatus = z.infer<typeof statusSchema>;\n\n/** A logout's result: why the login couldn't log out, when its container had to be removed instead. */\nexport const logoutSchema = z.strictObject({ failure: z.string().optional() });\n\n/** Who ran a command, and with which tsPLC, as the client reports it in these headers. */\nexport const clientHeaders = {\n\tuser: \"x-tsplc-user\",\n\thost: \"x-tsplc-host\",\n\tversion: \"x-tsplc-version\",\n\t/** The client's `workerScriptsDigest`, which tells a local build from a release of its version. */\n\tscripts: \"x-tsplc-scripts\",\n} as const;\n\n/** The header each agent response names the agent's tsPLC version in; agents before 0.3.0 send none. */\nexport const agentVersionHeader = \"x-tsplc-agent-version\";\n\n/** Whether `version` is at least `minimum`, comparing major, minor and patch. */\nconst atLeast = (version: string, minimum: [number, number, number]) => {\n\tconst parts = version.split(/[.+-]/).slice(0, 3).map(Number);\n\tfor (const [index, wanted] of minimum.entries()) {\n\t\tconst part = parts[index] ?? 0;\n\t\tif (part !== wanted) {\n\t\t\treturn part > wanted;\n\t\t}\n\t}\n\treturn true;\n};\n\n/** Whether an agent of `version` has `tsplc-agent upgrade`, which arrived in 0.5.0. */\nexport const upgradesItself = (version: string | null) =>\n\tversion !== null && atLeast(version, [0, 5, 0]);\n\n/** Why a client and an agent of different tsPLC versions don't deploy, and what to do about it. */\nexport const versionMismatch = (versions: {\n\tagent: string | null;\n\tclient: string;\n\t/** The agent has `tsplc-agent upgrade`. */\n\tagentUpgrades: boolean;\n}) =>\n\t`The plant agent runs ${versions.agent ? `tsPLC ${versions.agent}` : \"a tsPLC older than 0.3.0\"}, but this deployment comes from tsPLC ${versions.client}. A release is compiled by the agent's own CODESYS scripts, so the two must match: on the plant PC, run ${versions.agentUpgrades ? `tsplc-agent upgrade ${versions.client}` : `bun add --global @tsplc/agent@${versions.client}, then restart tsplc-agent serve`}${versions.agent ? `, or deploy with tsPLC ${versions.agent}` : \"\"}`;\n\n/** Who sent a request, as the client reports it. */\nexport const clientIdentity = (request: Request) => {\n\tconst header = (name: string) =>\n\t\trequest.headers.get(name)?.slice(0, 200) || undefined;\n\treturn { user: header(clientHeaders.user), host: header(clientHeaders.host) };\n};\nexport type ClientIdentity = ReturnType<typeof clientIdentity>;\n\n/** The tsPLC a request's client runs, as it reports it; clients before 0.3.0 report none. */\nexport const clientRelease = (request: Request) => ({\n\tversion:\n\t\trequest.headers.get(clientHeaders.version)?.slice(0, 50) || undefined,\n\tscripts:\n\t\trequest.headers.get(clientHeaders.scripts)?.slice(0, 100) || undefined,\n});\nexport type ClientRelease = ReturnType<typeof clientRelease>;\n\n/** A line of the agent's `deployments.jsonl`. */\nexport const deploymentSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\trelease: z.string(),\n\t/** The debug manifest's build id, when the release has one. */\n\tbuild: z.string().optional(),\n\toperation: deployOperationSchema,\n\t/** Whether the request sent the controller user or the agent used its stored one; lines from before 0.2.18 lack it. */\n\tcredentials: z.enum([\"provided\", \"stored\"]).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n});\nexport type Deployment = z.infer<typeof deploymentSchema>;\n\n/** A line of the agent's `audit.jsonl`: a login command that changed the controller. */\nexport const auditSchema = z.strictObject({\n\tat: z.iso.datetime(),\n\t/** As typed after `tsplc`, such as `force` or `reset cold`. */\n\tcommand: z.string(),\n\t/** Expressions written or forced, with their values; unforced expressions map to \"\". */\n\tvalues: z.record(z.string(), z.string()),\n\t/** The values read just before the command, when the read succeeded. */\n\tprevious: z.record(z.string(), z.string()).optional(),\n\tuser: z.string().optional(),\n\thost: z.string().optional(),\n\trelease: z.string().optional(),\n\terror: z.string().optional(),\n});\nexport type Audit = z.infer<typeof auditSchema>;\n",
7
7
  "import { createHash } from \"node:crypto\";\nimport { releaseBuckets } from \"./protocol\";\n\n/**\n * How `tsplc deploy` sends a release the agent can build from one it already holds. The release's\n * files fall into buckets by path, and each bucket has a digest; the agent answers which buckets\n * differ from a release it stores and that release's files in them, and the client sends only the\n * files the agent lacks, with the release's other parts named rather than sent. The whole upload\n * is one zstd stream: the release's ST files are thousands of small, similar files.\n */\n\n/** A file of a release, at its path in the release. */\nexport interface ReleaseContent {\n\tpath: string;\n\tcontent: Uint8Array<ArrayBuffer>;\n}\n\n/** The first 16 hex digits of a SHA-256: enough to tell a release's files apart, and short on the wire. */\nexport const shortDigest = (data: Uint8Array | string) =>\n\tcreateHash(\"sha256\").update(data).digest(\"hex\").slice(0, 16);\n\n/** The bucket a release path falls in, the same in every release. */\nexport const fileBucket = (path: string) =>\n\tcreateHash(\"sha256\").update(path).digest().readUInt8(0) % releaseBuckets;\n\n/** Each bucket's digest over the paths and contents of its files, from each file's `shortDigest`. */\nexport const bucketDigests = (\n\tfiles: Iterable<{ path: string; digest: string }>,\n): string[] => {\n\tconst buckets = Array.from({ length: releaseBuckets }, (): string[] => []);\n\tfor (const { path, digest } of files) {\n\t\tbuckets[fileBucket(path)]?.push(`${path}\\0${digest}`);\n\t}\n\treturn buckets.map((entries) => shortDigest(entries.sort().join(\"\\n\")));\n};\n\n/** A frame's length prefix: an unsigned 32-bit big-endian byte count. */\nconst lengthBytes = 4;\n\n/** Frames the upload's header and then each file's path and content, and compresses the lot. */\nexport const encodeUpload = async (\n\theader: unknown,\n\tfiles: readonly ReleaseContent[],\n): Promise<Uint8Array<ArrayBuffer>> => {\n\tconst encoder = new TextEncoder();\n\tconst frames = [\n\t\tencoder.encode(JSON.stringify(header)),\n\t\t...files.flatMap(({ path, content }) => [encoder.encode(path), content]),\n\t];\n\tconst body = new Uint8Array(\n\t\tframes.reduce((total, frame) => total + lengthBytes + frame.length, 0),\n\t);\n\tconst view = new DataView(body.buffer);\n\tlet offset = 0;\n\tfor (const frame of frames) {\n\t\tview.setUint32(offset, frame.length);\n\t\tbody.set(frame, offset + lengthBytes);\n\t\toffset += lengthBytes + frame.length;\n\t}\n\treturn new Uint8Array(await Bun.zstdCompress(body, { level: 12 }));\n};\n\n/** An upload's header, still to be validated, and its files. */\nexport const decodeUpload = async (\n\tcompressed: Uint8Array,\n): Promise<{ header: unknown; files: ReleaseContent[] }> => {\n\tconst body = new Uint8Array(await Bun.zstdDecompress(compressed));\n\tconst view = new DataView(body.buffer, body.byteOffset, body.byteLength);\n\tconst frames: Uint8Array<ArrayBuffer>[] = [];\n\tlet offset = 0;\n\twhile (offset < body.length) {\n\t\tif (offset + lengthBytes > body.length) {\n\t\t\tthrow new Error(\"The release upload ends inside a frame\");\n\t\t}\n\t\tconst end = offset + lengthBytes + view.getUint32(offset);\n\t\tif (end > body.length) {\n\t\t\tthrow new Error(\"The release upload ends inside a frame\");\n\t\t}\n\t\tframes.push(body.subarray(offset + lengthBytes, end));\n\t\toffset = end;\n\t}\n\tconst [header, ...rest] = frames;\n\tif (!header || rest.length % 2 !== 0) {\n\t\tthrow new Error(\n\t\t\t\"The release upload has no header or a file without content\",\n\t\t);\n\t}\n\tconst decoder = new TextDecoder();\n\tconst files = Array.from({ length: rest.length / 2 }, (_, index) => ({\n\t\tpath: decoder.decode(rest[2 * index]),\n\t\tcontent: rest[2 * index + 1] ?? new Uint8Array(),\n\t}));\n\treturn { header: JSON.parse(decoder.decode(header)), files };\n};\n"
8
8
  ],
9
- "mappings": ";AAAA;AACA;AAAA;AAAA;AAAA;AAMA,cAAS;;;ACPT;AACA;AACA;AACA;;;;;AAIO,IAAM,eAAe;AAGrB,IAAM,eAAe,EAAE,aAAa;AAAA,EAC1C,MAAM,EAAE,OAAO,EAAE,SAAS;AAAA,EAC1B,MAAM;AACP,CAAC;AAGM,IAAM,yBAAyB,EAAE,aAAa;AAAA,EACpD,MAAM,EAAE,OAAO;AAAA,EACf,SAAS,EAAE,KAAK;AAAA,EAChB,cAAc,EAA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