@orthograph/projections 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.
- package/LICENSE +202 -0
- package/README.md +26 -2
- package/dist/main.d.ts +9 -0
- package/dist/main.js +12 -0
- package/dist/modules/actions/internal/actions.d.ts +7 -0
- package/dist/modules/actions/internal/actions.js +22 -0
- package/dist/modules/actions/service.d.ts +5 -0
- package/dist/modules/actions/service.js +14 -0
- package/dist/modules/actions/types.d.ts +9 -0
- package/dist/modules/actions/types.js +5 -0
- package/dist/modules/api/internal/api.d.ts +4 -0
- package/dist/modules/api/internal/api.js +99 -0
- package/dist/modules/api/service.d.ts +5 -0
- package/dist/modules/api/service.js +16 -0
- package/dist/modules/api/types.d.ts +1 -0
- package/dist/modules/api/types.js +1 -0
- package/dist/modules/app/internal/links.d.ts +2 -0
- package/dist/modules/app/internal/links.js +22 -0
- package/dist/modules/app/internal/palette.d.ts +6 -0
- package/dist/modules/app/internal/palette.js +55 -0
- package/dist/modules/app/internal/render.d.ts +4 -0
- package/dist/modules/app/internal/render.js +30 -0
- package/dist/modules/app/internal/view.d.ts +3 -0
- package/dist/modules/app/internal/view.js +52 -0
- package/dist/modules/app/service.d.ts +5 -0
- package/dist/modules/app/service.js +17 -0
- package/dist/modules/app/types.d.ts +52 -0
- package/dist/modules/app/types.js +1 -0
- package/dist/modules/cli/internal/cli.d.ts +3 -0
- package/dist/modules/cli/internal/cli.js +35 -0
- package/dist/modules/cli/internal/session.d.ts +11 -0
- package/dist/modules/cli/internal/session.js +55 -0
- package/dist/modules/cli/service.d.ts +2 -0
- package/dist/modules/cli/service.js +10 -0
- package/dist/modules/cli/types.d.ts +1 -0
- package/dist/modules/cli/types.js +1 -0
- package/dist/modules/handlers/internal/body.d.ts +5 -0
- package/dist/modules/handlers/internal/body.js +79 -0
- package/dist/modules/handlers/internal/calls.d.ts +17 -0
- package/dist/modules/handlers/internal/calls.js +80 -0
- package/dist/modules/handlers/internal/header.d.ts +18 -0
- package/dist/modules/handlers/internal/header.js +106 -0
- package/dist/modules/handlers/internal/paths.d.ts +18 -0
- package/dist/modules/handlers/internal/paths.js +11 -0
- package/dist/modules/handlers/internal/scaffold.d.ts +7 -0
- package/dist/modules/handlers/internal/scaffold.js +73 -0
- package/dist/modules/handlers/internal/stubs.d.ts +3 -0
- package/dist/modules/handlers/internal/stubs.js +141 -0
- package/dist/modules/handlers/internal/words.d.ts +43 -0
- package/dist/modules/handlers/internal/words.js +87 -0
- package/dist/modules/handlers/service.d.ts +5 -0
- package/dist/modules/handlers/service.js +9 -0
- package/dist/modules/handlers/types.d.ts +2 -0
- package/dist/modules/handlers/types.js +1 -0
- package/dist/modules/infra/internal/stack.d.ts +3 -0
- package/dist/modules/infra/internal/stack.js +15 -0
- package/dist/modules/infra/service.d.ts +5 -0
- package/dist/modules/infra/service.js +13 -0
- package/dist/modules/infra/types.d.ts +1 -0
- package/dist/modules/infra/types.js +1 -0
- package/dist/modules/mcp/internal/mcp.d.ts +3 -0
- package/dist/modules/mcp/internal/mcp.js +20 -0
- package/dist/modules/mcp/service.d.ts +5 -0
- package/dist/modules/mcp/service.js +13 -0
- package/dist/modules/mcp/types.d.ts +1 -0
- package/dist/modules/mcp/types.js +1 -0
- package/dist/modules/model/internal/edges.d.ts +4 -0
- package/dist/modules/model/internal/edges.js +12 -0
- package/dist/modules/model/service.d.ts +6 -0
- package/dist/modules/model/service.js +20 -0
- package/dist/modules/model/types.d.ts +1 -0
- package/dist/modules/model/types.js +1 -0
- package/dist/modules/names/internal/names.d.ts +51 -0
- package/dist/modules/names/internal/names.js +47 -0
- package/dist/modules/names/internal/when.d.ts +5 -0
- package/dist/modules/names/internal/when.js +19 -0
- package/dist/modules/names/internal/words.d.ts +34 -0
- package/dist/modules/names/internal/words.js +61 -0
- package/dist/modules/names/service.d.ts +19 -0
- package/dist/modules/names/service.js +19 -0
- package/dist/modules/names/types.d.ts +16 -0
- package/dist/modules/names/types.js +5 -0
- package/dist/modules/sdk/internal/client.d.ts +2 -0
- package/dist/modules/sdk/internal/client.js +31 -0
- package/dist/modules/sdk/internal/sdk.d.ts +3 -0
- package/dist/modules/sdk/internal/sdk.js +68 -0
- package/dist/modules/sdk/internal/types.d.ts +8 -0
- package/dist/modules/sdk/internal/types.js +38 -0
- package/dist/modules/sdk/service.d.ts +5 -0
- package/dist/modules/sdk/service.js +13 -0
- package/dist/modules/sdk/types.d.ts +1 -0
- package/dist/modules/sdk/types.js +1 -0
- package/dist/modules/server/internal/actors.d.ts +3 -0
- package/dist/modules/server/internal/actors.js +5 -0
- package/dist/modules/server/internal/doors.d.ts +10 -0
- package/dist/modules/server/internal/doors.js +26 -0
- package/dist/modules/server/internal/helpers.d.ts +13 -0
- package/dist/modules/server/internal/helpers.js +70 -0
- package/dist/modules/server/internal/server.d.ts +3 -0
- package/dist/modules/server/internal/server.js +65 -0
- package/dist/modules/server/internal/versioned.d.ts +13 -0
- package/dist/modules/server/internal/versioned.js +17 -0
- package/dist/modules/server/internal/worker-config.d.ts +16 -0
- package/dist/modules/server/internal/worker-config.js +90 -0
- package/dist/modules/server/service.d.ts +10 -0
- package/dist/modules/server/service.js +20 -0
- package/dist/modules/server/types.d.ts +1 -0
- package/dist/modules/server/types.js +1 -0
- package/dist/shared.d.ts +6 -0
- package/dist/shared.js +6 -0
- package/package.json +37 -3
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { Model, OperationModel, StoreModel, ThingModel } from "@orthograph/compiler";
|
|
2
|
+
export declare const GENERATED = "// Generated from the blueprint. Do not edit.";
|
|
3
|
+
export declare const scaffolded: (from: string) => string;
|
|
4
|
+
export declare const pascal: (name: string) => string;
|
|
5
|
+
export declare const camel: (name: string) => string;
|
|
6
|
+
/**
|
|
7
|
+
* The name a verb gets as a local binding. A verb may be a reserved word (`import`, `delete`): it is still the property
|
|
8
|
+
* `Sdk.wallet.import` and the export name, but never a `const` of its own, so the binding gets an underscore and is
|
|
9
|
+
* exported under the verb (`export { import_ as import }`, which JavaScript allows).
|
|
10
|
+
*/
|
|
11
|
+
export declare const local: (name: string) => string;
|
|
12
|
+
/** The line that exports a binding under the verb's own name, when the binding had to be renamed. */
|
|
13
|
+
export declare const exportedAs: (verb: string) => ReadonlyArray<string>;
|
|
14
|
+
/** `.create`, or `["sign-in"]` for a name that isn't an identifier: how generated code reaches a thing, a verb or a client member. */
|
|
15
|
+
export declare const member: (name: string) => string;
|
|
16
|
+
/** The variable an operation goes by in generated code: `allowance.grant` is `allowanceGrant`. */
|
|
17
|
+
export declare const opVar: (op: OperationModel) => string;
|
|
18
|
+
/** Climb from a generated file back to the project root. */
|
|
19
|
+
export declare const toRoot: (from: string) => string;
|
|
20
|
+
/** Import a declaration: the project's own by path from `from`, a plugin's by its package specifier, as written. */
|
|
21
|
+
export declare const declarationAt: (from: string, file: string) => string;
|
|
22
|
+
/** A thing's own file (`thing`, `errors`, `events`, `invariants`): in the project, or in the plugin it came from. */
|
|
23
|
+
export declare const thingFileAt: (from: string, thing: ThingModel, file: "thing" | "errors" | "events" | "invariants") => string;
|
|
24
|
+
/** A store's own file: the project's `blueprint/stores/<name>.ts`, or the plugin's `stores/<store>.js`. */
|
|
25
|
+
export declare const storeFileAt: (from: string, store: StoreModel) => string;
|
|
26
|
+
/** The Worker binding of a declared database store's D1: `ledger` is `DB_LEDGER`, `echo-ledger` is `DB_ECHO_LEDGER`. */
|
|
27
|
+
export declare const bindingOf: (store: StoreModel) => string;
|
|
28
|
+
/** The declared stores the Worker binds a D1 for: a database store, in name order. */
|
|
29
|
+
export declare const databaseStores: (model: Model) => ReadonlyArray<StoreModel>;
|
|
30
|
+
/** An operation's handler for the worker: the project's `src/<thing>/<verb>.ts`, or the plugin's `src/<thing>/<verb>.js`. */
|
|
31
|
+
export declare const handlerAt: (from: string, op: OperationModel) => string;
|
|
32
|
+
export declare const lines: (...parts: ReadonlyArray<string | ReadonlyArray<string>>) => string;
|
|
33
|
+
/** HTTP status per kind of refusal: a declared data error, a machine in the wrong state, nothing with that id, a caller without the role. */
|
|
34
|
+
export declare const STATUS: {
|
|
35
|
+
readonly declared: 422;
|
|
36
|
+
readonly notFrom: 409;
|
|
37
|
+
readonly notFound: 404;
|
|
38
|
+
readonly notAllowed: 403;
|
|
39
|
+
readonly idempotencyConflict: 409;
|
|
40
|
+
readonly notServed: 501;
|
|
41
|
+
};
|
|
42
|
+
export declare const NOT_ALLOWED_EXIT = 3;
|
|
43
|
+
/** The runtime keeps 120 to 125 (G3): a request key reused with another payload exits 120 and is a 409. */
|
|
44
|
+
export declare const IDEMPOTENCY_CONFLICT_EXIT = 120;
|
|
45
|
+
/** A read the runtime does not serve yet (a pinned or derived one, until slice 7 of Goal 17) exits 121, the first the runtime keeps after 120. */
|
|
46
|
+
export declare const READ_NOT_SERVED_EXIT = 121;
|
|
47
|
+
export { IDEMPOTENCY_CONFLICT, READ_NOT_SERVED } from "@orthograph/compiler";
|
|
48
|
+
/** An operation that runs on the caller's device (a plugin's `runs: "client"`): never on the server, in no API route or tool. */
|
|
49
|
+
export declare const onDevice: (op: OperationModel) => boolean;
|
|
50
|
+
/** The model as the server sees it: without the operations that run on the device. */
|
|
51
|
+
export declare const serverModel: (model: Model) => Model;
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
export const GENERATED = "// Generated from the blueprint. Do not edit.";
|
|
2
|
+
export const scaffolded = (from) => `// Scaffolded from ${from}. Yours from now on.`;
|
|
3
|
+
export const pascal = (name) => name.split("-").map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join("");
|
|
4
|
+
export const camel = (name) => pascal(name).replace(/^./, (c) => c.toLowerCase());
|
|
5
|
+
const RESERVED = new Set(["await", "break", "case", "catch", "class", "const", "continue", "arguments", "debugger", "default", "delete", "do", "else", "enum", "eval", "export", "extends", "false", "finally", "for", "function", "if", "implements", "import", "in", "instanceof", "interface", "let", "new", "null", "package", "private", "protected", "public", "return", "static", "super", "switch", "this", "throw", "true", "try", "typeof", "var", "void", "while", "with", "yield"]);
|
|
6
|
+
/**
|
|
7
|
+
* The name a verb gets as a local binding. A verb may be a reserved word (`import`, `delete`): it is still the property
|
|
8
|
+
* `Sdk.wallet.import` and the export name, but never a `const` of its own, so the binding gets an underscore and is
|
|
9
|
+
* exported under the verb (`export { import_ as import }`, which JavaScript allows).
|
|
10
|
+
*/
|
|
11
|
+
export const local = (name) => (RESERVED.has(name) ? `${name}_` : name);
|
|
12
|
+
/** The line that exports a binding under the verb's own name, when the binding had to be renamed. */
|
|
13
|
+
export const exportedAs = (verb) => (local(camel(verb)) === camel(verb) ? [] : [`export { ${local(camel(verb))} as ${camel(verb)} };`]);
|
|
14
|
+
/** `.create`, or `["sign-in"]` for a name that isn't an identifier: how generated code reaches a thing, a verb or a client member. */
|
|
15
|
+
export const member = (name) => (/^[A-Za-z_$][\w$]*$/.test(name) ? `.${name}` : `[${JSON.stringify(name)}]`);
|
|
16
|
+
/** The variable an operation goes by in generated code: `allowance.grant` is `allowanceGrant`. */
|
|
17
|
+
export const opVar = (op) => `${camel(op.thing)}${pascal(op.verb)}`;
|
|
18
|
+
/** Climb from a generated file back to the project root. */
|
|
19
|
+
export const toRoot = (from) => "../".repeat(from.split("/").length - 1);
|
|
20
|
+
/** Import a declaration: the project's own by path from `from`, a plugin's by its package specifier, as written. */
|
|
21
|
+
export const declarationAt = (from, file) => (file.startsWith("blueprint/") ? `${toRoot(from)}${file}` : file);
|
|
22
|
+
/** A thing's own file (`thing`, `errors`, `events`, `invariants`): in the project, or in the plugin it came from. */
|
|
23
|
+
export const thingFileAt = (from, thing, file) => thing.from.kind !== "app" ? `${thing.from.package}/blueprint/things/${thing.from.thing}/${file}.js` : `${toRoot(from)}blueprint/things/${thing.name}/${file}.ts`;
|
|
24
|
+
/** A store's own file: the project's `blueprint/stores/<name>.ts`, or the plugin's `stores/<store>.js`. */
|
|
25
|
+
export const storeFileAt = (from, store) => store.from ? `${store.from.package}/blueprint/stores/${store.from.store}.js` : `${toRoot(from)}blueprint/stores/${store.name}.ts`;
|
|
26
|
+
/** The Worker binding of a declared database store's D1: `ledger` is `DB_LEDGER`, `echo-ledger` is `DB_ECHO_LEDGER`. */
|
|
27
|
+
export const bindingOf = (store) => `DB_${store.name.toUpperCase().replaceAll("-", "_")}`;
|
|
28
|
+
/** The declared stores the Worker binds a D1 for: a database store, in name order. */
|
|
29
|
+
export const databaseStores = (model) => Object.values(model.stores ?? {}).filter((s) => s.kind === "database");
|
|
30
|
+
/** An operation's handler for the worker: the project's `src/<thing>/<verb>.ts`, or the plugin's `src/<thing>/<verb>.js`. */
|
|
31
|
+
export const handlerAt = (from, op) => op.from.kind !== "app" ? `${op.from.package}/src/${op.from.thing}/${op.verb}.js` : `${toRoot(from)}src/${op.thing}/${op.verb}.ts`;
|
|
32
|
+
export const lines = (...parts) => parts.flat().join("\n") + "\n";
|
|
33
|
+
/** HTTP status per kind of refusal: a declared data error, a machine in the wrong state, nothing with that id, a caller without the role. */
|
|
34
|
+
export const STATUS = { declared: 422, notFrom: 409, notFound: 404, notAllowed: 403, idempotencyConflict: 409, notServed: 501 };
|
|
35
|
+
export const NOT_ALLOWED_EXIT = 3;
|
|
36
|
+
/** The runtime keeps 120 to 125 (G3): a request key reused with another payload exits 120 and is a 409. */
|
|
37
|
+
export const IDEMPOTENCY_CONFLICT_EXIT = 120;
|
|
38
|
+
/** A read the runtime does not serve yet (a pinned or derived one, until slice 7 of Goal 17) exits 121, the first the runtime keeps after 120. */
|
|
39
|
+
export const READ_NOT_SERVED_EXIT = 121;
|
|
40
|
+
export { IDEMPOTENCY_CONFLICT, READ_NOT_SERVED } from "@orthograph/compiler";
|
|
41
|
+
/** An operation that runs on the caller's device (a plugin's `runs: "client"`): never on the server, in no API route or tool. */
|
|
42
|
+
export const onDevice = (op) => op.runs === "client";
|
|
43
|
+
/** The model as the server sees it: without the operations that run on the device. */
|
|
44
|
+
export const serverModel = (model) => ({
|
|
45
|
+
...model,
|
|
46
|
+
operations: Object.fromEntries(Object.entries(model.operations).filter(([, op]) => !onDevice(op))),
|
|
47
|
+
});
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import type { MoveTimeModel, OperationModel, Model } from "@orthograph/compiler";
|
|
2
|
+
/** The move an operation makes, when it is made by time. */
|
|
3
|
+
export declare const timeMoveOf: (model: Model, op: OperationModel) => MoveTimeModel | undefined;
|
|
4
|
+
/** The sentence, without its full stop; `mark` quotes a field name (backticks in markdown, nothing in plain text). */
|
|
5
|
+
export declare const whenWords: (thing: string, time: MoveTimeModel, mark: string) => string;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/** `"1 month"` is "month" and `"2 months"` stays as it is: "every month", "every 2 months". */
|
|
2
|
+
const period = (span) => (span.startsWith("1 ") ? span.slice(2).replace(/s$/, "") : span);
|
|
3
|
+
const anchor = (by, mark) => {
|
|
4
|
+
if (by.kind === "after")
|
|
5
|
+
return `${by.span} after ${mark}${by.field}${mark}`;
|
|
6
|
+
const every = `every ${period(by.span)}`;
|
|
7
|
+
if (by.from !== undefined)
|
|
8
|
+
return `${every} from ${mark}${by.from}${mark}`;
|
|
9
|
+
const on = by.on === undefined ? "" : "weekday" in by.on ? ` on ${by.on.weekday}` : by.on.day === "last" ? " on the last day" : ` on day ${by.on.day}`;
|
|
10
|
+
return `${every}${on}, in ${by.zone ?? "UTC"}`;
|
|
11
|
+
};
|
|
12
|
+
/** The move an operation makes, when it is made by time. */
|
|
13
|
+
export const timeMoveOf = (model, op) => {
|
|
14
|
+
const moves = model.things[op.thing]?.machine?.moves;
|
|
15
|
+
const move = op.move === null ? undefined : moves?.[op.move.key];
|
|
16
|
+
return move?.by === undefined ? undefined : { by: move.by, ...(move.late === undefined ? {} : { late: move.late }), ...(move.lazy === undefined ? {} : { lazy: move.lazy }) };
|
|
17
|
+
};
|
|
18
|
+
/** The sentence, without its full stop; `mark` quotes a field name (backticks in markdown, nothing in plain text). */
|
|
19
|
+
export const whenWords = (thing, time, mark) => [anchor(time.by, mark), time.lazy === true ? `worked out at the ${thing}'s next use` : "by the keeper", ...(time.late === undefined ? [] : [`up to ${time.late} late`])].join(", ");
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
import type { FieldModel, Model, OperationModel } from "@orthograph/compiler";
|
|
2
|
+
import { ruleSentence, words } from "orthograph/sentences";
|
|
3
|
+
export { ruleSentence, words };
|
|
4
|
+
/** `a handle`, `an allowance`, `an hour`-less: by the first letter, which is right for every name a blueprint is likely to give. */
|
|
5
|
+
export declare const article: (word: string) => "a" | "an";
|
|
6
|
+
export declare const refAny: (f: FieldModel) => boolean;
|
|
7
|
+
/** What a text flag takes, in the words a caller uses: a wide number is a `uint` (kept as text, so no digit is lost), an id says what it names, a named value its own name. */
|
|
8
|
+
export declare const metavar: (f: FieldModel) => string;
|
|
9
|
+
/**
|
|
10
|
+
* A flag's help: the field's own description, then what kind of value it takes. With no description it still says what the flag is: the
|
|
11
|
+
* thing field it is taken from, or the value's name, or the flag's own name, and the kind of value; never a bare "Text.".
|
|
12
|
+
*/
|
|
13
|
+
export declare const flagNote: (name: string, f: FieldModel) => string;
|
|
14
|
+
/**
|
|
15
|
+
* The operation's description, then what its move does to the thing, in a sentence a person would write: a move that creates says what the
|
|
16
|
+
* thing starts as, any other which states it goes from and to.
|
|
17
|
+
*/
|
|
18
|
+
export declare const helpOf: (op: OperationModel) => string;
|
|
19
|
+
/**
|
|
20
|
+
* The flag's declaration, as generated code: a number that fits is a number flag (handed on as digits); a wider one stays text. An any-thing
|
|
21
|
+
* reference, a list or an object is parsed as JSON at the flag, so malformed JSON is refused there, naming the flag.
|
|
22
|
+
*/
|
|
23
|
+
export declare const flagCode: (name: string, f: FieldModel) => string;
|
|
24
|
+
/** The rule behind one of an operation's refusals, by the model: its full name (`handle.oneHolderPerName`), the thing that holds it, and the sentence every output says. */
|
|
25
|
+
export interface RuleBehind {
|
|
26
|
+
readonly full: string;
|
|
27
|
+
readonly thing: string;
|
|
28
|
+
readonly name: string;
|
|
29
|
+
readonly sentence: string;
|
|
30
|
+
/** The fields the rule keys on, which the refusal carries by place. */
|
|
31
|
+
readonly fields: ReadonlyArray<string>;
|
|
32
|
+
}
|
|
33
|
+
/** The rule an operation's refusal is made for (`op.invariants`), or undefined when the runtime refuses it for another reason. */
|
|
34
|
+
export declare const ruleBehind: (model: Model, op: OperationModel, refusal: string) => RuleBehind | undefined;
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { ruleSentence, words } from "orthograph/sentences";
|
|
2
|
+
// The sentence for a rule, and a name as words, are `orthograph`'s: the portal's browser client says them too, and a runtime package cannot import this one.
|
|
3
|
+
export { ruleSentence, words };
|
|
4
|
+
/** `a handle`, `an allowance`, `an hour`-less: by the first letter, which is right for every name a blueprint is likely to give. */
|
|
5
|
+
export const article = (word) => (/^[aeiou]/i.test(word) ? "an" : "a");
|
|
6
|
+
const sentence = (text) => text.charAt(0).toUpperCase() + text.slice(1);
|
|
7
|
+
export const refAny = (f) => f.value.type === "schema" && f.value.format === "ref-any";
|
|
8
|
+
/** What a text flag takes, in the words a caller uses: a wide number is a `uint` (kept as text, so no digit is lost), an id says what it names, a named value its own name. */
|
|
9
|
+
export const metavar = (f) => f.value.type === "uint" ? "uint" : f.value.type === "id" ? "id" : refAny(f) || f.json !== undefined ? "json" : f.named !== undefined ? words(f.named).replace(/ /g, "-") : "text";
|
|
10
|
+
/** What kind of value a field holds, as words. */
|
|
11
|
+
const kindOf = (f) => f.value.type === "uint" ? `a whole number below 2^${f.value.bits}`
|
|
12
|
+
: f.value.type === "id" ? `an id (${f.value.prefix}_...)`
|
|
13
|
+
: f.value.type === "text" ? `text of up to ${f.value.max} characters`
|
|
14
|
+
: refAny(f) ? "a JSON object with the declaration and the id"
|
|
15
|
+
: f.json === "list" ? "a list, as JSON"
|
|
16
|
+
: f.json === "object" ? "an object, as JSON"
|
|
17
|
+
: "text";
|
|
18
|
+
/**
|
|
19
|
+
* A flag's help: the field's own description, then what kind of value it takes. With no description it still says what the flag is: the
|
|
20
|
+
* thing field it is taken from, or the value's name, or the flag's own name, and the kind of value; never a bare "Text.".
|
|
21
|
+
*/
|
|
22
|
+
export const flagNote = (name, f) => {
|
|
23
|
+
if (f.description !== undefined)
|
|
24
|
+
return `${f.description} ${sentence(kindOf(f))}.`;
|
|
25
|
+
const of = f.ref !== undefined ? words(f.ref.replace(/\./g, " ")) : f.named !== undefined ? `${article(words(f.named))} ${words(f.named)}` : `the ${words(name)}`;
|
|
26
|
+
return `${sentence(of)}: ${kindOf(f)}.`;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* The operation's description, then what its move does to the thing, in a sentence a person would write: a move that creates says what the
|
|
30
|
+
* thing starts as, any other which states it goes from and to.
|
|
31
|
+
*/
|
|
32
|
+
export const helpOf = (op) => {
|
|
33
|
+
if (!op.move)
|
|
34
|
+
return op.description;
|
|
35
|
+
const to = op.move.to.join(" or ");
|
|
36
|
+
return op.move.from.length === 0
|
|
37
|
+
? `${op.description} Creates ${article(op.thing)} ${words(op.thing)}, which starts ${to}.`
|
|
38
|
+
: `${op.description} Moves ${article(op.thing)} ${words(op.thing)} from ${op.move.from.join(" or ")} to ${to}.`;
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* The flag's declaration, as generated code: a number that fits is a number flag (handed on as digits); a wider one stays text. An any-thing
|
|
42
|
+
* reference, a list or an object is parsed as JSON at the flag, so malformed JSON is refused there, naming the flag.
|
|
43
|
+
*/
|
|
44
|
+
export const flagCode = (name, f) => {
|
|
45
|
+
const note = `Flag.withDescription(${JSON.stringify(flagNote(name, f))})`;
|
|
46
|
+
if (f.value.type === "uint" && f.value.bits <= 53)
|
|
47
|
+
return `Flag.Int("${name}").pipe(Flag.map(String), ${note})`;
|
|
48
|
+
const text = `Flag.String("${name}").pipe(Flag.withMetavar(${JSON.stringify(metavar(f))}), ${note})`;
|
|
49
|
+
return refAny(f) || f.json !== undefined ? `${text}.pipe(Flag.withSchema(Schema.fromJsonString(Schema.Unknown)))` : text;
|
|
50
|
+
};
|
|
51
|
+
/** The rule an operation's refusal is made for (`op.invariants`), or undefined when the runtime refuses it for another reason. */
|
|
52
|
+
export const ruleBehind = (model, op, refusal) => {
|
|
53
|
+
const full = op.invariants?.[refusal];
|
|
54
|
+
if (full === undefined)
|
|
55
|
+
return undefined;
|
|
56
|
+
const at = full.lastIndexOf(".");
|
|
57
|
+
const thing = full.slice(0, at);
|
|
58
|
+
const name = full.slice(at + 1);
|
|
59
|
+
const rule = model.things[thing]?.invariants?.[name];
|
|
60
|
+
return rule === undefined ? undefined : { full, thing, name, sentence: ruleSentence(thing, rule), fields: rule.fields };
|
|
61
|
+
};
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import type { Output } from "orthograph";
|
|
3
|
+
import type { Model } from "@orthograph/compiler";
|
|
4
|
+
import { MountedElsewhere, type RenderedFile } from "./types.ts";
|
|
5
|
+
export * from "./internal/names.ts";
|
|
6
|
+
export * from "./internal/words.ts";
|
|
7
|
+
export * from "./internal/when.ts";
|
|
8
|
+
/** The model a projection renders from: the compiler's, which `orthograph` types as unknown. */
|
|
9
|
+
export declare const modelOf: (input: {
|
|
10
|
+
readonly model: unknown;
|
|
11
|
+
}) => Model;
|
|
12
|
+
/**
|
|
13
|
+
* A built-in projection's files as its mount's output: each path relative to `generated/<mount>/`. The renderers write
|
|
14
|
+
* the paths the rest of the tooling reads (`generated/server/main.ts`), so a built-in projection is mounted under its own
|
|
15
|
+
* name, and a mount named otherwise is refused here, naming the file it should be.
|
|
16
|
+
*/
|
|
17
|
+
export declare const within: (input: {
|
|
18
|
+
readonly mount: string;
|
|
19
|
+
}, folder: string, files: ReadonlyArray<RenderedFile>) => Effect.Effect<ReadonlyArray<Output>, MountedElsewhere>;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { Effect } from "effect";
|
|
2
|
+
import { MountedElsewhere } from "./types.js";
|
|
3
|
+
export * from "./internal/names.js";
|
|
4
|
+
export * from "./internal/words.js";
|
|
5
|
+
export * from "./internal/when.js";
|
|
6
|
+
/** The model a projection renders from: the compiler's, which `orthograph` types as unknown. */
|
|
7
|
+
export const modelOf = (input) => input.model;
|
|
8
|
+
/**
|
|
9
|
+
* A built-in projection's files as its mount's output: each path relative to `generated/<mount>/`. The renderers write
|
|
10
|
+
* the paths the rest of the tooling reads (`generated/server/main.ts`), so a built-in projection is mounted under its own
|
|
11
|
+
* name, and a mount named otherwise is refused here, naming the file it should be.
|
|
12
|
+
*/
|
|
13
|
+
export const within = (input, folder, files) => {
|
|
14
|
+
if (input.mount !== folder) {
|
|
15
|
+
return Effect.fail(new MountedElsewhere({ message: `blueprint/projections/${input.mount}.ts: this projection writes generated/${folder}/, which the other tools read by that name: mount it as blueprint/projections/${folder}.ts` }));
|
|
16
|
+
}
|
|
17
|
+
const prefix = `generated/${folder}/`;
|
|
18
|
+
return Effect.succeed(files.map((f) => ({ path: f.path.startsWith(prefix) ? f.path.slice(prefix.length) : f.path, content: f.content })));
|
|
19
|
+
};
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/** A file a renderer makes. `path` is relative to the project root, with forward slashes. */
|
|
2
|
+
export interface RenderedFile {
|
|
3
|
+
readonly path: string;
|
|
4
|
+
readonly content: string;
|
|
5
|
+
/** A scaffold: written once if absent, then the project's own. Everything else is regenerated every time. */
|
|
6
|
+
readonly scaffold: boolean;
|
|
7
|
+
}
|
|
8
|
+
declare const MountedElsewhere_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
|
|
9
|
+
readonly _tag: "MountedElsewhere";
|
|
10
|
+
} & Readonly<A>;
|
|
11
|
+
/** A projection mounted where its output can't be: the tooling reads `generated/<folder>/`, so the mount must be named for it. */
|
|
12
|
+
export declare class MountedElsewhere extends MountedElsewhere_base<{
|
|
13
|
+
readonly message: string;
|
|
14
|
+
}> {
|
|
15
|
+
}
|
|
16
|
+
export {};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
// What every renderer here shares: the file it hands back, and the one refusal a projection has of its own.
|
|
2
|
+
import { Data } from "effect";
|
|
3
|
+
/** A projection mounted where its output can't be: the tooling reads `generated/<folder>/`, so the mount must be named for it. */
|
|
4
|
+
export class MountedElsewhere extends Data.TaggedError("MountedElsewhere") {
|
|
5
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// generated/sdk/src/client.ts: the client's layer (the caller is set here, once) and `call`, which every operation's function goes
|
|
2
|
+
// through: its payload encoded first, one request key from the start kept across retries, and a lost answer retried.
|
|
3
|
+
import { Names } from "orthograph/server";
|
|
4
|
+
import { GENERATED, lines } from "#modules/names/service.js";
|
|
5
|
+
/** The text of `client.ts` for a project: `client` is its service's name, `hasDevice` whether an operation runs on the device. */
|
|
6
|
+
export const clientSource = (name, client, hasDevice) => lines(GENERATED, `import { Context, Data, Effect, Layer, Schedule, Schema } from "effect";`, `import { SecureRandom } from "effect/crypto";`, `import { FetchHttpClient, HttpClient, HttpClientError, HttpClientRequest } from "effect/http";`, `import { HttpApiClient } from "effect/http-api";`, hasDevice ? `import type { DeviceWhere } from "${Names.pkg("language-effect")}/device";` : [], `import { Api } from "../../api/src/index.ts";`, "", `export class ${client} extends Context.Service<${client}, HttpApiClient.ForApi<typeof Api>>()("${name}/Client") {}`, "", "/** Who a client's calls are made as. It is set once, on the client's layer, and never on a call. */", "export type Credential = { readonly kind: \"session\"; readonly token: string };", "export const Credential = {", " /** A signed-in session: the token a sign-in gave, sent as a bearer token. */", " session: (token: string): Credential => ({ kind: \"session\", token }),", "};", "", "/** A payload its schema refuses: the message names where and why, never the value. The call never left the client. */", "export class InvalidPayload extends Data.TaggedError(\"InvalidPayload\")<{ readonly message: string }> {}", "", "/** What a call may be given: the key that makes its retries one request. Never a credential. */", "export interface CallOptions {", " /** The key the server keeps the answer under. Made when the call starts when not given, and kept across its retries. */", " readonly requestKey?: string | undefined;", "}", "", `const RequestKey = Context.Reference<string | undefined>("${name}/RequestKey", { defaultValue: () => undefined });`, "", "/** Where a payload is refused and why, never what it held: a value can be a password, and this message can reach a span. */", "const said = (issue: { readonly _tag: string; readonly path?: ReadonlyArray<unknown>; readonly issue?: unknown; readonly issues?: ReadonlyArray<unknown> }, path: ReadonlyArray<unknown> = []): ReadonlyArray<string> => {", " const where = path.length === 0 ? \"the payload\" : path.map(String).join(\".\");", " const inner = (next: unknown, more: ReadonlyArray<unknown> = []) => said(next as Parameters<typeof said>[0], [...path, ...more]);", " switch (issue._tag) {", " case \"Pointer\": return inner(issue.issue, issue.path);", " case \"Encoding\": return inner(issue.issue);", " case \"Composite\": case \"AnyOf\": case \"OneOf\": return (issue.issues ?? []).flatMap((next) => inner(next));", " case \"MissingKey\": return [`${where} is missing`];", " case \"UnexpectedKey\": return [`${where} is not expected`];", " case \"InvalidType\": return [`${where} is not the right kind of value`];", " case \"Filter\": return [`${where} does not satisfy its check`];", " default: return [`${where} is refused`];", " }", "};", "", "const isTransport = (error: unknown) => HttpClientError.isHttpClientError(error) && error.reason._tag === \"TransportError\";", "", "/**", " * One call. Its payload is encoded first: one the schema refuses is `InvalidPayload`, and nothing is sent. A request key is made", " * when the call starts (or the caller's is used) and sent as `idempotency-key` on every try. An operation the server keeps an", " * answer for is tried again when the connection was cut before the answer came, with the same key, so it commits once.", " * A response the server could not answer is a defect (a die), never a typed failure.", " * A call wrapped in your own `Effect.retry` makes a new key on each try unless you pass `requestKey`.", " * The retry waits on Effect's own clock: `Timers` is the server runtime's, and this client runs in the caller's process.", " */", "export const call = <A, E, R>(", " declaration: { readonly payloadSchema: Schema.Codec<any, any> },", " payload: unknown,", " options: CallOptions | undefined,", " retry: boolean,", " send: Effect.Effect<A, E, R>,", "): Effect.Effect<A, E | InvalidPayload, R> =>", " Effect.gen(function* () {", " yield* Schema.encodeUnknownEffect(declaration.payloadSchema)(payload, { errors: \"all\" }).pipe(Effect.mapError((cause) => new InvalidPayload({ message: said((cause as { readonly issue: Parameters<typeof said>[0] }).issue).join(\"; \") })));", " const key = options?.requestKey ?? (yield* Effect.flatMap(SecureRandom.SecureRandom, (random) => random.uuidV4()));", " const tries = retry ? Effect.retry(send, { schedule: Schedule.exponential(\"50 millis\"), times: 3, while: isTransport }) : send;", " return yield* tries.pipe(", " Effect.catchIf((error) => HttpClientError.isHttpClientError(error) && !isTransport(error), (error) => Effect.die(error)),", " Effect.provideService(RequestKey, key),", " );", " }).pipe(Effect.provide(SecureRandom.layerWebCrypto));", "", "const connect = (url: string, credential: Credential | undefined) =>", ` Layer.effect(${client}, HttpApiClient.make(Api, {`, " transformClient: HttpClient.mapRequestEffect((request) =>", " Effect.map(Effect.service(RequestKey), (key) => {", " const at = HttpClientRequest.prependUrl(request, url);", " const signed = credential === undefined ? at : HttpClientRequest.bearerToken(at, credential.token);", " return key === undefined ? signed : HttpClientRequest.setHeader(signed, \"idempotency-key\", key);", " })),", " })).pipe(Layer.provide(FetchHttpClient.layer));", "", hasDevice ? [
|
|
7
|
+
"/** Where the spans of an operation that runs on this device go, and the service they say they are from. */",
|
|
8
|
+
`export class ${client}Spans extends Context.Service<${client}Spans, DeviceWhere>()("${name}/Spans") {}`,
|
|
9
|
+
"",
|
|
10
|
+
"/** The standard variable, read where the SDK is made: a program that names no collector gets the one its environment does. */",
|
|
11
|
+
`const ambient = () => (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env?.["OTEL_EXPORTER_OTLP_ENDPOINT"];`,
|
|
12
|
+
"",
|
|
13
|
+
"/** A client for the server at `url`, as `credential` when there is one; the spans of operations that run here go to `otlp`. */",
|
|
14
|
+
"export interface Options { readonly url: string; readonly credential?: Credential | undefined; readonly otlp?: string | undefined }",
|
|
15
|
+
"",
|
|
16
|
+
"/** `layer({ url, credential })`, or `layer(url, token)`: the same client, the token being a session's. */",
|
|
17
|
+
"export const layer = (options: string | Options, token?: string, otlp?: string) => {",
|
|
18
|
+
" const given: Options = typeof options === \"string\" ? { url: options, credential: token === undefined || token === \"\" ? undefined : Credential.session(token), otlp } : options;",
|
|
19
|
+
" return Layer.mergeAll(",
|
|
20
|
+
" connect(given.url, given.credential),",
|
|
21
|
+
` Layer.succeed(${client}Spans, { otlp: given.otlp ?? ambient(), service: "${name}" }),`,
|
|
22
|
+
" );",
|
|
23
|
+
"};",
|
|
24
|
+
] : [
|
|
25
|
+
"/** A client for the server at `url`, as `credential` when there is one. */",
|
|
26
|
+
"export interface Options { readonly url: string; readonly credential?: Credential | undefined }",
|
|
27
|
+
"",
|
|
28
|
+
"/** `layer({ url, credential })`, or `layer(url, token)`: the same client, the token being a session's. */",
|
|
29
|
+
"export const layer = (options: string | Options, token?: string) =>",
|
|
30
|
+
" typeof options === \"string\" ? connect(options, token === undefined || token === \"\" ? undefined : Credential.session(token)) : connect(options.url, options.credential);",
|
|
31
|
+
]);
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// generated/sdk: a typed client. One function per operation; refusals arrive as their own classes.
|
|
2
|
+
import { Names } from "orthograph/server";
|
|
3
|
+
import { GENERATED, camel, exportedAs, lines, local, member, onDevice, pascal, toRoot } from "#modules/names/service.js";
|
|
4
|
+
import { sdkTypes } from "./types.js";
|
|
5
|
+
import { clientSource } from "./client.js";
|
|
6
|
+
/** The plugin's entry for the host that imports this, found by the SDK's own `imports` (`generated/sdk/package.json`). */
|
|
7
|
+
const hostEntry = (o) => `#host/${o.name}`;
|
|
8
|
+
const server = (o, client) => ({
|
|
9
|
+
path: `generated/sdk/src/${o.thing}/${o.verb}.ts`,
|
|
10
|
+
scaffold: false,
|
|
11
|
+
content: lines(GENERATED, `import { Effect } from "effect";`, `import type { PayloadOf } from "${Names.frontDoor}";`, `import { declaration } from "../../../api/src/${o.thing}/${o.verb}.ts";`, `import { ${client}, call, type CallOptions } from "../client.ts";`, "", `/** ${o.description} */`, `export const ${local(camel(o.verb))} = (payload: PayloadOf<typeof declaration>, options?: CallOptions) =>`, ` call(declaration, payload, options, ${o.idempotent === "request"}, Effect.flatMap(${client}, (client) => client${member(o.thing)}${member(o.verb)}({ payload })));`, exportedAs(o.verb)),
|
|
12
|
+
});
|
|
13
|
+
/**
|
|
14
|
+
* An operation that runs on the device: the plugin's own handler, run in this process under the app's mount, its spans
|
|
15
|
+
* sent from here. No request is made. Which handler is the host's: `browser` for a browser, `node` for Node.
|
|
16
|
+
*/
|
|
17
|
+
const device = (model, o, client) => {
|
|
18
|
+
const path = `generated/sdk/src/${o.thing}/${o.verb}.ts`;
|
|
19
|
+
const mount = o.from.kind === "app" ? undefined : model.mounts?.[o.from.mount];
|
|
20
|
+
return {
|
|
21
|
+
path,
|
|
22
|
+
scaffold: false,
|
|
23
|
+
content: lines(GENERATED, `import { Effect } from "effect";`, `import { Device, Mount } from "${Names.pkg("language-effect")}/device";`, `import type { PayloadOf } from "${Names.frontDoor}";`, `import { declaration } from "../../../api/src/${o.thing}/${o.verb}.ts";`, `import handler from "${hostEntry(o)}";`, mount ? `import mount from "${toRoot(path)}${mount.file}";` : [], `import { ${client}Spans } from "../client.ts";`, "", `const device = Device.serve({ name: "${o.name}", operation: declaration, handler: ${mount ? "Mount.serving(mount, handler)" : "handler"} });`, "", `/** ${o.description} Runs here, on this device: nothing is sent to the server. */`, `export const ${local(camel(o.verb))} = (payload: PayloadOf<typeof declaration>) =>`, ` Effect.flatMap(${client}Spans, (where) => device.run(payload, where));`, exportedAs(o.verb)),
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* `generated/sdk/package.json`: for each device operation, the plugin's entry for the host that imports it. A browser
|
|
28
|
+
* (or a bundler building for one) gets the `.browser.js` entry, Node the `.node.js`; the `world` entry is never picked by
|
|
29
|
+
* a condition, only named by the journey runner. With no condition matched, the browser entry, which imports nothing of Node's.
|
|
30
|
+
*/
|
|
31
|
+
const sdkPackage = (ops) => {
|
|
32
|
+
const entry = (o, host) => (o.from.kind === "app" ? "" : `${o.from.package}/src/${o.from.thing}/${o.verb}.${host}.js`);
|
|
33
|
+
return {
|
|
34
|
+
path: "generated/sdk/package.json",
|
|
35
|
+
scaffold: false,
|
|
36
|
+
content: JSON.stringify({
|
|
37
|
+
"//": GENERATED,
|
|
38
|
+
type: "module",
|
|
39
|
+
imports: Object.fromEntries(ops.map((o) => [hostEntry(o), { browser: entry(o, "browser"), node: entry(o, "node"), default: entry(o, "browser") }])),
|
|
40
|
+
}, null, 2) + "\n",
|
|
41
|
+
};
|
|
42
|
+
};
|
|
43
|
+
const clientFile = (name, client, hasDevice) => ({
|
|
44
|
+
path: "generated/sdk/src/client.ts",
|
|
45
|
+
scaffold: false,
|
|
46
|
+
content: clientSource(name, client, hasDevice),
|
|
47
|
+
});
|
|
48
|
+
export const renderSdk = (model, name) => {
|
|
49
|
+
const ops = Object.values(model.operations);
|
|
50
|
+
const things = [...new Set(ops.map((o) => o.thing))];
|
|
51
|
+
// The client's class is named for the project; a thing, a state or an event of that name keeps its own, and the client is `<Name>Client`.
|
|
52
|
+
const named = Object.values(model.things).flatMap((t) => [t.identifier, `${t.identifier}State`, ...Object.keys(t.events)]);
|
|
53
|
+
const client = named.includes(pascal(name)) ? `${pascal(name)}Client` : pascal(name);
|
|
54
|
+
const devices = ops.filter((o) => onDevice(o) && o.from.kind !== "app");
|
|
55
|
+
const perOp = ops.map((o) => (devices.includes(o) ? device(model, o, client) : server(o, client)));
|
|
56
|
+
const types = sdkTypes(model);
|
|
57
|
+
const index = {
|
|
58
|
+
path: "generated/sdk/src/index.ts",
|
|
59
|
+
scaffold: false,
|
|
60
|
+
content: lines(GENERATED, `export { ${client}, layer, Credential, InvalidPayload } from "./client.ts";`, `export type { CallOptions } from "./client.ts";`, `export { Errors } from "../../api/src/index.ts";`, things.map((t) => `export * as ${camel(t)} from "./${t}/index.ts";`), types.exports),
|
|
61
|
+
};
|
|
62
|
+
const thingIndexes = things.map((t) => ({
|
|
63
|
+
path: `generated/sdk/src/${t}/index.ts`,
|
|
64
|
+
scaffold: false,
|
|
65
|
+
content: lines(GENERATED, ops.filter((o) => o.thing === t).map((o) => `export { ${camel(o.verb)} } from "./${o.verb}.ts";`)),
|
|
66
|
+
}));
|
|
67
|
+
return [clientFile(name, client, devices.length > 0), index, ...types.files, ...thingIndexes, ...perOp, ...(devices.length > 0 ? [sdkPackage(devices)] : [])];
|
|
68
|
+
};
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import type { Model } from "@orthograph/compiler";
|
|
2
|
+
import type { RenderedFile } from "#modules/names/types.js";
|
|
3
|
+
export declare const comment: (text: string) => string;
|
|
4
|
+
/** One types file per thing, and the lines that put its names in the SDK's front door. */
|
|
5
|
+
export declare const sdkTypes: (model: Model) => {
|
|
6
|
+
readonly files: ReadonlyArray<RenderedFile>;
|
|
7
|
+
readonly exports: ReadonlyArray<string>;
|
|
8
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { article } from "#modules/names/service.js";
|
|
2
|
+
import { GENERATED, lines, thingFileAt } from "#modules/names/service.js";
|
|
3
|
+
// A sentence inside a doc comment: its own comment end would close the comment early.
|
|
4
|
+
export const comment = (text) => text.replace(/\*\//g, "*\\/").replace(/\s*\n\s*/g, " ");
|
|
5
|
+
/** The fields of one type, each with its sentence as a doc comment and its type from the blueprint's own value. */
|
|
6
|
+
const members = (fields, source, of, extra = []) => [
|
|
7
|
+
...Object.entries(fields).flatMap(([k, f]) => [
|
|
8
|
+
...(f.description === undefined ? [] : [` /** ${comment(f.description)} */`]),
|
|
9
|
+
// A field may be missing when the blueprint makes it optional, or when not every caller is shown it.
|
|
10
|
+
` readonly ${JSON.stringify(k)}${f.optional === true || f.visibility !== undefined ? "?" : ""}: ${of}<${source}[${JSON.stringify(k)}]>;`,
|
|
11
|
+
]),
|
|
12
|
+
...extra,
|
|
13
|
+
];
|
|
14
|
+
/** The types file of one thing: `Link` (each field), `LinkState` (`"listed" | "removed"`) and each event it emits. */
|
|
15
|
+
const typesOf = (t) => {
|
|
16
|
+
const path = `generated/sdk/src/${t.name}/types.ts`;
|
|
17
|
+
const state = `${t.identifier}State`;
|
|
18
|
+
const events = Object.keys(t.events);
|
|
19
|
+
// The module aliases below are local: one that a thing's own name, state or event would clash with takes a trailing underscore.
|
|
20
|
+
const taken = new Set([t.identifier, state, ...events]);
|
|
21
|
+
const alias = (n) => (taken.has(n) ? `${n}_` : n);
|
|
22
|
+
const [Source, Events, Declared, Of] = [alias("Source"), alias("Events"), alias("Declared"), alias("Of")];
|
|
23
|
+
return {
|
|
24
|
+
path,
|
|
25
|
+
scaffold: false,
|
|
26
|
+
content: lines(GENERATED,
|
|
27
|
+
// A thing and its events are found by what they are, not by their exports' names: a blueprint file may name them as it likes.
|
|
28
|
+
`import type * as ${Source} from "${thingFileAt(path, t, "thing")}";`, events.length > 0 ? `import type * as ${Events} from "${thingFileAt(path, t, "events")}";` : [], "", `type ${Declared} = Extract<(typeof ${Source})[keyof typeof ${Source}], { readonly kind: "thing" }>["fields"];`, "/** What a field or value holds, as the blueprint's own schema decodes it. */", `type ${Of}<F> = F extends { readonly value: { readonly schema: { readonly Type: infer T } } } ? T : F extends { readonly schema: { readonly Type: infer T } } ? T : never;`, "", t.machine ? [`/** The states ${article(t.name)} ${t.name} moves between, as its machine declares them. */`, `export type ${state} = ${t.machine.states.map((s) => JSON.stringify(s)).join(" | ")};`, ""] : [], `/** ${comment(t.description)} A field not every caller is shown (secret, or private to roles) may be missing from what a call returns. */`, `export type ${t.identifier} = {`, ...members(t.fields, Declared, Of, t.machine && !("state" in t.fields) ? [` readonly "state": ${state};`] : []), "};", ...events.flatMap((e) => ["", `/** The event ${e}: what it carries when ${article(t.name)} ${t.name} moves. */`, `export type ${e} = {`, ...members(t.events[e], `(typeof ${Events})[${JSON.stringify(e)}]["fields"]`, Of), "};"])),
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
/** One types file per thing, and the lines that put its names in the SDK's front door. */
|
|
32
|
+
export const sdkTypes = (model) => {
|
|
33
|
+
const things = Object.values(model.things);
|
|
34
|
+
return {
|
|
35
|
+
files: things.map(typesOf),
|
|
36
|
+
exports: things.map((t) => `export type { ${[t.identifier, ...(t.machine ? [`${t.identifier}State`] : []), ...Object.keys(t.events)].join(", ")} } from "./${t.name}/types.ts";`),
|
|
37
|
+
};
|
|
38
|
+
};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The typed client (`generated/sdk/`): one function per operation, the caller on the client's layer, a request key kept
|
|
3
|
+
* across retries, and declared refusals as typed failures. The CLI is built on it.
|
|
4
|
+
*/
|
|
5
|
+
export declare const sdk: import("orthograph").Projection<{}>;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { Blueprint, Host, Ships } from "orthograph";
|
|
2
|
+
import { modelOf, within } from "#modules/names/service.js";
|
|
3
|
+
import { renderSdk } from "./internal/sdk.js";
|
|
4
|
+
/**
|
|
5
|
+
* The typed client (`generated/sdk/`): one function per operation, the caller on the client's layer, a request key kept
|
|
6
|
+
* across retries, and declared refusals as typed failures. The CLI is built on it.
|
|
7
|
+
*/
|
|
8
|
+
export const sdk = Blueprint.projection({
|
|
9
|
+
description: "The typed client: a function per operation, the caller on its layer, a request key kept across retries, refusals as typed failures.",
|
|
10
|
+
host: [Host.node, Host.browser],
|
|
11
|
+
ships: [Ships.release],
|
|
12
|
+
render: (input) => within(input, "sdk", renderSdk(modelOf(input), input.name)),
|
|
13
|
+
});
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export type { Projection } from "orthograph";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** The options `toWorld` takes for actors: none for an app that has none, so its generated server is as it was. */
|
|
2
|
+
export const actorOptionOf = (model) => {
|
|
3
|
+
const tables = Object.values(model.things).filter((t) => t.lives === "actor").map((t) => `"${t.name}"`);
|
|
4
|
+
return tables.length > 0 ? `, actors: env.ACTORS, actorTables: [${tables.join(", ")}]` : "";
|
|
5
|
+
};
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { Model } from "@orthograph/compiler";
|
|
2
|
+
export declare const doorsOf: (model: Model, name: string, mountVar: (mount: string) => string, imported: ReadonlyArray<string>) => {
|
|
3
|
+
any: boolean;
|
|
4
|
+
/** The mounts' files not already imported, and each source kind that maps them. */
|
|
5
|
+
imports: string[];
|
|
6
|
+
/** Each door: the adapter that says how its sender signs, the events the mount includes, the sources that map them, and the binding of its signing secret. */
|
|
7
|
+
table: string[];
|
|
8
|
+
env: string[];
|
|
9
|
+
route: string[];
|
|
10
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { toRoot } from "#modules/names/service.js";
|
|
2
|
+
export const doorsOf = (model, name, mountVar, imported) => {
|
|
3
|
+
const doored = Object.entries(model.mounts ?? {}).filter(([, m]) => m.door !== undefined).sort(([a], [b]) => a.localeCompare(b));
|
|
4
|
+
const sourcesOf = (mount) => Object.values((model.sources ?? {})).filter((s) => s.mount === mount);
|
|
5
|
+
const sourceAt = (file) => (file.startsWith("@") ? file.replace(/\.ts$/, ".js") : `${toRoot("generated/server/main.ts")}${file}`);
|
|
6
|
+
return {
|
|
7
|
+
any: doored.length > 0,
|
|
8
|
+
/** The mounts' files not already imported, and each source kind that maps them. */
|
|
9
|
+
imports: [
|
|
10
|
+
...doored.filter(([m]) => !imported.includes(m)).map(([m]) => `import ${mountVar(m)} from "${toRoot("generated/server/main.ts")}${model.mounts[m].file}";`),
|
|
11
|
+
...doored.flatMap(([m]) => sourcesOf(m)).map((src) => `import { ${src.export} } from "${sourceAt(src.file)}";`),
|
|
12
|
+
],
|
|
13
|
+
/** Each door: the adapter that says how its sender signs, the events the mount includes, the sources that map them, and the binding of its signing secret. */
|
|
14
|
+
table: doored.length === 0 ? [] : [
|
|
15
|
+
"/** Each door: the adapter that says how its sender signs, the events the mount includes, the sources that map them, and the binding of its signing secret. */",
|
|
16
|
+
`const doors = [${doored.map(([m, mm]) => `{ mount: "${m}", adapter: ${mountVar(m)}.plugin, events: ${JSON.stringify(mm.events ?? [])}, sources: [${sourcesOf(m).map((x) => x.export).join(", ")}], secret: "${mm.door.secret}" }`).join(", ")}];`,
|
|
17
|
+
"",
|
|
18
|
+
],
|
|
19
|
+
env: doored.map(([, mm]) => ` /** The signing secret of a door: set by whoever runs the Worker, never written in a file. */\n readonly ${mm.door.secret}?: string;`),
|
|
20
|
+
route: doored.length === 0 ? [] : [
|
|
21
|
+
" if (new URL(request.url).pathname.startsWith(\"/_in/\")) {",
|
|
22
|
+
` return Telemetry.serve({ url: env.OTLP_URL || undefined, sinks: env.OTLP_SINKS, environment: env.ORTHO_ENVIRONMENT, service: "${name}", handler: (req, context) => Inbound.handle({ doors, db: env.DB, secrets: env as unknown as Record<string, unknown> }, req, context), waitUntil: (p) => ctx.waitUntil(p) }, request);`,
|
|
23
|
+
" }",
|
|
24
|
+
],
|
|
25
|
+
};
|
|
26
|
+
};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Model, OperationModel } from "@orthograph/compiler";
|
|
2
|
+
export declare const emptyPath: (o: OperationModel) => string;
|
|
3
|
+
/** The runtime's refusals the generated code names: the machine's, when the move starts from a state (D2 #37), and each not-found. */
|
|
4
|
+
export declare const notFromOf: (model: Model, o: OperationModel) => string;
|
|
5
|
+
export declare const peopleOf: (model: Model) => string;
|
|
6
|
+
/**
|
|
7
|
+
* How the Worker exports its world (and its actors). A blueprint with a stepped or scaled clock extends the world with its wake
|
|
8
|
+
* route (M8.07): each kind of durable timer to the code that wakes it, empty until a feature registers a kind. Any other
|
|
9
|
+
* blueprint re-exports the host's, exactly as it always did.
|
|
10
|
+
*/
|
|
11
|
+
export declare const worldExports: (timed: boolean, actors: boolean) => ReadonlyArray<string>;
|
|
12
|
+
/** One thing's routes: each operation handled through the runtime's wrapper, under the services taken once. */
|
|
13
|
+
export declare const groupOf: (ops: ReadonlyArray<OperationModel>, empty: boolean, timed: boolean) => (t: string) => ReadonlyArray<string>;
|