@gmitch215/folio 0.0.0-stage → 1.0.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.
Files changed (57) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +541 -2
  3. package/dist/bake.d.ts +179 -0
  4. package/dist/bake.js +704 -0
  5. package/dist/browser-worker.d.ts +9 -0
  6. package/dist/browser-worker.js +37 -0
  7. package/dist/browser.d.ts +68 -0
  8. package/dist/browser.js +274 -0
  9. package/dist/compiler.d.ts +79 -0
  10. package/dist/compiler.js +620 -0
  11. package/dist/context.d.ts +33 -0
  12. package/dist/context.js +93 -0
  13. package/dist/coordinator.d.ts +27 -0
  14. package/dist/coordinator.js +191 -0
  15. package/dist/extract.d.ts +165 -0
  16. package/dist/extract.js +1817 -0
  17. package/dist/frames.d.ts +33 -0
  18. package/dist/frames.js +159 -0
  19. package/dist/guards.d.ts +12 -0
  20. package/dist/guards.js +202 -0
  21. package/dist/host.d.ts +60 -0
  22. package/dist/host.js +374 -0
  23. package/dist/import-order.d.ts +2 -0
  24. package/dist/import-order.js +114 -0
  25. package/dist/index.d.ts +4 -0
  26. package/dist/index.js +2 -0
  27. package/dist/inline.d.ts +68 -0
  28. package/dist/inline.js +503 -0
  29. package/dist/iteration-admission.d.ts +76 -0
  30. package/dist/iteration-admission.js +72 -0
  31. package/dist/iteration-layout.d.ts +75 -0
  32. package/dist/iteration-layout.js +118 -0
  33. package/dist/iteration-owner.d.ts +32 -0
  34. package/dist/iteration-owner.js +223 -0
  35. package/dist/iteration-worker.d.ts +1 -0
  36. package/dist/iteration-worker.js +150 -0
  37. package/dist/iteration.d.ts +163 -0
  38. package/dist/iteration.js +435 -0
  39. package/dist/managed.d.ts +92 -0
  40. package/dist/managed.js +421 -0
  41. package/dist/memory.d.ts +10 -0
  42. package/dist/memory.js +89 -0
  43. package/dist/node.d.ts +138 -0
  44. package/dist/node.js +1153 -0
  45. package/dist/pages.d.ts +109 -0
  46. package/dist/pages.js +339 -0
  47. package/dist/remote.d.ts +86 -0
  48. package/dist/remote.js +255 -0
  49. package/dist/tasks.d.ts +107 -0
  50. package/dist/tasks.js +330 -0
  51. package/dist/transaction.d.ts +23 -0
  52. package/dist/transaction.js +93 -0
  53. package/dist/values.d.ts +3 -0
  54. package/dist/values.js +25 -0
  55. package/dist/worker.d.ts +1 -0
  56. package/dist/worker.js +86 -0
  57. package/package.json +130 -5
@@ -0,0 +1,33 @@
1
+ import type { TransactionResult } from './transaction.ts';
2
+ /** Lossless page encoding; omitted pages contain only zero bytes. */
3
+ export interface SnapshotPages {
4
+ memoryBytes: number;
5
+ pages: number[];
6
+ }
7
+ /** Encodes sparse arenas. A dense payload borrows the input until encodeFrame copies it. */
8
+ export declare function encodeSnapshot(bytes: Uint8Array): {
9
+ snapshot?: SnapshotPages;
10
+ payload: Uint8Array;
11
+ };
12
+ /** Checks sparse metadata before allocation or writes; returns the complete logical byte length. */
13
+ export declare function snapshotLength(snapshot: SnapshotPages | undefined, payload: Uint8Array): number;
14
+ /** Restores a complete snapshot, clearing pages omitted by the sparse representation. */
15
+ export declare function restoreSnapshot(target: Uint8Array, payload: Uint8Array, snapshot?: SnapshotPages): void;
16
+ export declare function encodeFrame(header: unknown, payload?: Uint8Array, maximum?: number): Uint8Array;
17
+ export declare function decodeFrame<T>(bytes: Uint8Array, maximum: number): {
18
+ header: T;
19
+ payload: Uint8Array;
20
+ };
21
+ export interface FrameIdentity {
22
+ session: string;
23
+ epoch: number;
24
+ sequence: number;
25
+ }
26
+ export declare function validateIdentity(value: FrameIdentity): void;
27
+ export declare function encodeResults(identity: FrameIdentity, results: TransactionResult[], maximum?: number): Uint8Array;
28
+ export declare function decodeResults(bytes: Uint8Array, identity: FrameIdentity, options: {
29
+ maximumFrameBytes: number;
30
+ memoryBytes: number;
31
+ maxBytes: number;
32
+ calls: number;
33
+ }): TransactionResult[];
package/dist/frames.js ADDED
@@ -0,0 +1,159 @@
1
+ import { decodeValue, encodeValue } from "./remote.js";
2
+ const magic = 0x314f4c46;
3
+ const encoder = new TextEncoder();
4
+ const decoder = new TextDecoder('utf-8', { fatal: true });
5
+ /** Encodes sparse arenas. A dense payload borrows the input until encodeFrame copies it. */
6
+ export function encodeSnapshot(bytes) {
7
+ if (bytes.length % 65536)
8
+ throw new RangeError('invalid snapshot page size');
9
+ const pages = [];
10
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
11
+ for (let offset = 0; offset < bytes.length; offset += 65536) {
12
+ for (let word = offset; word < offset + 65536; word += 4)
13
+ if (view.getUint32(word, true) !== 0) {
14
+ pages.push(offset / 65536);
15
+ break;
16
+ }
17
+ }
18
+ if (pages.length > 4096 || pages.length * 65536 + pages.length * 8 + 64 >= bytes.length)
19
+ return { payload: bytes };
20
+ const payload = new Uint8Array(pages.length * 65536);
21
+ pages.forEach((page, index) => payload.set(bytes.subarray(page * 65536, (page + 1) * 65536), index * 65536));
22
+ return { snapshot: { memoryBytes: bytes.length, pages }, payload };
23
+ }
24
+ /** Checks sparse metadata before allocation or writes; returns the complete logical byte length. */
25
+ export function snapshotLength(snapshot, payload) {
26
+ if (snapshot === undefined)
27
+ return payload.length;
28
+ if (!Number.isSafeInteger(snapshot?.memoryBytes) ||
29
+ snapshot.memoryBytes < 0 ||
30
+ snapshot.memoryBytes % 65536 ||
31
+ !Array.isArray(snapshot.pages) ||
32
+ snapshot.pages.length * 65536 !== payload.length)
33
+ throw new TypeError('invalid sparse snapshot');
34
+ let previous = -1;
35
+ for (const page of snapshot.pages) {
36
+ if (!Number.isSafeInteger(page) || page <= previous || page * 65536 >= snapshot.memoryBytes)
37
+ throw new TypeError('invalid sparse snapshot page');
38
+ previous = page;
39
+ }
40
+ return snapshot.memoryBytes;
41
+ }
42
+ /** Restores a complete snapshot, clearing pages omitted by the sparse representation. */
43
+ export function restoreSnapshot(target, payload, snapshot) {
44
+ if (snapshotLength(snapshot, payload) !== target.length)
45
+ throw new RangeError('snapshot size differs');
46
+ if (!snapshot) {
47
+ target.set(payload);
48
+ return;
49
+ }
50
+ target.fill(0);
51
+ snapshot.pages.forEach((page, index) => target.set(payload.subarray(index * 65536, (index + 1) * 65536), page * 65536));
52
+ }
53
+ export function encodeFrame(header, payload = new Uint8Array(), maximum = 0x100100000) {
54
+ const metadata = encoder.encode(JSON.stringify(encodeValue(header)));
55
+ if (metadata.length > 65536)
56
+ throw new RangeError('frame header exceeds limit');
57
+ const length = 12 + metadata.length + payload.length;
58
+ if (payload.length > 0xffffffff || length > maximum)
59
+ throw new RangeError(`frame of ${length} bytes exceeds the limit of ${maximum} bytes`);
60
+ const bytes = new Uint8Array(length);
61
+ const view = new DataView(bytes.buffer);
62
+ view.setUint32(0, magic, true);
63
+ view.setUint32(4, metadata.length, true);
64
+ view.setUint32(8, payload.length, true);
65
+ bytes.set(metadata, 12);
66
+ bytes.set(payload, 12 + metadata.length);
67
+ return bytes;
68
+ }
69
+ export function decodeFrame(bytes, maximum) {
70
+ if (bytes.length < 12 || bytes.length > maximum)
71
+ throw new RangeError('invalid frame size');
72
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
73
+ const header = view.getUint32(4, true), payload = view.getUint32(8, true);
74
+ if (view.getUint32(0, true) !== magic ||
75
+ header > 65536 ||
76
+ 12 + header + payload !== bytes.length)
77
+ throw new TypeError('invalid frame layout');
78
+ return {
79
+ header: decodeValue(JSON.parse(decoder.decode(bytes.subarray(12, 12 + header)))),
80
+ payload: bytes.subarray(12 + header)
81
+ };
82
+ }
83
+ export function validateIdentity(value) {
84
+ if (typeof value?.session !== 'string' ||
85
+ value.session.length < 1 ||
86
+ value.session.length > 128 ||
87
+ !Number.isSafeInteger(value.epoch) ||
88
+ value.epoch < 0 ||
89
+ !Number.isSafeInteger(value.sequence) ||
90
+ value.sequence < 0)
91
+ throw new TypeError('invalid frame identity');
92
+ }
93
+ export function encodeResults(identity, results, maximum = 0x100100000) {
94
+ const length = results.reduce((sum, result) => sum + result.reads.length * 4 + result.writes.length * 8, 0);
95
+ if (length > 0xffffffff || length + 12 > maximum)
96
+ throw new RangeError('result payload exceeds limit');
97
+ const payload = new Uint8Array(length), view = new DataView(payload.buffer);
98
+ let offset = 0;
99
+ const descriptors = results.map(({ reads, writes, ...result }) => {
100
+ for (const address of reads) {
101
+ view.setUint32(offset, address, true);
102
+ offset += 4;
103
+ }
104
+ for (const [address, value] of writes) {
105
+ view.setUint32(offset, address, true);
106
+ view.setUint32(offset + 4, value, true);
107
+ offset += 8;
108
+ }
109
+ return { ...result, reads: reads.length, writes: writes.length };
110
+ });
111
+ return encodeFrame({
112
+ session: identity.session,
113
+ epoch: identity.epoch,
114
+ sequence: identity.sequence,
115
+ results: descriptors
116
+ }, payload, maximum);
117
+ }
118
+ export function decodeResults(bytes, identity, options) {
119
+ const { header, payload } = decodeFrame(bytes, options.maximumFrameBytes);
120
+ validateIdentity(header);
121
+ if (header.session !== identity.session ||
122
+ header.epoch !== identity.epoch ||
123
+ header.sequence !== identity.sequence)
124
+ throw new TypeError('stale lane response');
125
+ if (!Array.isArray(header.results) || header.results.length !== options.calls)
126
+ throw new TypeError('invalid lane result count');
127
+ let offset = 0, retained = 0;
128
+ const view = new DataView(payload.buffer, payload.byteOffset, payload.byteLength);
129
+ const results = header.results.map(({ reads, writes, ...result }) => {
130
+ if (![reads, writes].every((n) => Number.isSafeInteger(n) && n >= 0))
131
+ throw new TypeError('invalid lane tracking counts');
132
+ retained += reads + writes;
133
+ if (retained > options.maxBytes + 8 || offset + reads * 4 + writes * 8 > payload.length)
134
+ throw new RangeError('lane tracking exceeds limit');
135
+ if ((result.trap !== undefined && typeof result.trap !== 'string') ||
136
+ (result.errorKind !== undefined && typeof result.errorKind !== 'string') ||
137
+ (result.exhausted !== undefined && typeof result.exhausted !== 'boolean'))
138
+ throw new TypeError('invalid lane trap');
139
+ const readSet = [], writeSet = [];
140
+ for (let i = 0; i < reads; i++) {
141
+ const address = view.getUint32(offset, true);
142
+ offset += 4;
143
+ if (address >= options.memoryBytes)
144
+ throw new RangeError('lane read outside arena');
145
+ readSet.push(address);
146
+ }
147
+ for (let i = 0; i < writes; i++) {
148
+ const address = view.getUint32(offset, true), value = view.getUint32(offset + 4, true);
149
+ offset += 8;
150
+ if (address >= options.memoryBytes || value > 255)
151
+ throw new RangeError('lane write outside arena');
152
+ writeSet.push([address, value]);
153
+ }
154
+ return { ...result, reads: readSet, writes: writeSet };
155
+ });
156
+ if (offset !== payload.length)
157
+ throw new TypeError('unconsumed lane payload');
158
+ return results;
159
+ }
@@ -0,0 +1,12 @@
1
+ import binaryen from 'binaryen';
2
+ export interface NativeAccess {
3
+ parameter: number;
4
+ offset: number;
5
+ bytes: number;
6
+ write: boolean;
7
+ }
8
+ export interface NativePlan {
9
+ accesses: NativeAccess[];
10
+ workParameters: number[];
11
+ }
12
+ export declare function nativePlan(module: binaryen.Module, fn: binaryen.FunctionRef): NativePlan | undefined;
package/dist/guards.js ADDED
@@ -0,0 +1,202 @@
1
+ import binaryen from 'binaryen';
2
+ function info(expression) {
3
+ const id = binaryen.getExpressionId(expression);
4
+ if (id === binaryen.NopId)
5
+ return { id, type: binaryen.none };
6
+ return binaryen.getExpressionInfo(expression);
7
+ }
8
+ const unary = new Set([
9
+ binaryen.ClzInt32,
10
+ binaryen.CtzInt32,
11
+ binaryen.PopcntInt32,
12
+ binaryen.EqZInt32,
13
+ binaryen.ExtendS8Int32,
14
+ binaryen.ExtendS16Int32
15
+ ]);
16
+ const binary = new Set([
17
+ binaryen.AddInt32,
18
+ binaryen.SubInt32,
19
+ binaryen.MulInt32,
20
+ binaryen.AndInt32,
21
+ binaryen.OrInt32,
22
+ binaryen.XorInt32,
23
+ binaryen.ShlInt32,
24
+ binaryen.ShrUInt32,
25
+ binaryen.ShrSInt32,
26
+ binaryen.RotLInt32,
27
+ binaryen.RotRInt32,
28
+ binaryen.EqInt32,
29
+ binaryen.NeInt32,
30
+ binaryen.LtSInt32,
31
+ binaryen.LtUInt32,
32
+ binaryen.LeSInt32,
33
+ binaryen.LeUInt32,
34
+ binaryen.GtSInt32,
35
+ binaryen.GtUInt32,
36
+ binaryen.GeSInt32,
37
+ binaryen.GeUInt32
38
+ ]);
39
+ export function nativePlan(module, fn) {
40
+ try {
41
+ const outer = binaryen.getFunctionInfo(fn);
42
+ const parameters = binaryen.expandType(outer.params);
43
+ const root = info(outer.body);
44
+ if (root.id !== binaryen.BlockId || root.children.length !== 2)
45
+ return;
46
+ const loop = info(root.children[1]);
47
+ if (loop.id !== binaryen.LoopId)
48
+ return;
49
+ const body = info(loop.body);
50
+ if (body.id !== binaryen.BlockId || body.children.length < 2)
51
+ return;
52
+ let payload = info(body.children[0]);
53
+ if (payload.id === binaryen.DropId)
54
+ payload = info(payload.value);
55
+ if (payload.id !== binaryen.CallId || payload.isReturn)
56
+ return;
57
+ for (const expression of body.children.slice(1, -1)) {
58
+ const set = info(expression);
59
+ if (set.id !== binaryen.LocalSetId || set.isTee)
60
+ return;
61
+ const add = info(set.value);
62
+ if (add.id !== binaryen.BinaryId || add.op !== binaryen.AddInt32)
63
+ return;
64
+ const left = info(add.left), right = info(add.right);
65
+ if (left.id !== binaryen.LocalGetId || left.index !== set.index)
66
+ return;
67
+ if (right.id !== binaryen.ConstId || right.type !== binaryen.i32)
68
+ return;
69
+ }
70
+ const arguments_ = [];
71
+ for (const expression of payload.operands) {
72
+ const argument = info(expression);
73
+ if (argument.id !== binaryen.LocalGetId || argument.index >= parameters.length)
74
+ return;
75
+ arguments_.push(argument.index);
76
+ }
77
+ const calleeRef = module.getFunction(payload.target);
78
+ if (!calleeRef)
79
+ return;
80
+ const callee = binaryen.getFunctionInfo(calleeRef);
81
+ const calleeParameters = binaryen.expandType(callee.params);
82
+ if (!callee.body || calleeParameters.length !== arguments_.length)
83
+ return;
84
+ if (![binaryen.none, binaryen.i32].includes(callee.results))
85
+ return;
86
+ if ([...parameters, ...calleeParameters, ...callee.vars].some((t) => t !== binaryen.i32))
87
+ return;
88
+ const accesses = [];
89
+ const pointers = new Set();
90
+ const writes = [];
91
+ const countdowns = new Map();
92
+ function visit(expression) {
93
+ const value = info(expression);
94
+ if (![binaryen.none, binaryen.i32].includes(value.type))
95
+ return false;
96
+ switch (value.id) {
97
+ case binaryen.BlockId: {
98
+ const loops = value.children.filter((e) => info(e).id === binaryen.LoopId);
99
+ if (!loops.length)
100
+ return value.children.every(visit);
101
+ if (value.children.length !== 2 || loops[0] !== value.children[1])
102
+ return false;
103
+ const guard = info(value.children[0]), inner = info(loops[0]);
104
+ if (guard.id !== binaryen.BreakId ||
105
+ guard.name !== value.name ||
106
+ guard.value ||
107
+ !guard.condition)
108
+ return false;
109
+ const zero = info(guard.condition);
110
+ if (zero.id !== binaryen.UnaryId || zero.op !== binaryen.EqZInt32)
111
+ return false;
112
+ const counter = info(zero.value), innerBody = info(inner.body);
113
+ if (counter.id !== binaryen.LocalGetId || countdowns.has(counter.index))
114
+ return false;
115
+ if (innerBody.id !== binaryen.BlockId || !innerBody.children.length)
116
+ return false;
117
+ const tail = info(innerBody.children.at(-1));
118
+ if (tail.id !== binaryen.BreakId ||
119
+ tail.name !== inner.name ||
120
+ tail.value ||
121
+ !tail.condition)
122
+ return false;
123
+ const decrement = info(tail.condition);
124
+ if (decrement.id !== binaryen.LocalSetId ||
125
+ !decrement.isTee ||
126
+ decrement.index !== counter.index)
127
+ return false;
128
+ const add = info(decrement.value);
129
+ if (add.id !== binaryen.BinaryId || add.op !== binaryen.AddInt32)
130
+ return false;
131
+ const left = info(add.left), right = info(add.right);
132
+ if (left.id !== binaryen.LocalGetId || left.index !== counter.index)
133
+ return false;
134
+ if (right.id !== binaryen.ConstId || right.value !== -1)
135
+ return false;
136
+ countdowns.set(counter.index, tail.condition);
137
+ writes.push({ expression: tail.condition, index: counter.index });
138
+ return innerBody.children.slice(0, -1).every(visit);
139
+ }
140
+ case binaryen.IfId:
141
+ return (visit(value.condition) &&
142
+ visit(value.ifTrue) &&
143
+ (!value.ifFalse || visit(value.ifFalse)));
144
+ case binaryen.SelectId:
145
+ return visit(value.condition) && visit(value.ifTrue) && visit(value.ifFalse);
146
+ case binaryen.LocalGetId:
147
+ case binaryen.ConstId:
148
+ case binaryen.NopId:
149
+ return true;
150
+ case binaryen.LocalSetId:
151
+ writes.push({ expression, index: value.index });
152
+ return visit(value.value);
153
+ case binaryen.UnaryId:
154
+ return unary.has(value.op) && visit(value.value);
155
+ case binaryen.BinaryId:
156
+ return binary.has(value.op) && visit(value.left) && visit(value.right);
157
+ case binaryen.DropId:
158
+ return visit(value.value);
159
+ case binaryen.LoadId:
160
+ case binaryen.StoreId: {
161
+ const ptr = info(value.ptr), write = value.id === binaryen.StoreId;
162
+ if (value.isAtomic ||
163
+ ptr.id !== binaryen.LocalGetId ||
164
+ ptr.index >= calleeParameters.length)
165
+ return false;
166
+ if (![1, 2, 4].includes(value.bytes) ||
167
+ !Number.isInteger(value.offset) ||
168
+ value.offset < 0 ||
169
+ value.offset > 0xffffffff)
170
+ return false;
171
+ if (write && (info(value.value).type !== binaryen.i32 || !visit(value.value)))
172
+ return false;
173
+ pointers.add(ptr.index);
174
+ accesses.push({
175
+ parameter: arguments_[ptr.index],
176
+ offset: value.offset,
177
+ bytes: value.bytes,
178
+ write
179
+ });
180
+ return true;
181
+ }
182
+ default:
183
+ return false;
184
+ }
185
+ }
186
+ if (!visit(callee.body) || !accesses.length)
187
+ return;
188
+ if (writes.some((write) => pointers.has(write.index) ||
189
+ (countdowns.has(write.index) &&
190
+ countdowns.get(write.index) !== write.expression)))
191
+ return;
192
+ return {
193
+ accesses,
194
+ workParameters: [...countdowns.keys()]
195
+ .filter((index) => index < arguments_.length)
196
+ .map((index) => arguments_[index])
197
+ };
198
+ }
199
+ catch {
200
+ return;
201
+ }
202
+ }
package/dist/host.d.ts ADDED
@@ -0,0 +1,60 @@
1
+ import type { FolioOptions, ProgramInput } from './node.ts';
2
+ /** A trusted program registered under an artifact id. */
3
+ export interface HostArtifact {
4
+ /** The program or prepared plan every session of this artifact runs. */
5
+ program: ProgramInput;
6
+ /** Explicit allowlist; a registered module does not expose every export. */
7
+ exports: readonly string[];
8
+ /**
9
+ * Trusted bindings. The request cannot provide executable host code. Returns pool options such
10
+ * as the memory and imports, and a `dispose` called once after the group's workers join.
11
+ */
12
+ create?: () => Promise<{
13
+ options?: FolioOptions;
14
+ dispose?: () => void | Promise<void>;
15
+ }> | {
16
+ options?: FolioOptions;
17
+ dispose?: () => void | Promise<void>;
18
+ };
19
+ }
20
+ /** Admission and transport bounds. Defaults are conservative for a shared host. */
21
+ export interface HostLimits {
22
+ /** Groups open at once; further opens are refused. */
23
+ liveGroups: number;
24
+ /** Workers a single session may request. */
25
+ workersPerGroup: number;
26
+ /** Initial accessible canonical backing admission; trusted bindings enforce growth maxima. */
27
+ memoryBytesPerGroup: number;
28
+ /** Largest request body. */
29
+ requestBytes: number;
30
+ /** Largest response body. */
31
+ responseBytes: number;
32
+ /** Largest single memory read. */
33
+ readBytes: number;
34
+ /** Largest single memory write. */
35
+ writeBytes: number;
36
+ /** Most arguments in one call. */
37
+ argumentsPerCall: number;
38
+ /** Idle time before a session expires; active operations postpone expiry. */
39
+ idleMilliseconds: number;
40
+ /** Sessions whose last response the host keeps for `retryPending()`. */
41
+ retainedSessions: number;
42
+ }
43
+ /** Same-process execution behind an authenticated fetch handler, with no public code upload. */
44
+ export declare class FolioHost {
45
+ #private;
46
+ constructor(options: {
47
+ artifacts: Readonly<Record<string, HostArtifact>>;
48
+ authorize: (request: Request) => boolean | Promise<boolean>;
49
+ limits?: Partial<HostLimits>;
50
+ path?: string;
51
+ });
52
+ /** Groups open or opening, counting those still joining their workers. */
53
+ get activeGroups(): number;
54
+ /** The authenticated handler to mount behind a service binding or an HTTP server. */
55
+ readonly fetch: (request: Request) => Promise<Response>;
56
+ /** Refuses new sessions, then joins every group's workers and pending effects. */
57
+ close(): Promise<void>;
58
+ /** `await using` support; equivalent to `close()`. */
59
+ [Symbol.asyncDispose](): Promise<void>;
60
+ }