@xenosystem/primitives 0.5.0 → 0.6.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.
@@ -0,0 +1,41 @@
1
+ /** Largest file this family reads or writes (1 MiB). */
2
+ export declare const PRIVATE_FILE_MAX_BYTES = 1048576;
3
+ export interface PrivateFileReceipt {
4
+ /**
5
+ * `committed`: done (for a read or delete this is also the answer when there was no file).
6
+ * `exists`: a write with `ifAbsent` found a file and left it alone.
7
+ * `not-committed`: refused or failed before anything was published.
8
+ * `uncertain`: failed during publication; the target may hold either version. `retainedFiles` are kept as evidence.
9
+ */
10
+ outcome: 'committed' | 'not-committed' | 'uncertain' | 'exists';
11
+ /** The step that was running when the operation ended. */
12
+ phase: string;
13
+ /** The Windows error code of a failure, 0 on success. */
14
+ errorCode: number;
15
+ /** Temp or backup files left behind in the directory (file names only). */
16
+ retainedFiles: string[];
17
+ /** A read's bytes, or null when the file does not exist. */
18
+ data: Uint8Array | null;
19
+ /** True when a delete removed a file. */
20
+ deleted: boolean;
21
+ }
22
+ export interface PrivateFileRequest {
23
+ path: string;
24
+ operation: 'read' | 'write' | 'delete';
25
+ /** The bytes to write. */
26
+ payload?: Uint8Array;
27
+ /** Write only when the file does not exist yet. */
28
+ ifAbsent?: boolean;
29
+ /** A lower-case UUID naming this operation's temp and backup files. */
30
+ operationId: string;
31
+ }
32
+ /** Whether `privateFileOperation` can run on this machine, and why not when it cannot. */
33
+ export declare function privateFileSupport(): {
34
+ available: boolean;
35
+ reason?: string;
36
+ };
37
+ /**
38
+ * Run one operation. A file-system refusal is reported in the receipt, never thrown. Throws only when the native
39
+ * binary is unavailable (check `privateFileSupport()` first) or the request itself is malformed.
40
+ */
41
+ export declare function privateFileOperation(request: PrivateFileRequest): PrivateFileReceipt;
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PRIVATE_FILE_MAX_BYTES = void 0;
4
+ exports.privateFileSupport = privateFileSupport;
5
+ exports.privateFileOperation = privateFileOperation;
6
+ /**
7
+ * `@xenosystem/primitives/private-file` — read, write or delete one file that only its owner and SYSTEM may open.
8
+ *
9
+ * Each operation takes a gate file in the same directory (so processes take turns), and a write is published so
10
+ * that a reader sees the old bytes or the new bytes, never a partial file: new bytes go to a private temp file,
11
+ * are flushed, and replace the target in one step (`ReplaceFileW`), or are linked into place when the target does
12
+ * not exist yet (so a create never overwrites).
13
+ *
14
+ * Why this exists: the agent SDK ran exactly this through a PowerShell helper that compiled C# on every call.
15
+ * Measured 2026-11-11: 0.6 to 1.2 s per operation on a quiet machine, more under load. A sign-out does many of
16
+ * them, passed the 30 s the Agent host allows one account request, and left the owner signed in on a blank
17
+ * window. Here the same steps run inside the calling process from a binary that ships in this package
18
+ * (`native/win32-<arch>/process.node`); nothing is compiled or started at run time.
19
+ *
20
+ * The files on disk are the same as the helper's (gate `.xeno-protected-write.lock`, temp and backup
21
+ * `.xeno-protected-<operation id>.tmp|.backup`), so a process still using the helper and a process using this
22
+ * can share a directory and still take turns.
23
+ *
24
+ * Windows only. `privateFileSupport()` says whether it can be used; a caller keeps its own fallback otherwise.
25
+ */
26
+ const node_fs_1 = require("node:fs");
27
+ const node_module_1 = require("node:module");
28
+ const node_path_1 = require("node:path");
29
+ const here_ts_1 = require("../process/here.js");
30
+ /** Largest file this family reads or writes (1 MiB). */
31
+ exports.PRIVATE_FILE_MAX_BYTES = 1_048_576;
32
+ let nativeCache;
33
+ function loadNative() {
34
+ if (nativeCache)
35
+ return nativeCache;
36
+ if (process.platform !== 'win32')
37
+ return (nativeCache = { reason: 'not Windows' });
38
+ const name = `win32-${process.arch}`;
39
+ // src/private-file (tests) and dist/{esm,cjs}/private-file (published) both sit under the package directory.
40
+ const candidates = [(0, node_path_1.join)(here_ts_1.moduleDir, '..', '..', 'native', name, 'process.node'), (0, node_path_1.join)(here_ts_1.moduleDir, '..', '..', '..', 'native', name, 'process.node')];
41
+ const file = candidates.find((p) => (0, node_fs_1.existsSync)(p));
42
+ if (!file)
43
+ return (nativeCache = { reason: `no native binary for ${name}` });
44
+ try {
45
+ const binding = (0, node_module_1.createRequire)(file)(file);
46
+ if (typeof binding.privateFileOperation !== 'function')
47
+ return (nativeCache = { reason: 'native binary has no privateFileOperation' });
48
+ return (nativeCache = { run: binding.privateFileOperation });
49
+ }
50
+ catch (error) {
51
+ return (nativeCache = { reason: `native binary failed to load: ${error.message}` });
52
+ }
53
+ }
54
+ /** Whether `privateFileOperation` can run on this machine, and why not when it cannot. */
55
+ function privateFileSupport() {
56
+ const native = loadNative();
57
+ return native.run ? { available: true } : { available: false, ...(native.reason ? { reason: native.reason } : {}) };
58
+ }
59
+ const OUTCOMES = new Set(['committed', 'not-committed', 'uncertain', 'exists']);
60
+ /**
61
+ * Run one operation. A file-system refusal is reported in the receipt, never thrown. Throws only when the native
62
+ * binary is unavailable (check `privateFileSupport()` first) or the request itself is malformed.
63
+ */
64
+ function privateFileOperation(request) {
65
+ const native = loadNative();
66
+ if (!native.run)
67
+ throw new Error(`private-file is unavailable: ${native.reason ?? 'unknown reason'}`);
68
+ if (typeof request.path !== 'string' || !request.path)
69
+ throw new TypeError('private-file: path is required');
70
+ if (!['read', 'write', 'delete'].includes(request.operation))
71
+ throw new TypeError('private-file: unknown operation');
72
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(request.operationId))
73
+ throw new TypeError('private-file: operationId must be a lower-case UUID');
74
+ const payload = request.operation === 'write' ? request.payload ?? new Uint8Array(0) : null;
75
+ if (payload && payload.byteLength > exports.PRIVATE_FILE_MAX_BYTES) {
76
+ return { outcome: 'not-committed', phase: 'validate', errorCode: 0, retainedFiles: [], data: null, deleted: false };
77
+ }
78
+ // The binding takes a Buffer; a plain Uint8Array view is wrapped without copying.
79
+ const bytes = payload ? Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength) : null;
80
+ const raw = native.run(request.path, request.operation, bytes, request.ifAbsent === true, request.operationId);
81
+ if (!OUTCOMES.has(raw.outcome))
82
+ throw new Error('private-file: native binary returned an unknown outcome');
83
+ return {
84
+ outcome: raw.outcome,
85
+ phase: raw.phase,
86
+ errorCode: raw.errorCode,
87
+ retainedFiles: [...raw.retainedFiles],
88
+ data: raw.data ?? null,
89
+ deleted: raw.deleted === true,
90
+ };
91
+ }
@@ -0,0 +1,41 @@
1
+ /** Largest file this family reads or writes (1 MiB). */
2
+ export declare const PRIVATE_FILE_MAX_BYTES = 1048576;
3
+ export interface PrivateFileReceipt {
4
+ /**
5
+ * `committed`: done (for a read or delete this is also the answer when there was no file).
6
+ * `exists`: a write with `ifAbsent` found a file and left it alone.
7
+ * `not-committed`: refused or failed before anything was published.
8
+ * `uncertain`: failed during publication; the target may hold either version. `retainedFiles` are kept as evidence.
9
+ */
10
+ outcome: 'committed' | 'not-committed' | 'uncertain' | 'exists';
11
+ /** The step that was running when the operation ended. */
12
+ phase: string;
13
+ /** The Windows error code of a failure, 0 on success. */
14
+ errorCode: number;
15
+ /** Temp or backup files left behind in the directory (file names only). */
16
+ retainedFiles: string[];
17
+ /** A read's bytes, or null when the file does not exist. */
18
+ data: Uint8Array | null;
19
+ /** True when a delete removed a file. */
20
+ deleted: boolean;
21
+ }
22
+ export interface PrivateFileRequest {
23
+ path: string;
24
+ operation: 'read' | 'write' | 'delete';
25
+ /** The bytes to write. */
26
+ payload?: Uint8Array;
27
+ /** Write only when the file does not exist yet. */
28
+ ifAbsent?: boolean;
29
+ /** A lower-case UUID naming this operation's temp and backup files. */
30
+ operationId: string;
31
+ }
32
+ /** Whether `privateFileOperation` can run on this machine, and why not when it cannot. */
33
+ export declare function privateFileSupport(): {
34
+ available: boolean;
35
+ reason?: string;
36
+ };
37
+ /**
38
+ * Run one operation. A file-system refusal is reported in the receipt, never thrown. Throws only when the native
39
+ * binary is unavailable (check `privateFileSupport()` first) or the request itself is malformed.
40
+ */
41
+ export declare function privateFileOperation(request: PrivateFileRequest): PrivateFileReceipt;
@@ -0,0 +1,86 @@
1
+ /**
2
+ * `@xenosystem/primitives/private-file` — read, write or delete one file that only its owner and SYSTEM may open.
3
+ *
4
+ * Each operation takes a gate file in the same directory (so processes take turns), and a write is published so
5
+ * that a reader sees the old bytes or the new bytes, never a partial file: new bytes go to a private temp file,
6
+ * are flushed, and replace the target in one step (`ReplaceFileW`), or are linked into place when the target does
7
+ * not exist yet (so a create never overwrites).
8
+ *
9
+ * Why this exists: the agent SDK ran exactly this through a PowerShell helper that compiled C# on every call.
10
+ * Measured 2026-11-11: 0.6 to 1.2 s per operation on a quiet machine, more under load. A sign-out does many of
11
+ * them, passed the 30 s the Agent host allows one account request, and left the owner signed in on a blank
12
+ * window. Here the same steps run inside the calling process from a binary that ships in this package
13
+ * (`native/win32-<arch>/process.node`); nothing is compiled or started at run time.
14
+ *
15
+ * The files on disk are the same as the helper's (gate `.xeno-protected-write.lock`, temp and backup
16
+ * `.xeno-protected-<operation id>.tmp|.backup`), so a process still using the helper and a process using this
17
+ * can share a directory and still take turns.
18
+ *
19
+ * Windows only. `privateFileSupport()` says whether it can be used; a caller keeps its own fallback otherwise.
20
+ */
21
+ import { existsSync } from 'node:fs';
22
+ import { createRequire } from 'node:module';
23
+ import { join } from 'node:path';
24
+ import { moduleDir } from "../process/here.js";
25
+ /** Largest file this family reads or writes (1 MiB). */
26
+ export const PRIVATE_FILE_MAX_BYTES = 1_048_576;
27
+ let nativeCache;
28
+ function loadNative() {
29
+ if (nativeCache)
30
+ return nativeCache;
31
+ if (process.platform !== 'win32')
32
+ return (nativeCache = { reason: 'not Windows' });
33
+ const name = `win32-${process.arch}`;
34
+ // src/private-file (tests) and dist/{esm,cjs}/private-file (published) both sit under the package directory.
35
+ const candidates = [join(moduleDir, '..', '..', 'native', name, 'process.node'), join(moduleDir, '..', '..', '..', 'native', name, 'process.node')];
36
+ const file = candidates.find((p) => existsSync(p));
37
+ if (!file)
38
+ return (nativeCache = { reason: `no native binary for ${name}` });
39
+ try {
40
+ const binding = createRequire(file)(file);
41
+ if (typeof binding.privateFileOperation !== 'function')
42
+ return (nativeCache = { reason: 'native binary has no privateFileOperation' });
43
+ return (nativeCache = { run: binding.privateFileOperation });
44
+ }
45
+ catch (error) {
46
+ return (nativeCache = { reason: `native binary failed to load: ${error.message}` });
47
+ }
48
+ }
49
+ /** Whether `privateFileOperation` can run on this machine, and why not when it cannot. */
50
+ export function privateFileSupport() {
51
+ const native = loadNative();
52
+ return native.run ? { available: true } : { available: false, ...(native.reason ? { reason: native.reason } : {}) };
53
+ }
54
+ const OUTCOMES = new Set(['committed', 'not-committed', 'uncertain', 'exists']);
55
+ /**
56
+ * Run one operation. A file-system refusal is reported in the receipt, never thrown. Throws only when the native
57
+ * binary is unavailable (check `privateFileSupport()` first) or the request itself is malformed.
58
+ */
59
+ export function privateFileOperation(request) {
60
+ const native = loadNative();
61
+ if (!native.run)
62
+ throw new Error(`private-file is unavailable: ${native.reason ?? 'unknown reason'}`);
63
+ if (typeof request.path !== 'string' || !request.path)
64
+ throw new TypeError('private-file: path is required');
65
+ if (!['read', 'write', 'delete'].includes(request.operation))
66
+ throw new TypeError('private-file: unknown operation');
67
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(request.operationId))
68
+ throw new TypeError('private-file: operationId must be a lower-case UUID');
69
+ const payload = request.operation === 'write' ? request.payload ?? new Uint8Array(0) : null;
70
+ if (payload && payload.byteLength > PRIVATE_FILE_MAX_BYTES) {
71
+ return { outcome: 'not-committed', phase: 'validate', errorCode: 0, retainedFiles: [], data: null, deleted: false };
72
+ }
73
+ // The binding takes a Buffer; a plain Uint8Array view is wrapped without copying.
74
+ const bytes = payload ? Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength) : null;
75
+ const raw = native.run(request.path, request.operation, bytes, request.ifAbsent === true, request.operationId);
76
+ if (!OUTCOMES.has(raw.outcome))
77
+ throw new Error('private-file: native binary returned an unknown outcome');
78
+ return {
79
+ outcome: raw.outcome,
80
+ phase: raw.phase,
81
+ errorCode: raw.errorCode,
82
+ retainedFiles: [...raw.retainedFiles],
83
+ data: raw.data ?? null,
84
+ deleted: raw.deleted === true,
85
+ };
86
+ }
Binary file
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@xenosystem/primitives",
3
- "version": "0.5.0",
4
- "description": "XENO back-end rung 1 primitives: dirs (the XENO local home), secrets (envelope-encrypted credentials), updates (the gated app updater), live (the client for XENO Multiplayer) and process (start a command so that stopping it stops everything it started).",
3
+ "version": "0.6.0",
4
+ "description": "XENO back-end rung 1 primitives: dirs (the XENO local home), secrets (envelope-encrypted credentials), updates (the gated app updater), live (the client for XENO Multiplayer) process (start a command so that stopping it stops everything it started) and private-file (owner-only files, published atomically, without a helper process).",
5
5
  "license": "UNLICENSED",
6
6
  "type": "module",
7
7
  "sideEffects": false,
@@ -74,6 +74,16 @@
74
74
  "default": "./dist/cjs/process/index.js"
75
75
  }
76
76
  },
77
+ "./private-file": {
78
+ "import": {
79
+ "types": "./dist/esm/private-file/index.d.ts",
80
+ "default": "./dist/esm/private-file/index.js"
81
+ },
82
+ "require": {
83
+ "types": "./dist/cjs/private-file/index.d.ts",
84
+ "default": "./dist/cjs/private-file/index.js"
85
+ }
86
+ },
77
87
  "./package.json": "./package.json"
78
88
  },
79
89
  "bin": {