@orthograph/projections 0.0.0-stage → 0.1.0-next.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 (111) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +26 -2
  3. package/dist/main.d.ts +9 -0
  4. package/dist/main.js +12 -0
  5. package/dist/modules/actions/internal/actions.d.ts +7 -0
  6. package/dist/modules/actions/internal/actions.js +22 -0
  7. package/dist/modules/actions/service.d.ts +5 -0
  8. package/dist/modules/actions/service.js +14 -0
  9. package/dist/modules/actions/types.d.ts +9 -0
  10. package/dist/modules/actions/types.js +5 -0
  11. package/dist/modules/api/internal/api.d.ts +4 -0
  12. package/dist/modules/api/internal/api.js +99 -0
  13. package/dist/modules/api/service.d.ts +5 -0
  14. package/dist/modules/api/service.js +16 -0
  15. package/dist/modules/api/types.d.ts +1 -0
  16. package/dist/modules/api/types.js +1 -0
  17. package/dist/modules/app/internal/links.d.ts +2 -0
  18. package/dist/modules/app/internal/links.js +22 -0
  19. package/dist/modules/app/internal/palette.d.ts +6 -0
  20. package/dist/modules/app/internal/palette.js +55 -0
  21. package/dist/modules/app/internal/render.d.ts +4 -0
  22. package/dist/modules/app/internal/render.js +30 -0
  23. package/dist/modules/app/internal/view.d.ts +3 -0
  24. package/dist/modules/app/internal/view.js +52 -0
  25. package/dist/modules/app/service.d.ts +5 -0
  26. package/dist/modules/app/service.js +17 -0
  27. package/dist/modules/app/types.d.ts +52 -0
  28. package/dist/modules/app/types.js +1 -0
  29. package/dist/modules/cli/internal/cli.d.ts +3 -0
  30. package/dist/modules/cli/internal/cli.js +35 -0
  31. package/dist/modules/cli/internal/session.d.ts +11 -0
  32. package/dist/modules/cli/internal/session.js +55 -0
  33. package/dist/modules/cli/service.d.ts +2 -0
  34. package/dist/modules/cli/service.js +10 -0
  35. package/dist/modules/cli/types.d.ts +1 -0
  36. package/dist/modules/cli/types.js +1 -0
  37. package/dist/modules/handlers/internal/body.d.ts +5 -0
  38. package/dist/modules/handlers/internal/body.js +79 -0
  39. package/dist/modules/handlers/internal/calls.d.ts +17 -0
  40. package/dist/modules/handlers/internal/calls.js +80 -0
  41. package/dist/modules/handlers/internal/header.d.ts +18 -0
  42. package/dist/modules/handlers/internal/header.js +106 -0
  43. package/dist/modules/handlers/internal/paths.d.ts +18 -0
  44. package/dist/modules/handlers/internal/paths.js +11 -0
  45. package/dist/modules/handlers/internal/scaffold.d.ts +7 -0
  46. package/dist/modules/handlers/internal/scaffold.js +73 -0
  47. package/dist/modules/handlers/internal/stubs.d.ts +3 -0
  48. package/dist/modules/handlers/internal/stubs.js +120 -0
  49. package/dist/modules/handlers/internal/words.d.ts +43 -0
  50. package/dist/modules/handlers/internal/words.js +87 -0
  51. package/dist/modules/handlers/service.d.ts +5 -0
  52. package/dist/modules/handlers/service.js +9 -0
  53. package/dist/modules/handlers/types.d.ts +2 -0
  54. package/dist/modules/handlers/types.js +1 -0
  55. package/dist/modules/infra/internal/stack.d.ts +3 -0
  56. package/dist/modules/infra/internal/stack.js +15 -0
  57. package/dist/modules/infra/service.d.ts +5 -0
  58. package/dist/modules/infra/service.js +13 -0
  59. package/dist/modules/infra/types.d.ts +1 -0
  60. package/dist/modules/infra/types.js +1 -0
  61. package/dist/modules/mcp/internal/mcp.d.ts +3 -0
  62. package/dist/modules/mcp/internal/mcp.js +20 -0
  63. package/dist/modules/mcp/service.d.ts +5 -0
  64. package/dist/modules/mcp/service.js +13 -0
  65. package/dist/modules/mcp/types.d.ts +1 -0
  66. package/dist/modules/mcp/types.js +1 -0
  67. package/dist/modules/model/internal/edges.d.ts +4 -0
  68. package/dist/modules/model/internal/edges.js +12 -0
  69. package/dist/modules/model/service.d.ts +6 -0
  70. package/dist/modules/model/service.js +20 -0
  71. package/dist/modules/model/types.d.ts +1 -0
  72. package/dist/modules/model/types.js +1 -0
  73. package/dist/modules/names/internal/names.d.ts +51 -0
  74. package/dist/modules/names/internal/names.js +47 -0
  75. package/dist/modules/names/internal/when.d.ts +5 -0
  76. package/dist/modules/names/internal/when.js +19 -0
  77. package/dist/modules/names/internal/words.d.ts +34 -0
  78. package/dist/modules/names/internal/words.js +61 -0
  79. package/dist/modules/names/service.d.ts +19 -0
  80. package/dist/modules/names/service.js +19 -0
  81. package/dist/modules/names/types.d.ts +16 -0
  82. package/dist/modules/names/types.js +5 -0
  83. package/dist/modules/sdk/internal/client.d.ts +2 -0
  84. package/dist/modules/sdk/internal/client.js +31 -0
  85. package/dist/modules/sdk/internal/sdk.d.ts +3 -0
  86. package/dist/modules/sdk/internal/sdk.js +68 -0
  87. package/dist/modules/sdk/internal/types.d.ts +8 -0
  88. package/dist/modules/sdk/internal/types.js +38 -0
  89. package/dist/modules/sdk/service.d.ts +5 -0
  90. package/dist/modules/sdk/service.js +13 -0
  91. package/dist/modules/sdk/types.d.ts +1 -0
  92. package/dist/modules/sdk/types.js +1 -0
  93. package/dist/modules/server/internal/actors.d.ts +3 -0
  94. package/dist/modules/server/internal/actors.js +5 -0
  95. package/dist/modules/server/internal/doors.d.ts +10 -0
  96. package/dist/modules/server/internal/doors.js +26 -0
  97. package/dist/modules/server/internal/helpers.d.ts +13 -0
  98. package/dist/modules/server/internal/helpers.js +70 -0
  99. package/dist/modules/server/internal/server.d.ts +3 -0
  100. package/dist/modules/server/internal/server.js +65 -0
  101. package/dist/modules/server/internal/versioned.d.ts +13 -0
  102. package/dist/modules/server/internal/versioned.js +17 -0
  103. package/dist/modules/server/internal/worker-config.d.ts +16 -0
  104. package/dist/modules/server/internal/worker-config.js +90 -0
  105. package/dist/modules/server/service.d.ts +10 -0
  106. package/dist/modules/server/service.js +20 -0
  107. package/dist/modules/server/types.d.ts +1 -0
  108. package/dist/modules/server/types.js +1 -0
  109. package/dist/shared.d.ts +6 -0
  110. package/dist/shared.js +6 -0
  111. package/package.json +32 -3
@@ -0,0 +1,70 @@
1
+ import { Names } from "orthograph/server";
2
+ import { camel, opVar, pascal } from "#modules/names/service.js";
3
+ export const emptyPath = (o) => `empty/${o.thing}/${o.verb}.ts`;
4
+ /** The runtime's refusals the generated code names: the machine's, when the move starts from a state (D2 #37), and each not-found. */
5
+ export const notFromOf = (model, o) => {
6
+ const machine = model.things[o.thing]?.machine;
7
+ const notFrom = o.move && o.move.from.length > 0 && machine ? `, notFrom: "${machine.notFrom.error}"` : "";
8
+ // Each payload field no role check reads, and the `<Thing>NotFound` a missing one is refused with (K16, M1.46).
9
+ const missing = Object.entries(o.notFound ?? {});
10
+ // Each refusal the runtime makes for a rule this operation can break (G5), and the rule it is for.
11
+ const ruled = Object.entries(o.invariants ?? {});
12
+ return `${notFrom}${missing.length > 0 ? `, notFound: { ${missing.map(([k, e]) => `${k}: "${e}"`).join(", ")} }` : ""}${ruled.length > 0 ? `, invariants: { ${ruled.map(([tag, rule]) => `${tag}: "${rule}"`).join(", ")} }` : ""}`;
13
+ };
14
+ /**
15
+ * Where the identity keeps its users: Better Auth's table, today the identity behind `AuthD1`. Named here, in what the
16
+ * generated server says, never in host code; the identity plugin (M2.05) will own it.
17
+ */
18
+ const IDENTITY_USERS = "auth_user";
19
+ /**
20
+ * The thing the identity keeps, bound explicitly: the identity's users are what a `Principal` calls a `person`, so its
21
+ * thing is the one named `person` (K16 review, 22.1). Never found by its id prefix: an app thing may use `per_` too.
22
+ */
23
+ const IDENTITY_THING = "person";
24
+ export const peopleOf = (model) => {
25
+ const people = model.things[IDENTITY_THING];
26
+ return people ? `, people: { thing: thingIn(${camel(people.name)}Thing), table: "${IDENTITY_USERS}" }` : "";
27
+ };
28
+ /**
29
+ * How the Worker exports its world (and its actors). A blueprint with a stepped or scaled clock extends the world with its wake
30
+ * route (M8.07): each kind of durable timer to the code that wakes it, empty until a feature registers a kind. Any other
31
+ * blueprint re-exports the host's, exactly as it always did.
32
+ */
33
+ export const worldExports = (timed, actors) => {
34
+ const host = Names.pkg("host-cloudflare");
35
+ if (!timed)
36
+ return [actors ? `export { Actor, World } from "${host}";` : `export { World } from "${host}";`];
37
+ return [
38
+ `import { World as WorldHost, type WorldWakes } from "${host}";`,
39
+ ...(actors ? [`export { Actor } from "${host}";`] : []),
40
+ "",
41
+ "/** Which code wakes each kind of durable timer when it falls due: empty until a feature registers a kind (a workflow, an agent, the keeper). */",
42
+ "const wakes: WorldWakes = {};",
43
+ "",
44
+ "/** The world, with its wake route: a due timer of a kind that is not here fails its step and stays pending. */",
45
+ "export class World extends WorldHost {",
46
+ " protected override wakeKinds(): WorldWakes {",
47
+ " return wakes;",
48
+ " }",
49
+ "}",
50
+ ];
51
+ };
52
+ /** One thing's routes: each operation handled through the runtime's wrapper, under the services taken once. */
53
+ export const groupOf = (ops, empty, timed) => (t) => {
54
+ const handles = ops
55
+ .filter((o) => o.thing === t)
56
+ .map((o) => {
57
+ const serve = empty && o.kind === "operation"
58
+ ? `request.headers["x-ortho-starting-world"] === "1" ? ${opVar(o)}Served : ${opVar(o)}Scaffolded`
59
+ : `${opVar(o)}Served`;
60
+ return ` .handle("${o.verb}", ({ payload, request }) => call(${serve}, payload, request.headers).pipe(Effect.provideContext(services)))`;
61
+ });
62
+ return [
63
+ `const ${pascal(t)}Live = HttpApiBuilder.group(CallApi, "${t}", Effect.fn(function* (handlers) {`,
64
+ " // The services are taken once, when the routes are built; each request keeps its own tracer and span.",
65
+ ` const services = Context.pick(SqlClient.SqlClient, Store, Busy, Principals, Journal, Auth${timed ? ", Timers, DurableTimers" : ""})(yield* Effect.context<Services>());`,
66
+ " return handlers",
67
+ ...handles.map((h, i) => (i === handles.length - 1 ? `${h};` : h)),
68
+ "}));",
69
+ ];
70
+ };
@@ -0,0 +1,3 @@
1
+ import type { Model } from "@orthograph/compiler";
2
+ import type { RenderedFile } from "#modules/names/types.js";
3
+ export declare const renderServer: (model: Model, name: string, empty?: boolean) => ReadonlyArray<RenderedFile>;
@@ -0,0 +1,65 @@
1
+ // generated/server: the Worker. Every operation's route wired to its handler in src/, by path; the world's
2
+ // front door at /_world/*; the portal at /portal and /_portal/*; D1 tables from the model.
3
+ import { Names } from "orthograph/server";
4
+ import { callImports, renderHandlerScaffold, wired } from "#modules/handlers/service.js";
5
+ import { GENERATED, bindingOf, camel, databaseStores, handlerAt, lines, opVar, pascal, storeFileAt, thingFileAt, toRoot } from "#modules/names/service.js";
6
+ import { emptyPath, groupOf, notFromOf, peopleOf, worldExports } from "./helpers.js";
7
+ import { clocksOf, renderMigration, renderStoreMigrations, renderWrangler } from "./worker-config.js";
8
+ import { doorsOf } from "./doors.js";
9
+ import { actorOptionOf } from "./actors.js";
10
+ import { rulesByOrigin, staleOf, versioned } from "./versioned.js";
11
+ const main = (model, name, empty) => {
12
+ const ops = Object.values(model.operations);
13
+ const timed = Object.keys(clocksOf(model)).length > 0;
14
+ const actors = Object.values(model.things).some((t) => t.lives === "actor");
15
+ const handled = ops.filter((o) => o.kind === "operation");
16
+ const groups = [...new Set(ops.map((o) => o.thing))];
17
+ const things = Object.values(model.things);
18
+ // The things with rules (G5): their `invariants.ts` is imported, and the store and the runtime are handed each rule under its full name.
19
+ const ruled = things.filter((t) => Object.keys(t.invariants ?? {}).length > 0);
20
+ const rulesOption = ruled.length > 0 ? ", rules" : "";
21
+ const { declaredRules, versionedRules } = rulesByOrigin(ruled);
22
+ // Each mount a served operation came from, imported once: its plugin's handlers run under it (Mount.serving).
23
+ const mounted = [...new Set(handled.flatMap((o) => (o.from.kind !== "app" ? [o.from.mount] : [])))].filter((m) => model.mounts?.[m]);
24
+ const mountVar = (mount) => `${camel(mount)}Mount`;
25
+ // Each adapter a `service` role names (M2-auth, fork 3): the runtime reads the role against the mount's name, so the server hands it each mount by name.
26
+ const serviced = [...new Set(ops.flatMap((o) => o.allowed.flatMap((a) => ("service" in a && a.service !== undefined ? [a.service] : []))))].filter((m) => model.mounts?.[m]).sort();
27
+ const doors = doorsOf(model, name, mountVar, [...mounted, ...serviced]);
28
+ const mountsOption = serviced.length > 0 ? ", mounts" : "";
29
+ // The four operations of a thing with versions are the framework's (see versioned.ts): no handler file.
30
+ const framework = (o) => versioned(model, o);
31
+ const served = (o) => framework(o) ? `Versions.handler("${o.verb}", thingIn(${camel(o.thing)}Thing), ${staleOf(o)}${o.move === null ? ", false" : ""})`
32
+ : o.from.kind !== "app" && mounted.includes(o.from.mount) ? `Mount.serving(${mountVar(o.from.mount)}, ${opVar(o)}Handler)` : `${opVar(o)}Handler`;
33
+ // Each declared database store (K3) has a D1 binding of its own, and its own journal and request keys.
34
+ const stores = databaseStores(model);
35
+ const storeOption = stores.length > 0 ? `, stores: [${stores.map((s) => `[${camel(s.name)}Store, env.${bindingOf(s)}]`).join(", ")}]` : "";
36
+ // Counted work and timers: one process's own, or (a world with a clock) the world's, reported to its Durable Object (M8.07).
37
+ const work = timed ? "WorldEntry.work(env, wakes)" : "BusyLive";
38
+ // A world whose clock steps is reset under its requests: every statement of a request is a write section its token holds (M8.07, I2).
39
+ const db = timed ? "WorldEntry.fenced(env, env.DB)" : "env.DB";
40
+ const journal = stores.length > 0 ? `JournalD1.across([${stores.map((s) => `env.${bindingOf(s)}`).join(", ")}])` : "JournalD1.layer";
41
+ const apart = new Set(Object.values(model.things).filter((t) => t.store !== undefined && stores.some((s) => s.name === t.store)).map((t) => t.name));
42
+ const actorOption = actorOptionOf(model);
43
+ const world = (stores.length > 0
44
+ ? `tables: [${Object.values(model.things).filter((t) => !apart.has(t.name)).map((t) => `"${t.name}"`).join(", ")}], stores: [${stores.map((s) => `{ db: env.${bindingOf(s)}, tables: [${Object.values(model.things).filter((t) => t.store === s.name).map((t) => `"${t.name}"`).join(", ")}] }`).join(", ")}]`
45
+ : "tables: tables.map(([, table]) => table)") + actorOption;
46
+ const group = groupOf(ops, empty, timed);
47
+ return {
48
+ path: "generated/server/main.ts",
49
+ scaffold: false,
50
+ content: lines(GENERATED, "// The Worker: each operation's route runs its handler through the runtime's wrapper; /_world/* goes to the world.", `import { Context, Effect, Layer } from "effect";`, `import { ManagedRuntime, Tracer } from "effect";`, `import { HttpRouter, HttpServer } from "effect/http";`, `import { HttpApi, HttpApiBuilder } from "effect/http-api";`, `import { SqlClient } from "effect/sql";`, `import type { Principal } from "${Names.frontDoor}";`, `import { AuthD1, Database, ${doors.any ? "Inbound, " : ""}JournalD1, StoreD1, Telemetry, ${timed ? "WorldEntry, " : ""}toWorld } from "${Names.pkg("host-cloudflare")}";`, `import { Auth, Busy, ${timed ? "" : "BusyLive, "}CallTelemetry, ${timed ? "DurableTimers, " : ""}Environment, Handlers, Journal, ${mounted.length > 0 ? "Mount, " : ""}Principals, Reads, Store, ${timed ? "Timers, " : ""}${handled.some(framework) || versionedRules.length > 0 ? "Versions, " : ""}Wire, ${declaredRules.length > 0 ? "invariantsIn, " : ""}thingIn } from "${Names.pkg("language-effect")}";`, `import { Mcp, type McpResult, type ShownOperation } from "${Names.pkg("language-effect")}";`, `import { Api, Errors } from "../api/src/index.ts";`, `import * as portal from "../portal/main.ts";`, `import { catalog } from "../mcp/src/index.ts";`, ops.map((o) => `import * as ${opVar(o)} from "../api/src/${o.thing}/${o.verb}.ts";`), handled.filter((o) => !framework(o)).map((o) => `import ${opVar(o)}Handler from "${handlerAt("generated/server/main.ts", o)}";`), empty ? handled.map((o) => `import ${opVar(o)}Blank from "./${emptyPath(o)}";`) : [], callImports(model), mounted.map((m) => `import ${mountVar(m)} from "${toRoot("generated/server/main.ts")}${model.mounts[m].file}";`), serviced.filter((m) => !mounted.includes(m)).map((m) => `import ${mountVar(m)} from "${toRoot("generated/server/main.ts")}${model.mounts[m].file}";`), doors.imports, things.map((t) => `import * as ${camel(t.name)}Thing from "${thingFileAt("generated/server/main.ts", t, "thing")}";`), declaredRules.map((t) => `import * as ${camel(t.name)}Invariants from "${thingFileAt("generated/server/main.ts", t, "invariants")}";`), stores.map((s) => `import ${camel(s.name)}Store from "${storeFileAt("generated/server/main.ts", s)}";`), "", worldExports(timed, actors), "", serviced.length > 0 ? ["/** Each adapter's mount by the name it is mounted under: what a `service` role in `allowed` is read against. */", `const mounts = new Map<unknown, string>([${serviced.map((m) => `[${mountVar(m)}, "${m}"]`).join(", ")}]);`, ""] : [], ops.map((o) => o.kind === "read"
51
+ ? `const ${opVar(o)}Served = Reads.serve({ name: "${o.name}", read: ${opVar(o)}.declaration${mountsOption} });`
52
+ : `const ${opVar(o)}Served = Handlers.serve({ name: "${o.name}", operation: ${opVar(o)}.declaration, handler: ${served(o)}${notFromOf(model, o)}, codes: Errors.codes${wired(model, o)}${mountsOption} });`), empty ? handled.map((o) => `const ${opVar(o)}Scaffolded = Handlers.serve({ name: "${o.name}", operation: ${opVar(o)}.declaration, handler: ${opVar(o)}Blank${notFromOf(model, o)}, codes: Errors.codes${wired(model, o)}${mountsOption} });`) : [], "", "/** Each thing and its table: a D1 table, or the name its actors go by. */", `const tables = [${things.map((t) => `[thingIn(${camel(t.name)}Thing), "${t.name}"]`).join(", ")}] as const;`, ruled.length > 0 ? ["", "/** Each rule (G5) under its full name, `<thing>.<rule>`: the store's index refuses a second holder at commit, and the runtime refuses before it. */", `const rules = [${[...declaredRules.map((t) => `...invariantsIn("${t.name}", ${camel(t.name)}Invariants)`), ...versionedRules.map((t) => `...Versions.rulesOf("${t.name}", thingIn(${camel(t.name)}Thing))`)].join(", ")}] as const;`] : [], "", doors.table, "const refusals = Wire.refusals(Errors.wire);", "// A refused payload names every field it was refused for, not only the first (#988).", "const CallApi = Api.middleware(CallTelemetry).annotate(HttpApi.PayloadParseOptions, { errors: \"all\" });", `type Services = SqlClient.SqlClient | Store | Busy | Principals | Journal | Auth${timed ? " | Timers | DurableTimers" : ""};`, "", "/** Who is calling, then the operation or read, its refusals sent as their wire classes. */", "type Run = (payload: never, principal: Principal, request?: string) => Effect.Effect<unknown, unknown, unknown>;", "/** Every answer and every refusal is cut by the visibility rule for this caller before it is sent. */", "const shown = Wire.shown(Errors.declared);", "const call = <P extends object>(served: { readonly run: Run; readonly operation: ShownOperation }, payload: P, headers: Readonly<Record<string, string | undefined>>) =>", " Effect.flatMap(Principals, (principals) => principals.of(headers[\"authorization\"])).pipe(", " Effect.withTracerEnabled(false),", " // The caller's idempotency key: for an operation declared `idempotent: \"request\"`, the same key is one call.", " Effect.flatMap((principal: Principal) => served.run(payload as never, principal, headers[\"idempotency-key\"]).pipe(shown(served, payload, principal))),", " refusals,", " ) as Effect.Effect<never, never, Services>;", "", groups.map(group).flat(), "", "export interface Env {", " readonly DB: D1Database;", stores.map((s) => ` /** The database of store ${s.name}: its own tables, journal and request keys. */\n readonly ${bindingOf(s)}: D1Database;`), " readonly WORLD: DurableObjectNamespace;", actors ? " readonly ACTORS: DurableObjectNamespace;" : [], " /** Better Auth's secret, at least 32 characters: fresh per local world, a named secret per environment. */", " readonly AUTH_SECRET: string;", doors.env, " readonly OTLP_URL?: string;", " /** The environment's telemetry sinks beside the collector, as JSON: each one's OTLP endpoints and headers. A secret. */", " readonly OTLP_SINKS?: string;", " /** The environment's name, written on every span as `deployment.environment`: `local` for a world of dev or prove. */", " readonly ORTHO_ENVIRONMENT?: string;", " /** Which build this environment runs, set by `ortho env up`; unset for a world made by `ortho dev` or prove. */", " readonly ORTHO_REVISION?: string;", " readonly ORTHO_BUNDLE_SHA256?: string;", " /** The portal's: where the logbook is, which environment this is. Read by `portal.serve`; neither is sent to a browser. */", " readonly ORTHO_LOGBOOK_URL?: string;", " /** `1` in an environment that hosts worlds with lifetimes (a test environment), set by `ortho env up`. */", " readonly ORTHO_WORLDS?: string;", "}", "", "/** Which steps each operation runs, by the operation's name: the server's own record, never in the API package (the caller's contract names no step, K14). */", "export const steps = {", ops.filter((o) => Object.keys(o.steps).length > 0).map((o) => ` "${o.name}": [${Object.values(o.steps).map((s) => `"${s.name}"`).join(", ")}],`), "} as const;", "", "// Better Auth's own routes at /api/auth/*: the device sign-in of this project's CLI. Same database and secret as the", "// layer's instance, so a session either one issues is a person to both.", "let routes: ReturnType<typeof AuthD1.make> | undefined;", `const routesOf = (env: Env) => (routes ??= AuthD1.make({ db: ${db}, secret: env.AUTH_SECRET, cli: "${name}-cli", worlds: hostsWorlds(env) }));`, "", "const build = (env: Env) =>", " HttpRouter.toWebHandler(", " HttpApiBuilder.layer(CallApi).pipe(", ` Layer.provide([${groups.map((t) => `${pascal(t)}Live`).join(", ")}]),`, " Layer.provideMerge(CallTelemetry.layer),", ` Layer.provide([StoreD1.layer({ tables${actors ? ", actors: env.ACTORS" : ""}${storeOption}${peopleOf(model)}${rulesOption} }), ${journal}, ${work}, Layer.succeed(Environment, env.ORTHO_ENVIRONMENT || "local"), AuthD1.layer(AuthD1.make({ db: ${db}, secret: env.AUTH_SECRET, worlds: hostsWorlds(env) }))]),`, ` Layer.provideMerge(Database.d1(${db})),`, " Layer.provide(HttpServer.layerServices),", " ),", " );", "", "// Built once per isolate, from the first request's bindings.", "let built: ReturnType<typeof build> | undefined;", "", "/** The environments of the blueprint that host worlds: those that declare a `lifetime` (D3 #126). */", `const WORLD_ENVIRONMENTS: ReadonlyArray<string> = ${JSON.stringify(Object.values(model.environments ?? {}).filter((e) => e.lifetimeMs !== null).map((e) => e.name))};`, "", "/**", " * `/_world/*` (the cast that signs people up with known passwords, the facts, the registry of worlds) answers only where", " * worlds live: a world made by `ortho dev` or prove (`local`, or no environment), and an environment that declares a lifetime and", " * was started to host worlds. Anywhere else, staging and production included, it is a 404 before any handler runs.", " */", "const hostsWorlds = (env: Env) =>", " !env.ORTHO_ENVIRONMENT || env.ORTHO_ENVIRONMENT === \"local\" || (env.ORTHO_WORLDS === \"1\" && WORLD_ENVIRONMENTS.includes(env.ORTHO_ENVIRONMENT));", "", "/** One tool per operation and read: the same served operations as the API, called as the person the access token names. */", "const tools = Mcp.tools<Services>({", " catalog,", ` served: { ${ops.map((o) => `"${o.name}": ${opVar(o)}Served`).join(", ")} },`, " refusals: { codes: Errors.codes, declared: Errors.declared, table: Errors.refusals },", "});", "", "// The MCP server's own runtime, built once per isolate: the same store, journal, busy count and auth as the API's.", "let mcpRuntime: ManagedRuntime.ManagedRuntime<Services, never> | undefined;", "const runtimeOf = (env: Env) =>", " (mcpRuntime ??= ManagedRuntime.make(", ` Layer.mergeAll(StoreD1.layer({ tables${actors ? ", actors: env.ACTORS" : ""}${storeOption}${peopleOf(model)}${rulesOption} }), ${journal}, ${work}, Layer.succeed(Environment, env.ORTHO_ENVIRONMENT || "local"), AuthD1.layer(AuthD1.make({ db: ${db}, secret: env.AUTH_SECRET, worlds: hostsWorlds(env) }))).pipe(Layer.provideMerge(Database.d1(${db}))),`, " ));", "", "const TRACEPARENT = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/;", "", "/** Who is asking at `/mcp`: any credential the identity knows, or an OAuth access token. This door is the agent's, so each is an agent for its person (M2-auth, fork 2). */", "const asker = (env: Env, request: Request) =>", " runtimeOf(env).runPromise(Effect.flatMap(Principals, (principals) => principals.of(request.headers.get(\"authorization\") ?? undefined, \"mcp\"))).then((principal) =>", " principal.kind !== \"anonymous\"", " ? { kind: \"asked\" as const, principal }", " : Effect.runPromise(AuthD1.oauth.bearer(routesOf(env), request)).then((who) => (who.kind === \"person\" ? { kind: \"asked\" as const, principal: who.principal } : who)));", "", "/** `/mcp`: an agent's credential, or a 401 that says where to get one; then the tool call. */", "const mcp = (env: Env, request: Request, context: Context.Context<never> | undefined): Promise<Response> =>", " asker(env, request).then((who) => {", " if (who.kind !== \"asked\") {", " const invalid = who.kind === \"invalid\";", " return Response.json({ error: invalid ? \"invalid_token\" : \"unauthorized\" }, { status: 401, headers: { \"www-authenticate\": AuthD1.oauth.challenge(request, invalid ? \"invalid_token\" : undefined) } });", " }", " // The caller's span, when it sent one, is the parent of every span of the call.", " const sent = request.headers.get(\"traceparent\")?.match(TRACEPARENT);", " const parent = sent ? Tracer.externalSpan({ traceId: sent[1]!, spanId: sent[2]!, sampled: true }) : undefined;", " const run = (effect: Effect.Effect<McpResult, never, Services>) => {", " const traced = parent ? Effect.withParentSpan(effect, parent) : effect;", " return runtimeOf(env).runPromise(context ? Effect.provideContext(traced, context) : traced);", " };", ` return Mcp.handle({ name: "${name}", version: env.ORTHO_REVISION ?? "0.0.0", tools, principal: who.principal, run }, request);`, " });", "",
53
+ // An environment with a stepped or scaled clock (K23): the entry reads its world's instant and runs each request in it (M8.06).
54
+ timed ? ["/** Each request runs in its world's time: `Date` and Effect's `Clock` read the instant its world keeps (stepped and scaled worlds only). */", "export default WorldEntry.entry<Env>({"] : "export default {", " fetch(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {", " // Closed before anything reads it: outside worlds there is no door to cast, to read facts, or to register a world.", " if (new URL(request.url).pathname.startsWith(\"/_world/\") && !hostsWorlds(env)) return Promise.resolve(Response.json({ error: \"not found\" }, { status: 404 }));", " if (new URL(request.url).pathname.startsWith(\"/_world/\")) {", ` return toWorld({ worlds: env.WORLD, db: env.DB, ${world}, leases: env.ORTHO_WORLDS === "1" }, request);`, " }", " if (new URL(request.url).pathname === \"/_ortho/bundle\") {", " return env.ORTHO_REVISION && env.ORTHO_BUNDLE_SHA256", " ? Promise.resolve(Response.json({ revision: env.ORTHO_REVISION, sha256: env.ORTHO_BUNDLE_SHA256 }))", " : Promise.resolve(Response.json({ _tag: \"NotAnEnvironment\" }, { status: 404 }));", " }", doors.route, " if (portal.owns(new URL(request.url).pathname)) return portal.serve(request, env);", timed
55
+ ? " if (new URL(request.url).pathname.startsWith(\"/api/auth/\")) return WorldEntry.section(env, () => Effect.runPromise(AuthD1.handle(routesOf(env), request)));"
56
+ : " if (new URL(request.url).pathname.startsWith(\"/api/auth/\")) return Effect.runPromise(AuthD1.handle(routesOf(env), request));", " if (new URL(request.url).pathname.startsWith(\"/.well-known/\")) {", " return Effect.runPromise(AuthD1.oauth.discovery(routesOf(env), request)).then((found) => found ?? Response.json({ error: \"not found\" }, { status: 404 }));", " }", " if (new URL(request.url).pathname === \"/mcp\") {", ` return Telemetry.serve({ url: env.OTLP_URL || undefined, sinks: env.OTLP_SINKS, environment: env.ORTHO_ENVIRONMENT, service: "${name}", handler: (req, context) => mcp(env, req, context), waitUntil: (p) => ctx.waitUntil(p) }, request);`, " }", " const app = (built ??= build(env));", " Telemetry.configure({ sinks: env.OTLP_SINKS, environment: env.ORTHO_ENVIRONMENT });", ` return Telemetry.serve({ url: env.OTLP_URL || undefined, service: "${name}", handler: app.handler, waitUntil: (p) => ctx.waitUntil(p) }, request);`, " },", timed ? "});" : "};"),
57
+ };
58
+ };
59
+ export const renderServer = (model, name, empty = false) => [
60
+ main(model, name, empty),
61
+ renderWrangler(name, Object.values(model.things).some((t) => t.lives === "actor"), databaseStores(model), clocksOf(model)),
62
+ renderMigration(model),
63
+ ...renderStoreMigrations(model),
64
+ ...(empty ? Object.values(model.operations).filter((o) => o.kind === "operation").map((o) => renderHandlerScaffold(o, `generated/server/${emptyPath(o)}`, model)) : []),
65
+ ];
@@ -0,0 +1,13 @@
1
+ import type { Model, OperationModel, ThingModel } from "@orthograph/compiler";
2
+ /** Is this one of the four: its verb is one of them, and its thing's key is a field of its payload? */
3
+ export declare const versioned: (model: Model, o: OperationModel) => boolean;
4
+ /**
5
+ * The things with rules, told apart by where a rule comes from. The framework holds one rule for a thing with versions (one row per
6
+ * revision of a key) that no `invariants.ts` declares: the runtime makes it (`Versions.rulesOf`). The others are read from their files.
7
+ */
8
+ export declare const rulesByOrigin: (ruled: ReadonlyArray<ThingModel>) => {
9
+ declaredRules: ThingModel[];
10
+ versionedRules: ThingModel[];
11
+ };
12
+ /** The refusal a stale save or restore answers with, as the model names it; a get or a history has none. */
13
+ export declare const staleOf: (o: OperationModel) => string;
@@ -0,0 +1,17 @@
1
+ /** The verbs of the four operations a thing with versions has. */
2
+ const VERSION_VERBS = ["save", "get", "history", "restore"];
3
+ /** Is this one of the four: its verb is one of them, and its thing's key is a field of its payload? */
4
+ export const versioned = (model, o) => {
5
+ const versions = model.things[o.thing]?.versions;
6
+ return o.kind === "operation" && VERSION_VERBS.includes(o.verb) && versions !== undefined && Object.keys(o.payload).includes(versions.key);
7
+ };
8
+ /**
9
+ * The things with rules, told apart by where a rule comes from. The framework holds one rule for a thing with versions (one row per
10
+ * revision of a key) that no `invariants.ts` declares: the runtime makes it (`Versions.rulesOf`). The others are read from their files.
11
+ */
12
+ export const rulesByOrigin = (ruled) => ({
13
+ declaredRules: ruled.filter((t) => Object.values(t.invariants ?? {}).some((r) => r.framework !== true)),
14
+ versionedRules: ruled.filter((t) => Object.values(t.invariants ?? {}).some((r) => r.framework === true)),
15
+ });
16
+ /** The refusal a stale save or restore answers with, as the model names it; a get or a history has none. */
17
+ export const staleOf = (o) => (o.stale === undefined ? "undefined" : `Errors.declared.${o.stale}`);
@@ -0,0 +1,16 @@
1
+ import type { ClockModel, Model, StoreModel } from "@orthograph/compiler";
2
+ import type { RenderedFile } from "#modules/names/types.js";
3
+ /** The compatibility date every Worker and test uses: the test pool's workerd accepts dates up to 2026-08-22. */
4
+ export declare const COMPATIBILITY_DATE = "2026-08-01";
5
+ /**
6
+ * Each environment whose clock is stepped or scaled, by name: what the world's Durable Objects and the Worker's entry read
7
+ * (`ORTHO_CLOCKS`, M8.06). A real clock, and no clock at all, are the default and are left out, so a blueprint with
8
+ * neither generates what it always did.
9
+ */
10
+ export declare const clocksOf: (model: Model) => Readonly<Record<string, ClockModel>>;
11
+ export declare const renderWrangler: (name: string, actors: boolean, stores?: ReadonlyArray<StoreModel>, clocks?: Readonly<Record<string, ClockModel>>) => RenderedFile;
12
+ export declare const hasDoors: (model: Model) => boolean;
13
+ /** The default database's tables: one per thing that lives in the database and in no declared store. Actors keep their own rows. */
14
+ export declare const renderMigration: (model: Model) => RenderedFile;
15
+ /** Each declared database store's own migration (K3 item 6): its things, and the journal and request keys its commits write beside them. */
16
+ export declare const renderStoreMigrations: (model: Model) => ReadonlyArray<RenderedFile>;
@@ -0,0 +1,90 @@
1
+ // The Worker's configuration and its database, both from the model.
2
+ import { Names } from "orthograph/server";
3
+ import { GENERATED, bindingOf, databaseStores, lines } from "#modules/names/service.js";
4
+ /** The compatibility date every Worker and test uses: the test pool's workerd accepts dates up to 2026-08-22. */
5
+ export const COMPATIBILITY_DATE = "2026-08-01";
6
+ /**
7
+ * Each environment whose clock is stepped or scaled, by name: what the world's Durable Objects and the Worker's entry read
8
+ * (`ORTHO_CLOCKS`, M8.06). A real clock, and no clock at all, are the default and are left out, so a blueprint with
9
+ * neither generates what it always did.
10
+ */
11
+ export const clocksOf = (model) => Object.fromEntries(Object.values(model.environments ?? {}).flatMap((e) => (e.clock !== undefined && e.clock.kind !== "real" ? [[e.name, e.clock]] : [])));
12
+ export const renderWrangler = (name, actors, stores = [], clocks = {}) => ({
13
+ path: "generated/server/wrangler.jsonc",
14
+ scaffold: false,
15
+ content: lines(GENERATED, "// Local only: the database id is a placeholder until a deploy names a real one (stage two).", "{", ` "name": "${name}",`, ` "main": "main.ts",`, ` "compatibility_date": "${COMPATIBILITY_DATE}",`, ` "compatibility_flags": ["nodejs_compat"],`, ` "d1_databases": [`,
16
+ // Each declared database store (K3) is a database of its own (its own placeholder id, so local state is kept apart) with its own migrations folder.
17
+ [` { "binding": "DB", "database_name": "${name}", "database_id": "00000000-0000-0000-0000-000000000000", "migrations_dir": "migrations" }`,
18
+ ...stores.map((s, i) => ` { "binding": "${bindingOf(s)}", "database_name": "${name}-${s.name}", "database_id": "00000000-0000-0000-0000-${String(i + 1).padStart(12, "0")}", "migrations_dir": "migrations/${s.name}" }`)]
19
+ .map((l, i, all) => (i < all.length - 1 ? `${l},` : l)), " ],", actors
20
+ ? ` "durable_objects": { "bindings": [{ "name": "WORLD", "class_name": "World" }, { "name": "ACTORS", "class_name": "Actor" }] },`
21
+ : ` "durable_objects": { "bindings": [{ "name": "WORLD", "class_name": "World" }] },`, actors
22
+ ? ` "migrations": [{ "tag": "v1", "new_sqlite_classes": ["World", "Actor"] }],`
23
+ : ` "migrations": [{ "tag": "v1", "new_sqlite_classes": ["World"] }],`, " // Where telemetry goes. `ortho prove` and `ortho dev --otlp` set it; unset, nothing is exported.", Object.keys(clocks).length === 0
24
+ ? ` "vars": { "OTLP_URL": "" }`
25
+ : [
26
+ " // Each environment's stepped or scaled clock (K23): the world's Durable Objects and the Worker's entry read it.",
27
+ ` "vars": { "OTLP_URL": "", "${Names.variable("CLOCKS")}": ${JSON.stringify(JSON.stringify(clocks))} }`,
28
+ ], "}"),
29
+ });
30
+ const JOURNAL = `CREATE TABLE "_journal" (
31
+ "seq" INTEGER PRIMARY KEY AUTOINCREMENT,
32
+ "trace" TEXT NOT NULL,
33
+ "operation" TEXT NOT NULL,
34
+ "move" TEXT NOT NULL,
35
+ "subject" TEXT NOT NULL,
36
+ "event" TEXT NOT NULL,
37
+ "fields" TEXT NOT NULL
38
+ );
39
+ CREATE INDEX "_journal_trace" ON "_journal" ("trace");
40
+ -- Each idempotent call's answer, under its operation, caller and request key, committed with the call itself.
41
+ CREATE TABLE "_requests" (
42
+ "key" TEXT PRIMARY KEY,
43
+ "answer" TEXT NOT NULL
44
+ );`;
45
+ /**
46
+ * A field's column, from the form its value encodes to: INTEGER for a boolean (the store binds 1 or 0 and reads a
47
+ * boolean back), TEXT for everything else (ids and amounts as text, a list, a struct, a union or an unknown as its JSON).
48
+ * A field that may have no value, optional or nullable, is a column that may be NULL; any other is NOT NULL.
49
+ */
50
+ const columnOf = (field) => `${field.value.type === "schema" && field.value.format === "bool" ? "INTEGER" : "TEXT"}${field.optional === true || field.nullable === true ? "" : " NOT NULL"}`;
51
+ /**
52
+ * One table per thing: a column per field (see `columnOf`), `state` when it has a machine, and the
53
+ * `version` every update is guarded by (D2 #36). A field that is an array or a struct is its JSON text (STO-23).
54
+ */
55
+ const tablesOf = (things) => things.map((t) => {
56
+ const columns = Object.entries(t.fields).map(([f, field]) => (f === "id" ? ` "id" TEXT PRIMARY KEY` : ` "${f}" ${columnOf(field)}`));
57
+ // Empty until the thing's first move sets it.
58
+ if (t.machine)
59
+ columns.push(` "state" TEXT`);
60
+ columns.push(` "version" INTEGER NOT NULL DEFAULT 0`);
61
+ // A rule (G5) is one partial unique index too, named after it (`<table>_<rule>`) so two rules over one field keep two: over the rule's key, within its `while` states.
62
+ const ruleIndexes = Object.entries(t.invariants ?? {}).map(([rule, { fields, while: states }]) => {
63
+ const scope = states ? ` WHERE "state" IN (${states.map((s) => `'${s.replaceAll("'", "''")}'`).join(", ")})` : "";
64
+ return `CREATE UNIQUE INDEX "${t.name}_${rule}" ON "${t.name}" (${fields.map((f) => `"${f}"`).join(", ")})${scope};`;
65
+ });
66
+ return [`CREATE TABLE "${t.name}" (\n${columns.join(",\n")}\n);`, ...ruleIndexes].join("\n");
67
+ });
68
+ const header = (...extra) => [
69
+ "-- Generated from the blueprint. Do not edit.",
70
+ "-- Stage one rebuilds the local database on every `ortho dev`; migrations between versions arrive in stage three.",
71
+ ...extra,
72
+ ];
73
+ /** A door-enabled app's journal is also its inbox: each accepted delivery is a row with a unique `id` (`<mount>:<the event's identity>`) and the account that sent it. */
74
+ const INBOX = `-- The inbox (M5-reach-out Q2.3): an accepted delivery is one row, by a unique id, so a delivery that comes twice settles once.
75
+ ALTER TABLE "_journal" ADD COLUMN "id" TEXT;
76
+ ALTER TABLE "_journal" ADD COLUMN "actor" TEXT;
77
+ CREATE UNIQUE INDEX "_journal_id" ON "_journal" ("id");`;
78
+ export const hasDoors = (model) => Object.values(model.mounts ?? {}).some((m) => m.door !== undefined);
79
+ /** The default database's tables: one per thing that lives in the database and in no declared store. Actors keep their own rows. */
80
+ export const renderMigration = (model) => ({
81
+ path: "generated/server/migrations/0001_things.sql",
82
+ scaffold: false,
83
+ content: lines(header(), tablesOf(Object.values(model.things).filter((t) => t.lives === "database" && !t.store)), "-- Every event a move emitted, with the trace of the call that made it (language-effect's Journal).", JOURNAL, hasDoors(model) ? INBOX : []),
84
+ });
85
+ /** Each declared database store's own migration (K3 item 6): its things, and the journal and request keys its commits write beside them. */
86
+ export const renderStoreMigrations = (model) => databaseStores(model).map((s) => ({
87
+ path: `generated/server/migrations/${s.name}/0001_things.sql`,
88
+ scaffold: false,
89
+ content: lines(header(`-- Store ${s.name}: the database that ${bindingOf(s)} is bound to.`), tablesOf(Object.values(model.things).filter((t) => t.store === s.name)), "-- Every event a move of this store emitted, with the trace of the call that made it.", JOURNAL),
90
+ }));
@@ -0,0 +1,10 @@
1
+ import type { Model } from "@orthograph/compiler";
2
+ import type { RenderedFile } from "#modules/names/types.js";
3
+ /**
4
+ * The Worker: every served operation's route wired to its handler, the world's door, the portal, the D1 tables and
5
+ * their migrations, and the types of the handlers that call an adapter (`generated/server/`).
6
+ */
7
+ export declare const server: import("orthograph").Projection<{}>;
8
+ /** A temporary Worker with the original handlers for setup and scaffolds for journey calls (`ortho prove`, never `generated/`). */
9
+ export declare const emptyServer: (model: Model, name: string) => ReadonlyArray<RenderedFile>;
10
+ export { COMPATIBILITY_DATE } from "./internal/worker-config.ts";
@@ -0,0 +1,20 @@
1
+ import { Blueprint, Host, Ships } from "orthograph";
2
+ import { modelOf, serverModel, within } from "#modules/names/service.js";
3
+ import { renderHandlerTypes } from "#modules/handlers/service.js";
4
+ import { renderServer } from "./internal/server.js";
5
+ /**
6
+ * The Worker: every served operation's route wired to its handler, the world's door, the portal, the D1 tables and
7
+ * their migrations, and the types of the handlers that call an adapter (`generated/server/`).
8
+ */
9
+ export const server = Blueprint.projection({
10
+ description: "The Worker: each operation's route wired to its handler, the world's door, the portal, and the database's tables.",
11
+ host: [Host.worker],
12
+ ships: [Ships.deploy],
13
+ render: (input) => {
14
+ const served = serverModel(modelOf(input));
15
+ return within(input, "server", [...renderServer(served, input.name), ...renderHandlerTypes(served)]);
16
+ },
17
+ });
18
+ /** A temporary Worker with the original handlers for setup and scaffolds for journey calls (`ortho prove`, never `generated/`). */
19
+ export const emptyServer = (model, name) => renderServer(serverModel(model), name, true);
20
+ export { COMPATIBILITY_DATE } from "./internal/worker-config.js";
@@ -0,0 +1 @@
1
+ export type { Projection } from "orthograph";
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ export * from "#modules/names/service.js";
2
+ export type { RenderedFile } from "#modules/names/types.js";
3
+ export { machinePaths, renderHandlerScaffold, renderJourneyStubs } from "#modules/handlers/service.js";
4
+ export type { MachinePath } from "#modules/handlers/types.js";
5
+ export { who } from "#modules/handlers/service.js";
6
+ export { emptyServer } from "#modules/server/service.js";
package/dist/shared.js ADDED
@@ -0,0 +1,6 @@
1
+ // What the generators still need of this package while the docs and the portal wait on the fixed list (M1.13 moves
2
+ // them here, and this entry goes): the names every renderer shares, the handler scaffold, and the empty server of `prove`.
3
+ export * from "#modules/names/service.js";
4
+ export { machinePaths, renderHandlerScaffold, renderJourneyStubs } from "#modules/handlers/service.js";
5
+ export { who } from "#modules/handlers/service.js";
6
+ export { emptyServer } from "#modules/server/service.js";
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@orthograph/projections",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-next.1",
4
+ "license": "Apache-2.0",
5
+ "type": "module",
6
+ "dependencies": {
7
+ "effect": "4.1.4",
8
+ "@orthograph/compiler": "0.1.0-next.1",
9
+ "orthograph": "0.1.0-next.1"
10
+ },
11
+ "orthograph": {
12
+ "kind": "projection"
13
+ },
14
+ "imports": {
15
+ "#modules/*.js": "./dist/modules/*.js"
16
+ },
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/main.d.ts",
20
+ "default": "./dist/main.js"
21
+ },
22
+ "./shared": {
23
+ "types": "./dist/shared.d.ts",
24
+ "default": "./dist/shared.js"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "dist"
30
+ ],
31
+ "publishConfig": {
32
+ "access": "public",
33
+ "tag": "next"
34
+ }
6
35
  }