Skip to content
Myr

prelude.ts

This file

Path

packages/rules/src/prelude.ts

304 lines · 9.1 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 1–2why, one step back
1// Module text for the Worker Loader: nothing here runs in the platform's own
2// isolate except to write it.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 3–41why, one step back
3import { Functions } from "@repo/sdk/functions";
45/**6 * The clock and seed config code sees, injected by the caller: an7 * evaluation's are the landed commit's time and a hash of its SHA; a rule8 * call's are the Unix epoch and 0, so a rule gets time only through its9 * facts (as `/bun` does).10 */11export interface FrozenFacts {12 readonly now: number;13 readonly seed: number;14}1516export interface DateClass {17 new (...args: readonly (Date | number | string)[]): Date;18 now: () => number;19 readonly prototype: Date;20}2122export interface FreezableScope {23 Date: DateClass;24 readonly Math: { random: () => number };25 readonly crypto: {26 getRandomValues: <T extends ArrayBufferView>(array: T) => T;27 randomUUID: () => string;28 };29 readonly performance: { now: () => number };30}3132export interface Frozen {33 /**34 * Puts the randomness back where it stood the first time this was called:35 * the main calls it once its modules are loaded, before each job's own36 * code, so a warm worker gives every job the numbers a fresh one would.37 */38 readonly settle: () => void;39}4041/**

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 42–47why, one step back
42 * Serialised into the prelude module with `Function#toString`, so its body
43 * names nothing outside itself and defines no function or class a bundler44 * would name (only methods, and functions assigned to a member; an arrow45 * bound to a name or written as an object literal's property value is46 * named): a `keepNames` build, wrangler's default, would otherwise call a47 * naming helper the prelude module doesn't have.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 48–167why, one step back
48 */
49export const installFrozenGlobals = (50 scope: FreezableScope,51 facts: FrozenFacts52): Frozen => {53 const RealDate = scope.Date;54 const frozenAt = facts.now;5556 // mulberry32, Tommy Ettinger's seeded 32-bit generator (public domain),57 // the same as `/bun`'s, so both adapters give one seed the same numbers.58 /* oxlint-disable no-bitwise -- mulberry32 is 32-bit integer arithmetic, and it must match /bun's prelude number for number */59 const generator = {60 next(): number {61 generator.state = (generator.state + 0x6d_2b_79_f5) >>> 0;6263 let mixed = generator.state;6465 mixed = Math.imul(mixed ^ (mixed >>> 15), mixed | 1);66 mixed ^= mixed + Math.imul(mixed ^ (mixed >>> 7), mixed | 61);6768 return ((mixed ^ (mixed >>> 14)) >>> 0) / 4_294_967_296;69 },70 settled: -1,71 state: facts.seed >>> 0,72 };73 /* oxlint-enable no-bitwise */7475 // The frozen `Date` is the scope's own behind a proxy: `new Date()` with76 // no time gets the frozen one, and `Date()` without `new` tells it, as77 // the real one tells the real time. Everything else (`prototype`,78 // `parse`, `UTC`, what sits above it) is the scope's own, so no path79 // leads past it to another clock.80 const frozenDate = new Proxy(RealDate, {81 apply(): string {82 return new RealDate(frozenAt).toString();83 },84 // `newTarget` is the frozen `Date`, or a class config code derived85 // from it, whose prototype the new date takes.86 construct(87 target,88 args: readonly (Date | number | string)[],89 newTarget: DateClass90 ): Date {91 return Reflect.construct(92 target,93 args.length === 0 ? [frozenAt] : args,94 newTarget95 );96 },97 });9899 // The scope's own `Date` tells the frozen time too, and every date's100 // constructor (one the runtime makes itself included) is the frozen one.101 RealDate.now = () => frozenAt;102103 Object.defineProperty(RealDate.prototype, "constructor", {104 configurable: true,105 value: frozenDate,106 writable: true,107 });108109 scope.Date = frozenDate;110 scope.performance.now = () => 0;111 scope.Math.random = () => generator.next();112113 scope.crypto.getRandomValues = (array) => {114 const bytes = new Uint8Array(115 array.buffer,116 array.byteOffset,117 array.byteLength118 );119120 for (let index = 0; index < bytes.length; index += 1) {121 bytes[index] = Math.floor(generator.next() * 256);122 }123124 return array;125 };126127 scope.crypto.randomUUID = () => {128 const bytes = scope.crypto.getRandomValues(new Uint8Array(16));129130 // A random UUID's version nibble is 4 and its variant bits are 10.131 bytes[6] = ((bytes[6] ?? 0) % 16) + 0x40;132 bytes[8] = ((bytes[8] ?? 0) % 64) + 0x80;133134 const hex = Array.from(bytes, (byte) =>135 byte.toString(16).padStart(2, "0")136 ).join("");137138 return [139 hex.slice(0, 8),140 hex.slice(8, 12),141 hex.slice(12, 16),142 hex.slice(16, 20),143 hex.slice(20),144 ].join("-");145 };146147 return {148 settle(): void {149 if (generator.settled < 0) {150 generator.settled = generator.state;151 }152153 generator.state = generator.settled;154 },155 };156};157158export const preludeModule = (facts: FrozenFacts): string =>159 `export const frozen = (${String(installFrozenGlobals)})(globalThis, ${JSON.stringify({ now: facts.now, seed: facts.seed })});\n`;160161export const preludeName = "prelude.js";162163export const mainName = "main.js";164165export interface MainModules {166 readonly asks: readonly string[];167 readonly project?: string | undefined;

Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9

line 168why, one step back
168 readonly visibility?: string | undefined;

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 169–174why, one step back
169}
170171const importer = (path: string) =>172 `{ load: () => import(${JSON.stringify(`./${path}`)}), path: ${JSON.stringify(path)} }`;173174/**

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 175–176why, one step back
175 * It imports the prelude first, so the clock is frozen before any config code
176 * exists, and answers each request with one JSON document:

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

line 177why, one step back
177 *

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 178–179why, one step back
178 * - `{}` → `Collected {asks: [{ask, path}], project?, visibility?}`;
179 * - `{rule, facts}` → `Called {result}` (`false` when there is no rule);

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 180–188why, one step back
180 * - either → `Failed {reason: "load" | "threw", detail}`.
181 */182export const mainModule = (modules: MainModules): string => `183import { frozen } from "./${preludeName}";184185const project = ${modules.project === undefined ? "undefined" : importer(modules.project)};186187const asks = [${modules.asks.map(importer).join(", ")}];188

Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9

lines 189–190why, one step back
189const visibility = ${modules.visibility === undefined ? "undefined" : importer(modules.visibility)};
190

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 191–264why, one step back
191const functions = Symbol.for(${JSON.stringify(Symbol.keyFor(Functions) ?? "")});
192193// What a module that would not load throws: a syntax error, an import that194// resolves to nothing (workerd), or Bun's build and resolve messages.195const loadErrors = new Set(["BuildMessage", "ResolveMessage", "SyntaxError"]);196197const isLoadError = (error) =>198 error instanceof AggregateError199 ? error.errors.length > 0 && error.errors.every(isLoadError)200 : loadErrors.has(error?.constructor?.name) || /^No such module/u.test(String(error?.message));201202const describe = (error) =>203 error instanceof AggregateError204 ? error.errors.map(describe).join("; ")205 : error instanceof Error206 ? error.name + ": " + error.message207 : String(error);208209const failed = (where, error, reason) => ({210 _tag: "Failed",211 detail: where + ": " + describe(error),212 reason: reason ?? (isLoadError(error) ? "load" : "threw"),213});214215const imported = async ({ load, path }) => {216 try {217 const module = await load();218 return { exported: { definition: module.default, path } };219 } catch (error) {220 return { failure: failed(path, error) };221 }222};223224// A module with no default export gives null, which the host refuses.225const dataOf = (definition) => definition ?? null;226227const ruleOf = (definition, rule) => {228 const carries = (value, key) =>229 ((typeof value === "object" && value !== null) || typeof value === "function") && key in value;230 const found = carries(definition, functions) && carries(definition[functions], rule)231 ? definition[functions][rule]232 : undefined;233 return typeof found === "function" ? found : undefined;234};235236const run = async (job) => {237 const loaded = project === undefined ? undefined : await imported(project);238239 if (loaded?.failure !== undefined) {240 return loaded.failure;241 }242243 if (job.rule !== undefined) {244 frozen.settle();245 try {246 const rule = ruleOf(loaded?.exported.definition, job.rule);247 return { _tag: "Called", result: rule === undefined ? false : await rule(job.facts) };248 } catch (error) {249 return failed(job.rule, error, "threw");250 }251 }252253 const exported = [];254255 for (const ask of asks) {256 const each = await imported(ask);257258 if (each.failure !== undefined) {259 return each.failure;260 }261262 exported.push(each.exported);263 }264

Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9

lines 265–270why, one step back
265 const stated = visibility === undefined ? undefined : await imported(visibility);
266267 if (stated?.failure !== undefined) {268 return stated.failure;269 }270

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 271–274why, one step back
271 frozen.settle();
272273 const collected = exported.map(({ definition, path }) => ({ ask: dataOf(definition), path }));274

Merge build/608-datekit-maintainers-layer: datekit has a maintainers layer of sealed checks, each citing the clause it enforces, and the seed pushes itoscabrielbefore adoption166f6c9

lines 275–280why, one step back
275 return {
276 _tag: "Collected",277 asks: collected,278 ...(loaded === undefined ? {} : { project: dataOf(loaded.exported.definition) }),279 ...(stated === undefined ? {} : { visibility: dataOf(stated.exported.definition) }),280 };

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 281–304why, one step back
281};
282283const encoded = (result) => {284 try {285 return JSON.stringify(result);286 } catch (error) {287 return JSON.stringify(failed("the config folder's exports", error, "threw"));288 }289};290291export default {292 async fetch(request) {293 let result;294295 try {296 result = await run(await request.json());297 } catch (error) {298 result = failed("the evaluator", error, "load");299 }300301 return new Response(encoded(result), { headers: { "content-type": "application/json" } });302 },303};304`;