@orthograph/compiler 0.0.0-stage → 0.1.0-next.2

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 (147) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +4 -2
  3. package/dist/index.d.ts +12 -0
  4. package/dist/index.js +9 -0
  5. package/dist/main.d.ts +2 -0
  6. package/dist/main.js +18 -0
  7. package/dist/modules/app/internal/checks.d.ts +30 -0
  8. package/dist/modules/app/internal/checks.js +99 -0
  9. package/dist/modules/app/internal/describe.d.ts +6 -0
  10. package/dist/modules/app/internal/describe.js +59 -0
  11. package/dist/modules/app/internal/hash.d.ts +1 -0
  12. package/dist/modules/app/internal/hash.js +7 -0
  13. package/dist/modules/app/internal/known.d.ts +19 -0
  14. package/dist/modules/app/internal/known.js +45 -0
  15. package/dist/modules/app/internal/read.d.ts +6 -0
  16. package/dist/modules/app/internal/read.js +45 -0
  17. package/dist/modules/app/service.d.ts +2 -0
  18. package/dist/modules/app/service.js +3 -0
  19. package/dist/modules/app/types.d.ts +87 -0
  20. package/dist/modules/app/types.js +1 -0
  21. package/dist/modules/compare/internal/assets.d.ts +4 -0
  22. package/dist/modules/compare/internal/assets.js +40 -0
  23. package/dist/modules/compare/internal/chain.d.ts +4 -0
  24. package/dist/modules/compare/internal/chain.js +37 -0
  25. package/dist/modules/compare/internal/diff.d.ts +3 -0
  26. package/dist/modules/compare/internal/diff.js +27 -0
  27. package/dist/modules/compare/internal/versions.d.ts +9 -0
  28. package/dist/modules/compare/internal/versions.js +75 -0
  29. package/dist/modules/compare/service.d.ts +2 -0
  30. package/dist/modules/compare/service.js +43 -0
  31. package/dist/modules/compare/types.d.ts +47 -0
  32. package/dist/modules/compare/types.js +1 -0
  33. package/dist/modules/lock/internal/evolve.d.ts +7 -0
  34. package/dist/modules/lock/internal/evolve.js +52 -0
  35. package/dist/modules/lock/internal/runtime.d.ts +3 -0
  36. package/dist/modules/lock/internal/runtime.js +12 -0
  37. package/dist/modules/lock/service.d.ts +4 -0
  38. package/dist/modules/lock/service.js +20 -0
  39. package/dist/modules/lock/types.d.ts +101 -0
  40. package/dist/modules/lock/types.js +6 -0
  41. package/dist/modules/model/internal/allowed.d.ts +26 -0
  42. package/dist/modules/model/internal/allowed.js +78 -0
  43. package/dist/modules/model/internal/approval.d.ts +4 -0
  44. package/dist/modules/model/internal/approval.js +10 -0
  45. package/dist/modules/model/internal/assets.d.ts +5 -0
  46. package/dist/modules/model/internal/assets.js +31 -0
  47. package/dist/modules/model/internal/bits.d.ts +6 -0
  48. package/dist/modules/model/internal/bits.js +9 -0
  49. package/dist/modules/model/internal/chain.d.ts +9 -0
  50. package/dist/modules/model/internal/chain.js +47 -0
  51. package/dist/modules/model/internal/codes.d.ts +59 -0
  52. package/dist/modules/model/internal/codes.js +80 -0
  53. package/dist/modules/model/internal/derive.d.ts +11 -0
  54. package/dist/modules/model/internal/derive.js +31 -0
  55. package/dist/modules/model/internal/describe.d.ts +8 -0
  56. package/dist/modules/model/internal/describe.js +248 -0
  57. package/dist/modules/model/internal/device.d.ts +5 -0
  58. package/dist/modules/model/internal/device.js +12 -0
  59. package/dist/modules/model/internal/environments.d.ts +7 -0
  60. package/dist/modules/model/internal/environments.js +90 -0
  61. package/dist/modules/model/internal/exits.d.ts +49 -0
  62. package/dist/modules/model/internal/exits.js +85 -0
  63. package/dist/modules/model/internal/fields.d.ts +23 -0
  64. package/dist/modules/model/internal/fields.js +50 -0
  65. package/dist/modules/model/internal/fillable.d.ts +3 -0
  66. package/dist/modules/model/internal/fillable.js +9 -0
  67. package/dist/modules/model/internal/forms.d.ts +47 -0
  68. package/dist/modules/model/internal/forms.js +75 -0
  69. package/dist/modules/model/internal/found.d.ts +40 -0
  70. package/dist/modules/model/internal/found.js +60 -0
  71. package/dist/modules/model/internal/handler-files.d.ts +18 -0
  72. package/dist/modules/model/internal/handler-files.js +23 -0
  73. package/dist/modules/model/internal/hash.d.ts +4 -0
  74. package/dist/modules/model/internal/hash.js +7 -0
  75. package/dist/modules/model/internal/holds.d.ts +19 -0
  76. package/dist/modules/model/internal/holds.js +65 -0
  77. package/dist/modules/model/internal/invariants.d.ts +38 -0
  78. package/dist/modules/model/internal/invariants.js +134 -0
  79. package/dist/modules/model/internal/journeys.d.ts +15 -0
  80. package/dist/modules/model/internal/journeys.js +135 -0
  81. package/dist/modules/model/internal/layout.d.ts +143 -0
  82. package/dist/modules/model/internal/layout.js +203 -0
  83. package/dist/modules/model/internal/lock-fields.d.ts +3 -0
  84. package/dist/modules/model/internal/lock-fields.js +17 -0
  85. package/dist/modules/model/internal/money.d.ts +17 -0
  86. package/dist/modules/model/internal/money.js +49 -0
  87. package/dist/modules/model/internal/nullable.d.ts +7 -0
  88. package/dist/modules/model/internal/nullable.js +21 -0
  89. package/dist/modules/model/internal/operations.d.ts +27 -0
  90. package/dist/modules/model/internal/operations.js +81 -0
  91. package/dist/modules/model/internal/reads.d.ts +16 -0
  92. package/dist/modules/model/internal/reads.js +58 -0
  93. package/dist/modules/model/internal/rules.d.ts +2 -0
  94. package/dist/modules/model/internal/rules.js +33 -0
  95. package/dist/modules/model/internal/same-value.d.ts +10 -0
  96. package/dist/modules/model/internal/same-value.js +50 -0
  97. package/dist/modules/model/internal/secrets.d.ts +4 -0
  98. package/dist/modules/model/internal/secrets.js +35 -0
  99. package/dist/modules/model/internal/source-refusals.d.ts +7 -0
  100. package/dist/modules/model/internal/source-refusals.js +52 -0
  101. package/dist/modules/model/internal/sources.d.ts +12 -0
  102. package/dist/modules/model/internal/sources.js +65 -0
  103. package/dist/modules/model/internal/stores.d.ts +20 -0
  104. package/dist/modules/model/internal/stores.js +44 -0
  105. package/dist/modules/model/internal/things.d.ts +33 -0
  106. package/dist/modules/model/internal/things.js +99 -0
  107. package/dist/modules/model/service.d.ts +4 -0
  108. package/dist/modules/model/service.js +105 -0
  109. package/dist/modules/model/types.d.ts +485 -0
  110. package/dist/modules/model/types.js +5 -0
  111. package/dist/modules/mounts/fixtures/both/things/echo/thing.d.ts +1 -0
  112. package/dist/modules/mounts/fixtures/both/things/echo/thing.js +1 -0
  113. package/dist/modules/mounts/fixtures/both/things/echo/verbs/only.d.ts +1 -0
  114. package/dist/modules/mounts/fixtures/both/things/echo/verbs/only.js +1 -0
  115. package/dist/modules/mounts/internal/attribute.d.ts +2 -0
  116. package/dist/modules/mounts/internal/attribute.js +4 -0
  117. package/dist/modules/mounts/internal/calls.d.ts +12 -0
  118. package/dist/modules/mounts/internal/calls.js +42 -0
  119. package/dist/modules/mounts/internal/choices.d.ts +11 -0
  120. package/dist/modules/mounts/internal/choices.js +34 -0
  121. package/dist/modules/mounts/internal/fold.d.ts +6 -0
  122. package/dist/modules/mounts/internal/fold.js +8 -0
  123. package/dist/modules/mounts/internal/needs.d.ts +14 -0
  124. package/dist/modules/mounts/internal/needs.js +26 -0
  125. package/dist/modules/mounts/internal/verbs.d.ts +11 -0
  126. package/dist/modules/mounts/internal/verbs.js +44 -0
  127. package/dist/modules/mounts/service.d.ts +2 -0
  128. package/dist/modules/mounts/service.js +165 -0
  129. package/dist/modules/mounts/types.d.ts +78 -0
  130. package/dist/modules/mounts/types.js +1 -0
  131. package/dist/modules/source/internal/plugins.d.ts +25 -0
  132. package/dist/modules/source/internal/plugins.js +49 -0
  133. package/dist/modules/source/service.d.ts +6 -0
  134. package/dist/modules/source/service.js +86 -0
  135. package/dist/modules/source/types.d.ts +55 -0
  136. package/dist/modules/source/types.js +6 -0
  137. package/dist/modules/time/internal/anchor.d.ts +2 -0
  138. package/dist/modules/time/internal/anchor.js +48 -0
  139. package/dist/modules/time/internal/keeper.d.ts +13 -0
  140. package/dist/modules/time/internal/keeper.js +19 -0
  141. package/dist/modules/time/internal/zones.d.ts +1 -0
  142. package/dist/modules/time/internal/zones.js +3 -0
  143. package/dist/modules/time/service.d.ts +2 -0
  144. package/dist/modules/time/service.js +56 -0
  145. package/dist/modules/time/types.d.ts +89 -0
  146. package/dist/modules/time/types.js +1 -0
  147. package/package.json +35 -3
@@ -0,0 +1,81 @@
1
+ import { canonical } from "./hash.js";
2
+ /** The payload names the generated signed entry takes for itself. */
3
+ const RESERVED_FIELDS = ["signer", "nonce", "deadline", "signature"];
4
+ /** The entries the generated contract has of its own: a verb named like one would be declared twice. */
5
+ export const RESERVED_ENTRIES = ["nonces", "eip712Domain", "hasRole", "getRoleAdmin", "grantRole", "revokeRole", "renounceRole"];
6
+ /** The role an entry names, person's or service's. */
7
+ const roleOf = (a) => (a.kind === "role" ? a : a.kind === "role-of" ? a.role : undefined);
8
+ /** A step the generated contract can't take: it reaches only its own store and the account adapter (item 8). */
9
+ const FOREIGN_STEPS = ["database", "actor"];
10
+ export const chainOperationProblems = ({ file, name, thing, op, roleNames, payload, answer, event, emits, mints }) => {
11
+ const problems = [];
12
+ const said = `${file}: ${name}`;
13
+ if (op.runsDeclared !== undefined)
14
+ problems.push(`${said} writes runs: "${op.runsDeclared}", which an author never writes: it runs on the chain because ${thing} lives in a chain store`);
15
+ if (op.idempotent !== undefined)
16
+ problems.push(`${said} declares idempotent, but the nonce makes every call land at most once on chain: leave it out`);
17
+ if ("signedBy" in op)
18
+ problems.push(`${said} writes signedBy, which no one writes any more: the role that allows the operation is who must sign (M6-chain item 1)`);
19
+ for (const [key, step] of Object.entries(op.steps)) {
20
+ if (FOREIGN_STEPS.includes(step.type))
21
+ problems.push(`${said} declares the ${step.type} step ${key}: an operation of a chain-stored thing reaches only its own store and the account adapter, so it has no ${step.type} step`);
22
+ }
23
+ for (const entry of op.allowed) {
24
+ // A contract sees only the signer: how a caller arrived, the runtime's own work and an outside service mean nothing to it.
25
+ if (entry.kind === "narrowed")
26
+ problems.push(`${said} narrows an entry with .via or .notVia: how a caller arrived means nothing to a contract, which sees only the signer`);
27
+ const a = entry.kind === "narrowed" ? entry.entry : entry;
28
+ if (a.kind === "system")
29
+ problems.push(`${said} is allowed to Blueprint.system: the runtime's own work is no signer, so a contract can't tell it from anyone: allow a who role or Blueprint.anyone`);
30
+ if (a.kind === "signed-in")
31
+ problems.push(`${said} is allowed to Blueprint.signedIn: every caller on chain has signed, so allow a who role or Blueprint.anyone`);
32
+ const found = roleOf(a);
33
+ if (found === undefined)
34
+ continue;
35
+ const named = roleNames.get(found) ?? "a role";
36
+ if (found.service !== undefined) {
37
+ problems.push(`${said} is allowed to the service role ${named}: a contract sees only the signer, so an outside service is no one it can admit: use a who role on an account() field`);
38
+ continue;
39
+ }
40
+ const role = found;
41
+ if (role.who === undefined)
42
+ problems.push(`${said} is allowed to the role ${named}, whose rule is TypeScript only: a contract can't run it, so use a who role on an account() field`);
43
+ else if (role.who.value.meta.type !== "account")
44
+ problems.push(`${said} is allowed to the who role ${named} on ${role.who.key}, which is no account(): on a chain store a who role is the account that signed`);
45
+ else if (a.kind === "role" && op.move?.from.length === 0 && role.thing === op.thing && !(role.who.key in payload)) {
46
+ problems.push(`${said} creates a row and is allowed to ${named}, which is decided on the payload's ${role.who.key}, but the payload has no ${role.who.key}`);
47
+ }
48
+ }
49
+ // A move that makes the row counts, in each amount, the token its payload carries: there is no stored row to read it from yet (M6-money item 1).
50
+ if (op.move?.from.length === 0) {
51
+ for (const [key, f] of Object.entries(payload)) {
52
+ if (f.value.type === "money" && "field" in f.value.asset && !(f.value.asset.field in payload)) {
53
+ problems.push(`${said}'s payload field ${key} is an amount of the asset in ${f.value.asset.field}, and the operation makes the row, so its payload must carry ${f.value.asset.field} too`);
54
+ }
55
+ }
56
+ }
57
+ for (const key of RESERVED_FIELDS.filter((k) => k in payload)) {
58
+ problems.push(`${said}'s payload field ${key} collides with the generated contract, which adds a ${key} of its own to every entry: rename it`);
59
+ }
60
+ for (const [key, field] of Object.entries(answer)) {
61
+ const read = event?.[key];
62
+ const fromEvent = read !== undefined && canonical(read.value) === canonical(field.value);
63
+ if (!fromEvent && key !== mints) {
64
+ problems.push(`${said}'s answer field ${key} is neither a field of its event ${emits} nor the new row's id: a call on chain lands later, so its answer is read from the event`);
65
+ }
66
+ }
67
+ return problems;
68
+ };
69
+ /** A read of a chain-stored thing is a public `view`: only `Blueprint.anyone` may be allowed, and only a read by id is one. */
70
+ export const chainReadProblems = (file, name, read) => [
71
+ ...(read.allowed.length === 1 && read.allowed[0]?.kind === "anyone" ? [] : [`${file}: ${name} is a read of a chain-stored thing, which a public chain shows to everyone: allowed must be [Blueprint.anyone], not a role or signedIn`]),
72
+ ...(read.by === "list" ? [`${file}: ${name} is a list read of a chain-stored thing: a contract has no list to read, so a read is by id`] : []),
73
+ ];
74
+ /** Verbs of one chain store whose entry name collides: with an entry the generated contract has, or with another operation's signed entry. */
75
+ export const collisionProblems = (verbs) => {
76
+ const identifiers = new Set(verbs.map((v) => v.identifier));
77
+ return verbs.flatMap((v) => [
78
+ ...(RESERVED_ENTRIES.includes(v.identifier) ? [`${v.file}: ${v.name} is named like ${v.identifier}, an entry the generated contract has of its own: rename it`] : []),
79
+ ...(v.identifier.endsWith("BySig") && identifiers.has(v.identifier.slice(0, -"BySig".length)) ? [`${v.file}: ${v.name} is named like ${v.identifier}, the signed entry the generated contract gives ${v.identifier.slice(0, -"BySig".length)}: rename it`] : []),
80
+ ]);
81
+ };
@@ -0,0 +1,16 @@
1
+ import type { AllowedModel, FieldsModel, OperationModel } from "../types.ts";
2
+ import { type Allowed, type FieldsInput, type Read, type Thing } from "orthograph";
3
+ import { type Layout } from "./layout.ts";
4
+ import type { FieldContext } from "./fields.ts";
5
+ export interface ReadContext {
6
+ readonly layout: Layout;
7
+ readonly thingNames: ReadonlyMap<Thing, string>;
8
+ readonly problems: Array<string>;
9
+ readonly allowedModel: (entry: Allowed, file: string) => AllowedModel;
10
+ readonly fieldsModel: (fields: FieldsInput, where: string, ctx: FieldContext) => FieldsModel;
11
+ readonly onChain: (thing: Thing | undefined) => boolean;
12
+ readonly openToAll: (allowed: ReadonlyArray<AllowedModel>) => boolean;
13
+ /** The problems with a read's role paths (#767). */
14
+ readonly rolePaths: (thing: string, read: Read, file: string) => ReadonlyArray<string>;
15
+ }
16
+ export declare const readModelOf: (c: ReadContext, thing: string, verb: string, file: string, from: OperationModel["from"], read: Read) => OperationModel;
@@ -0,0 +1,58 @@
1
+ // A read in the model: answered from the thing's records with no handler, so no move, no steps, no declared errors; a derived read
2
+ // also says what it looks at and adds, and a list read what it pins.
3
+ import { Duration } from "effect";
4
+ import { admitsAgent } from "orthograph";
5
+ import { Times } from "#modules/time/service.js";
6
+ import { camel } from "./layout.js";
7
+ import { chainReadProblems } from "./operations.js";
8
+ import { deriveModel } from "./derive.js";
9
+ import { READ_NOT_SERVED } from "./codes.js";
10
+ import { hashOf } from "./hash.js";
11
+ export const readModelOf = (c, thing, verb, file, from, read) => {
12
+ const { problems, fieldsModel } = c;
13
+ const allowed = read.allowed.map((a) => c.allowedModel(a, file));
14
+ problems.push(...c.rolePaths(thing, read, file));
15
+ problems.push(...Times.keeper({ file, name: `${thing}.${verb}`, kind: "read", move: undefined, allowed }));
16
+ const list = read.by === "list";
17
+ const t = c.layout.things.get(thing);
18
+ const chain = c.onChain(t?.thing);
19
+ if (list && t?.thing?.lives === "actor")
20
+ problems.push(`${file}: a list read needs a thing that lives in the database, and ${thing} lives as actors`);
21
+ if (chain)
22
+ problems.push(...chainReadProblems(file, `${thing}.${verb}`, read));
23
+ if (list && read.where.includes("state") && !t?.machine)
24
+ problems.push(`${file}: where "state" needs ${thing} to have a machine`);
25
+ if (list && (!Number.isInteger(read.page) || (read.page ?? 0) < 1 || (read.page ?? 0) > 1000))
26
+ problems.push(`${file}: page must be a whole number from 1 to 1000`);
27
+ const ctx = { owner: { name: thing, thing: read.thing }, chain: chain && !list };
28
+ const payload = Object.fromEntries(Object.entries(fieldsModel(read.payload, `${file} payload`, { place: "a payload", ...ctx })).map(([k, f]) => [k, read.optional.includes(k) ? { ...f, optional: true } : f]));
29
+ const adds = read.derive === undefined ? undefined : fieldsModel(read.derive.adds, `${file} derive adds`, { place: "answer", ...ctx });
30
+ const derive = read.derive === undefined ? undefined : deriveModel(read.derive, file, adds, { thingNames: c.thingNames, problems });
31
+ const known = (n) => n in (t?.thing?.fields ?? {}) || n === "state" || n in (read.derive?.adds ?? {});
32
+ for (const n of read.where)
33
+ if (!known(n))
34
+ problems.push(`${file}: where names ${n}, which is neither a stored field of ${thing} nor one a derive adds`);
35
+ for (const n of Object.keys(read.only ?? {}))
36
+ if (!known(n))
37
+ problems.push(`${file}: only pins ${n}, which is neither a stored field of ${thing} nor one a derive adds`);
38
+ const pinned = Object.keys(read.only ?? {});
39
+ // A read's `state` is the machine's number on chain, a uint8 (M6-chain item 2).
40
+ const answer = Object.fromEntries(Object.entries(fieldsModel(read.answer, `${file} answer`, { place: "a read answer", ...ctx })).map(([k, f]) => [k, ctx.chain && k === "state" ? { ...f, solidity: "uint8" } : f]));
41
+ const entry = {
42
+ kind: "read",
43
+ name: `${thing}.${verb}`, thing, verb, identifier: camel(verb), file, from,
44
+ description: list
45
+ ? `List ${thing}s, ${read.order === "newest" ? "newest first" : "oldest first"}, ${read.page} to a page${read.where.length > 0 ? `, filtered by ${read.where.join(", ")}` : ""}.`
46
+ : `Read one ${thing} by its id: ${read.fields.map(String).join(", ")}.`,
47
+ payload, answer,
48
+ move: null, errors: [], breaks: [],
49
+ // A pinned or derived read is served (slice 7), but for a derive that looks at the app's problems, which no store lists yet: that one can refuse it, by name.
50
+ refusals: [...(c.openToAll(allowed) ? [] : ["NotAllowed"]), ...(derive !== undefined && Object.values(derive.looks).some((l) => "kind" in l) ? [READ_NOT_SERVED] : [])], allowed, agentTool: admitsAgent(read.allowed),
51
+ steps: {}, idempotent: null, runs: (chain ? "chain" : "server"), test: "unit",
52
+ budget: read.budget ? { p95Ms: Duration.toMillis(read.budget.p95) } : null,
53
+ ...(list ? { list: { where: read.where.filter((n) => !pinned.includes(n)), order: read.order ?? "newest", page: read.page ?? 0 } } : {}),
54
+ ...(read.only === undefined ? {} : { only: read.only }),
55
+ ...(derive === undefined ? {} : { derive }),
56
+ };
57
+ return { ...entry, hash: hashOf(entry) };
58
+ };
@@ -0,0 +1,2 @@
1
+ import type { AlertRuleModel, Model } from "../types.ts";
2
+ export declare const alertRulesOf: (model: Pick<Model, "operations" | "refusals" | "things" | "journeys" | "environments">) => ReadonlyArray<AlertRuleModel>;
@@ -0,0 +1,33 @@
1
+ const MIN = 60_000;
2
+ const HOUR = 60 * MIN;
3
+ const DAY = 24 * HOUR;
4
+ const LATENCY = { target: 0.95, windowDays: 28 };
5
+ const DEFECT = { target: 0.999, windowDays: 28 };
6
+ const MIN_CALLS = 20;
7
+ const burns = () => [
8
+ { name: "fast", burn: 14.4, windowsMs: [HOUR, 5 * MIN], severity: "page" },
9
+ { name: "slow", burn: 6, windowsMs: [6 * HOUR, 30 * MIN], severity: "page" },
10
+ { name: "ticket", burn: 1, windowsMs: [3 * DAY, 6 * HOUR], severity: "ticket" },
11
+ ];
12
+ /** The owner of an anomaly: the file of the thing whose errors declare the code, else the runtime's. */
13
+ const anomalyOwner = (model, code) => {
14
+ const thing = Object.entries(model.things).find(([, t]) => Object.values(t.errors).some((e) => e.code === code))?.[0];
15
+ return thing === undefined ? "orthograph" : `blueprint/things/${thing}/errors.ts`;
16
+ };
17
+ const byId = (a, b) => (a.id < b.id ? -1 : a.id > b.id ? 1 : 0);
18
+ export const alertRulesOf = (model) => [
19
+ ...Object.entries(model.operations).filter(([, op]) => op.budget != null).map(([name, op]) => ({
20
+ id: `latency:${name}`, kind: "latency", labels: { environment: "*", operation: name, severity: "page", owner: op.file },
21
+ ...LATENCY, thresholdMs: op.budget.p95Ms, minCalls: MIN_CALLS, alerts: burns(),
22
+ })),
23
+ ...Object.entries(model.operations).map(([name, op]) => ({
24
+ id: `defect:${name}`, kind: "defect", labels: { environment: "*", operation: name, severity: "page", owner: op.file },
25
+ ...DEFECT, minCalls: MIN_CALLS, alerts: burns(),
26
+ })),
27
+ ...Object.values(model.refusals).map((code) => ({
28
+ id: `anomaly:${code}`, kind: "anomaly", labels: { environment: "*", code, severity: "ticket", owner: anomalyOwner(model, code) },
29
+ })),
30
+ ...Object.values(model.journeys).flatMap((journey) => Object.keys(model.environments ?? {}).map((environment) => ({
31
+ id: `verdict:${journey.name}:${environment}`, kind: "verdict", labels: { environment, journey: journey.name, severity: "page", owner: journey.file },
32
+ }))),
33
+ ].sort(byId);
@@ -0,0 +1,10 @@
1
+ import type { FieldInput, Value } from "orthograph";
2
+ /** The value a field input stands for: the value itself, or a thing field's value. */
3
+ export declare const valueOfInput: (input: FieldInput) => Value;
4
+ /**
5
+ * Strict equality. A value whose schema has no named type (`meta.type` is "schema") is equal only to the same schema object, since two
6
+ * schemas cannot be compared by what they accept. Any other value is equal when its kind of type and the type's own numbers match and its schema makes the same checks (`email()` and `text({ max: 254 })` share a meta, but only the email checks the pattern).
7
+ */
8
+ export declare const sameValue: (a: Value, b: Value) => boolean;
9
+ /** A value in a few words for a message: `text of at most 40 characters`. */
10
+ export declare const describeValue: (v: Value) => string;
@@ -0,0 +1,50 @@
1
+ /** The value a field input stands for: the value itself, or a thing field's value. */
2
+ export const valueOfInput = (input) => (input.kind === "field" ? input.value : input);
3
+ /** What a value's schema checks, in the words each check describes itself with (`a value with a length of at most 254`). */
4
+ const checksOf = (v) => {
5
+ const ast = v.schema.ast;
6
+ return JSON.stringify((ast.checks ?? []).map((c) => c.annotations?.expected ?? null));
7
+ };
8
+ const ids = new WeakMap();
9
+ let issued = 0;
10
+ /** A number for an object that stays the same for as long as the object lives: two references to one value object agree. */
11
+ const idOf = (x) => {
12
+ const known = ids.get(x);
13
+ if (known !== undefined)
14
+ return known;
15
+ issued += 1;
16
+ ids.set(x, issued);
17
+ return issued;
18
+ };
19
+ /**
20
+ * A value's meta as text, with no cycle in it. Money's asset is a live reference (a field of a thing holds the thing, which holds the field):
21
+ * a fixed asset is its own data, and a per-row one is the value object of the field that holds it, so `Thing.fields.token` and the `token`
22
+ * put in that field are the same asset (M6-money item 1).
23
+ */
24
+ const metaText = (v) => JSON.stringify(v.meta, (key, x) => {
25
+ if (key !== "asset" || typeof x !== "object" || x === null)
26
+ return x;
27
+ const ref = x;
28
+ return ref.kind === "fixed" ? { fixed: ref.asset } : { of: idOf(valueOfInput(ref.of)) };
29
+ });
30
+ /**
31
+ * Strict equality. A value whose schema has no named type (`meta.type` is "schema") is equal only to the same schema object, since two
32
+ * schemas cannot be compared by what they accept. Any other value is equal when its kind of type and the type's own numbers match and its schema makes the same checks (`email()` and `text({ max: 254 })` share a meta, but only the email checks the pattern).
33
+ */
34
+ export const sameValue = (a, b) => {
35
+ if (a.schema === b.schema)
36
+ return true;
37
+ if (a.meta.type === "schema" || b.meta.type === "schema")
38
+ return false;
39
+ return metaText(a) === metaText(b) && checksOf(a) === checksOf(b);
40
+ };
41
+ /** A value in a few words for a message: `text of at most 40 characters`. */
42
+ export const describeValue = (v) => {
43
+ switch (v.meta.type) {
44
+ case "id": return `an id with the prefix ${v.meta.prefix}`;
45
+ case "uint": return `a ${v.meta.bits}-bit number`;
46
+ case "text": return `text of at most ${v.meta.max} characters`;
47
+ case "decimal": return `a decimal with ${v.meta.places} places`;
48
+ default: return "a schema declared on its own";
49
+ }
50
+ };
@@ -0,0 +1,4 @@
1
+ import type { SecretModel } from "../types.ts";
2
+ import type { Layout } from "./layout.ts";
3
+ /** Every declared secret by its derived name, sorted; two on one name, or one that can't be split, are problems. */
4
+ export declare const secretsOf: (layout: Layout, problems: Array<string>) => Readonly<Record<string, SecretModel>>;
@@ -0,0 +1,35 @@
1
+ /** Lowercase words, each capitalized after the first: `webhookSigning`. A digit or a run of capitals (`key2`, `apiURL`) could split two ways. */
2
+ const WORDS = /^[a-z]+(?:[A-Z][a-z]+)*$/;
3
+ const words = (name) => name.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase();
4
+ const mountWords = (mount) => mount.replace(/-/g, "_").toUpperCase();
5
+ /** Every declared secret by its derived name, sorted; two on one name, or one that can't be split, are problems. */
6
+ export const secretsOf = (layout, problems) => {
7
+ const found = [];
8
+ const take = (exported, file, name, model, where) => {
9
+ if (!WORDS.test(exported)) {
10
+ problems.push(`${file}: export "${exported}" can't be turned into a secret's name without guessing where its words split: write it as lowercase words in camelCase, with no digits and no run of capitals (apiKey, not apiURL or key2)`);
11
+ return;
12
+ }
13
+ found.push({ name, model, where });
14
+ };
15
+ for (const s of layout.secrets.values()) {
16
+ const d = s.declaration;
17
+ take(s.export, s.file, words(s.export), { how: d.how, kind: d.secretKind, export: s.export, from: { kind: "app" }, ...(d.describe === undefined ? {} : { describe: d.describe }) }, `export ${s.export} in ${s.file}`);
18
+ }
19
+ for (const s of layout.mountSecrets) {
20
+ const d = s.declaration;
21
+ take(s.export, `${s.mountFile}`, `${mountWords(s.mount)}_${words(s.export)}`, {
22
+ how: d.how, kind: d.secretKind, export: s.export,
23
+ from: { kind: s.kind, mount: s.mount, package: s.package, version: s.version },
24
+ ...(d.describe === undefined ? {} : { describe: d.describe }),
25
+ }, `export ${s.export} of ${s.package}, mounted in ${s.mountFile}`);
26
+ }
27
+ const byName = new Map();
28
+ for (const c of found)
29
+ byName.set(c.name, [...(byName.get(c.name) ?? []), c]);
30
+ for (const [name, same] of byName) {
31
+ if (same.length > 1)
32
+ problems.push(`secret ${name} is declared twice: ${same.map((c) => c.where).join(" and ")}: mount one under another name, or rename an export`);
33
+ }
34
+ return Object.fromEntries([...byName].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([name, [first]]) => [name, first.model]));
35
+ };
@@ -0,0 +1,7 @@
1
+ import type { SourceKind } from "orthograph";
2
+ import type { Layout } from "./layout.ts";
3
+ type Spec = NonNullable<SourceKind<any>["spec"]>;
4
+ export declare const refuseSpec: (problems: Array<string>, file: string, exportName: string, spec: Spec, callName: (call: unknown) => string | undefined) => void;
5
+ /** What kinds a source makes: the string literals of each `kind:` in its `on` mappings (see `kindsOf`). */
6
+ export declare const refuseConnection: (problems: Array<string>, file: string, layout: Layout, kind: SourceKind<any>, config: unknown, kindsOf: (on: Readonly<Record<string, unknown>>) => ReadonlyArray<string>) => void;
7
+ export {};
@@ -0,0 +1,52 @@
1
+ // What the compiler refuses of a source's mapping that TypeScript cannot, each on one problem line of the file the fault is in
2
+ // (GOAL17-source-from, "The model"; built in slice 11): a `gone` error the reply call does not declare, a config with no `me`
3
+ // of the `{ id, login }` shape, an `environment.of` whose keys are not the names `variables` declares, and a connection
4
+ // naming an event no kind the source makes produces.
5
+ import { Effect } from "effect";
6
+ /** A required string field: a `Schema.String`, which the schema does not mark optional. */
7
+ const requiredString = (field) => {
8
+ const ast = field?.ast;
9
+ return ast?._tag === "String" && ast.context?.isOptional !== true;
10
+ };
11
+ /** `me` is a struct of exactly `id` and `login`, each a required string: the shape is judged, not the identity of the schema. */
12
+ const meShape = (config) => {
13
+ const me = config.fields?.["me"];
14
+ const fields = me?.fields;
15
+ return fields !== undefined && Object.keys(fields).sort().join() === "id,login" && requiredString(fields["id"]) && requiredString(fields["login"]);
16
+ };
17
+ /** The names `environment.of` answers for a trigger whose address answers any property with text; `undefined` where it cannot be read that way. */
18
+ const keysOf = (spec) => {
19
+ const anything = new Proxy({}, { get: (_t, key) => (key === Symbol.toPrimitive ? () => "x" : "x") });
20
+ return Effect.runSync(Effect.try(() => Object.keys(spec.environment.of({ kind: "x", thread: "x", text: "x", channel: anything })).sort()).pipe(Effect.catch(() => Effect.succeed(undefined))));
21
+ };
22
+ export const refuseSpec = (problems, file, exportName, spec, callName) => {
23
+ if (!meShape(spec.config))
24
+ problems.push(`${file}: ${exportName}'s config has no \`me\` of the shape { id: string, login: string }: the gate and the mapping need the agent's own account`);
25
+ const declared = spec.reply?.call.errors ?? [];
26
+ for (const gone of spec.reply?.gone ?? []) {
27
+ if (!declared.includes(gone)) {
28
+ problems.push(`${file}: ${exportName}'s reply.gone lists ${gone.name ?? "an error"}, which ${callName(spec.reply.call) ?? "the reply call"} does not declare (its errors: ${declared.map((e) => e.name).join(", ") || "none"}): a gone error is one of the reply call's own`);
29
+ }
30
+ }
31
+ const named = Object.keys(spec.environment.variables).sort();
32
+ const made = keysOf(spec);
33
+ if (made !== undefined) {
34
+ for (const key of made.filter((k) => !named.includes(k)))
35
+ problems.push(`${file}: ${exportName}'s environment.of returns ${key}, which environment.variables does not declare`);
36
+ for (const key of named.filter((k) => !made.includes(k)))
37
+ problems.push(`${file}: ${exportName}'s environment.of does not return ${key}, which environment.variables declares`);
38
+ }
39
+ };
40
+ /** What kinds a source makes: the string literals of each `kind:` in its `on` mappings (see `kindsOf`). */
41
+ export const refuseConnection = (problems, file, layout, kind, config, kindsOf) => {
42
+ const entry = [...layout.sources].find(([, s]) => s.declaration === kind);
43
+ const events = config?.events;
44
+ if (entry === undefined || kind.spec === undefined || !Array.isArray(events))
45
+ return;
46
+ // A connection lists a kind (`comment`) or the group of them (`comments`).
47
+ const made = kindsOf(kind.spec.on ?? {});
48
+ for (const event of events.filter((e) => typeof e === "string")) {
49
+ if (!made.some((k) => event === k || event === `${k}s`))
50
+ problems.push(`${file}: a connection of ${entry[1].exportName} names the event "${event}", which no kind ${entry[1].exportName} makes produces (its kinds: ${made.join(", ")})`);
51
+ }
52
+ };
@@ -0,0 +1,12 @@
1
+ import type { SourceKind } from "orthograph";
2
+ import type { MountModel } from "../types.ts";
3
+ import type { Layout } from "./layout.ts";
4
+ export interface SourceContext {
5
+ readonly layout: Layout;
6
+ readonly mounts: Readonly<Record<string, MountModel>>;
7
+ readonly problems: Array<string>;
8
+ }
9
+ /** Every string literal of every `kind:` expression in what the `on` mappings make, sorted and distinct. */
10
+ export declare const kindsOf: (on: Readonly<Record<string, unknown>>) => ReadonlyArray<string>;
11
+ export declare const sourcesModel: (ctx: SourceContext) => Record<string, unknown>;
12
+ export declare const sourceNameOf: (layout: Layout, kind: SourceKind<any>) => string | undefined;
@@ -0,0 +1,65 @@
1
+ import { refuseSpec } from "./source-refusals.js";
2
+ const SECRET_WORD = /_(TOKEN|KEY|SECRET|PASSWORD)$/;
3
+ /** Every string literal of every `kind:` expression in what the `on` mappings make, sorted and distinct. */
4
+ export const kindsOf = (on) => {
5
+ const found = new Set();
6
+ for (const fn of Object.values(on)) {
7
+ for (const m of String(fn).matchAll(/\bkind\s*:\s*([^,}]*)/g)) {
8
+ for (const lit of m[1].matchAll(/"([^"]*)"|'([^']*)'/g))
9
+ found.add(lit[1] ?? lit[2] ?? "");
10
+ }
11
+ }
12
+ return [...found].sort();
13
+ };
14
+ const sorted = (xs) => [...new Set(xs)].sort();
15
+ export const sourcesModel = (ctx) => {
16
+ const out = {};
17
+ for (const [name, { file, declaration: kind, exportName }] of [...ctx.layout.sources].sort(([a], [b]) => a.localeCompare(b))) {
18
+ if (kind.adapter === null) {
19
+ const fields = Object.keys(kind.config.fields ?? {});
20
+ out[name] = { mount: null, config: Object.fromEntries(fields.map((f) => [f, "text"])) };
21
+ continue;
22
+ }
23
+ const spec = kind.spec;
24
+ const adapter = kind.adapter;
25
+ const mountEntry = [...ctx.layout.mounts].find(([, m]) => m.mount.plugin === adapter);
26
+ if (!mountEntry)
27
+ continue;
28
+ const [mount, mountFile] = mountEntry;
29
+ const offered = Object.keys(adapter.events ?? {});
30
+ const used = sorted([...Object.keys(spec.on ?? {}), ...Object.keys(spec.closed ?? {})]);
31
+ for (const e of used)
32
+ if (!offered.includes(e))
33
+ ctx.problems.push(`${file}: ${exportName} maps the event ${e}, which ${ctx.mounts[mount]?.package ?? mount} doesn't have (its events: ${offered.join(", ") || "none"})`);
34
+ const included = ctx.mounts[mount]?.events ?? [];
35
+ // A source is active when its adapter is mounted and the mount includes any event it maps.
36
+ if (!used.some((e) => included.includes(e)))
37
+ continue;
38
+ for (const e of used.filter((x) => offered.includes(x) && !included.includes(x))) {
39
+ ctx.problems.push(`${mountFile.file}: ${mount} does not include events.${e}, which ${exportName} maps: add p.include(p.events.${e})`);
40
+ }
41
+ const calls = [spec.reply?.call, spec.history?.call, spec.policyPart.sync?.call].flatMap((call) => (call === undefined ? [] : [ctx.layout.calls.get(call)]));
42
+ for (const reach of calls) {
43
+ if (reach === undefined)
44
+ ctx.problems.push(`${file}: ${exportName} uses a call that is not one of ${mount}'s calls`);
45
+ else if (!reach.included)
46
+ ctx.problems.push(`${reach.file}: ${mount} does not include calls.${reach.call}, which ${exportName} uses: add p.include(p.calls.${reach.call})`);
47
+ }
48
+ refuseSpec(ctx.problems, file, exportName, spec, (call) => ctx.layout.calls.get(call)?.call);
49
+ const prefix = `${name.toUpperCase().replaceAll("-", "_")}_`;
50
+ for (const v of Object.keys(spec.environment.variables)) {
51
+ if (!/^[A-Z][A-Z0-9_]*$/.test(v))
52
+ ctx.problems.push(`${file}: variable ${v} must be capitals, digits and underscores`);
53
+ if (SECRET_WORD.test(v))
54
+ ctx.problems.push(`${file}: variable ${v} ends in a secret's word (_TOKEN, _KEY, _SECRET, _PASSWORD): an execution variable is never a credential`);
55
+ if (!v.startsWith(prefix))
56
+ ctx.problems.push(`${file}: variable ${v} does not start with its source's own prefix ${prefix}`);
57
+ }
58
+ out[name] = {
59
+ mount, file, export: exportName, events: used, calls: sorted(calls.flatMap((c) => (c === undefined ? [] : [c.call]))),
60
+ variables: spec.environment.variables, kinds: kindsOf(spec.on ?? {}),
61
+ };
62
+ }
63
+ return out;
64
+ };
65
+ export const sourceNameOf = (layout, kind) => [...layout.sources].find(([, s]) => s.declaration === kind)?.[0];
@@ -0,0 +1,20 @@
1
+ import type { StoreModel, ThingModel } from "../types.ts";
2
+ import type { Layout } from "./layout.ts";
3
+ /**
4
+ * The kinds the host supplies: `database` and `actor` from @orthograph/host-cloudflare, and `chain.evm`, a contract
5
+ * the Solidity language writes and `Host.chain` deploys (K25, K27). A kind another host or language supplies is added here.
6
+ */
7
+ export declare const STORE_KINDS: ReadonlyArray<string>;
8
+ /** The declared stores by name, each hashed, and a problem for a kind no host supplies. */
9
+ export declare const storesOf: (layout: Layout, problems: Array<string>) => Readonly<Record<string, StoreModel>>;
10
+ /** One step of an operation, as the model has it. */
11
+ interface StepModel {
12
+ readonly type: string;
13
+ readonly writes?: ReadonlyArray<string>;
14
+ }
15
+ /**
16
+ * The problem with an operation whose writes land in more than one store, if it has one (K3 item 5). A `database`
17
+ * step writes the operation's own thing, or the things it names; a move writes the operation's own thing.
18
+ */
19
+ export declare const crossStore: (file: string, operation: string, own: string, hasMove: boolean, steps: Readonly<Record<string, StepModel>>, things: Readonly<Record<string, ThingModel>>) => string | undefined;
20
+ export {};
@@ -0,0 +1,44 @@
1
+ import { hashOf } from "./hash.js";
2
+ /**
3
+ * The kinds the host supplies: `database` and `actor` from @orthograph/host-cloudflare, and `chain.evm`, a contract
4
+ * the Solidity language writes and `Host.chain` deploys (K25, K27). A kind another host or language supplies is added here.
5
+ */
6
+ export const STORE_KINDS = ["database", "actor", "chain.evm"];
7
+ const byName = (m) => [...m].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));
8
+ /** The declared stores by name, each hashed, and a problem for a kind no host supplies. */
9
+ export const storesOf = (layout, problems) => Object.fromEntries(byName(layout.stores).map(([name, s]) => {
10
+ if (!STORE_KINDS.includes(s.store.of)) {
11
+ problems.push(`${s.file}: a store of kind "${s.store.of}", which no host of this project supplies (they supply ${STORE_KINDS.join(" and ")})`);
12
+ }
13
+ const entry = { name, file: s.file, kind: s.store.of, ...(s.from ? { from: s.from } : {}) };
14
+ return [name, { ...entry, hash: hashOf(entry) }];
15
+ }));
16
+ /** Where a thing lives, as a message names it. */
17
+ const placeOf = (t) => (t.store ? `store ${t.store}` : t.lives === "actor" ? "the actor store" : "the default store");
18
+ /**
19
+ * The problem with an operation whose writes land in more than one store, if it has one (K3 item 5). A `database`
20
+ * step writes the operation's own thing, or the things it names; a move writes the operation's own thing.
21
+ */
22
+ export const crossStore = (file, operation, own, hasMove, steps, things) => {
23
+ const places = new Map();
24
+ const write = (thing, by) => {
25
+ const t = thing ? things[thing] : undefined;
26
+ if (t)
27
+ places.set(placeOf(t), [...(places.get(placeOf(t)) ?? []), by]);
28
+ };
29
+ if (hasMove)
30
+ write(own, "its move");
31
+ for (const [key, s] of Object.entries(steps)) {
32
+ if (s.type !== "database")
33
+ continue;
34
+ if (s.writes)
35
+ for (const w of s.writes)
36
+ write(w, `step ${key} (${w})`);
37
+ else
38
+ write(own, `step ${key}`);
39
+ }
40
+ if (places.size < 2)
41
+ return undefined;
42
+ const named = [...places].map(([place, by]) => `${place} by ${[...new Set(by)].join(" and ")}`);
43
+ return `${file}: ${operation} writes to ${places.size === 2 ? "two" : places.size} stores (${named.join("; ")}): one call commits to one store, so run work across stores as a workflow`;
44
+ };
@@ -0,0 +1,33 @@
1
+ import type { AnyErrorClass, Event, Store, Thing } from "orthograph";
2
+ import type { Lock } from "#modules/lock/types.js";
3
+ import type { ThingModel } from "../types.ts";
4
+ import { type Layout } from "./layout.ts";
5
+ import type { Names } from "./money.ts";
6
+ import type { fieldsOf } from "./fields.ts";
7
+ export interface ThingsEnv {
8
+ readonly layout: Layout;
9
+ readonly before: Lock;
10
+ readonly problems: Array<string>;
11
+ readonly prefix: ReadonlyMap<string, string>;
12
+ readonly missable: ReadonlySet<Thing>;
13
+ readonly verbs: ReadonlyArray<{
14
+ readonly file: string;
15
+ readonly errors: ReadonlyArray<AnyErrorClass>;
16
+ }>;
17
+ readonly chain: {
18
+ readonly is: (t: Thing | undefined) => boolean;
19
+ readonly has: boolean;
20
+ readonly storeNames: ReadonlyMap<Store, string>;
21
+ };
22
+ readonly names: Names;
23
+ readonly thingNames: ReadonlyMap<Thing, string>;
24
+ readonly eventNames: ReadonlyMap<Event, string>;
25
+ readonly errorNames: ReadonlyMap<AnyErrorClass, string>;
26
+ readonly fieldsModel: ReturnType<typeof fieldsOf>["fieldsModel"];
27
+ readonly fieldModel: ReturnType<typeof fieldsOf>["fieldModel"];
28
+ readonly blankIn: (owner: string, parts: Record<string, unknown>) => boolean;
29
+ }
30
+ export declare const thingsOf: (env: ThingsEnv) => {
31
+ readonly things: Record<string, ThingModel>;
32
+ readonly lock: Lock;
33
+ };