@aitoroses/telar 0.0.0 → 0.1.0

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 (92) hide show
  1. package/README.md +453 -3
  2. package/dist/compile.d.ts +48 -0
  3. package/dist/compile.js +1238 -0
  4. package/dist/contract.d.ts +109 -0
  5. package/dist/contract.js +497 -0
  6. package/dist/evaluator.d.ts +23 -0
  7. package/dist/evaluator.js +40 -0
  8. package/dist/guide.d.ts +8 -0
  9. package/dist/guide.js +16 -0
  10. package/dist/install.d.ts +104 -0
  11. package/dist/install.js +402 -0
  12. package/dist/iso.d.ts +8 -0
  13. package/dist/iso.js +68 -0
  14. package/dist/node/build.d.ts +1 -0
  15. package/dist/node/build.js +34 -0
  16. package/dist/node/telar-module.d.ts +2 -0
  17. package/dist/node/telar-module.js +28 -0
  18. package/dist/observer.d.ts +47 -0
  19. package/dist/observer.js +53 -0
  20. package/dist/pieces.d.ts +230 -0
  21. package/dist/pieces.js +178 -0
  22. package/dist/powers.d.ts +46 -0
  23. package/dist/powers.js +126 -0
  24. package/dist/protocol.d.ts +212 -0
  25. package/dist/protocol.js +236 -0
  26. package/dist/query.d.ts +67 -0
  27. package/dist/query.js +102 -0
  28. package/dist/read.d.ts +37 -0
  29. package/dist/read.js +27 -0
  30. package/dist/runner.d.ts +112 -0
  31. package/dist/runner.js +134 -0
  32. package/dist/scenario/builder.d.ts +25 -0
  33. package/dist/scenario/builder.js +603 -0
  34. package/dist/scenario/templates.d.ts +35 -0
  35. package/dist/scenario/templates.js +64 -0
  36. package/dist/scenario/types.d.ts +441 -0
  37. package/dist/scenario/types.js +10 -0
  38. package/dist/scenario/validate.d.ts +7 -0
  39. package/dist/scenario/validate.js +19 -0
  40. package/dist/scenario.d.ts +4 -0
  41. package/dist/scenario.js +4 -0
  42. package/dist/schema.d.ts +219 -0
  43. package/dist/schema.js +221 -0
  44. package/dist/seating.d.ts +49 -0
  45. package/dist/seating.js +26 -0
  46. package/dist/send-hook.d.ts +46 -0
  47. package/dist/send-hook.js +123 -0
  48. package/dist/show.d.ts +34 -0
  49. package/dist/show.js +1 -0
  50. package/dist/source.d.ts +85 -0
  51. package/dist/source.js +104 -0
  52. package/dist/spec.d.ts +20 -0
  53. package/dist/spec.js +17 -0
  54. package/dist/standard-schema.d.ts +21 -0
  55. package/dist/standard-schema.js +1 -0
  56. package/dist/std/accuracy.d.ts +12 -0
  57. package/dist/std/accuracy.js +122 -0
  58. package/dist/std/ack.d.ts +14 -0
  59. package/dist/std/ack.js +43 -0
  60. package/dist/std/actions.d.ts +106 -0
  61. package/dist/std/actions.js +154 -0
  62. package/dist/std/brief.d.ts +36 -0
  63. package/dist/std/brief.js +78 -0
  64. package/dist/std/claude-code.d.ts +9 -0
  65. package/dist/std/claude-code.js +106 -0
  66. package/dist/std/compare.d.ts +29 -0
  67. package/dist/std/compare.js +36 -0
  68. package/dist/std/git-workspace.d.ts +44 -0
  69. package/dist/std/git-workspace.js +184 -0
  70. package/dist/std/judgment.d.ts +85 -0
  71. package/dist/std/judgment.js +462 -0
  72. package/dist/std/observe-command.d.ts +23 -0
  73. package/dist/std/observe-command.js +151 -0
  74. package/dist/std/observe-github-checks.d.ts +26 -0
  75. package/dist/std/observe-github-checks.js +299 -0
  76. package/dist/std/observe-http-status.d.ts +27 -0
  77. package/dist/std/observe-http-status.js +181 -0
  78. package/dist/std/plan.d.ts +7 -0
  79. package/dist/std/plan.js +28 -0
  80. package/dist/std/queries.d.ts +31 -0
  81. package/dist/std/queries.js +318 -0
  82. package/dist/std/reading.d.ts +17 -0
  83. package/dist/std/reading.js +88 -0
  84. package/dist/std/schedule.d.ts +19 -0
  85. package/dist/std/schedule.js +122 -0
  86. package/dist/std.d.ts +15 -0
  87. package/dist/std.js +15 -0
  88. package/dist/types.d.ts +366 -0
  89. package/dist/types.js +1 -0
  90. package/dist/values.d.ts +81 -0
  91. package/dist/values.js +129 -0
  92. package/package.json +62 -5
@@ -0,0 +1,212 @@
1
+ import type { Guide } from "./guide.js";
2
+ import type { AckDef, AnyAuthClass, AnyMessageKind, AnyRole, ArgsForContract, CallActionEffectNode, CheckNeedNode, MessageKind, ProtocolTarget, Role, RoleBriefOverride, RoleViewOverride, SeatLabelsDef, StepBoundInput } from "./pieces.js";
3
+ import type { AnyContract, AnyStructContract, Brand, FieldHandlesOf, FieldSchemaMap, Infer, OptionalType, StructContract, StructFieldsOfContract, VariantsOf } from "./schema.js";
4
+ import type { BriefPiece, NonEmpty, Rec, RecordMode } from "./types.js";
5
+ import { type FieldRef, type FieldTable, type RecordInput } from "./values.js";
6
+ type LabelsOfRole<R> = R extends Role<string, infer L> ? L : never;
7
+ type LabelsOfRoles<R> = R extends readonly (infer Item)[] ? LabelsOfRole<Item> : LabelsOfRole<R>;
8
+ export type SeatLabelReq<L extends SeatLabelsDef> = {
9
+ readonly [K in keyof L & string]: {
10
+ readonly key: K;
11
+ readonly values: NonEmpty<L[K][number]>;
12
+ };
13
+ }[keyof L & string];
14
+ export interface ChildFilterInput {
15
+ readonly childField: string | FieldRef;
16
+ readonly parentField: string | FieldRef;
17
+ }
18
+ export type Need = CheckNeedNode | {
19
+ readonly kind: "answer-need";
20
+ readonly roles: NonEmpty<AnyRole>;
21
+ readonly shape: AnyContract;
22
+ readonly variants?: NonEmpty<string>;
23
+ readonly seatLabel?: {
24
+ readonly key: string;
25
+ readonly values: NonEmpty<string>;
26
+ };
27
+ readonly guide?: string;
28
+ } | {
29
+ readonly kind: "auth-need";
30
+ readonly cls: AnyAuthClass;
31
+ readonly guide?: string;
32
+ } | {
33
+ readonly kind: "auth-from-field-need";
34
+ readonly field: string;
35
+ readonly allowed: NonEmpty<AnyAuthClass>;
36
+ readonly guide?: string;
37
+ } | {
38
+ readonly kind: "children-need";
39
+ readonly protocol?: ProtocolTarget;
40
+ readonly condition: "ended" | "state" | "ended-in";
41
+ readonly state?: string;
42
+ readonly where?: ChildFilterInput;
43
+ readonly allowEmpty: boolean;
44
+ readonly guide?: string;
45
+ } | {
46
+ readonly kind: "message-need";
47
+ readonly message: AnyMessageKind;
48
+ readonly from: NonEmpty<AnyRole>;
49
+ readonly guide?: string;
50
+ } | {
51
+ readonly kind: "bound-reached-need";
52
+ readonly step: string;
53
+ readonly guide?: string;
54
+ } | {
55
+ readonly kind: "any-need";
56
+ readonly of: readonly [Need, Need, ...Need[]];
57
+ readonly guide?: string;
58
+ };
59
+ export type Effect = CallActionEffectNode | {
60
+ readonly kind: "record-data-effect";
61
+ readonly mode: RecordMode;
62
+ readonly targetField: string;
63
+ readonly source: unknown;
64
+ } | {
65
+ readonly kind: "open-child-effect";
66
+ readonly protocol: ProtocolTarget;
67
+ readonly forRole: AnyRole;
68
+ readonly seatScopeFrom?: string;
69
+ readonly data: Rec<unknown>;
70
+ } | {
71
+ readonly kind: "emit-message-effect";
72
+ readonly message: AnyMessageKind;
73
+ readonly toRole: AnyRole;
74
+ readonly payload?: Rec<unknown>;
75
+ };
76
+ export interface Step<Name extends string = string, From extends string = string, To extends string = string> {
77
+ readonly kind: "step";
78
+ readonly name: Name;
79
+ readonly from: From;
80
+ readonly to: To;
81
+ readonly needs: readonly Need[];
82
+ readonly then: readonly Effect[];
83
+ readonly bound?: StepBoundInput;
84
+ readonly optional?: true;
85
+ readonly guide?: string;
86
+ }
87
+ export type AnyStep = Step;
88
+ export interface ProtocolRef<Name extends string = string, S extends string = string, F extends string = S> {
89
+ readonly kind: "protocol-ref";
90
+ readonly name: Name;
91
+ readonly states?: readonly S[];
92
+ readonly final?: readonly F[];
93
+ }
94
+ export type AnyProtocolRef = ProtocolRef;
95
+ export interface ProtocolAckOverride {
96
+ readonly message: AnyMessageKind;
97
+ readonly ack: AckDef;
98
+ }
99
+ export type ProtocolDataInput = FieldTable | AnyContract | FieldSchemaMap;
100
+ export type FieldHandlesOfProtocolData<D extends ProtocolDataInput> = D extends FieldTable<infer M> ? FieldTable<M> : D extends StructContract<string, infer F> ? FieldHandlesOf<F> : D extends FieldSchemaMap ? FieldHandlesOf<D> : Readonly<Record<string, never>>;
101
+ type IsBindingValue<T> = unknown extends T ? true : [T] extends [string] ? string extends T ? true : [T] extends [Brand<string, string>] ? true : false : false;
102
+ type RequiredStringFields<F extends FieldSchemaMap> = {
103
+ readonly [K in keyof F & string]-?: F[K] extends OptionalType ? never : IsBindingValue<Infer<F[K]>> extends true ? K : never;
104
+ }[keyof F & string];
105
+ type BindingFieldOfStruct<F> = [F] extends [never] ? string : F extends FieldSchemaMap ? RequiredStringFields<F> : string;
106
+ type BindingFieldOfData<D> = D extends FieldTable<infer _M> ? string : D extends AnyContract ? BindingFieldOfStruct<StructFieldsOfContract<D>> : D extends FieldSchemaMap ? RequiredStringFields<D> : string;
107
+ export type BindingFieldOf<P extends AnyProtocol> = BindingFieldOfData<P["data"]>;
108
+ export interface Protocol<Name extends string = string, S extends string = string, F extends string = S, D extends ProtocolDataInput = ProtocolDataInput> {
109
+ readonly kind: "protocol";
110
+ readonly name: Name;
111
+ readonly states: readonly [S, S, ...S[]];
112
+ readonly start: S;
113
+ readonly final: NonEmpty<F>;
114
+ readonly data: D;
115
+ readonly dataName?: string;
116
+ readonly openDataName?: string;
117
+ readonly predecessor?: {
118
+ readonly field: string;
119
+ readonly protocol?: ProtocolTarget;
120
+ };
121
+ readonly roleViews: readonly RoleViewOverride[];
122
+ readonly brief?: readonly BriefPiece[];
123
+ readonly roleBriefs: readonly RoleBriefOverride[];
124
+ readonly guide?: string;
125
+ readonly children: readonly ProtocolTarget[];
126
+ readonly acks: readonly ProtocolAckOverride[];
127
+ readonly steps: NonEmpty<AnyStep>;
128
+ }
129
+ export type AnyProtocol = Protocol;
130
+ export interface AnswerNeedOpts<V extends string, L extends SeatLabelsDef> {
131
+ readonly variants?: NonEmpty<V> | undefined;
132
+ readonly seatLabel?: SeatLabelReq<L> | undefined;
133
+ readonly guide?: Guide | undefined;
134
+ }
135
+ export declare function answer<R extends AnyRole | NonEmpty<AnyRole>, C extends AnyContract>(roles: R, shape: C, variantsOrOpts?: NonEmpty<VariantsOf<C>> | AnswerNeedOpts<VariantsOf<C>, LabelsOfRoles<R>>): Need;
136
+ export declare const authorize: {
137
+ (cls: AnyAuthClass, opts?: {
138
+ readonly guide?: Guide | undefined;
139
+ }): Need;
140
+ readonly fromField: (fieldRef: FieldRef<string, string | undefined>, allowed: NonEmpty<AnyAuthClass>, opts?: {
141
+ readonly guide?: Guide | undefined;
142
+ }) => Need;
143
+ };
144
+ export declare function childrenEnded(opts: {
145
+ readonly protocol?: ProtocolTarget | undefined;
146
+ readonly where?: ChildFilterInput | undefined;
147
+ readonly allowEmpty: boolean;
148
+ readonly guide?: Guide | undefined;
149
+ }): Need;
150
+ export declare function childrenIn<S extends string>(target: Protocol<string, S, string> | ProtocolRef<string, S, string>, state: NoInfer<S>, opts: {
151
+ readonly where?: ChildFilterInput | undefined;
152
+ readonly allowEmpty: boolean;
153
+ readonly guide?: Guide | undefined;
154
+ }): Need;
155
+ export declare function childrenEndedIn<F extends string>(target: Protocol<string, string, F> | ProtocolRef<string, string, F>, state: NoInfer<F>, opts: {
156
+ readonly where?: ChildFilterInput | undefined;
157
+ readonly allowEmpty: boolean;
158
+ readonly guide?: Guide | undefined;
159
+ }): Need;
160
+ export declare function received(msgKind: AnyMessageKind, opts: {
161
+ readonly from: AnyRole | NonEmpty<AnyRole>;
162
+ readonly guide?: Guide | undefined;
163
+ }): Need;
164
+ export declare function boundReached(stepName: string, opts?: {
165
+ readonly guide?: Guide | undefined;
166
+ }): Need;
167
+ export declare function anyOf(first: Need, second: Need, ...rest: readonly Need[]): Need;
168
+ export declare function withGuide(need: Need, g: Guide): Need;
169
+ export declare function set<T>(target: FieldRef<string, T>, value: RecordInput<T>): Effect;
170
+ export declare function append<E>(target: FieldRef<string, readonly E[]>, item: RecordInput<E>): Effect;
171
+ export declare function openChild(target: ProtocolTarget, opts: {
172
+ readonly for: AnyRole;
173
+ readonly seatScopeFrom?: string | FieldRef | undefined;
174
+ readonly data: Rec<unknown>;
175
+ }): Effect;
176
+ export declare function emit<P extends AnyStructContract>(msgKind: MessageKind<string, P>, opts: {
177
+ readonly to: AnyRole;
178
+ readonly payload?: ArgsForContract<P> | undefined;
179
+ }): Effect;
180
+ export declare function step<const Name extends string, const From extends string, const To extends string>(name: Name, def: {
181
+ readonly from: From;
182
+ readonly to: To;
183
+ readonly needs?: readonly Need[] | undefined;
184
+ readonly then?: readonly Effect[] | undefined;
185
+ readonly bound?: StepBoundInput | undefined;
186
+ readonly optional?: true | undefined;
187
+ readonly guide?: Guide | undefined;
188
+ }): Step<Name, From, To>;
189
+ export declare function protocolRef<const Name extends string, const S extends string = string, const F extends NoInfer<S> = S>(name: Name, def?: {
190
+ readonly states?: readonly S[] | undefined;
191
+ readonly final?: readonly F[] | undefined;
192
+ }): ProtocolRef<Name, S, F>;
193
+ export declare function protocol<const Name extends string, const S extends string, const F extends NoInfer<S>, D extends ProtocolDataInput = ProtocolDataInput>(name: Name, def: {
194
+ readonly states: readonly [S, S, ...S[]];
195
+ readonly start: NoInfer<S>;
196
+ readonly final: NonEmpty<F>;
197
+ readonly data: D;
198
+ readonly dataName?: string | undefined;
199
+ readonly openDataName?: string | undefined;
200
+ readonly predecessor?: {
201
+ readonly field: FieldRef<string, string | undefined>;
202
+ readonly protocol?: ProtocolTarget | undefined;
203
+ } | undefined;
204
+ readonly roleViews?: readonly RoleViewOverride[] | undefined;
205
+ readonly brief?: readonly BriefPiece[] | undefined;
206
+ readonly roleBriefs?: readonly RoleBriefOverride[] | undefined;
207
+ readonly guide?: Guide | ((data: FieldHandlesOfProtocolData<D>) => Guide) | undefined;
208
+ readonly children?: readonly ProtocolTarget[] | undefined;
209
+ readonly acks?: readonly ProtocolAckOverride[] | undefined;
210
+ readonly steps: NonEmpty<Step<string, NoInfer<S>, NoInfer<S>>>;
211
+ }): Protocol<Name, S, F, D>;
212
+ export {};
@@ -0,0 +1,236 @@
1
+ import { readFieldTableMeta } from "./values.js";
2
+ const THEN = "then";
3
+ function freezeNonEmpty(items) {
4
+ const [first, ...rest] = items;
5
+ return Object.freeze([first, ...rest]);
6
+ }
7
+ function isRoleList(roles) {
8
+ return Array.isArray(roles);
9
+ }
10
+ function normalizeRoles(roles) {
11
+ if (isRoleList(roles)) {
12
+ return freezeNonEmpty(roles);
13
+ }
14
+ return Object.freeze([roles]);
15
+ }
16
+ function isVariantList(value) {
17
+ return Array.isArray(value);
18
+ }
19
+ export function answer(roles, shape, variantsOrOpts) {
20
+ const roleList = normalizeRoles(roles);
21
+ if (variantsOrOpts === undefined) {
22
+ return Object.freeze({ kind: "answer-need", roles: roleList, shape });
23
+ }
24
+ if (isVariantList(variantsOrOpts)) {
25
+ return Object.freeze({
26
+ kind: "answer-need",
27
+ roles: roleList,
28
+ shape,
29
+ variants: freezeNonEmpty(variantsOrOpts),
30
+ });
31
+ }
32
+ return Object.freeze({
33
+ kind: "answer-need",
34
+ roles: roleList,
35
+ shape,
36
+ ...(variantsOrOpts.variants !== undefined
37
+ ? { variants: freezeNonEmpty(variantsOrOpts.variants) }
38
+ : {}),
39
+ ...(variantsOrOpts.seatLabel !== undefined
40
+ ? {
41
+ seatLabel: Object.freeze({
42
+ key: variantsOrOpts.seatLabel.key,
43
+ values: freezeNonEmpty(variantsOrOpts.seatLabel.values),
44
+ }),
45
+ }
46
+ : {}),
47
+ ...(variantsOrOpts.guide !== undefined ? { guide: variantsOrOpts.guide.template } : {}),
48
+ });
49
+ }
50
+ function makeAuthNeed(cls, opts) {
51
+ return Object.freeze({
52
+ kind: "auth-need",
53
+ cls,
54
+ ...(opts?.guide !== undefined ? { guide: opts.guide.template } : {}),
55
+ });
56
+ }
57
+ export const authorize = Object.freeze(Object.assign(makeAuthNeed, {
58
+ fromField(fieldRef, allowed, opts) {
59
+ return Object.freeze({
60
+ kind: "auth-from-field-need",
61
+ field: fieldRef.name,
62
+ allowed: freezeNonEmpty(allowed),
63
+ ...(opts?.guide !== undefined ? { guide: opts.guide.template } : {}),
64
+ });
65
+ },
66
+ }));
67
+ export function childrenEnded(opts) {
68
+ return Object.freeze({
69
+ kind: "children-need",
70
+ condition: "ended",
71
+ allowEmpty: opts.allowEmpty,
72
+ ...(opts.protocol !== undefined ? { protocol: opts.protocol } : {}),
73
+ ...(opts.where !== undefined ? { where: opts.where } : {}),
74
+ ...(opts.guide !== undefined ? { guide: opts.guide.template } : {}),
75
+ });
76
+ }
77
+ export function childrenIn(target, state, opts) {
78
+ return Object.freeze({
79
+ kind: "children-need",
80
+ protocol: target,
81
+ condition: "state",
82
+ state,
83
+ allowEmpty: opts.allowEmpty,
84
+ ...(opts.where !== undefined ? { where: opts.where } : {}),
85
+ ...(opts.guide !== undefined ? { guide: opts.guide.template } : {}),
86
+ });
87
+ }
88
+ export function childrenEndedIn(target, state, opts) {
89
+ return Object.freeze({
90
+ kind: "children-need",
91
+ protocol: target,
92
+ condition: "ended-in",
93
+ state,
94
+ allowEmpty: opts.allowEmpty,
95
+ ...(opts.where !== undefined ? { where: opts.where } : {}),
96
+ ...(opts.guide !== undefined ? { guide: opts.guide.template } : {}),
97
+ });
98
+ }
99
+ export function received(msgKind, opts) {
100
+ return Object.freeze({
101
+ kind: "message-need",
102
+ message: msgKind,
103
+ from: normalizeRoles(opts.from),
104
+ ...(opts.guide !== undefined ? { guide: opts.guide.template } : {}),
105
+ });
106
+ }
107
+ export function boundReached(stepName, opts) {
108
+ return Object.freeze({
109
+ kind: "bound-reached-need",
110
+ step: stepName,
111
+ ...(opts?.guide !== undefined ? { guide: opts.guide.template } : {}),
112
+ });
113
+ }
114
+ export function anyOf(first, second, ...rest) {
115
+ const of = Object.freeze([first, second, ...rest]);
116
+ return Object.freeze({ kind: "any-need", of });
117
+ }
118
+ export function withGuide(need, g) {
119
+ return Object.freeze({ ...need, guide: g.template });
120
+ }
121
+ export function set(target, value) {
122
+ return Object.freeze({
123
+ kind: "record-data-effect",
124
+ mode: "set",
125
+ targetField: target.name,
126
+ source: value,
127
+ });
128
+ }
129
+ export function append(target, item) {
130
+ return Object.freeze({
131
+ kind: "record-data-effect",
132
+ mode: "append",
133
+ targetField: target.name,
134
+ source: item,
135
+ });
136
+ }
137
+ export function openChild(target, opts) {
138
+ const scopeField = opts.seatScopeFrom === undefined
139
+ ? undefined
140
+ : typeof opts.seatScopeFrom === "string"
141
+ ? opts.seatScopeFrom
142
+ : opts.seatScopeFrom.name;
143
+ return Object.freeze({
144
+ kind: "open-child-effect",
145
+ protocol: target,
146
+ forRole: opts.for,
147
+ ...(scopeField !== undefined ? { seatScopeFrom: scopeField } : {}),
148
+ data: opts.data,
149
+ });
150
+ }
151
+ export function emit(msgKind, opts) {
152
+ return Object.freeze({
153
+ kind: "emit-message-effect",
154
+ message: msgKind,
155
+ toRole: opts.to,
156
+ ...(opts.payload !== undefined ? { payload: opts.payload } : {}),
157
+ });
158
+ }
159
+ export function step(name, def) {
160
+ return Object.freeze({
161
+ kind: "step",
162
+ name,
163
+ from: def.from,
164
+ to: def.to,
165
+ needs: Object.freeze([...(def.needs ?? [])]),
166
+ [THEN]: Object.freeze([...(def.then ?? [])]),
167
+ ...(def.bound !== undefined ? { bound: def.bound } : {}),
168
+ ...(def.optional !== undefined ? { optional: def.optional } : {}),
169
+ ...(def.guide !== undefined ? { guide: def.guide.template } : {}),
170
+ });
171
+ }
172
+ export function protocolRef(name, def) {
173
+ return Object.freeze({
174
+ kind: "protocol-ref",
175
+ name,
176
+ ...(def?.states !== undefined ? { states: Object.freeze([...def.states]) } : {}),
177
+ ...(def?.final !== undefined ? { final: Object.freeze([...def.final]) } : {}),
178
+ });
179
+ }
180
+ function isStructContract(data) {
181
+ return "kind" in data && data.kind === "contract" && "fields" in data;
182
+ }
183
+ function protocolFieldHandles(data) {
184
+ const meta = readFieldTableMeta(data);
185
+ if (meta !== undefined) {
186
+ const handles = {};
187
+ for (const key of Object.keys(meta.entries)) {
188
+ handles[key] = Object.freeze({ kind: "field", name: key });
189
+ }
190
+ return Object.freeze(handles);
191
+ }
192
+ if (isStructContract(data)) {
193
+ return data.fields;
194
+ }
195
+ const handles = {};
196
+ for (const key of Object.keys(data)) {
197
+ handles[key] = Object.freeze({ kind: "field", name: key });
198
+ }
199
+ return Object.freeze(handles);
200
+ }
201
+ export function protocol(name, def) {
202
+ const [s0, s1, ...sRest] = def.states;
203
+ const states = Object.freeze([s0, s1, ...sRest]);
204
+ const resolvedGuide = def.guide === undefined
205
+ ? undefined
206
+ : typeof def.guide === "function"
207
+ ? def.guide(protocolFieldHandles(def.data)).template
208
+ : def.guide.template;
209
+ return Object.freeze({
210
+ kind: "protocol",
211
+ name,
212
+ states,
213
+ start: def.start,
214
+ final: freezeNonEmpty(def.final),
215
+ data: def.data,
216
+ ...(def.dataName !== undefined ? { dataName: def.dataName } : {}),
217
+ ...(def.openDataName !== undefined ? { openDataName: def.openDataName } : {}),
218
+ ...(def.predecessor !== undefined
219
+ ? {
220
+ predecessor: Object.freeze({
221
+ field: def.predecessor.field.name,
222
+ ...(def.predecessor.protocol !== undefined
223
+ ? { protocol: def.predecessor.protocol }
224
+ : {}),
225
+ }),
226
+ }
227
+ : {}),
228
+ roleViews: Object.freeze([...(def.roleViews ?? [])]),
229
+ ...(def.brief !== undefined ? { brief: Object.freeze([...def.brief]) } : {}),
230
+ roleBriefs: Object.freeze([...(def.roleBriefs ?? [])]),
231
+ ...(resolvedGuide !== undefined ? { guide: resolvedGuide } : {}),
232
+ children: Object.freeze([...(def.children ?? [])]),
233
+ acks: Object.freeze([...(def.acks ?? [])]),
234
+ steps: freezeNonEmpty(def.steps),
235
+ });
236
+ }
@@ -0,0 +1,67 @@
1
+ import type { StandardSchema } from "./standard-schema.js";
2
+ export type QueryRowIssuePath = readonly (PropertyKey | {
3
+ readonly key: PropertyKey;
4
+ })[];
5
+ export interface QueryRowIssue {
6
+ readonly message: string;
7
+ readonly path?: QueryRowIssuePath | undefined;
8
+ }
9
+ export type QueryRowResult<Row> = {
10
+ readonly value: Row;
11
+ readonly issues?: undefined;
12
+ } | {
13
+ readonly issues: readonly QueryRowIssue[];
14
+ };
15
+ /** A Standard Schema (v1) for one row. An Effect schema becomes one through `Schema.toStandardSchemaV1`. */
16
+ export interface QueryRowSchema<Row> {
17
+ readonly "~standard": {
18
+ readonly version: 1;
19
+ readonly vendor: string;
20
+ readonly validate: (value: unknown) => QueryRowResult<Row> | PromiseLike<QueryRowResult<Row>>;
21
+ };
22
+ }
23
+ export type QueryParam = string | number | null;
24
+ /** One argument: its schema decodes the string a caller gives into the value the SQL binds as `:<name>`. */
25
+ export interface QueryArg<Out extends QueryParam = QueryParam> {
26
+ readonly schema: StandardSchema<Out>;
27
+ readonly description?: string;
28
+ }
29
+ export type QueryArgs = Readonly<Record<string, QueryArg>>;
30
+ export type NoQueryArgs = Readonly<Record<string, never>>;
31
+ export type QueryArgInput<A extends QueryArgs> = {
32
+ readonly [K in keyof A]: string;
33
+ };
34
+ export interface Query<Row = unknown, A extends QueryArgs = QueryArgs> {
35
+ readonly name: string;
36
+ readonly args: A;
37
+ readonly sql: string;
38
+ readonly row: QueryRowSchema<Row>;
39
+ }
40
+ export type QueryBinding = {
41
+ readonly ok: true;
42
+ readonly sql: string;
43
+ readonly params: Readonly<Record<string, QueryParam>>;
44
+ } | {
45
+ readonly ok: false;
46
+ readonly issues: readonly QueryRowIssue[];
47
+ };
48
+ export declare class QueryError extends Error {
49
+ readonly name: string;
50
+ readonly code: string;
51
+ constructor(code: string, message: string);
52
+ }
53
+ interface QueryDeclaration<Row> {
54
+ readonly name: string;
55
+ readonly sql: string;
56
+ readonly row: QueryRowSchema<Row>;
57
+ }
58
+ export declare function defineQuery<Row>(query: QueryDeclaration<Row>): Query<Row, NoQueryArgs>;
59
+ export declare function defineQuery<Row, A extends QueryArgs>(query: QueryDeclaration<Row> & {
60
+ readonly args: A;
61
+ }): Query<Row, A>;
62
+ /** Decodes a caller's arguments with the query's schemas into the named parameters its SQL binds. */
63
+ export declare function bindQuery<A extends QueryArgs>(query: Query<unknown, A>, input: QueryArgInput<A>): QueryBinding;
64
+ export declare function queryUsage(query: Query): string;
65
+ export declare function issueText(issue: QueryRowIssue): string;
66
+ export declare function decodeQueryRows<Row>(query: Query<Row>, rows: unknown): readonly Row[];
67
+ export {};
package/dist/query.js ADDED
@@ -0,0 +1,102 @@
1
+ export class QueryError extends Error {
2
+ name = "QueryError";
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.code = code;
7
+ }
8
+ }
9
+ const QUERY_NAME = /^[a-z][a-z0-9-]*$/;
10
+ const ARG_NAME = /^[a-z][a-zA-Z0-9]*$/;
11
+ export function defineQuery(query) {
12
+ if (!QUERY_NAME.test(query.name)) {
13
+ throw new QueryError("INVALID_QUERY", `query name ${JSON.stringify(query.name)} must match ${String(QUERY_NAME)}`);
14
+ }
15
+ const args = query.args ?? {};
16
+ for (const arg of Object.keys(args)) {
17
+ if (!ARG_NAME.test(arg)) {
18
+ throw new QueryError("INVALID_QUERY", `query ${query.name} argument ${JSON.stringify(arg)} must match ${String(ARG_NAME)}`);
19
+ }
20
+ }
21
+ const sql = query.sql.trim();
22
+ if (sql.length === 0) {
23
+ throw new QueryError("INVALID_QUERY", `query ${query.name} has empty SQL`);
24
+ }
25
+ return Object.freeze({ name: query.name, args, sql, row: query.row });
26
+ }
27
+ function isQueryParam(value) {
28
+ return (value === null ||
29
+ typeof value === "string" ||
30
+ (typeof value === "number" && Number.isFinite(value)));
31
+ }
32
+ function decodeArg(name, arg, raw) {
33
+ const refuse = (message) => ({
34
+ ok: false,
35
+ issues: [{ message, path: [name] }],
36
+ });
37
+ if (typeof raw !== "string")
38
+ return refuse("is missing");
39
+ const result = arg.schema["~standard"].validate(raw);
40
+ if (isPromiseLike(result))
41
+ return refuse("must decode synchronously");
42
+ if (result.issues !== undefined) {
43
+ const issues = result.issues.map((issue) => ({
44
+ message: issue.message,
45
+ path: [name, ...(issue.path ?? [])],
46
+ }));
47
+ return { ok: false, issues };
48
+ }
49
+ if (!isQueryParam(result.value))
50
+ return refuse("must decode to a string, a finite number or null");
51
+ return { ok: true, value: result.value };
52
+ }
53
+ /** Decodes a caller's arguments with the query's schemas into the named parameters its SQL binds. */
54
+ export function bindQuery(query, input) {
55
+ const issues = Object.keys(input)
56
+ .filter((key) => !Object.hasOwn(query.args, key))
57
+ .map((key) => ({ message: `is not an argument of ${query.name}`, path: [key] }));
58
+ const params = {};
59
+ for (const [name, arg] of Object.entries(query.args)) {
60
+ const decoded = decodeArg(name, arg, Reflect.get(input, name));
61
+ if (decoded.ok)
62
+ params[name] = decoded.value;
63
+ else
64
+ issues.push(...decoded.issues);
65
+ }
66
+ return issues.length > 0 ? { ok: false, issues } : { ok: true, sql: query.sql, params };
67
+ }
68
+ export function queryUsage(query) {
69
+ const names = Object.keys(query.args);
70
+ const call = ["telar query", query.name, ...names.map((name) => `<${name}>`)].join(" ");
71
+ const described = Object.entries(query.args)
72
+ .filter(([, arg]) => arg.description !== undefined)
73
+ .map(([name, arg]) => `<${name}>: ${arg.description ?? ""}`);
74
+ return described.length > 0 ? `${call} (${described.join("; ")})` : call;
75
+ }
76
+ export function issueText(issue) {
77
+ const path = (issue.path ?? [])
78
+ .map((part) => String(typeof part === "object" ? part.key : part))
79
+ .join(".");
80
+ return path.length > 0 ? `${path}: ${issue.message}` : issue.message;
81
+ }
82
+ function isPromiseLike(value) {
83
+ return (typeof value === "object" &&
84
+ value !== null &&
85
+ typeof value.then === "function");
86
+ }
87
+ export function decodeQueryRows(query, rows) {
88
+ if (!Array.isArray(rows)) {
89
+ throw new QueryError("ROW_DECODE_ERROR", `query ${query.name} expected an array of rows`);
90
+ }
91
+ return rows.map((raw, index) => {
92
+ const result = query.row["~standard"].validate(raw);
93
+ if (isPromiseLike(result)) {
94
+ throw new QueryError("ROW_DECODE_ERROR", `query ${query.name} row schema must decode synchronously`);
95
+ }
96
+ if (result.issues !== undefined) {
97
+ const detail = result.issues.map(issueText).join("; ");
98
+ throw new QueryError("ROW_DECODE_ERROR", `query ${query.name} row ${String(index)} does not decode: ${detail}`);
99
+ }
100
+ return result.value;
101
+ });
102
+ }
package/dist/read.d.ts ADDED
@@ -0,0 +1,37 @@
1
+ import { type Query, type QueryArgInput, type QueryArgs } from "./query.js";
2
+ import type { ShowCase, ShowSeat } from "./show.js";
3
+ /** Which seats `read.seats` returns: by role, and eligible for one case. */
4
+ export interface ReadSeatsFilter {
5
+ readonly role?: string | undefined;
6
+ readonly eligibleFor?: string | undefined;
7
+ }
8
+ /**
9
+ * The read-only view of the engine an extension gets, limited to its principal's view (ADR 0050).
10
+ * A case out of view reads the same as a case that does not exist.
11
+ */
12
+ export interface Read {
13
+ readonly case: (id: string) => ShowCase | undefined;
14
+ /** The case, then its parent, up to the first case out of view. */
15
+ readonly lineage: (id: string) => readonly ShowCase[];
16
+ /** Active seats eligible for a visible case, with their `holder`. */
17
+ readonly seats: (filter?: ReadSeatsFilter) => readonly ShowSeat[];
18
+ /**
19
+ * A declared query's rows, run on this principal's view of the trail: the read-model tables and
20
+ * `facts` hold only what the view shows (ADR 0050 D2). The rows are decoded with the query's `row`.
21
+ */
22
+ readonly query: <Row, A extends QueryArgs>(query: Query<Row, A>, args: QueryArgInput<A>) => readonly Row[];
23
+ }
24
+ /** A seat for `fakeRead`, with the cases it is eligible for. */
25
+ export interface FakeReadSeat extends ShowSeat {
26
+ readonly eligibleFor: readonly string[];
27
+ }
28
+ /**
29
+ * A `Read` over fixed data, for an installation's own unit tests. It enforces no view:
30
+ * it returns what the test gives. telar's contract tests hold the view.
31
+ */
32
+ export declare function fakeRead(input?: {
33
+ readonly cases?: readonly ShowCase[];
34
+ readonly seats?: readonly FakeReadSeat[];
35
+ /** Raw rows per query name; `read.query` decodes them with the query's `row`. */
36
+ readonly rows?: Readonly<Record<string, readonly unknown[]>>;
37
+ }): Read;
package/dist/read.js ADDED
@@ -0,0 +1,27 @@
1
+ import { decodeQueryRows } from "./query.js";
2
+ /**
3
+ * A `Read` over fixed data, for an installation's own unit tests. It enforces no view:
4
+ * it returns what the test gives. telar's contract tests hold the view.
5
+ */
6
+ export function fakeRead(input = {}) {
7
+ const cases = new Map((input.cases ?? []).map((c) => [c.id, c]));
8
+ const seats = input.seats ?? [];
9
+ const lineage = (id) => {
10
+ const chain = [];
11
+ let next = cases.get(id);
12
+ while (next !== undefined) {
13
+ chain.push(next);
14
+ next = next.parent === null ? undefined : cases.get(next.parent);
15
+ }
16
+ return chain;
17
+ };
18
+ return Object.freeze({
19
+ case: (id) => cases.get(id),
20
+ lineage,
21
+ seats: (filter = {}) => seats
22
+ .filter((s) => filter.role === undefined || s.role === filter.role)
23
+ .filter((s) => filter.eligibleFor === undefined || s.eligibleFor.includes(filter.eligibleFor))
24
+ .map(({ eligibleFor: _eligibleFor, ...seat }) => seat),
25
+ query: (query, _args) => decodeQueryRows(query, input.rows?.[query.name] ?? []),
26
+ });
27
+ }